Documentation
¶
Overview ¶
Package brainbackup keeps an end-to-end encrypted copy of 2nd Brain in the cloud (ADR-119): off until the user turns it on, free, and readable only with a recovery key that is made on this computer and never leaves it.
From the one recovery key three things are derived, with HKDF-SHA256 under distinct labels: the encryption key (XChaCha20-Poly1305), an auth token the server checks, and the account id the backups are filed under, which is a hash of the auth token. So the server needs no login, no email and no stored credential: a request is allowed when the token it carries hashes to the account it names. The server holds ciphertext, sizes and times; the key, the encryption key and the brain itself never reach it.
Index ¶
- Constants
- Variables
- func AccountFor(auth string) string
- func IDFor(t time.Time) string
- func NewToken() (string, error)
- func Open(d Derived, file []byte) (store.BrainSnapshot, error)
- func Seal(d Derived, ex store.BrainSnapshot) ([]byte, error)
- func SubHash(token string) string
- func SubRef(token string) string
- type Client
- func (c *Client) CloudStatus(ctx context.Context, token string) (CloudAnswer, error)
- func (c *Client) DeleteAll(ctx context.Context, d Derived) error
- func (c *Client) Get(ctx context.Context, d Derived, sub, id string) ([]byte, error)
- func (c *Client) List(ctx context.Context, d Derived, sub string) (Listing, error)
- func (c *Client) Put(ctx context.Context, d Derived, sub, id string, file []byte) error
- func (c *Client) SubGet(ctx context.Context, d Derived) ([]byte, error)
- func (c *Client) SubPut(ctx context.Context, d Derived, sub string, file []byte) error
- func (c *Client) SyncGet(ctx context.Context, d Derived, sub, device string, from, through int64) ([]byte, error)
- func (c *Client) SyncList(ctx context.Context, d Derived, sub string) (SyncListing, error)
- func (c *Client) SyncPut(ctx context.Context, d Derived, sub, device string, from, through int64, ...) error
- type CloudAnswer
- type CloudSub
- type CloudView
- type Derived
- type Key
- type Listing
- type Remote
- type RestoreResult
- type Segment
- type Service
- func (s *Service) BackupNow(ctx context.Context) (Status, error)
- func (s *Service) Cloud(ctx context.Context) CloudView
- func (s *Service) Confirm(ctx context.Context) error
- func (s *Service) DeleteCloud(ctx context.Context) error
- func (s *Service) Kick()
- func (s *Service) List(ctx context.Context, typed string) (Listing, error)
- func (s *Service) Refresh(ctx context.Context) (CloudView, error)
- func (s *Service) Restore(ctx context.Context, typed, id string, replace, keep bool) (RestoreResult, error)
- func (s *Service) RevealKey(ctx context.Context) (string, error)
- func (s *Service) Run(ctx context.Context)
- func (s *Service) Status(ctx context.Context) Status
- func (s *Service) Subscribe(ctx context.Context, period string) (string, error)
- func (s *Service) SyncNow(ctx context.Context) (SyncResult, error)
- func (s *Service) SyncRound(ctx context.Context) (SyncResult, error)
- func (s *Service) TurnOff() error
- func (s *Service) TurnOn(ctx context.Context) (string, error)
- type Status
- type SyncListing
- type SyncResult
Constants ¶
const ( DefaultURL = "https://caprock.dev/api/brain-backup" EnvURL = "CAPROCK_BRAIN_BACKUP_URL" )
DefaultURL is where backups go. EnvURL replaces it — a preview stand or a test sets it, and must never reach the real site.
const ( DefaultTick = 5 * time.Minute DefaultMinGap = 6 * time.Hour )
The schedule: the brain is looked at every Tick, and a backup is made when it changed since the last one and that one is at least MinGap old. So a day with changes gets at most four backups, and the server keeps the newest of each of the last 30 days (ADR-119). An unchanged brain is not uploaded again. The same tick runs a cloud sync round (cloudsync.go). Both need 2nd Brain Cloud (cloud.go).
const MaxFile = 25 << 20
MaxFile is the largest backup the server takes (caprock-web functions/_lib/brainbackup.ts MAX_OBJECT); checked here first, so a brain too big for it says so instead of uploading 25 MB to be refused.
const MaxPlain = 256 << 20
MaxPlain bounds what one backup opens to, so a hostile file cannot inflate without end.
const (
// MaxSub is the sealed token's largest size.
MaxSub = 64 << 10
)
const PromiseAfterEnd = 30 * 24 * time.Hour
PromiseAfterEnd is how long after a subscription ends users are promised their cloud copies stay restorable: at least 30 days. The server keeps them up to 90 (caprock-web functions/_lib/braincloud.ts).
const StateFile = "brain-backup.json"
StateFile, in the data directory, is the switch and what the last backup did. It holds no key.
const SubHeader = "X-Caprock-Brain-Cloud"
SubHeader carries the subscription token (cloud.go) on uploads and sync. The server hashes it and checks the hash is a paid subscription; it never stores which account the token came with.
const (
WaitFor = time.Hour
)
How often the site is asked about the subscription: twice a day while nothing is happening, every tick while a payment is awaited, and for at most WaitFor after Subscribe was clicked.
Variables ¶
var CloudItem = secret.Item{Service: "dev.caprock.braincloud", Label: "Caprock 2nd Brain Cloud subscription", File: "brain-cloud-token", Noun: "token"}
CloudItem is where the subscription token is kept on this computer.
var ErrBadKey = errors.New("that is not a recovery key: check it against the one you saved")
ErrBadKey is a recovery key that does not read: the wrong length, a character outside the alphabet, or a checksum that does not match.
var ErrFormat = errors.New("not a 2nd Brain backup this Caprock can read")
ErrFormat is a file that is not a backup this Caprock reads.
var ErrNoBackup = errors.New("no such backup in the cloud")
ErrNoBackup is an id the server does not have.
var ErrNotOnSale = errors.New("2nd Brain Cloud cannot be bought from caprock.dev yet; nothing was charged")
ErrNotOnSale is the site without payment links.
var ErrNotOpen = errors.New("cloud backup of 2nd Brain is not open on caprock.dev yet; nothing was sent")
ErrNotOpen is the server's switch being off (503 not_enabled).
var ErrNotSubscribed = errors.New("2nd Brain Cloud is not active for this brain, so nothing was uploaded (copies are kept at least 30 days after a subscription ends, then deleted from the cloud only); subscribe in Settings → 2nd Brain")
ErrNotSubscribed is the server's 402: uploads and sync need 2nd Brain Cloud, and copies of an account whose subscription ended over 90 days ago are gone from the cloud (at least 30 days are promised).
var ErrOpen = errors.New("this backup does not open with that recovery key, or it was changed")
ErrOpen is a backup that does not open with this key: a different key, or a file that was changed.
var ID = regexp.MustCompile(`^[0-9]{8}T[0-9]{6}Z$`)
ID names one backup: the UTC second it was made, 20261129T101500Z.
var Item = secret.Item{Service: "dev.caprock.brainbackup", Label: "Caprock 2nd Brain backup recovery key", File: "brain-backup-key", Noun: "key"}
Item is where the recovery key is kept on this computer: the login keychain on macOS, else a 0600 file in the data directory (internal/secret).
var Token = regexp.MustCompile(`^[0-9a-f]{64}$`)
Token is the subscription token's form: 64 lowercase hex characters.
Functions ¶
func AccountFor ¶
AccountFor is the account an auth token opens: the first 32 hex characters of SHA-256 over "caprock-brain-backup/v1:" and the token. The server computes the same (caprock-web functions/_lib/brainbackup.ts).
func Open ¶
func Open(d Derived, file []byte) (store.BrainSnapshot, error)
Open decrypts and reads a backup file.
func Seal ¶
func Seal(d Derived, ex store.BrainSnapshot) ([]byte, error)
Seal compresses and encrypts a brain export for one key.
Types ¶
type Client ¶
Client talks to the backup server. It sends only the account id, the auth token, the subscription token and ciphertext.
func (*Client) CloudStatus ¶
CloudStatus asks the site about a token's subscription; token "" asks only for the payment links.
func (*Client) DeleteAll ¶
DeleteAll removes every backup of the account, and with them its cloud sync copies and its sealed subscription token.
func (*Client) SubGet ¶
SubGet is the sealed subscription token, read with the account's auth alone: how a second computer of the same brain adopts the subscription.
func (*Client) SyncGet ¶
func (c *Client) SyncGet(ctx context.Context, d Derived, sub, device string, from, through int64) ([]byte, error)
SyncGet downloads one sealed segment.
type CloudAnswer ¶
type CloudAnswer struct {
Links *struct {
Month string `json:"month"`
Year string `json:"year"`
} `json:"links"`
ManageURL string `json:"manage_url"`
Subscription *CloudSub `json:"subscription"`
}
CloudAnswer is GET /api/brain-cloud/status.
type CloudSub ¶
type CloudSub struct {
Active bool `json:"active"`
Status string `json:"status"`
Period string `json:"period"` // month or year
CurrentPeriodEnd int64 `json:"current_period_end"` // unix seconds, 0 unknown
CancelAtPeriodEnd bool `json:"cancel_at_period_end"`
EndedAt int64 `json:"ended_at"`
// RestoreUntil is the server's real date, ended_at + 90 days; users are
// promised RestorePromisedUntil, ended_at + 30 days (ADR-119, amended
// 2026-11-30: promise the minimum).
RestoreUntil int64 `json:"restore_until"`
RestorePromisedUntil int64 `json:"restore_promised_until"`
}
CloudSub is the subscription as the site reports it.
type CloudView ¶
type CloudView struct {
Active bool `json:"active"`
Status string `json:"status,omitempty"`
Period string `json:"period,omitempty"`
// RenewsAt is the end of the paid period, unix seconds: the renewal
// date, or the last day when CancelAtPeriodEnd.
RenewsAt int64 `json:"renews_at,omitempty"`
CancelAtPeriodEnd bool `json:"cancel_at_period_end,omitempty"`
EndedAt int64 `json:"ended_at,omitempty"`
RestoreUntil int64 `json:"restore_until,omitempty"`
// RestorePromisedUntil is the date the app shows: ended_at + 30 days.
RestorePromisedUntil int64 `json:"restore_promised_until,omitempty"`
ManageURL string `json:"manage_url,omitempty"`
// OnSale says the site has payment links to open.
OnSale bool `json:"on_sale"`
HasToken bool `json:"has_token"`
CheckedAt int64 `json:"checked_at,omitempty"` // unix ms
// Waiting is a Subscribe clicked within the last hour and not yet paid.
Waiting bool `json:"waiting,omitempty"`
Error string `json:"error,omitempty"`
// The last cloud sync round.
SyncAt int64 `json:"sync_at,omitempty"`
SyncError string `json:"sync_error,omitempty"`
SyncComputers int `json:"sync_computers,omitempty"`
}
CloudView is the subscription as Settings shows it (GET /v1/brain/backup's cloud).
type Derived ¶
type Derived struct {
// Account is what the server files this key's backups under: 32 hex
// characters of SHA-256 over the auth token (AccountFor).
Account string
// Auth is the bearer token the server checks against Account: 64 hex
// characters. The server never stores it.
Auth string
// contains filtered or unexported fields
}
Derived is what one recovery key gives.
type Key ¶
type Key [keyLen]byte
Key is a recovery key: 32 random bytes.
func ParseKey ¶
ParseKey reads a key the way a person types it back: any case, with or without the dashes, spaces or line breaks, O for 0 and I or L for 1.
type Listing ¶
type Listing struct {
Backups []Remote `json:"backups"`
Used int64 `json:"used_bytes"`
MaxBytes int64 `json:"max_bytes"`
}
Listing is GET <account>.
type Remote ¶
type Remote struct {
ID string `json:"id"`
Size int64 `json:"size"`
Uploaded string `json:"uploaded"` // RFC 3339, the server's clock
}
Remote is one backup as the server lists it.
type RestoreResult ¶
type RestoreResult struct {
store.BrainRestore
// Before is the local copy of the brain taken first, a gzip'd export.
Before string `json:"before"`
// Kept is true when the typed key now backs up this computer too.
KeptKey bool `json:"kept_key"`
}
RestoreResult is what a restore did.
type Segment ¶
type Segment struct {
Device string `json:"device"`
From int64 `json:"from"`
Through int64 `json:"through"`
Size int64 `json:"size"`
Uploaded string `json:"uploaded"`
}
Segment is one computer's sealed changes as the server lists it.
type Service ¶
type Service struct {
Store *store.Store
Secret secret.Store
DataDir string
Client *Client
Log *slog.Logger
Now func() time.Time
Tick time.Duration // DefaultTick when 0
MinGap time.Duration // DefaultMinGap when 0
// SubSecret keeps the 2nd Brain Cloud subscription token (CloudItem).
SubSecret secret.Store
// Cloud sync: what never leaves this computer (ADR-118's scope), ADR-118's
// switch (nil is on), this computer's name, and a call after a round
// changed the brain.
Scope func() store.BrainSyncScope
Name func() string
Changed func()
// contains filtered or unexported fields
}
Service runs the backup.
func (*Service) Confirm ¶
Confirm is the user's "I saved it": the backup is on, and the first one is made now.
func (*Service) DeleteCloud ¶
DeleteCloud removes every backup of this computer's key from the server, then forgets the key here and turns the backup off.
func (*Service) Restore ¶
func (s *Service) Restore(ctx context.Context, typed, id string, replace, keep bool) (RestoreResult, error)
Restore downloads one backup, opens it with the key, copies this computer's brain aside, and writes the backup in: merged, or replacing what a backup holds. keep adopts the typed key for this computer's own backups when it has none yet.
func (*Service) RevealKey ¶
RevealKey is the recovery key kept here, for the owner who lost the copy they saved.
func (*Service) Run ¶
Run looks at the brain every Tick until ctx ends, and backs it up when due. It does nothing while the backup is off.
func (*Service) Subscribe ¶
Subscribe makes this computer's subscription token when it has none and returns the payment link to open for period (month or year), with the token's hash as client_reference_id. Nothing is charged here: the link opens in the browser, and Refresh learns when it was paid.
func (*Service) SyncNow ¶
func (s *Service) SyncNow(ctx context.Context) (SyncResult, error)
SyncNow runs one cloud round at once, for Settings.
func (*Service) SyncRound ¶
func (s *Service) SyncRound(ctx context.Context) (SyncResult, error)
SyncRound is one cloud sync round: take in the other computers' new segments, then upload this computer's changes since the last round.
func (*Service) TurnOff ¶
TurnOff stops backing up. The key and the backups already made stay, so turning it on again carries on with the same key.
type Status ¶
type Status struct {
On bool `json:"on"`
Pending bool `json:"pending"`
HasKey bool `json:"has_key"`
// KeyWhere says where the recovery key is kept on this computer.
KeyWhere secret.Where `json:"key_where"`
LastAt int64 `json:"last_at,omitempty"`
LastID string `json:"last_id,omitempty"`
LastSize int64 `json:"last_size,omitempty"`
CheckedAt int64 `json:"checked_at,omitempty"`
Error string `json:"error,omitempty"`
ErrorAt int64 `json:"error_at,omitempty"`
// Server is the host backups go to, for the disclosure line.
Server string `json:"server"`
// MinGapHours is the shortest time between two backups.
MinGapHours int `json:"min_gap_hours"`
// Cloud is 2nd Brain Cloud, which uploads and cloud sync need.
Cloud CloudView `json:"cloud"`
}
Status is GET /v1/brain/backup.
type SyncListing ¶
type SyncListing struct {
Segments []Segment `json:"segments"`
Sub *struct {
Size int64 `json:"size"`
Uploaded string `json:"uploaded"`
} `json:"sub"`
}
SyncListing is GET /api/brain-sync/<account>.
type SyncResult ¶
type SyncResult struct {
Pulled int `json:"pulled"` // segments taken in
Pushed int `json:"pushed"` // segments uploaded
Added int `json:"added"` // memories new here
Updated int `json:"updated"` // memories changed here
Deleted int `json:"deleted"` // memories deleted here
Computers int `json:"computers"` // other computers in the account
}
SyncResult is what one cloud round did.