store

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2026 License: AGPL-3.0 Imports: 25 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

Index

Constants

View Source
const (
	ReasonCapacity        = "capacity"
	ReasonListenError     = "listen_error"
	ReasonCredentials     = "credentials"
	ReasonRevokedByPhone  = "revoked_by_phone"
	ReasonCookiesExpired  = "cookies_expired"
	ReasonAccountSwitched = "account_switched"
	ReasonCrashRecovered  = "crash_recovered"
)

State reasons, so degraded and error are diagnosable without reading logs.

View Source
const (
	DownloadStateAvailable   = "available"
	DownloadStatePending     = "pending"
	DownloadStateFailed      = "failed"
	DownloadStateUnavailable = "unavailable"
)

Download states for attachments.

View Source
const (
	AuditOK      = "ok"
	AuditRefused = "refused"
	AuditFailed  = "failed"
)

AuditResult is the outcome vocabulary.

View Source
const (
	// AuthKindAdminBootstrap is a session minted by presenting
	// AGENT_GM_ADMIN_SECRET at POST /v1/auth/admin-session (spec section 9.7).
	AuthKindAdminBootstrap = "admin_bootstrap"
	// AuthKindOAuth is the Slice 3 grant.
	AuthKindOAuth = "oauth"
)

Authorization kinds. Slice 2 mints exactly one; Slice 3 adds a second token SOURCE under the same shape, not a second security model.

View Source
const (
	TokenKindAccess  = "access"
	TokenKindRefresh = "refresh"
)

Token kinds.

View Source
const (
	AttemptKindAdminSecret = "admin_secret"
	AttemptKindRefresh     = "refresh_token"
)

Attempt kinds, the `kind` half of oauth_attempts' primary key.

View Source
const (
	InfoSession       = "agent-gm/session/v1"
	InfoAttachmentKey = "agent-gm/attachment-key/v1"
	InfoTicket        = "agent-gm/ticket/v1"
	InfoCursor        = "agent-gm/cursor/v1"
)

Info strings for the four purposes the key is derived for. They are distinct so that a session envelope key can never be used to sign a ticket.

View Source
const (
	PrefixAccount       = "acct_"
	PrefixConversation  = "conv_"
	PrefixMessage       = "msg_"
	PrefixAttachment    = "att_"
	PrefixReaction      = "react_"
	PrefixContact       = "contact_"
	PrefixParticipant   = "part_"
	PrefixOperation     = "op_"
	PrefixUpload        = "upl_"
	PrefixAuthorization = "auth_"
	// PrefixClient is a dynamically registered OAuth client (spec section
	// 9.3). Every client this server will ever see registers itself, so
	// there is no other way a client_ ID comes into existence.
	PrefixClient = "client_"
	// PrefixEnrollment is an enrollment code's ROW, never its value: the
	// value is returned once and only its SHA-256 is stored (section 9.5).
	PrefixEnrollment = "enroll_"
	// PrefixAuthorizationRequest is one pending authorization (section 9.5).
	// The ID alone conveys no authority -- without the context cookie every
	// /oauth/requests route answers 404.
	PrefixAuthorizationRequest = "authreq_"
)

Public IDs are opaque, URL-safe, stable strings with a typed prefix. A caller never sees a raw Google conversation ID, message ID or participant ID on a public surface.

View Source
const (
	UploadReserved = "reserved"
	UploadComplete = "complete"
	UploadConsumed = "consumed"
	UploadExpired  = "expired"
)

Upload reservation states (spec section 10.2).

View Source
const (
	AuthRequestPending   = "pending"
	AuthRequestApproved  = "approved"
	AuthRequestDenied    = "denied"
	AuthRequestCompleted = "completed"
)

Authorization request statuses. A request moves pending -> approved | denied, and an approved one moves to completed when the browser redeems it. A completed request can never mint a second code (spec section 9.5).

View Source
const (
	// AttemptKindEnrollmentSource counts failed enrollment-code submissions
	// per client source. Section 9.4 checks it BEFORE the submission is
	// examined, so loading a fresh authorization page does not reset it.
	AttemptKindEnrollmentSource = "enrollment_code_source"
	// AttemptKindEnrollmentContext counts them per signed context, which is
	// the other half of the same rule.
	AttemptKindEnrollmentContext = "enrollment_code_context"
	// AttemptKindOAuthToken counts unknown or invalid presented values at
	// /oauth/token's refresh grant and at /oauth/revoke (section 9.8).
	AttemptKindOAuthToken = "oauth_token"
)

Attempt kinds this slice adds, the `kind` half of `oauth_attempts`' primary key (spec sections 9.4, 9.8).

View Source
const (
	EndpointConversations = "conversations.list"
	EndpointMessages      = "messages.list"
	EndpointSearch        = "search.messages"
	EndpointContacts      = "contacts.list"
	EndpointOperations    = "operations.list"
	EndpointAudit         = "audit.list"
)

Endpoint names, which a cursor is bound to along with the filter set.

View Source
const (
	DefaultLimit = 50
	MaxLimit     = 100
)

DefaultLimit and MaxLimit are section 7.4's page bounds.

View Source
const (
	SearchModeWords = "words"
	SearchModeExact = "exact"
)

Search modes. There is no mode named after a SQLite extension and no way to reach FTS5 operator syntax from the caller's `q` (spec section 7.6).

View Source
const (
	DirMode  os.FileMode = 0o700
	FileMode os.FileMode = 0o600
)

DirMode and FileMode are the at-rest permissions for everything under the data directory.

They are not a hardening extra. Message text, subjects and conversation names are stored in plain SQLite (spec section 4.5 encrypts the session envelope and the attachment keys, and says so precisely because the rest is not encrypted), so on a shared host the file mode IS the at-rest model for every message the owner has ever sent or received. A database left 0644 is readable by every account on the machine.

View Source
const AttemptGlobalSource = "*global*"

AttemptGlobalSource is the reserved `source` value for the server-wide half of a per-source limiter. It is not a valid client source: a resolved source is an IP address and is never the empty string nor this sentinel (spec section 12.3).

View Source
const BackupDirName = "backups"

BackupDirName is the directory under the data directory that snapshots go in. The caller does not choose the path (spec section 15.2).

View Source
const EffectSentence = "permanently deletes Agent GM's copy of this account's conversations, " +
	"messages, attachments and operations; your Google Messages account and the " +
	"messages in it are untouched"

EffectSentence is the exact wording spec section 4.7 requires the CLI and the API to print before a removal. It is defined once so the CLI can print the route's own string byte for byte (spec section 16 test 28).

View Source
const ErrCrashRecovered = "crash_recovered"

ErrCrashRecovered is the error_code written by the startup sweep.

View Source
const ErrPendingTimeout = "pending_timeout"

ErrPendingTimeout is the error_code written by the pending_timeout reaper.

View Source
const MediaCacheDirName = "media-cache"

MediaCacheDirName is the cached-media directory under the data directory.

Variables

View Source
var (
	ErrTicketNotFound = errors.New("download ticket not found")
	ErrTicketSpent    = errors.New("download ticket is spent or expired")
)

ErrTicketNotFound and ErrTicketSpent are the two refusals. The caller turns both into the same message: every refusal reads alike, whatever the reason, so a status code teaches an attacker nothing (spec section 10.3).

View Source
var (
	// ErrClientNotFound is an unknown client_id. At /oauth/authorize it is a
	// 4xx that never redirects (RFC 6749 section 4.1.2.1).
	ErrClientNotFound = errors.New("oauth client not found")
	// ErrEnrollmentCodeNotFound is an unknown code. Section 9.4 requires
	// unknown, expired, revoked and consumed to be indistinguishable to the
	// browser, so this value never reaches a rendered page.
	ErrEnrollmentCodeNotFound = errors.New("enrollment code not found")
	// ErrAuthorizationRequestNotFound is an unknown authorization request.
	ErrAuthorizationRequestNotFound = errors.New("authorization request not found")
	// ErrAuthorizationCodeNotFound is an unknown authorization code.
	ErrAuthorizationCodeNotFound = errors.New("authorization code not found")
)

Errors this file returns. Each maps to exactly one refusal in `internal/oauth`, so the HTTP layer translates rather than decides.

View Source
var ErrAccountNotFound = errors.New("account not found")

ErrAccountNotFound is returned when no account has that ID.

View Source
var ErrAttachmentKeyUndecryptable = errors.New("attachment key cannot be decrypted")

ErrAttachmentKeyUndecryptable means the data key differs from the one that sealed this column, exactly as for a session envelope.

View Source
var ErrAttachmentNotFound = errors.New("attachment not found")

ErrAttachmentNotFound is returned when no attachment has that ID.

View Source
var ErrAuthorizationNotFound = errors.New("authorization not found")

ErrAuthorizationNotFound is returned when no authorization has that ID.

View Source
var ErrBackfillStateNotFound = errors.New("backfill state not found")

ErrBackfillStateNotFound is returned when a conversation has no row.

View Source
var ErrBackwardTransition = errors.New("delivery_state may not move backwards")

ErrBackwardTransition means a delivery state moved backwards. The stored state is left alone and the event is audited as message.status_out_of_order (spec section 4.4).

View Source
var ErrBadDataKey = errors.New("AGENT_GM_DATA_KEY must be a 256-bit key, as 64 hex characters or standard base64")

ErrBadDataKey is returned when AGENT_GM_DATA_KEY is not a 256-bit value.

View Source
var ErrContactNotFound = errors.New("contact not found")

ErrContactNotFound is returned when no contact has that ID.

View Source
var ErrCursorFilterMismatch = errors.New("cursor was issued for a different query")

ErrCursorFilterMismatch means the cursor verified but was issued for a different endpoint or a different filter set. It is distinguishable from ErrCursorInvalid on purpose: one is tampering, the other is a client that changed its query mid-walk, and the operator wants to tell them apart even though both are invalid_request to the caller.

View Source
var ErrCursorInvalid = errors.New("cursor is not valid")

ErrCursorInvalid means the cursor did not verify: it was truncated, re-encoded, or its signature does not match. The API layer turns it into invalid_request.

View Source
var ErrNoAccountPredicate = errors.New("pass an AccountID or set AllAccounts")

ErrNoAccountPredicate means a query was built with neither an account_id nor the explicit all-accounts intent. The intent has to be stated, so that a query can never lose its account predicate by accident (spec section 13.2).

View Source
var ErrNoSession = errors.New("no session file for this account")

ErrNoSession means this account has no session file on disk.

View Source
var ErrOperationNotFound = errors.New("operation not found")

ErrOperationNotFound is returned when no operation has that ID or key.

View Source
var ErrOperationTransition = errors.New("operation status may not move that way")

ErrOperationTransition means a settle would have moved an operation backwards. The stored status is left alone.

View Source
var ErrSessionUndecryptable = errors.New("session envelope cannot be decrypted")

ErrSessionUndecryptable means the data key differs from the one that sealed the session. There is no in-place rotation; restore the original key.

View Source
var ErrSettingNotFound = errors.New("setting not found")

ErrSettingNotFound is returned when a key has no row.

View Source
var ErrStoreClosed = errors.New("store is closed")

ErrStoreClosed is returned by Write after Close.

View Source
var ErrTokenNotFound = errors.New("token not found")

ErrTokenNotFound is returned when no token has that hash.

View Source
var ErrUploadNotFound = errors.New("upload reservation not found")

ErrUploadNotFound is returned when no reservation has that ID or token.

View Source
var ErrUploadState = errors.New("upload reservation is not in that state")

ErrUploadState means the reservation is not in the state this step needs -- a second PUT against a spent token, or a second send of one upload.

View Source
var IDNamespace = uuid.MustParse("5ec9ab28-5363-57f8-b543-27672479b604")

IDNamespace is the one frozen namespace UUID every derived ID hangs from. It is declared exactly once and never changed (spec section 4.1). Its value is UUIDv5(NameSpaceURL, "https://github.com/thisnick/agent-gm/ids/v1"), recorded here as a literal so that nothing about the derivation can drift.

Functions

func AccountID

func AccountID(address string) string

AccountID is UUIDv5(ns, "account", the lowercased AuthData.Mobile.SourceID).

The address itself is therefore never an ID and never appears in a URL, and re-pairing the same Google account -- even onto a different phone -- reuses the same acct_ ID (D6, D28).

func AttachmentID

func AttachmentID(messageID, partIndex, mediaID string) string

AttachmentID is UUIDv5(message ID, part index, Google media ID).

func AuditID

func AuditID() string

AuditID is a bare UUIDv7 -- audit rows are the one object in spec section 4.1's table with no typed prefix, because an audit ID never appears in a path or as a caller-supplied parameter.

func AuthorizationID

func AuthorizationID() string

AuthorizationID is UUIDv7: Agent GM creates an authorization, so it is not derived from anything (spec section 4.1). The prefix is `auth_`, which is the table's, and NOT `authz_` -- an ID scheme is a public contract and a near-miss in it is the kind of thing that is discovered by a client's regular expression six months later.

func AuthorizationRequestID

func AuthorizationRequestID() string

AuthorizationRequestID mints the ID of one pending authorization request.

func ClientID

func ClientID() string

ClientID mints a fresh dynamically registered client ID (spec section 9.3). A client-chosen client_id is refused at registration, so this is the only place one is created.

func ContactID

func ContactID(accountID, sourceID string) string

ContactID is UUIDv5(ns, account_id, "contact", Google participant ID).

func ContentHash

func ContentHash(m gm.Message) string

ContentHash is computed over the canonical content: the text parts joined with a newline, then each media part's media ID and size, then the reaction set (spec section 5.3 step 4). An upsert whose content and raw status are both unchanged writes nothing at all, so a replay storm does not churn the WAL or bump updated_at_ms.

func ConversationID

func ConversationID(accountID, sourceID string) string

ConversationID is UUIDv5(ns, account_id, "conversation", Google conversation ID). account_id is in the derivation, so conversation IDs are globally unique across accounts and a route never needs both.

func CountsTowardAmbiguity

func CountsTowardAmbiguity(s AccountState) bool

CountsTowardAmbiguity reports whether a state counts toward the section 7.3 ambiguity rule, which counts accounts in a usable or recoverable state. `pairing` accounts do not: an abandoned pair can never start demanding account_id on writes for an account that may never exist.

func DownloadStateFor

func DownloadStateFor(mediaID, thumbnailMediaID string) string

DownloadStateFor decides an attachment's download_state from the attachment's own facts, rather than from a constant a writer chose.

It is a FACT ABOUT REACHABILITY, not about the cache: `available` means Agent GM can produce the bytes on demand -- from `media_cache_entries` if they are there and from `libgm.DownloadMedia` otherwise -- and the cache is its own table for exactly that reason (spec section 4.2).

Writing `pending` unconditionally at ingest, as this used to, made `GET /v1/attachments/{id}/content` unreachable for EVERY real attachment: the route answers `unsupported_capability` / `media_pending` for anything not `available`, `sha256` was therefore always null, and every download ticket minted could never be redeemed. Nothing in production could move an attachment out of `pending`, so the bytes a caller had just uploaded came back as not-yet-downloaded.

The three cases are section 10.1's:

  • a media ID → `available`. Google holds the bytes and the decryption key is on the row.
  • no media ID but a thumbnail → `pending`: `GetFullSizeImage` has to run first, and while that is outstanding the route says `media_pending`, which is what section 10.1 asks for.
  • neither → `unavailable`. There is nothing to fetch and never will be; saying `pending` would promise bytes that are not coming.

func DownloadStateForMessage

func DownloadStateForMessage(mediaID, thumbnailMediaID, deliveryState string) string

DownloadStateForMessage is DownloadStateFor with the owning message's delivery state, which can veto the other two.

Section 4.4 maps `INCOMING_DOWNLOAD_FAILED(106)` and its eight siblings to a message delivery_state of `download_failed`, and such a message can still carry a media ID -- Google told us the media exists and then told us the download did not work. Reading the media ID alone would serve that attachment as `available`, and the redemption would fail against Google instead of the route saying `failed` up front.

`failed` was a declared value of section 4.2's closed vocabulary that nothing produced, which is the worst kind: a caller branches on it and never exercises the branch.

func EncodeCursor

func EncodeCursor(key DataKey, endpoint, fingerprint string, c Cursor) (string, error)

EncodeCursor mints an opaque cursor for one position in one endpoint's listing under one filter fingerprint.

func EnrollmentCodeID

func EnrollmentCodeID() string

EnrollmentCodeID mints the ID of an enrollment code row (spec section 9.5).

func FTSQuery

func FTSQuery(q string) string

FTSQuery turns the caller's text into an FTS5 query that cannot carry operator syntax.

Every term is tokenised on non-alphanumeric runes and re-emitted as a double-quoted FTS5 string with internal quotes doubled, so `NEAR`, `*`, `OR`, a column filter and a parenthesis are all just words. `words` ANDs the terms, which is the ordinary case; `exact` builds the same query and the caller then filters the page by substring in SQL, so neither mode is an unindexed table scan (spec section 7.6).

func FilterFingerprint

func FilterFingerprint(params map[string][]string) string

FilterFingerprint hashes a filter set exactly as the caller wrote it.

The input is the raw query parameters with the pagination controls (`cursor`, `limit`) removed; nothing is defaulted, lowercased or dropped first. A key that is absent fingerprints differently from the same key present with any value, which is precisely the "issued without folder, replayed with folder=active" case spec section 7.4 names.

func HasPrefix

func HasPrefix(id, prefix string) bool

HasPrefix reports whether an ID carries the expected typed prefix. An ID with the wrong prefix is invalid_request naming the parameter and the expected prefix -- never not_found (spec section 4.1).

func JoinScopes

func JoinScopes(scopes []string) string

JoinScopes renders a scope list the way the two scope columns store it.

func MessageID

func MessageID(accountID, convSourceID, msgSourceID string) string

MessageID is UUIDv5(ns, account_id, "message", Google conversation ID, Google message ID).

func OpenAttachmentKey

func OpenAttachmentKey(dk DataKey, attachmentID string, sealed []byte) ([]byte, error)

OpenAttachmentKey reverses SealAttachmentKey.

func OperationID

func OperationID() string

OperationID is UUIDv7: Agent GM creates it, so it is not derived.

func OperationTerminal

func OperationTerminal(s OperationStatus) bool

OperationTerminal derives `terminal` from the status. It is never stored independently (spec section 6.5).

func OperationTransitionAllowed

func OperationTransitionAllowed(from, to OperationStatus) bool

OperationTransitionAllowed is spec section 6.4's transition table, exactly:

running -> succeeded | failed | pending
pending -> succeeded | failed          (the echo arrived)
pending -> unknown                     (pending_timeout elapsed)
running -> unknown                     (crash recovery)
unknown -> succeeded | failed          (late authoritative evidence)

Nothing leaves `succeeded` or `failed`: those are the two states a caller is entitled to treat as final.

func ParticipantID

func ParticipantID(conversationID, sourceID string) string

ParticipantID is UUIDv5(conversation ID, Google participant ID). It inherits the account transitively through its parent.

func PhoneMatch

func PhoneMatch(raw string) (exact, suffix string)

PhoneMatch turns what a caller typed into the two comparisons a phone lookup needs: the value as given, and its trailing digits.

Section 7.6 says `participant` and `sender` accept "an E.164 number (+12025550123), the bare digits, a national form". Stored numbers are E.164, so an exact comparison answers only the first, and the other two -- the forms a human actually types -- returned an empty page. That is the worst kind of wrong answer, because an empty page is a valid one.

The suffix is empty for anything under seven digits. A four-digit fragment would match half the address book, and a filter that matches everything is not a filter; a caller who genuinely means a short code can still give the exact stored value.

func ReactionID

func ReactionID(messageID, participantID, canonicalEmojiOrTypeName string) string

ReactionID is UUIDv5(message ID, participant ID, canonical EmojiType.Unicode()). For CUSTOM it is the caller's unicode after NFC normalisation; for a type with no unicode it is the EmojiType name. Every inbound emoji is canonicalised before it reaches here (spec section 3.7).

func RequestFingerprint

func RequestFingerprint(body []byte) (string, error)

RequestFingerprint is a SHA-256 over the canonically serialised body: keys sorted, no insignificant whitespace. Reordered JSON keys are therefore a replay and any changed value is not (spec section 6.3).

func SchemaVersion

func SchemaVersion() int

SchemaVersion is the highest migration this binary knows.

func SealAttachmentKey

func SealAttachmentKey(dk DataKey, attachmentID string, raw []byte) ([]byte, error)

SealAttachmentKey encrypts a media decryption key for the attachments.decryption_key column, under the data key derived for agent-gm/attachment-key/v1 with the att_ ID as associated data, so a key blob copied onto another attachment's row fails to open (spec section 4.5).

func SecureDataDir

func SecureDataDir(dir string) error

SecureDataDir creates the data directory if it is absent and tightens it if it is present.

The Chmod is not redundant with the MkdirAll: a directory that already exists -- made by a deployment script, a Docker volume, or `mkdir -p data` in a shell -- keeps whatever mode it was created with, and MkdirAll returns success without touching it. That is exactly how a live deployment ends up with a 0775 data directory nobody chose.

func SplitScopes

func SplitScopes(s string) []string

SplitScopes parses a stored scope column back into a list.

func UploadID

func UploadID() string

UploadID is UUIDv7: an upload reservation is created locally, so it is not derived. It carries no account (spec section 10.2): the account is fixed at send time by the conversation named in the send, not at reservation time.

Types

type Account

type Account struct {
	ID                   string
	GoogleAccount        string
	Label                string
	State                AccountState
	StateReason          string
	PhoneID              string
	GaiaDestRegUUID      string
	GaiaDeviceLastSeenMS int64
	SessionPresent       bool
	PairedAtMS           int64
	LastEventAtMS        int64
	LastSweepAtMS        int64
	BackfillCompleteAtMS int64
	CreatedAtMS          int64
	UpdatedAtMS          int64
}

Account is one Google account.

type AccountState

type AccountState string

AccountState is the vocabulary of spec section 4.7. There is no bad_credentials state and no unpaired state; this is the whole list.

const (
	// StatePairing means a pair is in flight and there is no session yet. It
	// is never a resting state.
	StatePairing AccountState = "pairing"
	// StateConnected means the session is valid and the long poll is up.
	StateConnected AccountState = "connected"
	// StateDegraded means a transient listen error is being retried.
	StateDegraded AccountState = "degraded"
	// StateError means the supervisor is retrying Reconnect with backoff.
	StateError AccountState = "error"
	// StateSignedOut means the owner signed this account out, or its cookies
	// died. Reads keep working; writes are refused with not_signed_in.
	StateSignedOut AccountState = "signed_out"
	// StateParked means accounts.max_concurrent is reached, so this account
	// holds no client and no goroutine. Not an error, and not transient.
	StateParked AccountState = "parked"
	// StateAccountChanged means the phone switched Google accounts under us.
	StateAccountChanged AccountState = "account_changed"
)

type Attachment

type Attachment struct {
	ID               string
	AccountID        string
	MessageID        string
	PartIndex        int
	MediaID          string
	ThumbnailMediaID string
	// DecryptionKey is the sealed column value, not the plaintext. Open it
	// with OpenAttachmentKey; it is encrypted at rest under the data key
	// (spec section 4.5).
	DecryptionKey []byte
	Filename      string
	MimeType      string
	MediaFormat   string
	SizeBytes     int64
	Width         int64
	Height        int64
	DownloadState string
	SHA256        string
}

Attachment is one media part of one message.

type Attempt

type Attempt struct {
	Kind            string
	Source          string
	WindowStartMS   int64
	Failures        int
	CooldownSteps   int
	CooldownUntilMS int64
	UpdatedAtMS     int64
}

Attempt is one row of `oauth_attempts`: the durable half of a credential-failure limiter (spec sections 9.8, 12.3). It is durable precisely because it is the limit an attacker would restart-cycle to reset.

type AuditEvent

type AuditEvent struct {
	ID              string
	Kind            string
	AccountID       string
	AuthorizationID string
	TargetType      string
	TargetID        string
	Result          string
	Source          string
	PayloadJSON     string
	CreatedAtMS     int64
}

AuditEvent is one recorded fact.

Payloads carry IDs, counts, codes and outcomes -- never message text, never a full phone number, never a token, never a cookie, never the data key. Redaction happens before the row reaches this package.

func (AuditEvent) CursorPosition

func (e AuditEvent) CursorPosition() Cursor

CursorPosition is the audit row's position in the newest-first order.

type AuditQuery

type AuditQuery struct {
	Kind            string
	KindPrefix      string
	AccountID       string
	AuthorizationID string
	AfterMS         int64
	BeforeMS        int64
	Cursor          *Cursor
	Limit           int
}

AuditQuery is the filter set of GET /v1/admin/audit and `agm admin audit list` (spec section 12.4).

type Authorization

type Authorization struct {
	ID     string
	Kind   string
	Client string
	// Scopes and MintedScopes are stored space-joined, in the caller's order.
	Scopes       string
	MintedScopes string
	// SecretGeneration identifies which AGENT_GM_ADMIN_SECRET minted this
	// authorization. It is a hash, never the secret (spec section 12.1).
	SecretGeneration string
	Source           string
	RevokedAtMS      int64
	ExpiresAtMS      int64
	CreatedAtMS      int64
	UpdatedAtMS      int64
}

Authorization is one row of `authorizations`.

Scopes is what the authorization currently carries; MintedScopes is what it was minted with and never changes. A refresh may only narrow relative to MintedScopes, never back up to it (spec section 9.6) -- without the second column a narrowed session would be one refresh away from full privilege.

func (Authorization) Revoked

func (a Authorization) Revoked() bool

Revoked reports whether the authorization has been revoked.

type AuthorizationCode

type AuthorizationCode struct {
	CodeHash        string
	RequestID       string
	ClientID        string
	RedirectURI     string
	CodeChallenge   string
	Scopes          string
	Resource        string
	AuthorizationID string
	ConsumedAtMS    int64
	ExpiresAtMS     int64
	CreatedAtMS     int64
}

AuthorizationCode is one issued code (spec section 9.6). Only its hash is stored. AuthorizationID is filled in when the code is exchanged, so that a replay can revoke the tokens the first exchange produced.

func (AuthorizationCode) Consumed

func (c AuthorizationCode) Consumed() bool

Consumed reports whether the code has been exchanged (or burned by a wrong PKCE verifier, which consumes it so a verifier cannot be guessed by retrying).

type AuthorizationRequest

type AuthorizationRequest struct {
	ID                  string
	ClientID            string
	RedirectURI         string
	State               string
	CodeChallenge       string
	CodeChallengeMethod string
	Resource            string
	RequestedScopes     string
	SelectedScopes      string
	GrantedScopes       string
	EnrollmentCodeID    string
	Status              string
	DenyReason          string
	HandleHash          string
	FormTokenHash       string
	Source              string
	ExpiresAtMS         int64
	DecidedAtMS         int64
	CompletedAtMS       int64
	CreatedAtMS         int64
	UpdatedAtMS         int64
}

AuthorizationRequest is one pending owner decision (spec section 9.5).

HandleHash and FormTokenHash are hashes of the two browser secrets: the handle carried in the signed `agm_oauth_context` cookie, and the anti-CSRF token the waiting page's form carries. Neither value is stored.

type AuthzTx

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

AuthzTx is the credential surface of one open write transaction.

func (*AuthzTx) ActivateOAuthClient

func (t *AuthzTx) ActivateOAuthClient(id string) error

ActivateOAuthClient marks a registration as used by an authorization, which is what stops the 24-hour sweep from removing it (spec section 9.3).

func (*AuthzTx) AppendAudit

func (t *AuthzTx) AppendAudit(kind, result, accountID, authorizationID, source, payloadJSON string) error

AppendAudit writes one audit_events row inside the transaction, so an audit record commits with the change it describes (spec sections 9.6, 12.4).

payloadJSON is rendered by the caller: this layer has no opinion about what belongs in a payload beyond the schema's requirement that it be present. The caller is responsible for section 12.4's rule that a payload carries IDs, counts, codes and outcomes and never a token, a secret or a phone number.

func (*AuthzTx) Attempt

func (t *AuthzTx) Attempt(kind, source string) (Attempt, error)

Attempt reads one oauth_attempts row inside the transaction.

func (*AuthzTx) Authorization

func (t *AuthzTx) Authorization(id string) (Authorization, error)

Authorization re-reads one authorization inside the transaction. Spec section 9.8: when the token does exist, the transaction re-reads the row before cascading, so revocation stays a single atomic decision.

func (*AuthzTx) AuthorizationCode

func (t *AuthzTx) AuthorizationCode(hash string) (AuthorizationCode, error)

AuthorizationCode re-reads one code inside the transaction.

func (*AuthzTx) AuthorizationRequest

func (t *AuthzTx) AuthorizationRequest(id string) (AuthorizationRequest, error)

AuthorizationRequest re-reads one request inside the transaction, which is what makes an approval and a completion single atomic decisions rather than read-then-write races.

func (*AuthzTx) CompleteAuthorizationRequest

func (t *AuthzTx) CompleteAuthorizationRequest(id string) (bool, error)

CompleteAuthorizationRequest marks an approved request completed, conditional on it still being approved. **A completed request can never mint a second code** (spec section 9.5), and this condition is the whole reason for that guarantee.

func (*AuthzTx) ConsumeAuthorizationCode

func (t *AuthzTx) ConsumeAuthorizationCode(hash, authorizationID string) (bool, error)

ConsumeAuthorizationCode marks a code spent, conditional on it being unspent. The boolean is the race answer: false means somebody exchanged it first, which is the replay section 9.6 punishes.

func (*AuthzTx) ConsumeEnrollmentCode

func (t *AuthzTx) ConsumeEnrollmentCode(id, requestID string) (bool, error)

ConsumeEnrollmentCode marks a code redeemed by one authorization request. It is conditional on the code still being unconsumed, so two submissions racing cannot both redeem it: the loser sees zero rows affected.

func (*AuthzTx) CreateAuthorization

func (t *AuthzTx) CreateAuthorization(a Authorization) error

CreateAuthorization inserts one authorization row.

func (*AuthzTx) CreateAuthorizationCode

func (t *AuthzTx) CreateAuthorizationCode(c AuthorizationCode) error

CreateAuthorizationCode inserts one issued code.

func (*AuthzTx) CreateAuthorizationRequest

func (t *AuthzTx) CreateAuthorizationRequest(a AuthorizationRequest) error

CreateAuthorizationRequest inserts one pending request.

func (*AuthzTx) CreateEnrollmentCode

func (t *AuthzTx) CreateEnrollmentCode(e EnrollmentCode) error

CreateEnrollmentCode inserts one code row.

func (*AuthzTx) CreateOAuthClient

func (t *AuthzTx) CreateOAuthClient(c OAuthClient) error

CreateOAuthClient inserts one registration inside a transaction.

func (*AuthzTx) DecideAuthorizationRequest

func (t *AuthzTx) DecideAuthorizationRequest(id, status, grantedScopes, denyReason string) (bool, error)

DecideAuthorizationRequest moves a request from pending to approved or denied, conditional on it still being pending. A no-longer-pending request is `idempotency_conflict` at the admin route, and this is where that is decided: zero rows affected means somebody got there first.

func (*AuthzTx) DeleteOAuthClient

func (t *AuthzTx) DeleteOAuthClient(id string) error

DeleteOAuthClient removes one registration.

func (*AuthzTx) EnrollmentCode

func (t *AuthzTx) EnrollmentCode(id string) (EnrollmentCode, error)

EnrollmentCode re-reads one code row inside the transaction.

func (*AuthzTx) ExpiredUnreferencedClients

func (t *AuthzTx) ExpiredUnreferencedClients() ([]string, error)

ExpiredUnreferencedClients lists registrations the 60-second maintenance pass may remove: expired, never activated, and named by no authorization request. "Unreferenced" is checked in SQL rather than in Go so that a request created between the list and the delete cannot be orphaned.

func (*AuthzTx) InsertToken

func (t *AuthzTx) InsertToken(tok Token) error

InsertToken stores one token by hash. The value never reaches this layer.

func (*AuthzTx) NowMS

func (t *AuthzTx) NowMS() int64

NowMS is the injected clock's reading when the transaction opened. Every timeout in the credential path is measured against it, never against time.Now (spec section 13.1).

func (*AuthzTx) OAuthClient

func (t *AuthzTx) OAuthClient(id string) (OAuthClient, error)

OAuthClient re-reads one registration inside the transaction.

func (*AuthzTx) PutAttempt

func (t *AuthzTx) PutAttempt(a Attempt) error

PutAttempt writes one oauth_attempts row inside the transaction.

func (*AuthzTx) RevokeAuthorization

func (t *AuthzTx) RevokeAuthorization(id string) error

RevokeAuthorization marks the authorization revoked. It is idempotent: an already-revoked row keeps its first revocation time.

func (*AuthzTx) RevokeEnrollmentCode

func (t *AuthzTx) RevokeEnrollmentCode(id, reason string) (bool, error)

RevokeEnrollmentCode revokes a code, reporting whether this call was the one that did it. Repeating a revocation answers 200 with `revoked: false` (spec section 9.5), which is why the boolean is returned rather than an error.

func (*AuthzTx) RevokeToken

func (t *AuthzTx) RevokeToken(hash string) error

RevokeToken revokes one token.

func (*AuthzTx) RevokeTokenFamily

func (t *AuthzTx) RevokeTokenFamily(familyID string) (int64, error)

RevokeTokenFamily revokes every token of one rotation family and reports how many rows it touched. Reuse of a spent refresh token revokes the whole family and its authorization (spec section 9.6).

func (*AuthzTx) RevokeTokensForAuthorization

func (t *AuthzTx) RevokeTokensForAuthorization(authorizationID string) (int64, error)

RevokeTokensForAuthorization revokes every token of one authorization.

func (*AuthzTx) SetAuthorizationScopes

func (t *AuthzTx) SetAuthorizationScopes(id, scopes string) error

SetAuthorizationScopes narrows (or otherwise rewrites) the current scopes. minted_scopes is deliberately not writable: it is what the session was minted with and a refresh is measured against it forever.

func (*AuthzTx) SpendToken

func (t *AuthzTx) SpendToken(hash string) error

SpendToken marks a refresh token redeemed. It fails with ErrTokenNotFound if the row is gone, so a caller cannot believe it rotated something that no longer exists.

func (*AuthzTx) Token

func (t *AuthzTx) Token(hash string) (Token, error)

Token re-reads one token by hash inside the transaction.

type BackfillState

type BackfillState struct {
	ConversationID string
	AccountID      string
	CursorItemID   string
	// CursorTimestampUS is gmproto.Cursor.lastItemTimestamp, in Google's own
	// microseconds, carried back verbatim. It is the one place a microsecond
	// value is stored, because it is an opaque token rather than a timestamp
	// Agent GM ever reads (spec section 4.4).
	CursorTimestampUS int64
	OldestSeenMS      int64
	MessagesDone      int64
	Complete          bool
	UpdatedAtMS       int64
}

BackfillState is one conversation's backfill progress (spec section 5.2). It carries account_id as well as conversation_id: the cursor is Google's own and is only meaningful within the account that issued it.

type Contact

type Contact struct {
	ID          string
	AccountID   string
	SourceID    string
	DisplayName string
	PhoneE164   string
	AvatarHash  string
	IsTop       bool
	UpdatedAtMS int64
}

Contact is somebody in one account's phone contact list.

The same person in two accounts is two contact rows with two contact_ IDs, which is why every contact DTO carries account_id: a cross-account list would otherwise be unattributable (spec section 7.6).

func (Contact) CursorPosition

func (c Contact) CursorPosition() Cursor

CursorPosition is the contact's position in the newest-first order.

type ContactQuery

type ContactQuery struct {
	AccountID   string
	AllAccounts bool
	Query       string
	Top         bool
	Cursor      *Cursor
	Limit       int
}

ContactQuery is the parameter set of GET /v1/contacts.

type Conversation

type Conversation struct {
	ID                string
	AccountID         string
	SourceID          string
	Name              string
	IsGroup           bool
	ConversationType  string
	SendModeRaw       string
	Folder            string
	Unread            bool
	Pinned            bool
	ReadOnly          bool
	ForceRCSEligible  bool
	DefaultOutgoingID string
	LatestMessageID   string
	LastActivityMS    int64
	GroupAvatarURL    string
	SIMPayload        []byte
	DeletedAtMS       int64
}

Conversation is one stored thread.

func (Conversation) CursorPosition

func (c Conversation) CursorPosition() Cursor

CursorPosition is the conversation's position in the newest-activity-first order; it is what the next page's cursor encodes.

type ConversationFilter

type ConversationFilter struct {
	AccountID string
	Folder    string
	Limit     int
}

ConversationFilter selects conversations. AccountID is optional; omitting it is the all-accounts form, which spec section 7.3 makes the default for reads, so both forms are indexed.

type ConversationQuery

type ConversationQuery struct {
	AccountID        string
	AllAccounts      bool
	Query            string
	ParticipantPhone string
	ParticipantID    string
	Folder           string
	Type             string
	UnreadOnly       bool
	GroupOnly        *bool
	PinnedOnly       bool
	AfterMS          *int64
	BeforeMS         *int64
	IncludeDeleted   bool
	Cursor           *Cursor
	Limit            int
}

ConversationQuery is the parameter set of GET /v1/conversations.

ParticipantPhone and ParticipantID are the two resolved forms of the route's single `participant` parameter; ResolveParticipant turns the caller's spelling into one of them. They are kept apart so that the SQL has exactly one indexed predicate rather than an OR across three columns, which would scan `participants` (spec section 16 test 39).

type Cursor

type Cursor struct {
	SentAtMS int64
	ID       string
}

Cursor is one position in an ordered listing.

func DecodeCursor

func DecodeCursor(key DataKey, endpoint, fingerprint, token string) (Cursor, error)

DecodeCursor verifies a cursor and returns its position.

The signature is checked before the binding, so a tampered cursor is never reported as a filter mismatch and a filter mismatch is never mistaken for tampering.

type DataKey

type DataKey [32]byte

DataKey is AGENT_GM_DATA_KEY: a 256-bit key supplied as 64 hex characters or standard base64 (spec section 4.5).

One data key covers every account, and it is not rotatable in place. The key and the data directory move together, always.

func ParseDataKey

func ParseDataKey(s string) (DataKey, error)

ParseDataKey accepts the two documented encodings.

func (DataKey) Derive

func (k DataKey) Derive(info string) ([]byte, error)

Derive produces a 32-byte subkey for one purpose by HKDF-SHA256.

type DownloadTicket

type DownloadTicket struct {
	TokenHash       string
	AttachmentID    string
	AuthorizationID string
	Redemptions     int
	MaxRedemptions  int
	ExpiresAtMS     int64
	CreatedAtMS     int64
}

DownloadTicket is one minted download authorisation.

Download tickets are stateful because a five-use cap cannot be enforced by a signed blob (D24): the counter lives here and is incremented in the same transaction that authorises the read (spec section 10.3).

type EnrollmentCode

type EnrollmentCode struct {
	ID            string
	CodeHash      string
	Label         string
	Scopes        string
	ExpiresAtMS   int64
	ConsumedAtMS  int64
	ConsumedBy    string
	RevokedAtMS   int64
	RevokedReason string
	CreatedAtMS   int64
	UpdatedAtMS   int64
}

EnrollmentCode is one owner-issued code (spec section 9.5). `Scopes` is the ceiling it caps a grant at, never a set of accounts: enrollment codes carry no account dimension, consistent with D29.

func (EnrollmentCode) Consumed

func (e EnrollmentCode) Consumed() bool

Consumed reports whether the code has already been redeemed.

func (EnrollmentCode) Revoked

func (e EnrollmentCode) Revoked() bool

Revoked reports whether the owner revoked this code.

type ErasureCounts

type ErasureCounts struct {
	Conversations     int64
	Participants      int64
	Messages          int64
	Attachments       int64
	Reactions         int64
	BackfillState     int64
	Operations        int64
	Contacts          int64
	MediaCacheEntries int64
}

ErasureCounts is what a removal deleted, per table, for the response body and the account.removed audit row.

type ErasureResult

type ErasureResult struct {
	MediaPaths []string
	Counts     ErasureCounts
}

ErasureResult is the outcome of EraseAccount.

MediaPaths are the cached relative paths, collected *inside* the delete transaction and returned to the caller, which unlinks them only after the commit. That order is deliberate: the eviction sweep finds every file it deletes through media_cache_entries, so deleting the rows without the files would leave bytes nothing references and a cache budget that silently stops matching the disk. A crash between the commit and the unlink leaves an orphan file, which an operator can delete, and never an orphan row (spec section 10.3).

type ErrSchemaTooNew

type ErrSchemaTooNew struct {
	Database int
	Binary   int
}

ErrSchemaTooNew means the database was written by a newer binary.

func (ErrSchemaTooNew) Error

func (e ErrSchemaTooNew) Error() string

type MediaCacheEntry

type MediaCacheEntry struct {
	AttachmentID string
	RelativePath string
	SizeBytes    int64
	Pinned       bool
	LastUsedMS   int64
}

MediaCacheEntry is one cached file.

media_cache_entries is the single authority for cached bytes: attachments carries no cache path and no cached size, so there is exactly one row per cached file and "no orphan row" is a well-defined assertion (spec section 4.2).

type Message

type Message struct {
	ID                string
	AccountID         string
	ConversationID    string
	SourceID          string
	Kind              string
	Direction         string
	SenderParticipant string
	Text              string
	Subject           string
	DeliveryState     string
	DeliveryStateRaw  int32
	ReplyToMessageID  string
	OperationID       string
	TmpID             string
	IsDeleted         bool
	SentAtMS          int64
	IngestedAtMS      int64
	UpdatedAtMS       int64
	ContentHash       string
}

Message is one stored message.

func (Message) CursorPosition

func (m Message) CursorPosition() Cursor

CursorPosition is the message's position in the newest-first order.

type MessageContext

type MessageContext struct {
	Before  []Message
	Message Message
	After   []Message
}

MessageContext is the neighbourhood of one message, newest-first in Before and oldest-first in After, as GET /v1/messages/{id}/context serves it.

type MessageFilter

type MessageFilter struct {
	AccountID      string
	AllAccounts    bool
	ConversationID string
	IncludeSystem  bool
	Limit          int
}

MessageFilter selects messages. AccountID is optional; AllAccounts must be set explicitly when it is omitted, so a query can never lose its account predicate by accident (spec section 13.2).

type MessageQuery

type MessageQuery struct {
	AccountID           string
	AllAccounts         bool
	ConversationID      string
	Direction           string
	SenderMe            bool
	SenderParticipantID string
	SenderPhone         string
	AfterMS             int64
	BeforeMS            int64
	HasAttachment       *bool
	DeliveryState       string
	IncludeSystem       bool
	Cursor              *Cursor
	Limit               int
}

MessageQuery is the parameter set of GET /v1/messages and GET /v1/conversations/{id}/messages.

SenderMe, SenderParticipantID and SenderPhone are the three resolved forms of the route's `sender`. `sender=me` is resolved per account rather than to one identity: on an account-scoped query it is that account's is_me participant, and on a cross-account query it is *each* account's, so sender=me returns everything the owner sent from anywhere (section 7.6).

type OAuthClient

type OAuthClient struct {
	ID                      string
	Name                    string
	RedirectURIs            []string
	GrantTypes              []string
	ResponseTypes           []string
	TokenEndpointAuthMethod string
	// MetadataJSON is the registration request as accepted, so that
	// GET-ing a registration back returns what was registered rather than a
	// reconstruction.
	MetadataJSON  string
	Source        string
	ActivatedAtMS int64
	ExpiresAtMS   int64
	CreatedAtMS   int64
}

OAuthClient is one dynamically registered public client (spec section 9.3). There is no client_secret column because there is no client secret: public native clients only, `token_endpoint_auth_method` is always `none`.

func (OAuthClient) Activated

func (c OAuthClient) Activated() bool

Activated reports whether an authorization has ever used this registration. An activated registration no longer expires (spec section 9.3).

type Operation

type Operation struct {
	ID                 string
	AccountID          string
	Kind               string
	AuthorizationID    string
	IdempotencyKey     string
	RequestFingerprint string
	ConversationID     string
	MessageID          string
	TmpID              string
	Status             OperationStatus
	Terminal           bool
	TerminalAtMS       int64
	CorrectedAtMS      int64
	ErrorCode          string
	ErrorMessage       string
	ErrorRetryable     bool
	HasErrorRetryable  bool
	GoogleStatusRaw    int32
	RequestPayloadJSON string
	// MediaSizeBytes is the plaintext size of the media this operation sent,
	// zero for every operation that sent none. It is kept because Google's
	// echo of our own media does not carry it (migration 0005).
	MediaSizeBytes int64
	CreatedAtMS    int64
	UpdatedAtMS    int64
}

Operation is one mutation's idempotency and status record.

func (Operation) CursorPosition

func (o Operation) CursorPosition() Cursor

CursorPosition is the operation's position in the newest-first order.

type OperationQuery

type OperationQuery struct {
	AuthorizationID string
	AllAccounts     bool
	AccountID       string
	Kind            string
	Status          OperationStatus
	Terminal        *bool
	AfterMS         int64
	BeforeMS        int64
	Cursor          *Cursor
	Limit           int
}

OperationQuery is the parameter set of GET /v1/operations. A caller sees only its own operations, keyed on the authorization that created them (spec section 6.5), so AuthorizationID is the caller's scope, not a filter the caller chooses.

type OperationStatus

type OperationStatus string

OperationStatus is the closed vocabulary of spec section 6.4.

const (
	// OpRunning means in flight, or the process died mid-call.
	OpRunning OperationStatus = "running"
	// OpSucceeded means the phone accepted it.
	OpSucceeded OperationStatus = "succeeded"
	// OpPending is libgm.ErrPhoneNotResponding and nothing else. The server
	// accepted the request; the phone may still act on it when it wakes.
	// This is not a failure: reporting it as one invites the caller to
	// resend, which sends the message twice when the phone wakes up.
	OpPending OperationStatus = "pending"
	// OpFailed means the phone refused it, or a non-retryable error.
	OpFailed OperationStatus = "failed"
	// OpUnknown means it never settled within pending_timeout, or it was
	// recovered from a crash.
	OpUnknown OperationStatus = "unknown"
)

type PermissionWarning

type PermissionWarning struct {
	Path string
	Mode os.FileMode
	Want os.FileMode
}

PermissionWarning is one path that is more permissive than it should be.

func CheckPermissions

func CheckPermissions(dataDir string) []PermissionWarning

CheckPermissions reports anything under the data directory that is readable or writable by somebody other than the owner.

It **warns rather than fails**, deliberately. Agent GM tightens what it creates, so a warning here means something outside Agent GM loosened it -- a restore, a bind mount with its own ownership, an operator's `chmod -R`. Refusing to start would turn a fixable disclosure into an outage, and an operator who cannot start the server cannot read the message telling them why. So it starts, and says so once, loudly, at startup.

func (PermissionWarning) String

func (w PermissionWarning) String() string

type PrunedBackup

type PrunedBackup struct {
	Path string
	// Err is set when the file could not be removed. Such a file is logged
	// and LEFT rather than failing a backup that had already succeeded
	// (spec section 15.2).
	Err error
}

PrunedBackup is one removal, for the audit row.

type Reaction

type Reaction struct {
	ID            string
	MessageID     string
	ParticipantID string
	Emoji         string
	HasEmoji      bool
	EmojiType     string
	IsMine        bool
	UpdatedAtMS   int64
}

Reaction is one person's single reaction to one message.

There is one row per (message, participant): Google's picker is single-select and an add over an existing one is SWITCH, not a second entry (D23). Emoji is empty when the EmojiType has no unicode of its own, which serves as {"emoji": null, "type": "emotify"} rather than being dropped (spec section 3.7).

type SearchQuery

type SearchQuery struct {
	Q              string
	Mode           string
	AccountID      string
	AllAccounts    bool
	ConversationID string
	SenderMe       bool
	// SenderParticipantID and SenderPhone are the resolved forms of `sender`.
	SenderParticipantID string
	SenderPhone         string
	AfterMS             int64
	BeforeMS            int64
	HasAttachment       *bool
	Cursor              *Cursor
	Limit               int
}

SearchQuery is the parameter set of GET /v1/search/messages.

type SearchResult

type SearchResult struct {
	Message Message
	Rank    float64
	Snippet string
}

SearchResult is one hit.

type SessionStore

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

SessionStore reads and writes the per-account session files.

func NewSessionStore

func NewSessionStore(dataDir string, key DataKey) (*SessionStore, error)

NewSessionStore creates sessions/ at mode 0700 under the data directory.

func (*SessionStore) Dir

func (s *SessionStore) Dir() string

Dir is the sessions directory.

func (*SessionStore) Load

func (s *SessionStore) Load(accountID string) ([]byte, error)

Load reads and decrypts one account's session.

func (*SessionStore) Path

func (s *SessionStore) Path(accountID string) string

Path is where one account's session lives.

func (*SessionStore) Present

func (s *SessionStore) Present(accountID string) bool

Present reports whether an account has a session file on disk.

func (*SessionStore) Save

func (s *SessionStore) Save(accountID string, plaintext []byte) error

Save writes the session atomically: a temp file in the same directory, an fsync, then a rename. The temp name is per account, so two accounts persisting at once cannot collide. Mode is 0600.

func (*SessionStore) Shred

func (s *SessionStore) Shred(accountID string) error

Shred removes one account's session file. Signing out shreds the file and zeroes the in-memory AuthData; it deletes no rows (spec section 4.7).

type Setting

type Setting struct {
	Key         string
	ValueJSON   string
	UpdatedAtMS int64
}

Setting is one stored override.

type SettingsStore

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

SettingsStore adapts the `settings` table to the persistence interface `internal/settings` declares.

The adapter exists because `internal/settings` deliberately does not import `internal/store`: the defaults, the bounds, the scope column and the validation of spec section 15.1 are a table of facts about the specification, not about SQLite, and a package that owned both would make the registry impossible to test without a database. So the registry declares a three-method interface and this is the one implementation of it that talks to a real database.

func NewSettingsStore

func NewSettingsStore(s *Store) *SettingsStore

NewSettingsStore adapts a store.

func (*SettingsStore) All

func (a *SettingsStore) All(ctx context.Context) (map[string]string, error)

All returns every stored row.

func (*SettingsStore) Get

func (a *SettingsStore) Get(ctx context.Context, key string) (string, bool, error)

Get returns the stored JSON for a key. ok is false when no row exists, which is how the registry tells "the operator set this" from "the default applies" -- and therefore how GET /v1/admin/settings reports `source`.

func (*SettingsStore) Put

func (a *SettingsStore) Put(ctx context.Context, key, valueJSON string) error

Put writes the stored JSON for a key.

type Settlement

type Settlement struct {
	Status          OperationStatus
	MessageID       string
	ConversationID  string
	ErrorCode       string
	ErrorMessage    string
	ErrorRetryable  bool
	GoogleStatusRaw int32
}

Settlement is the outcome being recorded on an operation.

type Store

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

Store is Agent GM's SQLite database.

One goroutine writes, for the whole process: every write from every account goes through Writer, a single goroutine consuming a channel of write closures. Accounts are concurrent at the network and at the ingest boundary, serialised at the database. Reads use a separate read-only pool (spec section 2.4).

func Open

func Open(dataDir string, clk clock.Clock) (*Store, error)

Open opens (and migrates) the database under the data directory.

func (*Store) Account

func (s *Store) Account(ctx context.Context, id string) (Account, error)

Account reads one account.

func (*Store) Accounts

func (s *Store) Accounts(ctx context.Context) ([]Account, error)

Accounts lists every account, newest event first -- the order accounts are connected in when accounts.max_concurrent bounds how many run at once.

This is the explicit all-accounts query: it has no account_id predicate because listing accounts is exactly the all-accounts case.

func (*Store) AppendAudit

func (s *Store) AppendAudit(ctx context.Context, e AuditEvent) (AuditEvent, error)

AppendAudit writes one audit row. Every row carries account_id where the event belongs to an account and NULL where it does not, such as an OAuth or settings event (spec section 12.4).

func (*Store) AppendAuditOnce

func (s *Store) AppendAuditOnce(ctx context.Context, e AuditEvent) (bool, error)

AppendAuditOnce appends one audit row unless a row of the same kind about the same target is already there, and reports whether this call was the one that wrote it.

