brainbackup

package
v0.207.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 30, 2026 License: Apache-2.0 Imports: 24 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
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.

View Source
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).

View Source
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.

View Source
const MaxPlain = 256 << 20

MaxPlain bounds what one backup opens to, so a hostile file cannot inflate without end.

View Source
const (

	// MaxSub is the sealed token's largest size.
	MaxSub = 64 << 10
)
View Source
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).

View Source
const StateFile = "brain-backup.json"

StateFile, in the data directory, is the switch and what the last backup did. It holds no key.

View Source
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.

View Source
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

View Source
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.

View Source
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.

View Source
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.

View Source
var ErrNoBackup = errors.New("no such backup in the cloud")

ErrNoBackup is an id the server does not have.

View Source
var ErrNotOnSale = errors.New("2nd Brain Cloud cannot be bought from caprock.dev yet; nothing was charged")

ErrNotOnSale is the site without payment links.

View Source
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).

View Source
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).

View Source
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.

View Source
var ID = regexp.MustCompile(`^[0-9]{8}T[0-9]{6}Z$`)

ID names one backup: the UTC second it was made, 20261129T101500Z.

View Source
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).

View Source
var Token = regexp.MustCompile(`^[0-9a-f]{64}$`)

Token is the subscription token's form: 64 lowercase hex characters.

Functions

func AccountFor

func AccountFor(auth string) string

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 IDFor

func IDFor(t time.Time) string

IDFor is the id of a backup made at t.

func NewToken

func NewToken() (string, error)

NewToken makes a subscription token from the system's random source.

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.

func SubHash

func SubHash(token string) string

SubHash is what the site files a subscription under: the first 32 hex characters of SHA-256 over the token's text. caprock-web functions/_lib/braincloud.ts computes the same.

func SubRef

func SubRef(token string) string

SubRef is the payment link's client_reference_id for a token.

Types

type Client

type Client struct {
	Base string // DefaultURL when empty (or EnvURL when set)
	HTTP *http.Client
}

Client talks to the backup server. It sends only the account id, the auth token, the subscription token and ciphertext.

func (*Client) CloudStatus

func (c *Client) CloudStatus(ctx context.Context, token string) (CloudAnswer, error)

CloudStatus asks the site about a token's subscription; token "" asks only for the payment links.

func (*Client) DeleteAll

func (c *Client) DeleteAll(ctx context.Context, d Derived) error

DeleteAll removes every backup of the account, and with them its cloud sync copies and its sealed subscription token.

func (*Client) Get

func (c *Client) Get(ctx context.Context, d Derived, sub, id string) ([]byte, error)

Get downloads one sealed backup.

func (*Client) List

func (c *Client) List(ctx context.Context, d Derived, sub string) (Listing, error)

List is the account's backups, newest first.

func (*Client) Put

func (c *Client) Put(ctx context.Context, d Derived, sub, id string, file []byte) error

Put uploads one sealed backup under id.

func (*Client) SubGet

func (c *Client) SubGet(ctx context.Context, d Derived) ([]byte, error)

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) SubPut

func (c *Client) SubPut(ctx context.Context, d Derived, sub string, file []byte) error

SubPut keeps the sealed subscription token in the account.

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.

func (*Client) SyncList

func (c *Client) SyncList(ctx context.Context, d Derived, sub string) (SyncListing, error)

SyncList is every segment of the account and whether a sealed token is kept.

func (*Client) SyncPut

func (c *Client) SyncPut(ctx context.Context, d Derived, sub, device string, from, through int64, file []byte) error

SyncPut uploads 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 NewKey

func NewKey() (Key, error)

NewKey makes a recovery key from the system's random source.

func ParseKey

func ParseKey(s string) (Key, error)

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.

func (Key) Derive

func (k Key) Derive() Derived

Derive turns a recovery key into its account, its auth token and its encryption key.

func (Key) String

func (k Key) String() string

String is the key as the user saves it: 56 characters in groups of four, the last group the checksum. "CB" or any other prefix is not part of it.

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
	ShareOn func() bool
	Name    func() string
	Changed func()
	// contains filtered or unexported fields
}

Service runs the backup.

func (*Service) BackupNow

func (s *Service) BackupNow(ctx context.Context) (Status, error)

BackupNow makes a backup at once, changed or not, gap or not.

func (*Service) Cloud

func (s *Service) Cloud(ctx context.Context) CloudView

Cloud is the subscription as last heard, without asking the site.

func (*Service) Confirm

func (s *Service) Confirm(ctx context.Context) error

Confirm is the user's "I saved it": the backup is on, and the first one is made now.

func (*Service) DeleteCloud

func (s *Service) DeleteCloud(ctx context.Context) error

DeleteCloud removes every backup of this computer's key from the server, then forgets the key here and turns the backup off.

func (*Service) Kick

func (s *Service) Kick()

Kick asks the loop to look now.

func (*Service) List

func (s *Service) List(ctx context.Context, typed string) (Listing, error)

List is the backups the key opens, newest first.

func (*Service) Refresh

func (s *Service) Refresh(ctx context.Context) (CloudView, error)

Refresh asks the site about this computer's subscription now.

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

func (s *Service) RevealKey(ctx context.Context) (string, error)

RevealKey is the recovery key kept here, for the owner who lost the copy they saved.

func (*Service) Run

func (s *Service) Run(ctx context.Context)

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) Status

func (s *Service) Status(ctx context.Context) Status

Status is the switch, the key's place and the last backup.

func (*Service) Subscribe

func (s *Service) Subscribe(ctx context.Context, period string) (string, error)

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

func (s *Service) TurnOff() error

TurnOff stops backing up. The key and the backups already made stay, so turning it on again carries on with the same key.

func (*Service) TurnOn

func (s *Service) TurnOn(ctx context.Context) (string, error)

TurnOn starts the backup. With no key on this computer it makes one, keeps it in the secret store and returns it to be shown once; nothing is uploaded until Confirm says the user saved it. With a key already here it switches on again with that key and returns "".

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL