server

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 42 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 server is the Nota sync server behind `nota serve`: a multi-user store of vaults with a version log (SQLite), content addressed blobs, device-token auth and the HTTP API of the sync protocol (internal/protocol, docs/sync-protocol.md).

The server keeps no state outside its data directory, so it runs the same on a laptop and in a container. The HTTP layer is a plain http.ServeMux: later phases mount their routes (/auth, /api, /mcp) on it with Handle.

Index

Constants

View Source
const (
	// ConnectCodeTTL is how long a desktop one-time code is valid.
	ConnectCodeTTL = 2 * time.Minute
	// DeviceCodeTTL is how long a CLI device code waits for approval.
	DeviceCodeTTL = 10 * time.Minute
	// DefaultPollInterval is the device-code poll interval.
	DefaultPollInterval = 5 * time.Second
)

Lifetimes of sign-in requests.

View Source
const (
	CodeRateLimited   = "rate_limited"
	CodeCSRF          = "csrf"
	CodeForbidden     = "forbidden"
	CodeSignupClosed  = "signup_closed"
	CodeInviteNeeded  = "invite_required"
	CodeBadInvite     = "invalid_invite"
	CodeWebAuthn      = "webauthn_failed"
	CodeNeedsPasskey  = "passkey_required"
	CodeExpired       = "expired"
	CodeLastPasskey   = "last_passkey"
	CodeBadCredential = "invalid_credentials"
)

Error codes of the account and web routes, next to the protocol's.

View Source
const DBFile = "nota.db"

DBFile is the database file name inside the data directory.

View Source
const DefaultBlobGrace = time.Hour

DefaultBlobGrace is how long an unreferenced blob file is left alone so an upload in flight is never swept.

View Source
const DefaultInviteTTL = 7 * 24 * time.Hour

DefaultInviteTTL is how long an invite stays valid.

View Source
const DefaultMaxFileSize = 100 << 20

DefaultMaxFileSize is the default size limit of one file (100 MB).

View Source
const DefaultRedirectURI = "nota://auth"

DefaultRedirectURI is the desktop app's deep link.

View Source
const DefaultSessionTTL = 30 * 24 * time.Hour

DefaultSessionTTL is how long a session lives without being used.

View Source
const DeviceServerHook = "server-hook"

DeviceServerHook is the device of versions written by server hooks.

View Source
const DeviceWeb = "web"

DeviceWeb is the device name of changes made through the web app.

View Source
const HeaderClient = "Nota-Client"

HeaderClient must be sent by the web app on every state-changing request that is authenticated by the session cookie (and on the sign-in calls). A custom header cannot be set cross-site without a CORS preflight, which only the configured web origins pass.

View Source
const HeaderVault = "Nota-Vault"

HeaderVault picks the vault of an /mcp request.

View Source
const InvitePrefix = "ninv_"

InvitePrefix starts every invite code.

View Source
const MCPPath = "/mcp"

MCPPath is where the HTTP MCP endpoint is mounted.

View Source
const OriginClient = "client"

OriginClient is the event origin of changes materialized from clients. Transform hooks run on them (unlike events.OriginSync on devices), which is how notes captured on a phone get filed by the server.

View Source
const RecoveryCodeCount = 10

RecoveryCodeCount is how many recovery codes an account gets.

View Source
const SessionCookie = "nota_session"

SessionCookie is the name of the web session cookie.

View Source
const SessionPrefix = "nses_"

SessionPrefix starts every session id.

View Source
const TokenPrefix = "nota_"

TokenPrefix starts every device token, so they are easy to spot in config files and secret scanners.

Variables

View Source
var (
	ErrExists   = errors.New("already exists")
	ErrNotFound = errors.New("not found")
)

Errors returned by Store methods.

View Source
var (
	// ErrExpired is returned for an invite, code or ceremony past its
	// expiry, or one that was already used.
	ErrExpired = errors.New("expired or already used")
)

Account errors.

View Source
var ErrTooLarge = errors.New("content too large")

ErrTooLarge is returned by BlobStore.Put for content above the limit.

Functions

func BlobPath

func BlobPath(dir, hash string) string

BlobPath is where DiskBlobs keeps a blob: <dir>/ab/abcdef…

func NormalizeEmail

func NormalizeEmail(email string) (string, error)

NormalizeEmail trims and lower-cases an email address and checks that it looks like one.

func ParseProxies

func ParseProxies(s string) ([]netip.Prefix, error)

ParseProxies reads a comma-separated list of trusted proxy addresses and CIDR prefixes. "private" stands for loopback plus the private ranges (10/8, 172.16/12, 192.168/16, fc00::/7), which covers a reverse proxy on the same Docker network such as Coolify's Traefik.

func RebuildWorkspaces

func RebuildWorkspaces(dataDir string) error

RebuildWorkspaces deletes every working copy (and index) of the data directory; they are rebuilt from the log on first use. Run it while the server is stopped.

func RemoveUserData

func RemoveUserData(ctx context.Context, st *Store, dataDir string, rm UserRemoval) (files int, bytes int64, err error)

RemoveUserData removes what DeleteUser left on disk: the working copy and index of each of the user's vaults, and the blob files no one references any more. It returns how many blob files went and their bytes.

Types

type AuthConfig

type AuthConfig struct {
	Signup   SignupMode `json:"signup"`
	RPID     string     `json:"rp_id"`
	Passkeys bool       `json:"passkeys"`
}

AuthConfig is the body of GET /v1/auth/config, for the web app.

type BeginRequest

type BeginRequest struct {
	Email  string `json:"email"`
	Invite string `json:"invite,omitempty"`
}

BeginRequest starts a registration or login ceremony.

type BeginResponse

type BeginResponse struct {
	Ceremony string `json:"ceremony"`
	Options  any    `json:"options"`
}

BeginResponse carries the WebAuthn options for the browser (navigator.credentials.create/get) and the ceremony id to send back.

type BlobGC

type BlobGC struct {
	// DryRun reports what would go without removing anything.
	DryRun bool
	// MinAge protects unreferenced files younger than this
	// (DefaultBlobGrace when 0).
	MinAge time.Duration
	// Now is the clock (the store's clock when zero).
	Now time.Time
}

BlobGC configures one garbage collection pass.

type BlobStore

type BlobStore interface {
	// Put reads r to the end, stores the bytes under their hash and
	// returns it with the size. It fails with ErrTooLarge when r has more
	// than limit bytes (no limit when limit <= 0); nothing is stored then.
	Put(ctx context.Context, r io.Reader, limit int64) (hash string, size int64, err error)
	// Open returns the content stored under hash, or an error wrapping
	// fs.ErrNotExist.
	Open(ctx context.Context, hash string) (io.ReadCloser, error)
}

BlobStore keeps file contents by their hash (protocol.Hash). Writing the same content twice stores it once. Implementations must be safe for concurrent use. The local disk store is DiskBlobs; an S3 store can implement the same interface later.

type Config

type Config struct {
	// DataDir holds the database (nota.db) and the blob store (blobs/).
	DataDir string
	// MaxFileSize caps the size of one file; DefaultMaxFileSize if 0.
	MaxFileSize int64
	// Logger receives one wide event per request; slog.Default if nil.
	Logger *slog.Logger
	// Blobs overrides the blob store (default: DiskBlobs in DataDir/blobs).
	Blobs BlobStore
	// KeepAlive is the SSE keepalive interval; 25 s if 0.
	KeepAlive time.Duration

	// PublicURL is where the API is reached from outside, e.g.
	// https://nota.app.banjoanton.com.
	PublicURL string
	// WebURL is the web app's base URL (e.g. https://nota.banjoanton.com):
	// sign-in links point at WebURL/app/connect. The first WebOrigins
	// entry when empty.
	WebURL string
	// WebOrigins are the browser origins of the web app: CORS with
	// credentials is allowed for them and passkeys are accepted from them.
	WebOrigins []string
	// RPID is the WebAuthn relying party id (the web app's domain, e.g.
	// nota.banjoanton.com). Passkeys are off when empty.
	RPID string
	// CookieDomain is the session cookie's Domain (e.g. banjoanton.com,
	// so the cookie set by the API also covers the web app's site). Host
	// only when empty.
	CookieDomain string
	// CookieInsecure drops the Secure flag of the session cookie, for
	// local development over plain http only.
	CookieInsecure bool
	// Signup is who may create an account (default SignupInvite).
	Signup SignupMode
	// SessionTTL is how long an unused browser session lives
	// (DefaultSessionTTL if 0); each use extends it.
	SessionTTL time.Duration
	// TrustedProxies are the reverse proxies whose X-Forwarded-For is
	// believed (see ParseProxies).
	TrustedProxies []netip.Prefix
	// AuthRateLimit is how many sign-in attempts one IP may make per
	// minute (default 30, burst 20); negative turns the limit off.
	AuthRateLimit int
	// PollInterval is the minimum interval between device-code polls
	// (DefaultPollInterval if 0).
	PollInterval time.Duration
	// Hooks runs the hooks in each vault's .nota/hooks.toml on changes
	// that arrive from clients (NOTA_SERVER_HOOKS=on). Off by default:
	// hooks are shell commands from the synced vault, run by the server
	// process with its permissions.
	Hooks bool
	// Version is the server's build version (shown to MCP clients).
	Version string
	// Now is the clock (time.Now if nil); tests move it.
	Now func() time.Time
}

Config configures a Server.

type CreateRequest

type CreateRequest struct {
	Title string `json:"title,omitempty"`
	Body  string `json:"body,omitempty"`
	// Folder defaults to the inbox; "/" is the vault root.
	Folder     string         `json:"folder,omitempty"`
	Tags       []string       `json:"tags,omitempty"`
	Properties map[string]any `json:"properties,omitempty"`
}

CreateRequest is the body of POST …/notes.

type DeviceAuth

type DeviceAuth struct {
	ID        int64     `json:"id"`
	Device    string    `json:"device"`
	CreatedAt time.Time `json:"created_at"`
	ExpiresAt time.Time `json:"expires_at"`
}

DeviceAuth is a pending CLI sign-in, as the approval page shows it.

type DiskBlobs

type DiskBlobs struct {
	// contains filtered or unexported fields
}

DiskBlobs is a content-addressed BlobStore in a local directory: <dir>/ab/abcdef…, written to a temp file and renamed into place, so a blob is either complete or absent.

func NewDiskBlobs

func NewDiskBlobs(dir string) (*DiskBlobs, error)

NewDiskBlobs returns a blob store in dir, creating it if needed.

func (*DiskBlobs) Open

func (d *DiskBlobs) Open(_ context.Context, hash string) (io.ReadCloser, error)

Open implements BlobStore.

func (*DiskBlobs) Put

func (d *DiskBlobs) Put(_ context.Context, r io.Reader, limit int64) (string, int64, error)

Put implements BlobStore.

type FinishRequest

type FinishRequest struct {
	Ceremony   string          `json:"ceremony"`
	Credential json.RawMessage `json:"credential"`
	// Name labels a new passkey ("MacBook", "iPhone").
	Name string `json:"name,omitempty"`
}

FinishRequest completes a ceremony with the browser's credential (PublicKeyCredential.toJSON()).

type GCResult

type GCResult struct {
	DryRun bool `json:"dry_run"`
	// Rows is the number of blobs-table rows removed (or to remove).
	Rows int `json:"rows"`
	// Files is the number of blob files removed (or to remove).
	Files int `json:"files"`
	// Bytes is the size of those files.
	Bytes int64 `json:"bytes"`
	// Orphans is how many of the files had no row at all (a failed
	// upload or a leftover of a deleted vault); the rest lost their last
	// row in this pass.
	Orphans int `json:"orphans"`
	// Young is unreferenced files kept because they are younger than
	// MinAge.
	Young int `json:"young"`
}

GCResult is what one pass found and did.

type HistoryEntry

type HistoryEntry struct {
	protocol.Entry
	Content *string `json:"content,omitempty"`
}

HistoryEntry is one version in a note's history; with ?version=N the response is that version with its content.

type Invite

type Invite struct {
	ID        int64      `json:"id"`
	Email     string     `json:"email,omitempty"`
	Note      string     `json:"note,omitempty"`
	CreatedAt time.Time  `json:"created_at"`
	ExpiresAt time.Time  `json:"expires_at"`
	UsedAt    *time.Time `json:"used_at,omitempty"`
}

Invite is an invite's metadata; the code is only known on creation.

type LoginResponse

type LoginResponse struct {
	User UserInfo `json:"user"`
	// NeedsPasskey is set after a recovery-code sign-in: add a passkey
	// (POST /v1/auth/passkeys/begin) before anything else.
	NeedsPasskey bool `json:"needs_passkey,omitempty"`
	// RecoveryCodesLeft counts the unused recovery codes.
	RecoveryCodesLeft int `json:"recovery_codes_left"`
}

LoginResponse is the result of a sign-in.

type MeResponse

type MeResponse struct {
	User              UserInfo `json:"user"`
	Via               string   `json:"via"`
	Device            string   `json:"device,omitempty"`
	NeedsPasskey      bool     `json:"needs_passkey"`
	Passkeys          int      `json:"passkeys"`
	RecoveryCodesLeft int      `json:"recovery_codes_left"`
}

MeResponse is the body of GET /v1/auth/me.

type MoveRequest

type MoveRequest struct {
	Path        string `json:"path"`
	Folder      string `json:"folder,omitempty"`
	To          string `json:"to,omitempty"`
	BaseVersion *int64 `json:"base_version,omitempty"`
}

MoveRequest is the body of POST …/move: move a note into Folder (keeping its name) or rename it to To.

type MoveResponse

type MoveResponse struct {
	From    string `json:"from"`
	Path    string `json:"path"`
	Version int64  `json:"version"`
}

MoveResponse is where the note went.

type Note

type Note struct {
	NoteInfo
	// Version is the note's version in the log: send it as Base-Version
	// when saving.
	Version int64 `json:"version"`
	// Hash is the content hash (protocol.Hash).
	Hash string `json:"hash"`
	// Body is the markdown after the frontmatter; Content the whole file.
	Body      string       `json:"body"`
	Content   string       `json:"content"`
	Backlinks []index.Link `json:"backlinks"`
	Links     []index.Link `json:"links"`
}

Note is one note with its content, version and links.

type NoteInfo

type NoteInfo struct {
	Path       string         `json:"path"`
	Folder     string         `json:"folder"`
	Title      string         `json:"title"`
	Tags       []string       `json:"tags"`
	Properties map[string]any `json:"properties"`
	Created    *time.Time     `json:"created,omitempty"`
	Updated    *time.Time     `json:"updated,omitempty"`
	Modified   time.Time      `json:"modified"`
	Size       int64          `json:"size"`
	Snippet    string         `json:"snippet,omitempty"`
}

NoteInfo is a note in lists: its metadata without the content.

type NotesList

type NotesList struct {
	Notes []NoteInfo `json:"notes"`
	Count int        `json:"count"`
}

NotesList is the body of list, search and inbox.

type Passkey

type Passkey struct {
	ID         int64      `json:"id"`
	Name       string     `json:"name"`
	CreatedAt  time.Time  `json:"created_at"`
	LastUsedAt *time.Time `json:"last_used_at"`
}

Passkey describes a registered WebAuthn credential.

type PatchRequest

type PatchRequest struct {
	Set   map[string]any `json:"set,omitempty"`
	Unset []string       `json:"unset,omitempty"`
	Tags  struct {
		Add    []string `json:"add,omitempty"`
		Remove []string `json:"remove,omitempty"`
	} `json:"tags,omitzero"`
}

PatchRequest is the body of PATCH …/notes/{path}: frontmatter edits. Only the touched keys' lines change.

type Principal

type Principal struct {
	UserID  int64
	Email   string
	TokenID int64
	Device  string
	// Via is "token" or "session".
	Via string
	// SessionID is set for sessions.
	SessionID int64
	// NeedsPasskey marks a session signed in with a recovery code: it
	// may only add a passkey (and sign out) until it has done so.
	NeedsPasskey bool
}

Principal is who a request is authenticated as: a device token (Via "token") or a browser session (Via "session").

type RecoveryRequest

type RecoveryRequest struct {
	Email string `json:"email"`
	Code  string `json:"code"`
}

RecoveryRequest signs in with a recovery code.

type RegisterResponse

type RegisterResponse struct {
	User          UserInfo `json:"user"`
	RecoveryCodes []string `json:"recovery_codes"`
}

RegisterResponse is the result of a sign-up: the account and its recovery codes, shown this one time only.

type RemovedVault

type RemovedVault struct {
	ID     int64  `json:"id"`
	Name   string `json:"name"`
	Cursor int64  `json:"cursor"`
}

RemovedVault is a vault that goes with a user.

type RestoreRequest

type RestoreRequest struct {
	Version int64 `json:"version"`
}

RestoreRequest is the body of POST …/history/{path}/restore.

type SaveRequest

type SaveRequest struct {
	Content *string `json:"content,omitempty"`
	Body    *string `json:"body,omitempty"`
}

SaveRequest is the body of PUT …/notes/{path}: the whole file, or only the body (the frontmatter is kept).

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server is the sync server. Create it with New and serve Handler.

func New

func New(ctx context.Context, cfg Config) (*Server, error)

New opens the data directory and returns a server ready to serve.

func (*Server) Close

func (s *Server) Close() error

Close closes the database. Call it after the HTTP server has shut down.

func (*Server) Handle

func (s *Server) Handle(pattern string, h http.Handler)

Handle registers a handler on the server's mux, for routes added by other packages (web API, auth, HTTP MCP). It gets the request logging but no authentication: wrap it with RequireToken when needed.

func (*Server) Handler

func (s *Server) Handler() http.Handler

Handler returns the HTTP handler of the whole server.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe(ctx context.Context, addr string, grace time.Duration, ready func(net.Addr)) error

ListenAndServe serves on addr until ctx is done, then shuts down gracefully: new connections are refused, running requests get up to grace to finish and SSE streams are closed. ready, when not nil, is called with the bound address (useful with port 0).

func (*Server) RequireToken

func (s *Server) RequireToken(h func(http.ResponseWriter, *http.Request, Principal)) http.Handler

RequireToken wraps h so that it only runs for requests with a valid device token, for routes mounted with Handle.

func (*Server) Store

func (s *Server) Store() *Store

Store returns the server's database.

type Session

type Session struct {
	ID           int64
	UserID       int64
	Email        string
	NeedsPasskey bool
	CreatedAt    time.Time
	LastSeenAt   time.Time
	ExpiresAt    time.Time
}

Session is a signed-in browser.

type SignupMode

type SignupMode string

SignupMode says who may create an account.

const (
	SignupInvite SignupMode = "invite"
	SignupOpen   SignupMode = "open"
	SignupClosed SignupMode = "closed"
)

Sign-up modes. Invite is the default: only people with an invite code (nota serve invite create) can sign up.

func ParseSignupMode

func ParseSignupMode(s string) (SignupMode, error)

ParseSignupMode reads a sign-up mode; "" is SignupInvite.

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store is the server's SQLite database: users, device tokens, vaults and the version log. Every query that touches user data is scoped by a user id (vaults) or by a vault id that was looked up by user id.

func OpenData

func OpenData(ctx context.Context, dir string) (*Store, error)

OpenData opens the store in a data directory, creating it if needed. The admin commands use it directly, next to a running server.

func OpenStore

func OpenStore(ctx context.Context, path string) (*Store, error)

OpenStore opens (creating if needed) the database at path and runs the embedded goose migrations.

func (*Store) AddPasskey

func (s *Store) AddPasskey(ctx context.Context, userID int64, c *webauthn.Credential, name string) error

AddPasskey stores a new credential for a user.

func (*Store) AddUser

func (s *Store) AddUser(ctx context.Context, email string) (User, error)

AddUser creates a user. It fails with ErrExists for a known email.

func (*Store) Authenticate

func (s *Store) Authenticate(ctx context.Context, secret string) (Principal, error)

Authenticate looks up a device token. Unknown and revoked tokens fail with ErrNotFound.

func (*Store) Close

func (s *Store) Close() error

Close closes the database.

func (*Store) CollectBlobs

func (s *Store) CollectBlobs(ctx context.Context, blobDir string, opt BlobGC) (GCResult, error)

CollectBlobs runs one garbage collection pass over the database and the blob directory (normally <data>/blobs). Call it only from one place at a time; CollectBlobs itself is safe next to the server's writes.

func (*Store) CreateInvite

func (s *Store) CreateInvite(ctx context.Context, email, note string, ttl time.Duration) (string, Invite, error)

CreateInvite makes an invite code. With email set only that address can sign up with it; for a user that already exists without a passkey (created by `nota serve user add`) it is how they register their first passkey.

func (*Store) CreateSession

func (s *Store) CreateSession(ctx context.Context, userID int64, ttl time.Duration, needsPasskey bool, userAgent string) (string, Session, error)

CreateSession starts a session for a user and returns its secret id (the cookie value) with the session.

func (*Store) CreateToken

func (s *Store) CreateToken(ctx context.Context, userID int64, device string) (string, Token, error)

CreateToken makes a new device token for a user and returns the secret, which is not stored and cannot be shown again.

func (*Store) CreateVault

func (s *Store) CreateVault(ctx context.Context, userID int64, name string) (protocol.VaultInfo, error)

CreateVault creates a vault for a user. It fails with ErrExists when the user already has one with that name.

func (*Store) DecideDeviceAuth

func (s *Store) DecideDeviceAuth(ctx context.Context, id, userID int64, approve bool) error

DecideDeviceAuth approves (or denies) a pending CLI sign-in for a user, by request id.

func (*Store) Delete

func (s *Store) Delete(ctx context.Context, userID int64, vaultName, p string, base int64, device string) (protocol.Entry, error)

Delete writes a tombstone for a path based on version base.

func (*Store) DeletePasskey

func (s *Store) DeletePasskey(ctx context.Context, userID, id int64) error

DeletePasskey removes one of a user's passkeys. The last one cannot be removed: the account would only be reachable through recovery codes.

func (*Store) DeleteSession

func (s *Store) DeleteSession(ctx context.Context, id int64) error

DeleteSession ends a session.

func (*Store) DeleteUser

func (s *Store) DeleteUser(ctx context.Context, email string) (UserRemoval, error)

DeleteUser deletes a user and everything owned by it in one write transaction: the tables cascade from users (tokens, vaults with their files and versions, blobs, credentials, sessions, recovery codes, ceremonies, auth requests), and invites bound to the address go first. The disk is left alone: the caller removes the working copies and the unreferenced blob files with RemoveUserData, so the database stays the truth if that fails.

func (*Store) DeleteVault

func (s *Store) DeleteVault(ctx context.Context, userID int64, name string) error

DeleteVault deletes a user's vault with its whole history. The blobs stay in the blob store. Admin only (nota serve vault rm).

func (*Store) Invites

func (s *Store) Invites(ctx context.Context) ([]Invite, error)

Invites lists every invite, newest first.

func (*Store) Move

func (s *Store) Move(ctx context.Context, userID int64, vaultName string, m protocol.Move, device string) (protocol.MoveResult, error)

Move renames a file atomically: a tombstone for from and a create of to that continues its history.

func (*Store) Passkeys

func (s *Store) Passkeys(ctx context.Context, userID int64) ([]Passkey, error)

Passkeys lists a user's passkeys.

func (*Store) PendingDeviceAuths

func (s *Store) PendingDeviceAuths(ctx context.Context) ([]DeviceAuth, error)

PendingDeviceAuths lists the unexpired pending CLI sign-ins, newest first (for `nota serve auth approve`).

func (*Store) PlanUserRemoval

func (s *Store) PlanUserRemoval(ctx context.Context, email string) (UserRemoval, error)

PlanUserRemoval reports what deleting a user would remove, including the blob files only this user references. It changes nothing.

func (*Store) Put

func (s *Store) Put(ctx context.Context, userID int64, vaultName string, base int64, w write) (protocol.Entry, error)

Put commits new content for a path (see the PUT endpoint). The blob must already be in the blob store.

func (*Store) RecoveryCodesLeft

func (s *Store) RecoveryCodesLeft(ctx context.Context, userID int64) (int, error)

RecoveryCodesLeft counts a user's unused recovery codes.

func (*Store) RegenerateRecoveryCodes

func (s *Store) RegenerateRecoveryCodes(ctx context.Context, userID int64) ([]string, error)

RegenerateRecoveryCodes invalidates a user's recovery codes and returns a new set.

func (*Store) RevokeInvite

func (s *Store) RevokeInvite(ctx context.Context, id int64) error

RevokeInvite deletes an unused invite.

func (*Store) RevokeToken

func (s *Store) RevokeToken(ctx context.Context, id int64) error

RevokeToken revokes a token by id. Revoking twice is not an error.

func (*Store) RevokeUserToken

func (s *Store) RevokeUserToken(ctx context.Context, userID, id int64) error

RevokeUserToken revokes one of a user's own tokens. Another user's token is ErrNotFound, like a missing one.

func (*Store) Session

func (s *Store) Session(ctx context.Context, secret string, ttl time.Duration) (ss Session, touched bool, err error)

Session looks up a session by its secret id. Expired sessions are deleted and fail with ErrNotFound. A live session's expiry rolls forward by ttl (at most every few minutes); touched reports that, so the caller can refresh the cookie.

func (*Store) Tokens

func (s *Store) Tokens(ctx context.Context, userID int64) ([]Token, error)

Tokens lists the tokens of one user, or of everyone when userID is 0.

func (*Store) UseRecoveryCode

func (s *Store) UseRecoveryCode(ctx context.Context, email, code string) (User, error)

UseRecoveryCode spends one recovery code of the user with that email. Unknown emails, unknown codes and used codes all fail with ErrNotFound, so the answer does not tell which one it was.

func (*Store) UserByEmail

func (s *Store) UserByEmail(ctx context.Context, email string) (User, error)

UserByEmail finds a user.

func (*Store) UserByID

func (s *Store) UserByID(ctx context.Context, id int64) (User, error)

UserByID finds a user by id.

func (*Store) Users

func (s *Store) Users(ctx context.Context) ([]User, error)

Users lists every user by email.

func (*Store) VaultID

func (s *Store) VaultID(ctx context.Context, userID int64, name string) (int64, error)

VaultID returns the id of a user's vault (its working copy is <data>/vaults/<id>).

func (*Store) Vaults

func (s *Store) Vaults(ctx context.Context, userID int64) ([]protocol.VaultInfo, error)

Vaults lists a user's vaults by name.

type Token

type Token struct {
	ID         int64      `json:"id"`
	UserID     int64      `json:"user_id"`
	Email      string     `json:"email"`
	Device     string     `json:"device"`
	CreatedAt  time.Time  `json:"created_at"`
	LastUsedAt *time.Time `json:"last_used_at"`
	RevokedAt  *time.Time `json:"revoked_at"`
}

Token is a device token's metadata. The secret itself is only known when it is created; the database keeps its SHA-256.

type Tree

type Tree struct {
	Inbox   string       `json:"inbox"`
	Folders []TreeFolder `json:"folders"`
	Notes   []NoteInfo   `json:"notes"`
	// Cursor is the vault's latest version when the tree was read.
	Cursor int64 `json:"cursor"`
}

Tree is the body of GET …/tree: every folder and every note.

type TreeFolder

type TreeFolder struct {
	Path  string `json:"path"`
	Name  string `json:"name"`
	Notes int    `json:"notes"`
}

TreeFolder is a folder of the tree with its note count (subfolders included).

type User

type User struct {
	ID        int64     `json:"id"`
	Email     string    `json:"email"`
	CreatedAt time.Time `json:"created_at"`
}

User is an account.

type UserCodeRequest

type UserCodeRequest struct {
	UserCode string `json:"user_code"`
	// Approve is false to deny; true when missing.
	Approve *bool `json:"approve,omitempty"`
}

UserCodeRequest names a CLI sign-in by its user code.

type UserInfo

type UserInfo struct {
	ID        int64     `json:"id"`
	Email     string    `json:"email"`
	CreatedAt time.Time `json:"created_at"`
}

UserInfo is the account as the API shows it.

type UserRemoval

type UserRemoval struct {
	User           User           `json:"user"`
	Vaults         []RemovedVault `json:"vaults"`
	Tokens         int            `json:"tokens"`
	Passkeys       int            `json:"passkeys"`
	Sessions       int            `json:"sessions"`
	RecoveryCodes  int            `json:"recovery_codes"`
	Invites        int            `json:"invites"`
	Blobs          int            `json:"blobs"`
	BlobBytes      int64          `json:"blob_bytes"`
	BlobsReclaimed int            `json:"blobs_reclaimed"`
	BytesReclaimed int64          `json:"bytes_reclaimed"`
	// contains filtered or unexported fields
}

UserRemoval is what deleting a user removes, or would remove.

type ViewInfo

type ViewInfo struct {
	views.View
	Count int `json:"count"`
}

ViewInfo is a saved view with its note count.

Jump to

Keyboard shortcuts

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