It exists for the two `*.expired` kinds of section 12.4. Expiry is derived at read time rather than swept (see internal/oauth's StatusExpired), so the moment it becomes true is the first read that observes it -- and every later read observes it again. Without a condition, "audit the expiry" would mean one row per poll of the waiting page.

This is still append-only: the guard is a WHERE NOT EXISTS on the INSERT, not an UPDATE. Nothing here rewrites a row, and the whole statement runs on the single writer, so two concurrent observers cannot both win.

TargetType and TargetID are the identity of the thing that expired and are required: they are what makes "already recorded" a question with an answer.

func (*Store) Attachment

func (s *Store) Attachment(ctx context.Context, id string) (Attachment, error)

Attachment reads one attachment by its att_ ID.

func (*Store) AttachmentsForMessage

func (s *Store) AttachmentsForMessage(ctx context.Context, messageID string) ([]Attachment, error)

AttachmentsForMessage lists one message's media parts in part order.

func (*Store) AttemptRow

func (s *Store) AttemptRow(ctx context.Context, kind, source string) (Attempt, bool, error)

AttemptRow reads one oauth_attempts row. The bool reports whether it exists; an absent row is not an error, it is a source that has never failed.

func (*Store) AuditKinds

func (s *Store) AuditKinds(ctx context.Context) ([]string, error)

AuditKinds lists the kinds of every audit row, newest first. It exists for tests and for GET /v1/admin/audit's callers to assert against without reaching for the payload.

func (*Store) AuditPayloads

func (s *Store) AuditPayloads(ctx context.Context, kind string) ([]string, error)

AuditPayloads returns the raw payload JSON of every audit row of one kind. The sentinel scan of spec section 12.2 reads this to prove no presented value ever reached a payload.

func (*Store) Authorization

func (s *Store) Authorization(ctx context.Context, id string) (Authorization, error)

Authorization reads one authorization by ID.

func (*Store) AuthorizationCodeByHash

func (s *Store) AuthorizationCodeByHash(ctx context.Context, hash string) (AuthorizationCode, error)

AuthorizationCodeByHash resolves a presented code read-only, before any write transaction opens (spec section 9.8).

func (*Store) AuthorizationIDForRequest

func (s *Store) AuthorizationIDForRequest(ctx context.Context, requestID string) (string, error)

AuthorizationIDForRequest returns the authorization one approved request eventually minted, or "" if the code has not been exchanged yet.

It is a join through `authorization_codes` rather than a column on `authorization_requests`, because the authorization does not exist when the request is approved: the owner approves, the browser completes, and only then does the token endpoint mint anything. A column would have to be written by the exchange anyway, and a nullable column that is null for a perfectly ordinary reason invites a reader to think something went wrong.

func (*Store) AuthorizationRequestByID

func (s *Store) AuthorizationRequestByID(ctx context.Context, id string) (AuthorizationRequest, error)

AuthorizationRequestByID reads one pending request, read-only.

func (*Store) AuthorizationRequests

func (s *Store) AuthorizationRequests(ctx context.Context, status string) ([]AuthorizationRequest, error)

AuthorizationRequests lists requests, optionally filtered by status, newest first.

func (*Store) Authorizations

func (s *Store) Authorizations(ctx context.Context, includeRevoked bool) ([]Authorization, error)

Authorizations lists every authorization, newest first, optionally only the live ones. It carries no token and no hash: an owner auditing their grants sees IDs, kinds, clients, scopes and times.

func (*Store) AuthorizationsByKind

func (s *Store) AuthorizationsByKind(ctx context.Context, kind string) ([]Authorization, error)

AuthorizationsByKind lists every authorization of one kind, newest first.

func (*Store) AuthorizationsForClient

func (s *Store) AuthorizationsForClient(ctx context.Context, clientID string) ([]Authorization, error)

AuthorizationsForClient lists the live authorizations one registration holds, which is what a client revocation has to take with it.

func (*Store) AuthzTx

func (s *Store) AuthzTx(ctx context.Context, fn func(*AuthzTx) error) error

AuthzTx runs fn inside one transaction on the single writer, handing it a credential-scoped view of that transaction. Everything fn does commits together or not at all: this is how a rotation, its audit record and a family revocation become one atomic decision (spec section 9.6).

func (*Store) BackfillProgress

func (s *Store) BackfillProgress(ctx context.Context, accountID string) (done, total int64, err error)

BackfillProgress counts one account's conversations and how many of them have finished backfilling, for the per-account `backfill` block of GET /v1/health (spec section 7.5).

func (*Store) BackfillState

func (s *Store) BackfillState(ctx context.Context, conversationID string) (BackfillState, error)

BackfillState reads one conversation's progress.

func (*Store) Backup

func (s *Store) Backup(ctx context.Context, dataDir string) (string, error)

Backup writes a snapshot to <data_dir>/backups/agent-gm-<ts>-<id>.sqlite3 and returns its path.

**Mechanism, and a documented deviation from spec section 15.2.** The spec says "using the SQLite backup API, not a file copy". `modernc.org/sqlite` at the pinned version does not expose `sqlite3_backup_init` from its driver package -- the symbol exists only inside the vendored C translation under `lib/`, which is not importable -- so the online backup API is not reachable from Agent GM at all. `VACUUM INTO` is used instead, and it delivers every property section 15.2 actually asks for:

  • it runs inside the database's own read transaction, so the snapshot is a consistent point in time and is never a torn file copy;
  • in WAL mode it does not block writers, so the server keeps serving;
  • the result is a single file with **no `-wal` sidecar** that opens on its own, which is the property a restore depends on;
  • it is not a file copy, which is the thing the spec was ruling out.

What it does not do is the restart-on-write behaviour of the incremental backup API, and it does not need to: `VACUUM INTO` copies within one transaction rather than page by page across many, so there is no window for a writer to invalidate a page already taken. The observable contract is unchanged; only the sentence naming the C function is.

func (*Store) BumpConversationActivity

func (s *Store) BumpConversationActivity(ctx context.Context, conversationID, latestMessageID string, activityMS int64) error

BumpConversationActivity moves last_activity_ms forward and records the latest message. It never moves backwards.

func (*Store) Close

func (s *Store) Close() error

Close stops the writer and closes both pools.

func (*Store) CollectMediaPaths

func (s *Store) CollectMediaPaths(ctx context.Context, accountID string) ([]string, error)

CollectMediaPaths returns the cached relative paths belonging to one account, or to every account when accountID is empty. Erasure calls the transaction-scoped form so the paths are collected before the rows go.

func (*Store) CompleteUpload

func (s *Store) CompleteUpload(ctx context.Context, uploadID, stagedPath string, ok bool) error

CompleteUpload spends the reservation's single redemption and records the staged bytes. It moves `reserved` to `complete`, and refuses a second PUT with the same token: the redemption is counted whether or not the body was acceptable, so a short body, a wrong sha256 or a contradicted content type each spend the reservation (spec section 16 test 17). The caller passes ok=false for those, which spends the reservation and leaves it `expired`.

func (*Store) ConsumeUpload

func (s *Store) ConsumeUpload(ctx context.Context, uploadID string) error

ConsumeUpload moves `complete` to `consumed` when the bytes are sent. A second send of the same upload -- into either account -- is refused here, which is what makes an account-agnostic reservation safe (section 10.2).

func (*Store) Contact

func (s *Store) Contact(ctx context.Context, id string) (Contact, error)

Contact reads one contact by its contact_ ID.

func (*Store) Conversation

func (s *Store) Conversation(ctx context.Context, id string) (Conversation, error)

Conversation reads one conversation by its conv_ ID.

func (*Store) Conversations

func (s *Store) Conversations(ctx context.Context, f ConversationFilter) ([]Conversation, error)

Conversations lists conversations, newest activity first with the ID as the tiebreaker. Ordering is never by ingestion order.

func (*Store) CountRegistrationsSince

func (s *Store) CountRegistrationsSince(ctx context.Context, source string, sinceMS int64) (int, error)

CountRegistrationsSince is the durable half of section 9.3's "20 per source per hour". Counting rows is exact and survives a restart, which an in-memory bucket would not -- and a registration is a durable object, so forgiving it on restart would be forgiving something that is still there.

func (*Store) DeletePairingAccount

func (s *Store) DeletePairingAccount(ctx context.Context, accountID string) error

DeletePairingAccount removes a `pairing` row that has never been connected. A startup sweep deletes every such row with no live pairing behind it: `pairing` is never a resting state (spec section 3.2).

func (*Store) DeleteSetting

func (s *Store) DeleteSetting(ctx context.Context, key string) error

DeleteSetting removes one override, returning that key to its compiled default.

func (*Store) DownloadTicketByHash

func (s *Store) DownloadTicketByHash(ctx context.Context, tokenHash string) (DownloadTicket, error)

DownloadTicketByHash reads a ticket without spending it.

func (*Store) EnrollmentCodeByHash

func (s *Store) EnrollmentCodeByHash(ctx context.Context, hash string) (EnrollmentCode, error)

EnrollmentCodeByHash resolves a presented code, read-only and BEFORE any write transaction opens (spec section 9.8's rule, which applies to every presented credential and not only to a refresh token).

func (*Store) EnrollmentCodeByID

func (s *Store) EnrollmentCodeByID(ctx context.Context, id string) (EnrollmentCode, error)

EnrollmentCodeByID reads one code row by its ID, for the admin listing.

func (*Store) EnrollmentCodes

func (s *Store) EnrollmentCodes(ctx context.Context) ([]EnrollmentCode, error)

EnrollmentCodes lists every code, newest first. The value is not in any of them: `data.code` is returned exactly once, at creation.

func (*Store) EraseAccount

func (s *Store) EraseAccount(ctx context.Context, accountID string) (ErasureResult, error)

EraseAccount deletes one account's data in a single transaction.

conversations cascades to participants, messages, attachments, reactions and backfill_state; attachments cascades to media_cache_entries and download_tickets. operations, contacts and the account row follow, in that order: contacts must go after participants, because participants.contact_id references contacts(id) with no cascade of its own, so deleting contacts first would violate the foreign key rather than the invariant.

Audit rows are NOT deleted. They record what happened when it happened, and they keep their account_id, so the trail of a removed account survives it (spec sections 4.3, 4.7, 12.4).

func (*Store) EvictMediaCacheLRU

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

EvictMediaCacheLRU deletes least-recently-used unpinned entries until the cache fits maxBytes, and returns the relative paths it removed rows for.

The rows go inside the transaction and the files are unlinked by the caller after the commit: the eviction sweep finds every file it deletes through those rows, so deleting a row without its file leaks a byte budget that silently stops matching the disk (spec section 10.3).

func (*Store) ExpireUploads

func (s *Store) ExpireUploads(ctx context.Context) ([]string, error)

ExpireUploads marks every reservation past its expiry. It returns the staged paths of the rows it expired so the caller can unlink them after the commit, in the erasure order of spec section 10.3.

func (*Store) FillMissingAttachmentSize

func (s *Store) FillMissingAttachmentSize(ctx context.Context, messageID string, size int64) error

FillMissingAttachmentSize writes a plaintext size onto this message's attachments that have none.

It exists because Google's echo of media WE sent carries a MediaContent with no Size, so the attachment row is written sizeless while the byte count is sitting on the operation that sent it (migration 0005). A size already on the row wins: Google's own number for an incoming attachment is never second-guessed, and this is a fill, not a correction.

func (*Store) ForeignKeyCheck

func (s *Store) ForeignKeyCheck(ctx context.Context) ([]string, error)

ForeignKeyCheck runs PRAGMA foreign_key_check and returns the offending rows. It must be empty after every migration (spec section 4.3).

func (*Store) InsertOperation

func (s *Store) InsertOperation(ctx context.Context, o Operation) error

InsertOperation writes a new operation in `running`. The row exists before the backend call, so a crash between the two is recoverable (spec sections 6.2, 6.6).

func (*Store) KeyUsedByAnotherAccount

func (s *Store) KeyUsedByAnotherAccount(ctx context.Context, authorizationID, kind, key, accountID string) (string, bool, error)

KeyUsedByAnotherAccount answers the mirror hazard of spec section 6.3.

Because the account is part of the idempotency tuple, reusing a key against a *different* account is not a replay -- it is a new operation, and it sends a second real message to a real person. That is the safe direction for the store and the dangerous one for a caller that "retries" a failed send by switching accounts, so both agent-facing surfaces refuse it. This query names the account the key was first used with, so the refusal can say which one.

func (*Store) LinkMessageOperation

func (s *Store) LinkMessageOperation(ctx context.Context, messageID, operationID string) error

LinkMessageOperation writes the op_ ID of the send this message is the echo of, which is the reverse of operations.message_id.

Both directions are written at the same moment, in correlateEcho, because only one of them was: `messages.operation_id` was declared in section 4.2, served in every message DTO, and never written by anything -- so "which send produced this message" was null on every row Agent GM had ever stored, and a caller reading it got a definite "there was no operation" for a message its own send had produced.

It is written once and never overwritten: a message belongs to the send that produced it, and a later echo of the same message is the same send.

func (*Store) ListAuditEvents

func (s *Store) ListAuditEvents(ctx context.Context, q AuditQuery) ([]AuditEvent, error)

ListAuditEvents serves the audit listing.

func (*Store) ListBackups

func (s *Store) ListBackups(dataDir string) ([]string, error)

ListBackups returns the snapshots in the data directory, oldest first.

func (*Store) ListContacts

func (s *Store) ListContacts(ctx context.Context, q ContactQuery) ([]Contact, error)

ListContacts serves GET /v1/contacts in both forms.

func (*Store) ListConversations

func (s *Store) ListConversations(ctx context.Context, q ConversationQuery) ([]Conversation, error)

ListConversations serves GET /v1/conversations in both forms.

func (*Store) ListMessages

func (s *Store) ListMessages(ctx context.Context, q MessageQuery) ([]Message, error)

ListMessages serves the message listings in both forms. A conversation_id already implies its account, so it satisfies the account predicate on its own (spec section 4.1).

func (*Store) ListOperations

func (s *Store) ListOperations(ctx context.Context, q OperationQuery) ([]Operation, error)

ListOperations serves GET /v1/operations in both forms.

func (*Store) MediaCacheBytes

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

MediaCacheBytes is the cache's current size. The budget is global across accounts, not per account: one account's backfill can evict another's cached media, and that is fine because the cache is a cache (spec section 10.3).

func (*Store) MediaCacheEntry

func (s *Store) MediaCacheEntry(ctx context.Context, attachmentID string) (MediaCacheEntry, error)

MediaCacheEntry reads one entry.

func (*Store) Message

func (s *Store) Message(ctx context.Context, id string) (Message, error)

Message reads one message by its msg_ ID.

func (*Store) MessageByTmpID

func (s *Store) MessageByTmpID(ctx context.Context, accountID, tmpID string) (Message, error)

MessageByTmpID finds the message the phone echoed back for one send attempt, correlating by tmp_id within the account (spec section 6.3).

func (*Store) MessageContextAround

func (s *Store) MessageContextAround(ctx context.Context, messageID string, before, after int, includeSystem bool) (MessageContext, error)

MessageContextAround serves GET /v1/messages/{id}/context. before and after default to 5 and cap at 100 (spec section 7.4).

func (*Store) Messages

func (s *Store) Messages(ctx context.Context, f MessageFilter) ([]Message, error)

Messages lists messages, newest first with the ID as the tiebreaker. System events are excluded unless IncludeSystem is set.

func (*Store) Meta

func (s *Store) Meta(ctx context.Context, key string) (string, bool, error)

Meta reads one server_meta key.

func (*Store) MintDownloadTicket

func (s *Store) MintDownloadTicket(ctx context.Context, t DownloadTicket) (DownloadTicket, error)

MintDownloadTicket writes a ticket row keyed by the token hash.

func (*Store) OAuthClientByID

func (s *Store) OAuthClientByID(ctx context.Context, id string) (OAuthClient, error)

OAuthClientByID reads one registration, read-only.

func (*Store) OAuthClients

func (s *Store) OAuthClients(ctx context.Context) ([]OAuthClient, error)

OAuthClients lists every registration, newest first.

func (*Store) Operation

func (s *Store) Operation(ctx context.Context, id string) (Operation, error)

Operation reads one operation by its op_ ID.

func (*Store) OperationByKey

func (s *Store) OperationByKey(ctx context.Context, authorizationID, accountID, kind, key string) (Operation, error)

OperationByKey is the idempotency lookup. Uniqueness is scoped to (authorization, account, kind, key): the same key sending to two accounts is two operations, because it is two messages to two people (spec section 6.3).

func (*Store) OperationByTmpID

func (s *Store) OperationByTmpID(ctx context.Context, accountID, tmpID string) (Operation, error)

OperationByTmpID correlates the remote echo back to its send attempt, within the account (spec section 6.3).

func (*Store) Participants

func (s *Store) Participants(ctx context.Context, conversationID string) ([]gm.Participant, error)

Participants lists one conversation's participant set.

func (*Store) Path

func (s *Store) Path() string

Path is the database file.

func (*Store) PruneBackups

func (s *Store) PruneBackups(dataDir string, keep int) ([]PrunedBackup, error)

PruneBackups keeps the newest `keep` snapshots and removes the rest, returning what it removed so each can be audited as `admin.backup_pruned`.

Two rules from spec section 15.2, both load-bearing:

  • **Pruning never touches a file that is not named `agent-gm-<timestamp>-<id>.sqlite3`.** An operator's own copy, a README, a partially transferred file: none of them are this function's business, and a pruner that deleted whatever it found in a directory called "backups" would eventually delete something irreplaceable.
  • **A file it cannot delete is reported and left**, rather than failing a backup that had already succeeded. The snapshot the caller asked for exists; a permission problem on an old one is a separate matter.

**Retention counts calls, not days.** An hourly cron with `backup.keep=7` keeps seven hours, which is worth knowing before relying on it for a week's cover.

func (*Store) PutMediaCacheEntry

func (s *Store) PutMediaCacheEntry(ctx context.Context, e MediaCacheEntry) error

PutMediaCacheEntry inserts or replaces one cached file's row.

func (*Store) Reaction

func (s *Store) Reaction(ctx context.Context, id string) (Reaction, error)

Reaction reads one reaction by its react_ ID.

func (*Store) ReactionsForMessage

func (s *Store) ReactionsForMessage(ctx context.Context, messageID string) ([]Reaction, error)

ReactionsForMessage lists one message's reactions.

func (*Store) Reader

func (s *Store) Reader() *sql.DB

Reader is the read-only pool. Every query it serves must carry an account_id predicate or an explicit all-accounts marker (spec section 13.2).

func (*Store) ReapPendingOperations

func (s *Store) ReapPendingOperations(ctx context.Context, timeoutMS int64) ([]Operation, error)

ReapPendingOperations settles every `pending` operation older than the timeout, measured from created_at_ms, to `unknown`. Like crash recovery it is process-wide (spec section 6.6).

func (*Store) RecoverRunningOperations

func (s *Store) RecoverRunningOperations(ctx context.Context) ([]Operation, error)

RecoverRunningOperations is the crash sweep of spec section 6.6. It runs at startup, before the listener binds, and it is process-wide rather than per-account on purpose: a crash is a property of the process, so every account's in-flight operations are settled at once.

It returns the rows it settled, each carrying its account_id, so the caller can write one operation.crash_recovered audit row per row. Nothing is retried: if the send did reach Google, the remote echo will arrive on reconnect and correct the operation to succeeded, which is exactly why the correction out of `unknown` exists.

A `pending` operation is left alone here; the reaper settles it.

func (*Store) RedeemDownloadTicket

func (s *Store) RedeemDownloadTicket(ctx context.Context, tokenHash string) (DownloadTicket, error)

RedeemDownloadTicket increments `redemptions` in the same transaction that authorises the read, and refuses the redemption past the cap or past the expiry. The counter therefore survives a restart, which is what makes "the sixth fails" true across one (spec section 16 test 18).

func (*Store) RelinkAccountContacts

func (s *Store) RelinkAccountContacts(ctx context.Context, accountID string) error

RelinkAccountContacts re-runs the participant-to-contact link for a whole account, for the ingest pass that learns contacts after the conversations that mention them.

func (*Store) ReplaceReactions

func (s *Store) ReplaceReactions(ctx context.Context, conversationID, messageID, myParticipantID string, rs []gm.Reaction) error

ReplaceReactions is a SET-REPLACE of one message's whole reaction set (spec section 5.3 step 7). Google sends the complete set on every change, so a merge would resurrect a reaction that was removed while Agent GM was not listening; the delete and the insert therefore share one transaction.

myParticipantID names this account's own participant in the thread, so is_mine is decided here rather than guessed by a later reader; pass "" when it is not known.

conversationID is needed because a reaction's participant is stored as a derived `part_` ID, never as Google's own participant ID: section 4.1 says a caller never sees a raw Google participant ID on a public surface, and `reactions.participant_id` is served straight through on the message DTO. In a real deployment that raw value embeds the owner's Google account ADDRESS, which section 12.2 restricts to /v1/accounts and /v1/health.

func (*Store) ReserveUpload

func (s *Store) ReserveUpload(ctx context.Context, u Upload) (Upload, error)

ReserveUpload writes a new reservation in `reserved`. Only the token's hash is stored; the value is signed with the ticket key and leaves the process once (spec sections 10.3, 12.1).

func (*Store) ResolveParticipant

func (s *Store) ResolveParticipant(ctx context.Context, raw string) (participantID, phone string, err error)

ResolveParticipant turns the caller's `participant` or `sender` spelling into the one indexed form the SQL uses. It accepts a part_ ID, a contact_ ID (resolved to that contact's number) or a phone number.

A contact_ ID is resolved rather than matched directly because participants carries no index on contact_id: matching it there would scan the table the section 16 test 39 forbids scanning.

func (*Store) RevokeAdminAuthorizationsFromOtherSecrets

func (s *Store) RevokeAdminAuthorizationsFromOtherSecrets(ctx context.Context, generation string) ([]string, error)

RevokeAdminAuthorizationsFromOtherSecrets revokes every unrevoked admin bootstrap authorization whose secret_generation is not `generation`, and revokes their tokens with them. It returns the IDs it revoked.

This is spec section 12.1's guarantee in one call: changing AGENT_GM_ADMIN_SECRET revokes every previous admin bootstrap authorization on the next start. It runs before any listener binds, so there is no window in which a session minted by the retired secret answers a request.

func (*Store) SearchMessages

func (s *Store) SearchMessages(ctx context.Context, q SearchQuery) ([]SearchResult, error)

SearchMessages serves GET /v1/search/messages in both forms.

func (*Store) SetAccountBackfillComplete

func (s *Store) SetAccountBackfillComplete(ctx context.Context, accountID string, at time.Time) error

SetAccountBackfillComplete records when THIS account finished its initial backfill (spec section 5.2 step 7).

Unlike the sweep timestamp this is set once and is not monotonic: a re-backfill after a re-pair legitimately re-stamps it, and an operator asking "when did this account last finish walking its history?" wants the latest answer rather than the first. Passing the zero time clears it, which is what re-opening a backfill does.

func (*Store) SetAccountLabel

func (s *Store) SetAccountLabel(ctx context.Context, accountID, label string) error

SetAccountLabel sets the owner's human label. It is never an ID.

func (*Store) SetAccountLastSweep

func (s *Store) SetAccountLastSweep(ctx context.Context, accountID string, at time.Time) error

SetAccountLastSweep records when this account's reconciliation sweep last ran (spec section 5.4 step 4).

It moves only forward, like TouchAccountEvent: two sweeps for one account can overlap -- a timer sweep and a BROWSER_ACTIVE sweep, say -- and the slower one finishing second must not rewind the record and cause the next sweep to re-walk ground the faster one already covered.

It is a column on accounts and never a server_meta key: two accounts would race on one row and the first to finish would mark the whole server swept (spec sections 4.2, 5.2).

func (*Store) SetAccountState

func (s *Store) SetAccountState(ctx context.Context, accountID string, state AccountState, reason string) error

SetAccountState moves one account's state, with its machine-readable reason. No event from one account ever changes another's state.

func (*Store) SetAttachmentDownloadState

func (s *Store) SetAttachmentDownloadState(ctx context.Context, attachmentID, state, sha256hex string) error

SetAttachmentDownloadState records the outcome of a fetch, with the SHA-256 of the bytes when there are any.

func (*Store) SetBackfillState

func (s *Store) SetBackfillState(ctx context.Context, b BackfillState) error

SetBackfillState writes one conversation's progress.

func (*Store) SetMediaCachePinned

func (s *Store) SetMediaCachePinned(ctx context.Context, attachmentID string, pinned bool) error

SetMediaCachePinned pins or unpins an entry, so an in-flight download or an open ticket is not evicted underneath itself (spec section 4.2).

func (*Store) SetMeta

func (s *Store) SetMeta(ctx context.Context, key, value string) error

SetMeta writes one server_meta key. Nothing account-shaped lives here: every per-account fact is a column on accounts, because two accounts would otherwise race on one row (spec section 4.2).

func (*Store) SetOperationMediaSize

func (s *Store) SetOperationMediaSize(ctx context.Context, operationID string, size int64) error

SetOperationMediaSize records the plaintext size of the media this operation is about to send, before the library call, so the echo that arrives later -- possibly after a restart -- can put it on the attachment row Google's own echo leaves sizeless (spec section 5.3, step 8).

func (*Store) SetOperationTmpID

func (s *Store) SetOperationTmpID(ctx context.Context, operationID, tmpID string) error

SetOperationTmpID records the bare UUID sent as TmpID, before the library call. A retry within one request reuses the same tmp_id, so a retried send cannot produce two correlations (spec section 6.3).

func (*Store) SetSessionPresent

func (s *Store) SetSessionPresent(ctx context.Context, accountID string, present bool) error

SetSessionPresent records whether sessions/<id>.enc is on disk.

func (*Store) SetSetting

func (s *Store) SetSetting(ctx context.Context, key, valueJSON string) error

SetSetting writes one key's JSON value.

func (*Store) SetUploadToken

func (s *Store) SetUploadToken(ctx context.Context, uploadID, tokenHash string) error

SetUploadToken replaces a reservation's token hash. A repeat reservation returns a fresh token because the first token's value left the process and cannot be recovered; the new token never outlives the reservation it fills (spec section 10.3).

func (*Store) Setting

func (s *Store) Setting(ctx context.Context, key string) (Setting, error)

Setting reads one key.

func (*Store) Settings

func (s *Store) Settings(ctx context.Context) ([]Setting, error)

Settings lists every stored override, in key order.

func (*Store) SettleOperation

func (s *Store) SettleOperation(ctx context.Context, operationID string, st Settlement) (Operation, error)

SettleOperation applies spec section 6.4's transition table.

terminal_at_ms records when the operation *first* became terminal and is never cleared or rewritten: a wait that was satisfied by `unknown` is not retroactively unsatisfied. corrected_at_ms is set when a late fact moves it out of `unknown`.

func (*Store) SweepAbandonedPairings

func (s *Store) SweepAbandonedPairings(ctx context.Context, live map[string]bool, olderThan time.Duration) ([]string, error)

SweepAbandonedPairings deletes every `pairing` row older than the timeout whose ID is not in live. It returns the IDs it deleted.

func (*Store) SweepExpiredTickets

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

SweepExpiredTickets deletes tickets past their expiry.

func (*Store) SweepIdempotencyKeys

func (s *Store) SweepIdempotencyKeys(ctx context.Context, ttlMS int64) (int64, error)

SweepIdempotencyKeys deletes operation rows past the retention window. It never deletes a row that is not terminal (spec section 6.6).

func (*Store) TokenByHash

func (s *Store) TokenByHash(ctx context.Context, hash string) (Token, error)

TokenByHash reads one token by its hash, read-only.

func (*Store) TouchAccountEvent

func (s *Store) TouchAccountEvent(ctx context.Context, accountID string, at time.Time) error

TouchAccountEvent moves an account's last_event_at_ms forward. It is a column on accounts, never a server_meta key: two accounts would race on one row (spec section 4.2).

func (*Store) TouchMediaCacheEntry

func (s *Store) TouchMediaCacheEntry(ctx context.Context, attachmentID string) error

TouchMediaCacheEntry moves an entry to the head of the LRU.

func (*Store) UpdateAttempt

func (s *Store) UpdateAttempt(ctx context.Context, kind, source string, fn func(Attempt) Attempt) (Attempt, error)

UpdateAttempt is the read-modify-write of one oauth_attempts row, inside one transaction on the single writer. fn receives the current row (zero-valued and with Kind/Source filled in if there is none) and returns the row to store. Returning the row unchanged still writes it, so a caller that only wants to read should use AttemptRow.

func (*Store) Upload

func (s *Store) Upload(ctx context.Context, id string) (Upload, error)

Upload reads one reservation by its upl_ ID.

func (*Store) UploadByIdempotencyKey

func (s *Store) UploadByIdempotencyKey(ctx context.Context, authorizationID, key string) (Upload, error)

UploadByIdempotencyKey finds a caller's earlier reservation for the same key, so a repeat returns the same reservation with a fresh token.

func (*Store) UploadByTokenHash

func (s *Store) UploadByTokenHash(ctx context.Context, tokenHash string) (Upload, error)

UploadByTokenHash finds the reservation a presented upload token names.

func (*Store) UpsertAccount

func (s *Store) UpsertAccount(ctx context.Context, a Account) error

UpsertAccount creates the account row or updates the mutable fields of an existing one. Re-pairing an existing account resumes it: the acct_ ID is derived from the address, so the same Google account -- even on a different phone -- lands on the same row (spec sections 3.2, 4.7).

func (*Store) UpsertAttachment

func (s *Store) UpsertAttachment(ctx context.Context, accountID, messageID string, a gm.Attachment, sealedKey []byte, downloadState string) (string, error)

UpsertAttachment writes one media part under its message, stamping account_id on the row so a cross-account attachment listing is attributable. sealedKey is the already-sealed decryption key, or nil.

func (*Store) UpsertContact

func (s *Store) UpsertContact(ctx context.Context, accountID string, c gm.Contact, avatarHash string) (string, error)

UpsertContact writes one contact under its account and returns its contact_ ID. avatarHash is a SHA-256 of the avatar bytes or empty: Agent GM stores the hash so a caller can detect a change, never the picture (spec section 7.6).

func (*Store) UpsertConversation

func (s *Store) UpsertConversation(ctx context.Context, accountID string, c gm.Conversation) (string, error)

UpsertConversation writes a conversation and replaces its participant set, stamping account_id on every row. Backfill and live ingestion write through this same function; there is no separate backfill writer whose behaviour could drift (spec section 5.1).

func (*Store) UpsertMessage

func (s *Store) UpsertMessage(ctx context.Context, accountID, convSourceID string, m gm.Message) (UpsertMessageResult, error)

UpsertMessage is spec section 5.3 steps 3-5 and the transition rules of spec section 4.4. It is the only writer of message rows, shared by backfill and the live stream.

func (*Store) UpsertParticipants

func (s *Store) UpsertParticipants(ctx context.Context, accountID, conversationID string, ps []gm.Participant) error

UpsertParticipants replaces one conversation's participant set, stamping account_id on every row. It is the same write UpsertConversation performs inline, exposed for the contact-linking pass that runs after contacts are known.

func (*Store) Version

func (s *Store) Version() (int, error)

Version reports the database's current schema version.

func (*Store) Write

func (s *Store) Write(ctx context.Context, fn func(*sql.Tx) error) error

Write runs fn on the single writer goroutine, inside one transaction.

type Token

type Token struct {
	TokenHash       string
	AuthorizationID string
	Kind            string
	FamilyID        string
	SpentAtMS       int64
	RevokedAtMS     int64
	ExpiresAtMS     int64
	CreatedAtMS     int64
}

Token is one row of `tokens`. Value is never stored: TokenHash is the primary key and the only representation the database ever sees.

func (Token) Revoked

func (t Token) Revoked() bool

Revoked reports whether this token was revoked.

func (Token) Spent

func (t Token) Spent() bool

Spent reports whether this token has already been redeemed. Presenting a spent refresh token is reuse, and reuse revokes the family (spec section 9.6).

type Upload

type Upload struct {
	ID              string
	AuthorizationID string
	IdempotencyKey  string
	Filename        string
	MimeType        string
	SizeBytes       int64
	SHA256Declared  string
	State           string
	TokenHash       string
	Redemptions     int
	StagedPath      string
	ExpiresAtMS     int64
	CreatedAtMS     int64
}

Upload is one staged-bytes reservation.

Uploads carry NO account_id, deliberately: an upl_ reservation is bytes staged by an authorization, and the account is fixed at send time by the conversation named in the send (spec section 10.2). An upload reserved with no account in mind therefore sends into any of them, exactly once.

type UpsertMessageResult

type UpsertMessageResult struct {
	ID                string
	Inserted          bool
	Updated           bool
	TransitionRefused bool
	PreviousState     string
}

UpsertMessageResult reports what an upsert did, so the caller can tell a no-op from a write and audit a refused transition.

Jump to

Keyboard shortcuts

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