Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(oauth): cap issued access tokens at 90 days and refuse an out-of-range serve --token-ttl (#5040)

time-attacke9681c04cb1e
diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.md
index 8089d0c0cc..3979dd8a4c 100644
--- a/docs/architecture/key-files/commands-1.md
+++ b/docs/architecture/key-files/commands-1.md
@@ -13,7 +13,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/anomalies.ts` — `gbrain anomalies [--since YYYY-MM-DD] [--lookback-days N] [--sigma N] [--json]`: cohort-level activity outliers. Calls `engine.findAnomalies(opts)`. Two cohort kinds: tag, type.
-- `src/commands/auth.ts` — token management. `gbrain auth create/list/revoke/test` for legacy bearer tokens (`create --scopes read,write` narrows a token via the `scopes TEXT[]` column with mint-time validation — a typo'd scope refuses loudly, never silently denies or widens; `list` shows id + scopes columns with grandfathered rows rendered honestly; `revoke --id <uuid>` revokes exactly one row since names are not unique, and bulk revoke-by-name says when it hit several; `permissions set-takes-holders` MERGES into the permissions JSONB via `COALESCE(permissions,'{}'::jsonb) || $2::jsonb` — a whole-object replace would silently wipe the `source_id` federation grant; it is the takes-holders alias of `rescope-token`), `gbrain auth rescope-token <name>|--id <uuid>` (the legacy-token twin of `rescope-client`, logic in `src/core/grants/legacy-token.ts`: `--sources`/`--takes-holders`/`--operations` take a list or `none` = explicit empty list, omitted flags preserve, `--reset-default` restores the `auth create` defaults, `--refresh-operations` previews and widens only by `--add`/`--all-new`; pinned by `test/auth-rescope-token.serial.test.ts`), plus `gbrain auth register-client` and `gbrain auth revoke-client <client_id>` for OAuth 2.1 client lifecycle. `revoke-client` runs an atomic `DELETE...RETURNING` on `oauth_clients`; FK `ON DELETE CASCADE` on `oauth_tokens.client_id` and `oauth_codes.client_id` purges every active token + auth code in one transaction; `process.exit(1)` on no-such-client (idempotent). Legacy tokens stored as SHA-256 hashes in `access_tokens`; OAuth clients in `oauth_clients`; legacy tokens with no scopes grant grandfather to `read+write+admin` on the OAuth HTTP server (no migration); scoped tokens are honored at exactly their grant. Every SQL site routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` (and `executeRawJsonb` for the takes-holders `permissions` JSONB column) so `gbrain auth` works against PGLite; the takes-holders write goes through `executeRawJsonb(engine, sql, [name, hash], [{takes_holders:[...]}])` which round-trips with `jsonb_typeof = 'object'`. `register-client` accepts `--source <id>` (write authority, scalar), `--federated-read <S1,S2,...>` (read scope, array), and `--token-ttl <seconds>` (per-client access-token TTL persisted to `oauth_clients.token_ttl`, bounds `TOKEN_TTL_MIN_SECONDS`=60 to `TOKEN_TTL_MAX_SECONDS`=7,776,000/90d) and prints the resolved `Write source` + `Federated reads`; clients without a `source_id` backfill to `'default'` via migration v60. The registration core is the exported `registerScopedClient(sql, engine, name, parsed, opts)` — exit-free, print-free, injected-handle (engine-bound callers like `agent register` pass the dispatcher's engine; a second `withConfiguredSql` engine self-deadlocks PGLite's single-writer lock), returns a `RegisteredClient` data object and throws on failure; the thin CLI wrapper owns exit/print. Its printer `formatRegisterClientOutput` is a BYTE-PINNED contract (connect.ts's `defaultRegisterOAuthClient` regex-scrapes `Client ID:`/`Client Secret:` from it in production) — pinned by `test/auth-register-client-output-pin.test.ts`. `preflightOauthClientColumns(sql)` probes `information_schema.columns` for the optional columns (`token_ttl`, `surface`, `federated_read`, `source_id`, `deleted_at`) so statement shapes are decided BEFORE any transaction — Postgres/PGLite abort the whole tx on any statement error (25P02) and SqlQuery has no savepoint seam, so "catch 42703 and continue" inside a tx is impossible; skipped optional writes surface as `RegisteredClient.skipped` with an apply-migrations hint. `gbrain auth clients [--usage] [--days N] [--json]` lists clients with scopes, per-client surface, write source (`source_id`), federated reads (`federated_read`) and the operation snapshot — one projection-widened SELECT with a degrade ladder for pre-migration brains (drops the newest columns first, never errors); `clientOperationsView` reports four distinct operation states (SQL NULL = `operations: "all"` with `includes_future_operations: true` and a re-pin `fix` naming `auth rescope --client <id> --operations <list>` or `--profile`; `[]` = deny-all; an explicit list; `unavailable` when the schema predates `allowed_operations`) and marks soft-revoked clients (`deleted_at`) `revoked` with no fix (`test/auth-clients-operations.test.ts`, both engines); `--usage` joins per-client op-call counts via `src/core/mcp-usage.ts`. The bare `gbrain auth create <name>` form (no `--takes-holders`) mints a token via the exported pure `parseAuthCreateArgs(rest)`. Pinned by `test/auth-create-args.test.ts` + `test/auth-register-client-args.test.ts`. F3: `gbrain auth rescope` (`runRescope`) is the one grant editor for tokens (`--token`/`--id`) and OAuth clients (`--client`), with a bare-name resolver, `--migrate-legacy [--dry-run]`, and refusals printed as JSON on stdout under `--json`; `rescope-token`, `rescope-client` and `permissions set-takes-holders` are aliases routed through it.
+- `src/commands/auth.ts` — token management. `gbrain auth create/list/revoke/test` for legacy bearer tokens (`create --scopes read,write` narrows a token via the `scopes TEXT[]` column with mint-time validation — a typo'd scope refuses loudly, never silently denies or widens; `list` shows id + scopes columns with grandfathered rows rendered honestly; `revoke --id <uuid>` revokes exactly one row since names are not unique, and bulk revoke-by-name says when it hit several; `permissions set-takes-holders` MERGES into the permissions JSONB via `COALESCE(permissions,'{}'::jsonb) || $2::jsonb` — a whole-object replace would silently wipe the `source_id` federation grant; it is the takes-holders alias of `rescope-token`), `gbrain auth rescope-token <name>|--id <uuid>` (the legacy-token twin of `rescope-client`, logic in `src/core/grants/legacy-token.ts`: `--sources`/`--takes-holders`/`--operations` take a list or `none` = explicit empty list, omitted flags preserve, `--reset-default` restores the `auth create` defaults, `--refresh-operations` previews and widens only by `--add`/`--all-new`; pinned by `test/auth-rescope-token.serial.test.ts`), plus `gbrain auth register-client` and `gbrain auth revoke-client <client_id>` for OAuth 2.1 client lifecycle. `revoke-client` runs an atomic `DELETE...RETURNING` on `oauth_clients`; FK `ON DELETE CASCADE` on `oauth_tokens.client_id` and `oauth_codes.client_id` purges every active token + auth code in one transaction; `process.exit(1)` on no-such-client (idempotent). Legacy tokens stored as SHA-256 hashes in `access_tokens`; OAuth clients in `oauth_clients`; legacy tokens with no scopes grant grandfather to `read+write+admin` on the OAuth HTTP server (no migration); scoped tokens are honored at exactly their grant. Every SQL site routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` (and `executeRawJsonb` for the takes-holders `permissions` JSONB column) so `gbrain auth` works against PGLite; the takes-holders write goes through `executeRawJsonb(engine, sql, [name, hash], [{takes_holders:[...]}])` which round-trips with `jsonb_typeof = 'object'`. `register-client` accepts `--source <id>` (write authority, scalar), `--federated-read <S1,S2,...>` (read scope, array), and `--token-ttl <seconds>` (per-client access-token TTL persisted to `oauth_clients.token_ttl`, bounds `TOKEN_TTL_MIN_SECONDS`=60 to `TOKEN_TTL_MAX_SECONDS`=7,776,000/90d) and prints the resolved `Write source` + `Federated reads`; clients without a `source_id` backfill to `'default'` via migration v60. The registration core is the exported `registerScopedClient(sql, engine, name, parsed, opts)` — exit-free, print-free, injected-handle (engine-bound callers like `agent register` pass the dispatcher's engine; a second `withConfiguredSql` engine self-deadlocks PGLite's single-writer lock), returns a `RegisteredClient` data object and throws on failure; the thin CLI wrapper owns exit/print. Its printer `formatRegisterClientOutput` is a BYTE-PINNED contract (connect.ts's `defaultRegisterOAuthClient` regex-scrapes `Client ID:`/`Client Secret:` from it in production) — pinned by `test/auth-register-client-output-pin.test.ts`. `preflightOauthClientColumns(sql)` probes `information_schema.columns` for the optional columns (`token_ttl`, `surface`, `federated_read`, `source_id`, `deleted_at`) so statement shapes are decided BEFORE any transaction — Postgres/PGLite abort the whole tx on any statement error (25P02) and SqlQuery has no savepoint seam, so "catch 42703 and continue" inside a tx is impossible; skipped optional writes surface as `RegisteredClient.skipped` with an apply-migrations hint. `gbrain auth clients [--usage] [--days N] [--json]` lists clients with scopes, per-client surface, write source (`source_id`), federated reads (`federated_read`) and the operation snapshot — one projection-widened SELECT with a degrade ladder for pre-migration brains (drops the newest columns first, never errors); `clientOperationsView` reports four distinct operation states (SQL NULL = `operations: "all"` with `includes_future_operations: true` and a re-pin `fix` naming `auth rescope --client <id> --operations <list>` or `--profile`; `[]` = deny-all; an explicit list; `unavailable` when the schema predates `allowed_operations`) and marks soft-revoked clients (`deleted_at`) `revoked` with no fix (`test/auth-clients-operations.test.ts`, both engines); `tokenLifetimeClampedClients` reads the migration's `clamp_token_ttl` / `shorten_access_tokens` audit rows so the listing marks clients whose access-token lifetime an upgrade brought inside 90 days (`token_lifetime_clamped` in `--json`); the `TOKEN_TTL_*` bounds are re-exported from `src/core/grants/model.ts`; `--usage` joins per-client op-call counts via `src/core/mcp-usage.ts`. The bare `gbrain auth create <name>` form (no `--takes-holders`) mints a token via the exported pure `parseAuthCreateArgs(rest)`. Pinned by `test/auth-create-args.test.ts` + `test/auth-register-client-args.test.ts`. F3: `gbrain auth rescope` (`runRescope`) is the one grant editor for tokens (`--token`/`--id`) and OAuth clients (`--client`), with a bare-name resolver, `--migrate-legacy [--dry-run]`, and refusals printed as JSON on stdout under `--json`; `rescope-token`, `rescope-client` and `permissions set-takes-holders` are aliases routed through it.
- `src/commands/autopilot-pause.ts` — engine-free `gbrain autopilot pause [--reason <text>]` / `resume`: writes or removes the operator marker `autopilot-operator-paused` (`autopilotOperatorPauseMarkerPath` in `src/core/autopilot-paths.ts`, with `autopilotPaused()` and `autopilotPauseReason()`). The daemon loop and job workers honor it like the migration hold; `--install` (and so `gbrain upgrade`) clears only a leaked migration hold, and resume never clears a migration or restore hold. Test: `test/autopilot-operator-pause.test.ts`.
- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity `pull` value derived from the source's parsed `remote_url`, so local-only sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes `detectTini()` from `src/core/minions/spawn-helpers.ts`, resolved once at startup. Composes a `ChildWorkerSupervisor` instance for spawn-and-respawn with `--max-rss 2048` and soft `maxCrashes: 5`, preferring the current source/compiled CLI over PATH. The child worker performs private-queue recovery only after its driver/selected-child readiness and schema check; autopilot does not duplicate that recovery before spawn. A configuration-blocked child leaves the owning daemon alive and heartbeating but gates dispatch, worker restarts and engine work until explicit owner restart after repair. `--status --json` adds processing readiness, reason and runtime identities without replacing existing freshness/exit semantics; see [the owner-specific repair guide](../../guides/minions-fix.md). `onMaxCrashesExceeded` routes through autopilot's own `shutdown('max_crashes')` so the autopilot lockfile gets cleaned up. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Pinned by `test/autopilot-fanout-wiring.test.ts` and `test/autopilot-supervisor-wiring.test.ts` (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, `--max-rss 2048` in argv, `maxCrashes: 5` literal, shutdown-via-callback, no workerProc reference). tick body invokes `runNightlyQualityProbe` when `cfg.autopilot.nightly_quality_probe.enabled === true` (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — `runNightlyQualityProbe`'s internal `shouldRunNightly` (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via `logError` and does NOT bump `consecutiveErrors` (probe failure is informational, never crashes the loop). Default `max_usd` cap = 5. Pinned by `test/autopilot-nightly-probe-wiring.test.ts`. per-source `extract_atoms` auto-drain. Postgres-only block after the freshness fan-out: gated on `autopilot.auto_drain.enabled` (default true) AND `!packDeclaresPhase(engine,'extract_atoms')` (the silent-backlog condition) AND per-source `countExtractAtomsBacklog > threshold` (default 25) AND a daily cap `floor(max_usd_per_day / ~$0.30)`. Enumerates `loadAllSources`. Submits the PROTECTED `extract-atoms-drain` job (`{allowProtectedSubmit:true}`) with a UTC-day time-sloted idempotency key `autopilot-extract-atoms-drain:<src.id>:<utcDay>` (a static key would block the source after the first job completed). `src/core/minions/protected-names.ts` lists `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`; a `provider_failure` result throws `formatDrainProviderFailure(result)` — batches/remaining plus the drain's sanitized `last_error` — so the dead-lettered job's `error_text` names the cause, e.g. a missing provider key); `src/core/config.ts` carries the `autopilot.auto_drain.*` config keys + the `autopilot.` key prefix. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`. federated-brain co-existence + launchd hygiene. (1) `LOCK_PATH` resolves via `gbrainPath('autopilot.lock')` so it honors `GBRAIN_HOME` (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID; `src/core/autopilot-lock.ts` checks liveness and the process command before takeover. `looksLikeGbrainAutopilotCommand` recognizes quoted or unquoted `cli.ts` / `cli.js` / `cli.mjs` paths, including spaces and normalized Windows separators, so a live matching autopilot retains even an old lock. Synthetic command-line and lock-decision cases are pinned by `test/autopilot-lock.test.ts`; they are not native Windows process-probe validation. (2) exported `classifyReconnectError(err)` returns `'recoverable' | 'unrecoverable'`; unrecoverable causes `process.exit(0)` so launchd backs off instead of looping `config.database_url undefined`. (3) exported pure `generateLaunchdPlist(wrapperPath, home)` sets `ThrottleInterval=300` so launchd respects the exit-0 backoff. Pinned by `test/autopilot-lock-path.test.ts` + `test/autopilot-reconnect-classifier.test.ts`. targeted-submit loop instead of blanket `autopilot-cycle` dispatch. Each tick: cheap `engine.getHealth()` (single SQL count) + `computeRecommendations()`, then route by shape — `score >= 95 AND no plan AND <60min since last full` → sleep; `score >= 95 AND >=60min` → submit `autopilot-cycle` (60-min floor exercises phase-coupling invariants on healthy brains); `plan <= 3 steps AND est <5min` → submit individual handlers; `plan large OR score < 70` → submit full `autopilot-cycle`. The `gbrain-cycle` lock ensures targeted submissions and the full cycle can't run concurrently. `maxWaiting: 1` per submit closes the queue-fan-out vector. daemon env lane: `writeWrapperScript` additively sources `<gbrainDir>/env` (honors `GBRAIN_HOME`) after the shell profiles with a `set -a` wrap so dotenv-style `KEY=value` lines export too, and creates a fully-commented 0600 template on install (never overwritten, never chmod'd, never removed by uninstall; template excludes `GBRAIN_HOME` — the wrapper bakes it AFTER sourcing). Exported pure `chatBootWarning(chatAvailable, gbrainDir)` derives both remediation paths from the passed dir and prints via `console.log` at daemon boot (stdout is the autopilot.log sink on all four targets; stderr lands in the unsurfaced autopilot.err) using the bare global-model `isAvailable('chat')` probe on purpose (mirrors the bare-gated phases; facts extraction is model-aware and doctor owns it). Install is reload-safe so the warning's re-run-`--install` remediation is true: launchd unloads before load (bare load errors on a loaded agent), systemd `try-restart`s after `enable --now`, cron/container print a residual-process notice instead of auto-killing. Pinned by `test/autopilot-install.test.ts` (16 cases incl. real-bash wrapper execution). Once processing is configuration-blocked, `guardAutopilotEngine` refuses new engine calls (except disconnect), guards transaction callback engines, and rolls back a transaction whose callback finishes after the block; already committed work is not revoked. Pinned by `test/autopilot-transaction-fence.test.ts`. #5195: install, status and uninstall act on one brain's job, named by `resolveAutopilotJob()` in `src/core/autopilot-paths.ts` (default brain: the shared names; any other brain: `<name>-<suffix>` from the random install id in `<brain>/.gbrain/autopilot-install-id`, with move/copy semantics); crontab lines carry `# gbrain-autopilot:<suffix>`; every log sink writes under the brain's home; a pre-#5195 shared job that runs this brain is replaced on install and reported by `--status` as `needs_reinstall: legacy_shared_job`; replacing or removing a job whose wrapper runs another live brain is refused (`autopilot_job_owned_by_other_brain`). Job-definition reads, legacy replacement and the `--status` job report live in `src/commands/autopilot/jobs.ts`. Pinned by `test/autopilot-install-id.test.ts` and `test/e2e/autopilot-multi-brain.serial.test.ts`.
diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.md
index 76fde9f524..e3c41fbcf9 100644
--- a/docs/architecture/key-files/commands-5.md
+++ b/docs/architecture/key-files/commands-5.md
@@ -23,7 +23,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/serve-http.ts` — Express 5 HTTP MCP server with OAuth 2.1, admin dashboard, and SSE live activity feed. The legacy `POST /ingest` queue refuses operation-snapshot clients; they use approved MCP writes so execution stays inside the shared grant contract. Started via `gbrain serve --http [--port N] [--token-ttl N] [--enable-dcr] [--public-url URL] [--bind HOST] [--log-full-params]`. OAuth discovery's `scopes_supported` (RFC 8414 AS metadata and both RFC 9728 protected-resource documents, one value through the SDK router) comes from `scopesSupportedForDiscovery({ enableDcr })` in `src/core/scope.ts`: with `--enable-dcr` it is exactly the self-registration ceiling (`read write`), so a client that copies discovery into its `/register` request succeeds; without DCR it is every scope except operator-only `agent`. The DCR ceiling still rejects an explicit privileged request, and operator-registered clients are never narrowed by the advertisement. Combines MCP SDK's `mcpAuthRouter` (authorize/token/register/revoke), a custom `client_credentials` handler running BEFORE the router (SDK's token endpoint throws `UnsupportedGrantTypeError` for CC; custom handler falls through for `auth_code` / `refresh_token`), `requireBearerAuth` middleware for `/mcp` with scope enforcement + `localOnly` rejection before op dispatch, and per-IP `express-rate-limit` buckets: the MCP SDK's defaults on `/authorize` (100 / 15 min), `/register` (20 / hour) and `/token` (50 / 15 min) because `authRouterOptions` passes no `rateLimit: false`, the custom `client_credentials` handler's `ccRateLimiter`, and independent owner limits: 60 total authentication requests/min/IP, 10 failed authentications/min/IP (verified authority, independent of response status), and 60 consent requests/min/authenticated session in `serve-http-admin-limits.ts`. Admin no-store, no-referrer and framing headers precede login/link handlers. Explicit pending IDs survive fresh-browser links; invalid or restarted requests require native authorization to restart. Serves the built admin SPA from `admin/dist/` with SPA fallback. `/admin/events` SSE broadcasts every MCP request. `cookie-parser` wired (Express 5 has no built-in). Startup logging prints port, engine, issuer URL (honors `--public-url`), client count, DCR status, and the admin bootstrap token line — but the generated token's raw value only prints when stderr is an interactive TTY (`shouldSuppressBootstrapPrint`): a non-TTY (containerized/piped) start hides it so the secret never lands in centralized log storage, env-sourced tokens (`$GBRAIN_ADMIN_BOOTSTRAP_TOKEN`) are always hidden, `--print-admin-token` forces the raw value on a trusted terminal, and `--suppress-bootstrap-token` hides everything. The `/mcp` request handler's OperationContext literal sets `remote: true` explicitly (without it `submit_job`'s protected-name guard would see a falsy undefined and a `read+write`-scoped OAuth token could submit `shell` jobs). `summarizeMcpParams` from `src/mcp/dispatch.ts` feeds both `mcp_request_log` writes and the SSE feed by default (raw via `--log-full-params`). Cookie `Secure` flag set behind HTTPS or a public-URL proxy; magic-link nonce store LRU-bounded; DCR disable routes through the `GBrainOAuthProvider` `dcrDisabled` constructor option (not a router monkey-patch); `transport.handleRequest` wrapped in try/catch to return a JSON-RPC 500 envelope; OperationError + unexpected exceptions unified through `buildError` / `serializeError` so `/mcp` always returns the same envelope. `/health` is liveness-only via `probeLiveness(engine, engineName, version, timeoutMs)` racing `engine.executeRaw('SELECT 1', undefined, { signal })` against the exported `HEALTH_TIMEOUT_MS = 3000`; when the timeout wins, an `AbortController` cancels the Postgres query (PGLite can only discard its eventual result) before the same tagged `ProbeHealthResult` 503 envelope is returned (single timer-cleanup site); body shape `{status, version, engine}` only. Full stats live at admin-only `/admin/api/full-stats` (gated by `requireAdmin`, calls `probeHealth(engine, ...)`) — keeps `getStats()`'s 6× count(*) off the public route so a saturated pool doesn't trigger orchestrator restart cascades. OAuth/admin/audit SQL outside the abortable liveness probe routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` so it works against PGLite; the four `mcp_request_log.params` INSERT sites (success / auth_failed / scope_denied / server-error) go through `executeRawJsonb(engine, ...)` so the column stores real objects (`params->>'op'` returns `search`, not the quoted string). `--bind HOST` defaults `127.0.0.1` (self-hosters pass `--bind 0.0.0.0`); a stderr WARN fires when `--public-url` is set without `--bind`; the banner prints a `Bind:` line. `AuthInfo.sourceId` + `AuthInfo.allowedSources` + `AuthInfo.takesHoldersAllowList` are the typed source of truth, populated by `oauth-provider.ts:verifyAccessToken` (source scope from the `oauth_clients` row; takes-holders from `access_tokens.permissions.takes_holders` for legacy bearer tokens). The `/mcp` dispatch site reads `authInfo.takesHoldersAllowList ?? ['world']` — absent grants (OAuth-client tokens, pre-v29 brains) fail closed to world-only takes visibility, while an explicit `[]` grant is preserved as deny-all; pinned end-to-end by `test/e2e/serve-http-takes-holders.test.ts`. The HTTP MCP `tools/list` handler at `:837-849` uses `paramDefToSchema(v)` from `src/mcp/tool-defs.ts` so array params keep `items` (strict-mode OAuth clients otherwise reject the whole tool list). `POST /ingest` enforces the slug-prefix write fence at the ROUTE, not the op layer: the route hands its payload to the `ingest_capture` minion handler, which deliberately bypasses `put_page`, so no `OperationContext` exists and `enforceClientSlugFence` never runs — a slug-bound client must therefore supply `X-Gbrain-Slug` and it must satisfy `slugUnderBoundPrefixes`, else 403 (without the check a bound client could overwrite any page inside its granted source). The write source is resolved server-side as `authInfo.sourceId ?? 'default'` and travels on the job as `job.data.sourceId`; the caller-supplied `X-Gbrain-Source-Id` header routes nothing and only names the emitter (`webhook-<clientId>`), which is what the event's `source_id` and the 202's back-compat `source_id` field carry. The 202 additionally reports the routed destination as `write_source_id`, and the resolved write source joins the queue idempotency key so a rescoped client lands a new capture instead of deduping against its old job. confidential revoke: a pre-router `/revoke` handler validates the RFC 7009 body, verifies hash-only secrets for both `client_secret_post` and `client_secret_basic`, rejects mixed authentication, preserves the SDK path for public clients, and separates opaque client-auth failures from retryable/backend failures. OAuth metadata advertises both confidential methods. Pinned by `test/e2e/serve-http-oauth.test.ts`. three admin routes: `/admin/api/calibration/profile`, `/admin/api/calibration/charts/:type` (image/svg+xml; type in {brier-trend, domain-bars, pattern-statements, abandoned-threads}), `/admin/api/calibration/pattern/:id` (drill-down). The manual mint route `/admin/api/register-client` in `serve-http-registration.ts` accepts optional `source` + `federatedRead` bindings mirroring the CLI's `--source`/`--federated-read` (validated via `normalizeSourceInput`/`normalizeFederatedReadInput` from `src/core/source-id.ts`; omitting both preserves the default binding `source_id='default'` / `federated_read=[source_id]`, invalid values return a structured 400 `invalid_source`), so an admin SPA or provisioning proxy can mint a source-confined client over HTTP. The route mirrors the CLI lane end to end: structured 400s for `unknown_source` / `archived_source` (one batched `ANY($1::text[])` existence check), `invalid_token_ttl` (shared `TOKEN_TTL_MIN/MAX_SECONDS` bounds, integer-validated BEFORE the tx), and `brain_too_old` (column pre-flight OUTSIDE the tx — a pre-scoped-clients brain refuses up front instead of aborting mid-transaction); the duplicate-name pre-check + INSERT run in ONE transaction under the SAME name-scoped advisory lock the CLI takes (`registerClientNameLockKey`), returning 409 `duplicate_name` with the existing `client_id`; the INSERT composes `registerScopedClient` (the CLI's registration core) so the two paths cannot drift; any post-commit failure includes the created `client_id` so the operator can revoke (never a false "nothing was created"). Pinned by `test/register-client-source-normalize.test.ts`. The `/mcp` tools/list is the honest catalog: per-request filters (token scope incl. the `agentCallable` carve-out, bound-client fence via `opAllowedForBoundClient`, publish gates via `disabledOpsForPublishGates`) over the surface-filtered op set, schemas via `buildToolDefs` (strict emission when `mcp.strict_params` resolves reject); the tools/list `mcp_request_log` row records the listed size as `params.tool_count`. Call-time op-level denials the list should have prevented — the inline scope deny, publish-gate backstop (`config_key=...`), fence op-level deny (`fence=op`, classified via `isListLevelDenialEnvelope`) — log `status='denied_after_list'` instead of `'error'` (the trend-to-zero honest-catalog metric, see docs/operations/mcp-surface-runbook.md) — every tools/call row's status resolves through `requestLogStatusForResult` (dispatch.ts) on BOTH transports. The admin health-indicators error rate counts `status NOT IN ('success','success_with_warnings')` and excludes `operation='surface_change'` audit rows from numerator AND denominator (audit rows record operator/self actions, not traffic). Per-request surface resolution lives in `resolveEffectiveSurface`: a `verbs` ceiling skips the default-surface config read, and a failed read applies the last successfully read default per process (fail-closed — a transient config outage cannot widen a NULL-surface client). OAuth protected-resource metadata (RFC 9728) names `/mcp` as the resource (`resourceServerUrl`), so the SDK mounts the PRM at `/.well-known/oauth-protected-resource/mcp` and the 401 `resource_metadata` URL is derived from the same value; the bare root path is kept as an alias by rewriting `req.url` onto the SDK's handler (same document, same CORS). Shutdown: `waitForHttpServerLifecycle` tracks accepted sockets weakly (`trackServerSockets`; Bun never emits socket `close`, so a strong set leaked one per request), severs the still-reachable ones right after `server.close()`, and bounds the close wait at `CLOSE_TIMEOUT_MS` (5s) — a collected keep-alive wrapper whose native handle keeps `close()` from returning gets one stderr line and shutdown proceeds instead of hanging. DCR startup copy: the SECURITY WARNING states self-registered clients are limited to read/write (read-only for `client_credentials` under `--enable-dcr-insecure`) and that every authorization_code connection needs owner approval in the admin UI; banner `DCR:` values are `enabled (consent; DCR max read write)` / `enabled (INSECURE: read-only M2M)` / `disabled`.
Layout: `runServeHttp` binds through `listenOrRefuse` (`serve-http-listen.ts`: `serve_port_in_use` on a taken port; with `options.adoptServer` from status-only recovery it hands the app to the already-bound listener instead of binding). `buildServeHttpApp` builds one shared `ServeHttpContext` (sessions, nonce stores, limiters, `requireAdmin`, SSE fan-out, OAuth provider, resource verifier, non-`localOnly` op list) and mounts in registration order `serve-http-oauth.ts` (CORS gates, DCR TTL hook, confidential credentials, SDK router, discovery, owner login links, consent), `serve-http-metrics.ts` (`/health`, `/metrics`, probes), `serve-http-admin-api.ts` (`requireAdmin`, `/admin/login`, `/admin/api/*`, `/admin/events`), `serve-http-spa.ts`, `serve-http-mcp.ts` (`/mcp`; writes `[gbrain-serve] dispatch op=<name> args_sha256=<16 hex>` to stderr before each tool call so a stall's last line names its request, never the arguments) and `serve-http-webhooks.ts` (`/ingest`, which maps a legacy-authority `permission_denied` from submission to 409 `{error, message, hint, docs_url}` (`test/serve-http-ingest-legacy.test.ts`) and every other submission error to 500, `/webhooks/github`); `runServeHttp` keeps listen, banner, resolve-IPC binding and shutdown, and the façade re-exports moved symbols. Order is pinned by `test/serve-http-route-golden.test.ts` (AST) and `test/serve-http-route-runtime-golden.test.ts` (router stack). Size ceiling: `scripts/module-size-limits.tsv`.
-- `src/commands/serve.ts` — `gbrain serve` stdio MCP entrypoint with idempotent shutdown across every parent-disconnect signal. Surface: stdio resolves `GBRAIN_SURFACE` > `--surface` > config > full (`resolveStdioSurface`; an invalid env value is ignored with a stderr line and handed to `startMcpServer` as `invalidSurfaceEnv`), `--http` resolves `--surface` > config > full and says on stderr that it ignores `GBRAIN_SURFACE`; both print `surface=<x> (source: …)` at start. Stdio EOF, SIGTERM, SIGINT, SIGHUP, and parent-process death (every reparent case — PID 1, launchd subreaper, systemd, tmux, or a parent shell with `PR_SET_CHILD_SUBREAPER`) all funnel into one `cleanup(reason)` that first awaits `shutdownDelegatedSync()` (idempotent shared promise; a running delegated sync is aborted and settles its checkpoint against the live engine, with the cleanup deadline extended by `GBRAIN_SERVE_SYNC_SETTLE_MS` only while a job runs) and then releases the engine and the PGLite write-lock dir within 5 seconds (otherwise the lock is held indefinitely after Claude Desktop / Cursor / launchd-managed gateways disconnect, forcing a 5-minute stale-lock wait on next start). Watchdog reparent check is `getParentPid() !== initialParentPid` (the `=== 1` check missed the subreaper case under launchd/systemd). Bun's `process.ppid` cache is stale across reparenting ([oven-sh/bun#30305](https://github.com/oven-sh/bun/issues/30305)) so `getParentPid()` runs `spawnSync('ps', ['-o', 'ppid=', '-p', PID])` per tick. Startup probe verifies `ps` is on PATH; if not (stripped containers, busybox), the watchdog skips installing AND emits a loud `[gbrain serve] watchdog disabled: ps unavailable ...` stderr line so operators see the degraded mode. The idle maintenance sweep skips ticks while a delegated sync runs and drains deferred embeds afterwards (`maybeDrainDeferredEmbeds`); it targets the source `resolveMcpStdioSourceScope` resolves (GBRAIN_SOURCE > `.gbrain-source` dotfile > local_path > `sources.default` > …) — the SAME ladder as stdio dispatch and the startup sweep, so dotfile/local_path-scoped serves reconcile their in-session MCP writes (pinned by `test/serve-idle-sweep-source.serial.test.ts`). Both stdin activity listeners (the default-on idle sweep and the opt-in `--stdio-idle-timeout`) attach only AFTER the MCP SDK transport's own stdin listener — the sweep on its first interval tick, the idle timeout through the activator `installStdioLifecycle` returns, which `runServe` invokes once `startMcpServer` resolves (and which re-arms the countdown so boot time does not eat into the idle window) — so neither can flip stdin into flowing mode and consume a fast client's initialize frame before the SDK sees it. The boot-readiness deadline (`GBRAIN_SERVE_BOOT_TIMEOUT_SECONDS`, default 60, 0 disables) measures time WITHOUT boot progress: every `onBootPhase` change and every `noteForwardProgress()` note (`src/core/forward-progress.ts`; progress ticks and each completed stdio request via `trackStdioRpc` in `src/mcp/server.ts`) restarts the window, so a large brain's slow but advancing boot is never killed; only a full window without progress releases the engine and exits 1 with the `serve_boot_timeout` line (stuck phase, pool pressure, seconds since boot started). Pinned by `test/serve-stdio-lifecycle.test.ts` (boot-readiness block).
+- `src/commands/serve.ts` — `gbrain serve` stdio MCP entrypoint with idempotent shutdown across every parent-disconnect signal. Surface: stdio resolves `GBRAIN_SURFACE` > `--surface` > config > full (`resolveStdioSurface`; an invalid env value is ignored with a stderr line and handed to `startMcpServer` as `invalidSurfaceEnv`), `--http` resolves `--surface` > config > full and says on stderr that it ignores `GBRAIN_SURFACE`; both print `surface=<x> (source: …)` at start. `--http --token-ttl` goes through `parseTokenTtl` (`src/commands/auth.ts`) and refuses anything outside 60 to 7,776,000 seconds before the server starts. Stdio EOF, SIGTERM, SIGINT, SIGHUP, and parent-process death (every reparent case — PID 1, launchd subreaper, systemd, tmux, or a parent shell with `PR_SET_CHILD_SUBREAPER`) all funnel into one `cleanup(reason)` that first awaits `shutdownDelegatedSync()` (idempotent shared promise; a running delegated sync is aborted and settles its checkpoint against the live engine, with the cleanup deadline extended by `GBRAIN_SERVE_SYNC_SETTLE_MS` only while a job runs) and then releases the engine and the PGLite write-lock dir within 5 seconds (otherwise the lock is held indefinitely after Claude Desktop / Cursor / launchd-managed gateways disconnect, forcing a 5-minute stale-lock wait on next start). Watchdog reparent check is `getParentPid() !== initialParentPid` (the `=== 1` check missed the subreaper case under launchd/systemd). Bun's `process.ppid` cache is stale across reparenting ([oven-sh/bun#30305](https://github.com/oven-sh/bun/issues/30305)) so `getParentPid()` runs `spawnSync('ps', ['-o', 'ppid=', '-p', PID])` per tick. Startup probe verifies `ps` is on PATH; if not (stripped containers, busybox), the watchdog skips installing AND emits a loud `[gbrain serve] watchdog disabled: ps unavailable ...` stderr line so operators see the degraded mode. The idle maintenance sweep skips ticks while a delegated sync runs and drains deferred embeds afterwards (`maybeDrainDeferredEmbeds`); it targets the source `resolveMcpStdioSourceScope` resolves (GBRAIN_SOURCE > `.gbrain-source` dotfile > local_path > `sources.default` > …) — the SAME ladder as stdio dispatch and the startup sweep, so dotfile/local_path-scoped serves reconcile their in-session MCP writes (pinned by `test/serve-idle-sweep-source.serial.test.ts`). Both stdin activity listeners (the default-on idle sweep and the opt-in `--stdio-idle-timeout`) attach only AFTER the MCP SDK transport's own stdin listener — the sweep on its first interval tick, the idle timeout through the activator `installStdioLifecycle` returns, which `runServe` invokes once `startMcpServer` resolves (and which re-arms the countdown so boot time does not eat into the idle window) — so neither can flip stdin into flowing mode and consume a fast client's initialize frame before the SDK sees it. The boot-readiness deadline (`GBRAIN_SERVE_BOOT_TIMEOUT_SECONDS`, default 60, 0 disables) measures time WITHOUT boot progress: every `onBootPhase` change and every `noteForwardProgress()` note (`src/core/forward-progress.ts`; progress ticks and each completed stdio request via `trackStdioRpc` in `src/mcp/server.ts`) restarts the window, so a large brain's slow but advancing boot is never killed; only a full window without progress releases the engine and exits 1 with the `serve_boot_timeout` line (stuck phase, pool pressure, seconds since boot started). Pinned by `test/serve-stdio-lifecycle.test.ts` (boot-readiness block).
- `src/commands/skillify-check.ts` — `gbrain skillpack-check` agent-readable health report. Exit 0/1/2 for CI gating; JSON for debugging. Wraps `check-resolvable --json`, `doctor --json`, and migration ledger into one payload. Required item 12 (`brain_first_compliance`) calls `analyzeSkillBrainFirst()` on the candidate SKILL.md; exits 1 when the verdict is `missing_brain_first` (external-lookup pattern present, no callout, no `brain_first: exempt`). The scaffold path in `src/core/skillify/templates.ts` pre-inserts the canonical Convention callout into new SKILL.md files so freshly-scaffolded skills pass item 12.
diff --git a/docs/architecture/key-files/google-and-loops.md b/docs/architecture/key-files/google-and-loops.md
index c5977ed930..88b5f418d5 100644
--- a/docs/architecture/key-files/google-and-loops.md
+++ b/docs/architecture/key-files/google-and-loops.md
@@ -43,7 +43,7 @@ Historical Gmail repair selects explicit nested MIME metadata fields, excluding
- `src/core/harness/credentials.ts` + `delivery.ts` + `install.ts` — Private credential handoff and host delivery journal, ownership-preserving native configuration and isolated thin launchers. A committed active client and matching current secret are prerequisites for recovery. Machine handoffs preserve optional POST/Basic authentication methods. Native setup is a distinct nested-client artifact; metadata reads never access journals or SDK client objects containing hashes. Configuration removal and server revocation are separate actions.
- `src/core/harness/oauth-setup.ts` + `client-setup.ts` — explicit client metadata projection, flow selection, native OAuth setup/private-file validation, and live-row-locked secret delivery recovery. Public PKCE needs no journal; confidential exports validate the retained secret against current registration, and machine exports discard cached tokens. Unknown/mixed flows refuse until an explicit supported flow is selected.
-- `src/core/harness/capabilities.ts` + `src/mcp/capabilities.ts` — Shared effective-grant orientation for OAuth whoami and authenticated `gbrain://capabilities`. The resource preserves the exact seven-tool surface; source, operation, scope, fence and server-gate restrictions remain enforced at dispatch. No worker probe or per-tool database query during discovery. Shared administration guidance explains separate owner authority, links the MCP admin runbook, and exposes an admin URL only for a configured credential-free HTTP MCP endpoint. Stdio never infers an HTTP address.
+- `src/core/harness/capabilities.ts` + `src/mcp/capabilities.ts` — Shared effective-grant orientation for OAuth whoami and authenticated `gbrain://capabilities`. A stored client token lifetime outside 60 to 7,776,000 seconds (`AuthInfo.tokenTtlSeconds`) reports `token_ttl_invalid`, and the delegation repair template then includes a `--token-ttl <APPROVED_TTL_SECONDS>` choice, since every grant write validates the merged lifetime. The resource preserves the exact seven-tool surface; source, operation, scope, fence and server-gate restrictions remain enforced at dispatch. No worker probe or per-tool database query during discovery. Shared administration guidance explains separate owner authority, links the MCP admin runbook, and exposes an admin URL only for a configured credential-free HTTP MCP endpoint. Stdio never infers an HTTP address.
- `src/commands/mcp.ts` + `mcp-provision.ts` + `harness-connect.ts` — Host-side grant/preview/CAS and recoverable private delivery, followed by installation inside the intended harness. Codex, Claude Code and opencode installs (`src/core/harness/install.ts`) store the bearer token inline in the harness config; `inlineTokenReceipt` adds `token_storage`, `config_path`, `renew_command`, `if_exposed` (invalidate-tokens preview/apply, renew, reload; `renew_command` carries `--fresh-token` for renewable handoffs so it always exchanges a new token) and a `token_warning` when a Git working tree would commit the file, and `harness-connect.ts` repeats them on stderr in human mode without printing the token (#5775; `test/harness-token-receipt.test.ts`). Running PGLite hosts are administered through their authenticated API, never by opening a second database process. CLI status uses the delivery-aware exit verdict. `mcp-admin.ts` and `mcp-admin-http.ts` provide engine-free owner commands with explicit-file/env credential precedence, in-memory sessions, private native exports, versioned lifecycle previews, and safe stage/outcome/remedy receipts. Unknown mutation outcomes require inspection instead of automatic repetition. `runMcp` also dispatches `gbrain mcp expose` to `runMcpExpose` (dynamic import of `./mcp-expose.ts`; HELP carries the expose lines so the flag registry harvests them) and sets the CLI exit verdict from its returned code. `mcpNeedsEngine(args)` is true only for `grant` without an owner credential (`--admin-token-file` or `GBRAIN_ADMIN_BOOTSTRAP_TOKEN`) and outside help; `admin`, `expose`, and `verify` never open the database.
- `src/commands/mcp-expose.ts` — `gbrain mcp expose [--port N] [--funnel] [--surface] [--enable-dcr] [--no-tailscale] [--no-service] [--no-install] [--force] [--dry-run] [--yes] [--json]` / `--status` / `--remove`: publishes `gbrain serve --http` on the user's Tailscale tailnet (Serve by default, Funnel only with the explicit flag) and keeps it running as a user service. `runMcpExpose(args, deps?)` returns the exit code (0 done, 1 failed, 2 needs `--yes`, the prompt was declined, or a step is pending — a tailnet feature to enable, Tailscale login, tailnet certificate). Arg validation via `validateHarnessArguments` (exclusive pairs `--status`/`--remove`, `--funnel`/`--no-tailscale`, `--dry-run`/`--status`); the help text names every flag and the `verify.local` / `verify.tailnet` checks. Ordered named checks — `plan` (platform, execution environment, engine kind from `loadConfig()`; thin clients are refused with "run on the brain host"; `engine === 'unknown'` — no config or an unreadable one — without `--no-service` is refused as `no_brain_config` / exit 1 with next action `gbrain init` BEFORE consent, because a service around a missing brain only crash-loops, while `--dry-run` still prints the plan with the refusal marked and exits 0; on a PGLite engine `deps.pgliteHolder` (default `probeLivePgliteHolder` from `src/core/bootstrap/uninstall.ts`, a read-only lock-file probe) is consulted with `cfg.database_path`, and a live holder that is not our own managed service — receipt present with `service.state` `running`/`loaded` — adds a `Lock` plan line plus a `pglite_lock` check with status `warn` (never a stop); `--no-tailscale` over an existing receipt whose `tailscale.dns_name` is set (a live Serve/Funnel mapping) is refused BEFORE consent as `tailscale_receipt_present` / exit 1 with next actions `gbrain mcp expose --remove --yes` and the re-run without the flag — `--dry-run` marks it `WOULD BE REFUSED`; then probes `127.0.0.1:<port>` with `probeOccupied(d, port, url)` — occupied when EITHER the injectable `deps.tcpProbe` (default `defaultTcpProbe`, one `node:net` connect, socket destroyed on every outcome; true on connect, false on refusal / timeout / throw) accepts a TCP connect OR the `/health` fetch RESOLVES with ANY status (2xx, 404, 500), so a non-HTTP listener counts too; only both rejecting is free — and refuses a foreign listener with no receipt claiming that port as `foreign_listener` BEFORE anything is published unless `--no-service`; the message names the interrupted-run escape hatch `gbrain mcp expose --remove --yes`; `probeHealth` (`res.ok`) stays the bar for `verify.local` / `verify.tailnet` / `--status`), `consent` (shared `confirmOrFinish` for publish and `--remove`: one stderr y/N prompt on a TTY; declining is `pending` / exit 2 / `declined` with "Nothing changed. Re-run with --yes to confirm."; non-interactive without `--yes` prints the plan and exits 2 / `confirmation_required`; every re-run hint is rendered by `rerunCommand(opts)` — the user's publish flags + `--yes`), `tailscale.binary` (install plan: brew cask on macOS — then `open -a Tailscale` and a bounded poll of `tailscale status --json`, up to 20 attempts 1s apart, breaking as soon as the app's daemon answers and otherwise falling through to the login step's daemon-not-running handling — official installer on Linux, `--no-install` → exit 1), `tailscale.login` (Linux `sudo tailscale set --operator=<user>` non-fatal then flagless `sudo tailscale up` — `sudo` is put in front of the binary ONLY when `isSystemTailscaleBinary(binary)` holds (one of `TAILSCALE_BINARY_CANDIDATES`, literally or via `realpathSync`); a user-writable `tailscale` found on PATH stops the step as `pending` / exit 2 / `tailscale_login_manual` with the message "tailscale at <path> is not a system install, so gbrain will not run it with sudo. If you trust that binary, sign in yourself (this runs it as root): `sudo <path> set --operator=$USER && sudo <path> up`, then re-run: <rerun>" — the command is `tailscaleManualLoginCommand(binary)`, naming the discovered path shell-quoted, because a binary outside sudo's `secure_path` is exactly this case — and never spawns `sudo`; macOS `tailscale up`; bounded wait via `GBRAIN_TAILSCALE_LOGIN_TIMEOUT_MS`), `tailscale.identity` (MagicDNS name → `public_url`; pre-checks so `tailscale serve`/`funnel` — which wait interactively instead of failing when a feature is off — are never started blind: empty `CertDomains` → `pending` / exit 2 / `tailscale_https_not_enabled` with `TAILSCALE_ADMIN_DNS_URL`; `--funnel` with `funnelCapable === false` → `tailscale_funnel_not_enabled` with the ACL admin + Funnel KB URLs; `funnelCapable === null` proceeds), `tailscale.publish` (reads the serve config through `readServeView`, which FAILS CLOSED — it returns `{ view: ServeStatusView | null, stderr, status }` with `view: null` when `tailscale serve status --json` exits non-zero / is killed (`status: null`) or when stdout is not a JSON object per `parseServeStatusStrict`; an empty document / `{}` / `null` from exit 0 is the legitimately empty view — a null view before `--bg` is described once by `describeServeReadFailure` (`{ kind, detail, fix }` from one `classifyTailscaleError` call), records `tailscale.publish` = fail and returns exit 1 with reason `tailscale_<kind>` without publishing; a null view after `--bg` is `tailscale_publish_unconfirmed` naming the read failure; refuses a `/` handler proxying a different port, a foreground session or a raw TCP forward without `--force` as `foreign_serve_config` — `next_actions` says `tailscale serve status`, only `message` explains `--force`; `PUBLISH_TIMEOUT_MS` (60s) bounds `--bg`, `SERVE_OFF_TIMEOUT_MS` (30s) every `--https=443 --set-path=/ off` and `STATUS_READ_TIMEOUT_MS` (15s) both status reads; a `status: null` timeout is `unknown` with a run-by-hand hint; stderr classified by `classifyTailscaleError` as the second line of defense; switching our own handler's shape pre-clears ONLY in the funnel → tailnet direction (`funnel --https=443 --set-path=/ off` before `serve --bg`, because `serve --bg` over a Funnel mount keeps `AllowFunnel`; tailnet → funnel is one atomic `funnel --bg`), and when that pre-off was followed by a failed publish (non-zero, timeout, or unconfirmed) `restorePrevious` best-effort re-publishes the previous shape with `tailscaleServeArgv(port, { funnel: true })`, re-reads the view, and appends to the `tailscale.publish` detail whether "the previous funnel handler was restored" or "could NOT be restored"; the existing receipt is never touched on those paths), `admin_token` (ensure the 0600 token file, never printed), `service` (launchd / systemd user unit / `manual` fallback with the exact foreground and `nohup` commands; a `--no-service` re-run carries the existing receipt's service block unchanged and does not rewrite the wrapper; `service_install_failed` still writes the receipt with `service.state: 'stopped'` before exit 1 so `--status`/`--remove` can clean up the published handler; the receipt is ALSO written right after a successful service step — service state as probed at that moment — before verify runs, so a kill during verify always leaves `--status`/`--remove` something to find), `verify.local` (wall-clock `/health` polling up to 20s, timeout → `warn`, exit 2, `verify.tailnet` skipped), `verify.tailnet` (up to 30s, `pending` is exit 2 — EXCEPT when the last probe's rejection was a name-resolution failure per `mcp-expose-probe.ts`: Bun's `fetch` rejects an unresolvable host and a refused connection with the same "Unable to connect. Is the computer able to access the url?" / `ConnectionRefused`, so after a rejected fetch the URL's hostname (never an IP literal or `localhost`) is handed to `deps.lookup` — default `dns.promises.lookup`, bounded by the probe timeout — and a rejection with code `ENOTFOUND` / `EAI_AGAIN` / `EAI_NONAME` / `EAI_NODATA` / `DNS_ENOTFOUND` (or a message naming one) is the verdict, the fetch-message regex staying a secondary hint; a name that resolves but does not answer stays `pending`: then the check is `warn` with `unresolvedDetail(dnsName)` — "this host cannot resolve <name> (MagicDNS may be off here: `tailscale set --accept-dns=true`); devices that do resolve it may already reach the server" — and the run exits 0, since this host's resolver says nothing about the server), `receipt` (rewrites the early receipt with the settled state — the supervisor is re-probed once verify.local ran — keeping `created_at`). The admin-token, service and verify steps run inside one try: a THROW there after this run's `--bg` succeeded but BEFORE the early receipt is rolled back by `rollbackAfterThrow(d, s, opts, published, error, receiptWritten)` — the fresh handler is turned off again with `tailscaleServeOffArgv({ funnel })` only when no `/` handler for our port existed before the run (a pre-existing one is left in place), a `rollback` check records what happened — "turned off again" is claimed only when a re-read of the serve view after an exit-0 `off` no longer shows our port; an exit-0 `off` whose re-read still shows it is a `warn` "NOT turned off (… the handler is still present)", an unreadable re-read is a `warn` "state unknown", and an `off` that exits non-zero or throws is a `warn` whose message says the handler was NOT turned off — no receipt is written, and the error is re-thrown so the outer catch reports `mcp_expose_failed` with a message naming the handler state; once the early receipt is on disk (`receiptWritten`, checked first) a throw tears nothing down (`rollback` = skipped pointing at `--status` / `--remove --yes`), because the receipt makes everything findable (the non-throwing `service_install_failed` path keeps its partial receipt). Success banner and `next_actions` gate the local-agent line on the engine: Postgres → `gbrain bootstrap harness --yes --port N`; PGLite → pre-mint (`gbrain auth create … --scopes read,write` before the service runs) + `--token`, or the scoped `mcp grant … --url http://127.0.0.1:N/mcp --admin-token-file …` + `gbrain connect … --install` path, and "host-side commands fail with `live_serve` — administer through the running server". `--json` emits one stdout document `{ status, receipt, checks[], next_actions, reason?, message? }` with prose on stderr; every `inherit` subprocess redirects its stdout to stderr under `--json`. `--status` and `--remove` read the receipt through `readExposeReceipt`'s shape guard (a partial receipt is `not_exposed` / "nothing to remove", never a crash) and execute the tailscale binary from `resolveReceiptBinary`: the receipt's recorded path is honored only when it still exists AND is either what `findTailscaleBinary` finds now or one of `TAILSCALE_BINARY_CANDIDATES`, otherwise discovery wins — a path in a receipt is data, never a licence to run it. the probes — `probeHealth` (`res.ok`), `probeOccupied` (any response, or an accepted TCP connect), the bounded never-throwing `tryFetch` → `FetchOutcome { res, unresolved }`, `pollHealth` → `{ ok, unresolved }` with the LAST probe's resolution verdict, `unresolvedDetail`, `defaultTcpProbe`, `defaultLookup` — live in `src/commands/mcp-expose-probe.ts` and take the narrow `ProbeDeps` slice of the resolved deps (`fetch`, `tcpProbe`, `lookup`, `now`, `sleep`, `healthIntervalMs`); `defaultTcpProbe` is re-exported here so its import site never moved; `isLiveService(state)` is the one definition of "the supervisor reports our service" (`running` or `loaded`) used by the lock-holder exemption, the service check, `--status` and both `--remove` paths; `serviceLabel` builds on `serviceKindLabel` (`launchd <label>` / `systemd (user) <unit>`). `--status` runs its four independent probes (serve config, supervisor state, local and tailnet `/health`) concurrently with `Promise.all` and still reports the checks in the fixed order `receipt`, `tailscale.publish`, `service`, `verify.local`, `verify.tailnet`; an unreadable serve config (null view) is a FAILED `tailscale.publish` check / exit 1, never "handler present"; a tailnet `/health` rejected for name resolution is `verify.tailnet` = warn (same `unresolvedDetail`), not `pending`, and does not by itself make the exit non-zero. `--status` with NO receipt is `runStatusWithoutReceipt`: it runs the read-only `probeLeftovers(d, opts.port)` (`--port` is honored) and, when the wrapper, the plist / unit or a live service, or a `/` handler on `:443` proxying the port is found, emits one `warn` check per artifact (`receipt`, `service`, `tailscale.publish`, `files`), pushes `recoveryCommand(port, force)` (`gbrain mcp expose --remove --yes`, `--force` only when a handler stands alone with no wrapper / service corroborating it, `--port N` when non-default) to `next_actions`, and finishes `error` / exit 1 / `leftovers_without_receipt` (also under `--json`); an unreadable serve status alone is a caveat warn, not a leftover; nothing found keeps the `not_exposed` answer (exit 0, `--json` exit 2). `--remove` (consent; decline is `pending` / exit 2) probes the supervisor and removes a service that exists even when the receipt says skipped — `recordServiceUninstall` prints the uninstall notes, and when `launchdBootoutFailed(result)` (a `launchctl bootout failed: …` / `unload failed: …` note, i.e. a non-"not loaded" failure) the `service` check is `warn` pointing at `launchctl print gui/$(id -u)/com.gbrain.serve` and "the launchd job (bootout failed)" is added to "Left in place"; it returns the one-line service summary quoted below — then clears only gbrain's own serve/funnel handler through `turnOffOurHandler` (Funnel off first; every `off` is `--https=443 --set-path=/ off`, scoped to our `/` mount; the serve config is re-read only after an `off` command ran, otherwise the view already read is reused; a failed re-read is reported as `unknown` — a warn, never "gone"; a foreign port on `:443` gets "nothing to turn off"). `--remove` never reports success while our handler survives: when `turnOffOurHandler` returns `remaining` as a handler (`tailscale.publish` = fail) or `'unknown'` (= warn), `finishHandlerNotRemoved` keeps the receipt AND the wrapper (mirroring the unreadable-status branch), records `receipt` = skipped "kept: …", pushes `tailscale serve status` + the re-run to `next_actions`, says which service outcome already happened, and exits 1 with reason `handler_not_removed`; `--remove` never runs `tailscale serve reset`, never uninstalls or logs out, keeps the admin token unless `--force` (deleted through the same `unlinkQuietly` as the wrapper and receipt), and unlinks the wrapper / receipt / token ONLY when the path's directory is the serve directory — a receipt path elsewhere is left untouched and named in "Left in place" (also in the plan). The receipt's recorded `plist_path` / `unit_path` are data, never a licence: `uninstallServeService` is always handed the computed `d.plistPath` / `d.unitPath` (home + the fixed label / unit name), and a recorded path that differs is not touched and is named in "Left in place" as "recorded in the receipt but not the expected location". A null serve view during `--remove` fails closed: `tailscale.publish` = fail "could not read tailscale serve status; handler left as is", reason `tailscale_serve_status_unreadable`, exit 1, and the receipt AND wrapper are kept so a re-run finishes the job. With NO receipt, `runRemoveWithoutReceipt` recovers from what is on disk through the same `probeLeftovers` `--status` uses (`wrapperPath(serveDir)`, the launchd plist / systemd unit or a `running`/`loaded` service, a `/` handler on `:443` proxying `opts.port` — `--port` may accompany `--remove`, default 3131); inside it the supervisor chain (`probeServiceTarget` → `serveServiceState`) and the `readServeView` read run concurrently under `Promise.all` (the binary is resolved synchronously first) and the plan / checks are emitted in the fixed order afterwards; the re-run hints come from `recoveryCommand`. The handler is turned off only with corroborating gbrain evidence — the wrapper present, our unit/plist present, or the supervisor reporting our service live — or with `--force`, because another tool may proxy `:443` to the same port: a handler standing alone is reported (`tailscale.publish` = warn naming the proxy target and `--force`, next action `gbrain mcp expose --remove --yes --force`) and left in place on the "not exposed — nothing to remove" exit-0 path; with `--force` the plan line says so. Otherwise it prints a "Recovering without a receipt" plan (`receipt` check = warn), takes consent as usual, removes exactly those artifacts (service via the supervisor — the same `recordServiceUninstall` bootout-failure warn applies — wrapper, the handler — funnel off first when `AllowFunnel` lists the host), leaves the admin token file, and finishes `removed` with reason `recovered_without_receipt`; a handler that survives the `off` is `handler_not_removed` / exit 1 here too, with the wrapper deliberately KEPT as the corroboration the re-run needs (`files` = skipped "kept: the wrapper"; the re-run hint carries `--force` when no wrapper is left); an unreadable serve status on this path (gbrain evidence present, `serveUnreadable` set) fails closed exactly like the receipt path — the service, when found, is still uninstalled, the plan says the handler cannot be checked and the wrapper is kept, `tailscale.publish` = fail "…; handler state unknown", `files` = skipped "kept: the wrapper" (or "nothing (no wrapper was found)"), `next_actions` = `tailscale serve status --json` + the recovery command (`--force` when no wrapper is left), exit 1 with reason `tailscale_serve_status_unreadable` and message "could not read tailscale serve status; handler state unknown"; when nothing of ours is found the answer stays "not exposed — nothing to remove", exit 0 (an unreadable serve status is then only the caveat warn — there is nothing to keep and a handler alone would not be touched anyway). Every filesystem/exec effect goes through injectable deps so tests run against a fake runner in a tmpdir. Success guidance separates owner login, native OAuth registration, and machine grant/install. It uses the expose-managed owner file only when installing or keeping that service; publication with `--no-service` and no managed service instead requires the existing server's independently configured owner credential. Publishing receipts and health checks do not certify client authorization or native activation.
diff --git a/docs/architecture/key-files/security.md b/docs/architecture/key-files/security.md
index 41da1ec159..b03d6704df 100644
--- a/docs/architecture/key-files/security.md
+++ b/docs/architecture/key-files/security.md
@@ -16,7 +16,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/guardrails.ts` — vendor-neutral content guardrail seams (`registerGuardrailProvider`, `classify`). `loadGuardrailProvidersFromEnv(env = process.env, opts?: { cwd, skipCwdCheck })` accepts ONLY an absolute path or a `~/` path for `GBRAIN_GUARDRAILS_MODULE`; cwd-relative specs (`./`, `../`, bare `.`) and bare package specifiers (`pkg`, `@scope/pkg`, `pkg/sub` — in the compiled binary Bun's module walk-up starts at the cwd, so a hostile checkout's `node_modules/<name>/` would load) throw `GuardrailLoadError` before any import, and when `env` is `process.env` (or `opts.cwd` is given) a spec that a cwd .env file assigns is refused via `cwdDotenvAssignsKey` (message composed from env-trust's `CWD_DOTENV_REMEDIATION`) unless `opts.skipCwdCheck` (preflight's cwd == config-dir case). node:path/url/os are static imports. Registration is counted by EVENTS against a pre-import baseline so import-time side-effect registration and same-id replacement are accepted (#3688 residual). Pinned by `test/guardrails.test.ts` + `test/guardrails-env-load.test.ts`.
-- `src/core/oauth-grants.ts` — client-row-locked grant transactions shared by OAuth issuance, code/refresh consumption, and revocation. Preserves scope/resource ceilings and rolls back consumption with replacement writes. `canonicalOAuthResource(requested, canonical)` is the one RFC 8707 resource canonicalizer: with the provider's `resourceUrl` (serve-http passes the /mcp URL derived from the configured public URL, never `Host`), `begin()`, code exchange and refresh map the issuer origin (any trailing slash, default port or host case) to the canonical /mcp resource and refuse anything else with `invalid_target` naming the accepted URL before a request is pending or a code is consumed; stored origin-bound grants canonicalize the same way and pre-resource grants stay valid. serve-http's bearer verifier uses the same function. Pending consent requests live in a bounded in-memory store (`MAX_PENDING_TOTAL` server-wide, `MAX_PENDING_PER_CLIENT` = 10 awaiting-decision requests per `client_id`; `assertCapacity` prunes expired entries and enforces both ceilings synchronously at the start of `begin()` and again immediately before the insert, with no await in between; decided entries stay until expiry but do not count toward a client's budget) and snapshot current operation and delegation policies. `begin()` rejects revoked or deleted clients before creating a request. `src/commands/serve-http-oauth.ts` authenticates request details, enforces session-bound CSRF decisions, and adds a `read write` bootstrap scope hint to scope-less `/mcp` Bearer challenges without changing token authority (`grantScopes` caps every request to the client row's scope, so a read-only row still yields a read-only token); `admin/src/pages/OAuthConsent.tsx` renders the existing admin login/approval flow without exposing protected details in the page shell.
+- `src/core/oauth-grants.ts` — client-row-locked grant transactions shared by OAuth issuance, code/refresh consumption, and revocation. Preserves scope/resource ceilings and rolls back consumption with replacement writes. Issuance caps the resolved access-token lifetime (positive `oauth_clients.token_ttl` override, else the server default) at `TOKEN_TTL_MAX_SECONDS` from `src/core/grants/model.ts`, so a stored or configured lifetime above 90 days never mints a longer token (`test/oauth-token-ttl-clamp.test.ts`, both engines). `canonicalOAuthResource(requested, canonical)` is the one RFC 8707 resource canonicalizer: with the provider's `resourceUrl` (serve-http passes the /mcp URL derived from the configured public URL, never `Host`), `begin()`, code exchange and refresh map the issuer origin (any trailing slash, default port or host case) to the canonical /mcp resource and refuse anything else with `invalid_target` naming the accepted URL before a request is pending or a code is consumed; stored origin-bound grants canonicalize the same way and pre-resource grants stay valid. serve-http's bearer verifier uses the same function. Pending consent requests live in a bounded in-memory store (`MAX_PENDING_TOTAL` server-wide, `MAX_PENDING_PER_CLIENT` = 10 awaiting-decision requests per `client_id`; `assertCapacity` prunes expired entries and enforces both ceilings synchronously at the start of `begin()` and again immediately before the insert, with no await in between; decided entries stay until expiry but do not count toward a client's budget) and snapshot current operation and delegation policies. `begin()` rejects revoked or deleted clients before creating a request. `src/commands/serve-http-oauth.ts` authenticates request details, enforces session-bound CSRF decisions, and adds a `read write` bootstrap scope hint to scope-less `/mcp` Bearer challenges without changing token authority (`grantScopes` caps every request to the client row's scope, so a read-only row still yields a read-only token); `admin/src/pages/OAuthConsent.tsx` renders the existing admin login/approval flow without exposing protected details in the page shell.
- `src/core/oauth-provider.ts` — `GBrainOAuthProvider` implementing the MCP SDK's `OAuthServerProvider` + `OAuthRegisteredClientsStore`. Backed by raw SQL (works on both PGLite and Postgres — OAuth is infrastructure, not a BrainEngine concern). Full OAuth 2.1: `authorize` + `exchangeAuthorizationCode` with PKCE, `client_credentials`, `refresh_token` with rotation, `revokeToken`, `registerClient` (DCR validates redirect_uri is `https://` or loopback per RFC 6749 §3.1.2.1). All tokens + client secrets SHA-256 hashed before storage. Owner-approved authorization codes have a 10-minute TTL. Grant transactions lock the active client row before consuming codes or refresh tokens and creating replacements; revocation uses the same lock. Provider-side S256 PKCE validation is mandatory (`skipLocalPkceValidation=true` prevents the SDK from discarding the verifier first). Existing active-client grants remain usable. `pgArray()` escapes commas/quotes/braces so a comma-bearing redirect_uri can't smuggle a second array element. Legacy `access_tokens` fallback in `verifyAccessToken` honors the original-schema `scopes TEXT[]` column via `normalizeTokenScopes` (NULL = grandfathered `read+write+admin`, so every pre-scopes token is byte-identical; an array is filtered to known scopes and honored as-is, `[]`/all-unknown preserved as deny — a dedicated column is structurally immune to the permissions-object-replacement wipe class), and reads the token's source, operation and takes-holder grant through `resolveTokenGrant` (`src/core/grants/legacy-token.ts`, shared with the legacy HTTP transport so the two transports cannot drift; a legacy-shape row converts to the grant columns on that read; `[]` takes-holders preserved as explicit deny-all, NULL → the `/mcp` dispatch site's fail-closed `['world']`). `sweepExpiredTokens()` runs on startup in try/catch and returns the count via `RETURNING 1` + array length. RFC hardening: `client_id` folded atomically into the `DELETE WHERE` for both auth-code exchange and refresh rotation (wrong-client paths don't burn the row); refresh-scope-subset enforced against the original grant on the row (RFC 6749 §6, so revoking a scope shrinks existing refresh tokens); `client_id` bound on `revokeToken` (RFC 7009 §2.1); `/token` `redirect_uri` validated against the `/authorize` value (RFC 6749 §4.1.3, empty-string treated as missing not wildcard); `verifyAccessToken`/`getClient` catch only `isUndefinedColumnError` from `src/core/utils.ts` (only SQLSTATE 42703 falls through to legacy; lock timeouts/network blips throw); `dcrDisabled` constructor option lets `serve-http.ts` disable `/register` without monkey-patching the router. Module-private `coerceTimestamp()` normalizes postgres-driver-as-string BIGINT columns to JS numbers at 5 read sites (`getClient` for RFC 7591 §3.2.1 numeric timestamps, `exchangeRefreshToken` + `verifyAccessToken` for the SDK's `typeof === 'number'` check); throws on NaN/Infinity (fail loud at boundary), returns undefined for SQL NULL (callers treat NULL as expired). Not promoted to `utils.ts` — generic BIGINT precision-loss risk. `registerClient` honors `token_endpoint_auth_method: "none"` (RFC 7591 §3.2.1): public PKCE clients store `client_secret_hash = NULL` and the response omits `client_secret`; confidential clients (`client_secret_post` / `client_secret_basic`) keep their one-time-reveal shape; `getClient` normalizes NULL `client_secret_hash` to JS `undefined` so the SDK's clientAuth path accepts public clients. `verifyAccessToken` JOINs `oauth_clients.source_id` (write scope, scalar) + `oauth_clients.federated_read` (read scope, TEXT[]) + `oauth_clients.bound_slug_prefixes` (write fence, TEXT[] — consumed by `enforceClientSlugFence` in `operations.ts`) onto the returned `AuthInfo`; legacy brains degrade via `isUndefinedColumnError` fallback, dropping the newest projection first. `rescopeClient(clientId, {sourceId?, federatedRead?, boundSlugPrefixes?})` is the trusted-operator rescope (CLI `gbrain auth rescope-client`, admin `POST /admin/api/rescope-client`); `boundSlugPrefixes` is tri-state — undefined leaves the binding untouched, `null` clears it, a non-empty array replaces it (explicit empty array rejected as ambiguous deny-all) — so roster churn updates the write fence in place without rotating secrets. with `src/commands/serve-http.ts`: custom `/token` middleware that runs BEFORE the MCP SDK's `clientAuth`. The SDK does plaintext compare against the request's `client_secret`; gbrain stores SHA-256 hashes only, so every confidential-client `/token` request would fail. The middleware detects confidential auth via `Authorization: Basic` header OR `client_secret_post` form body (both shapes per RFC 6749 §2.3.1), verifies via `verifyClient(client_id, presented_secret)` (SHA-256 hash compare), and falls through to the SDK for public PKCE clients (which the SDK's clientAuth still accepts via NULL-`client_secret_hash` normalization). Pinned by `test/oauth-confidential-client.test.ts` (both `client_secret_basic` and `client_secret_post`). `authorize()` only calls `grants.begin()` and redirects to `/admin/?oauth_request=<id>#oauth-consent`; codes are minted solely in `OAuthGrants.decide()` behind the admin cookie session and session-bound CSRF. `registerClient` (the unauthenticated DCR store method) computes the `grant_types` default (`authorization_code`) BEFORE the scope block, then calls `dcrScopeViolation` once and throws `InvalidClientMetadataError` (HTTP 400) on a privileged request — rejected, never silently dropped — before the unknown-scope filter runs; a registration that omits `scope` registers an empty scope (no default scope) and its consent request carries `scopes: []`. `allowClientCredentialsDcr` (`--enable-dcr-insecure`) yields anonymous READ-ONLY machine clients; that gate is evaluated BEFORE `dcrScopeViolation`, so a `client_credentials` request without the flag gets 'not permitted via dynamic client registration' rather than the misleading 'limited to `read`' ceiling message (pinned in `test/oauth-dcr-scope-ceiling.test.ts`). Downstream is already bounded: `OAuthGrants.begin()` snapshots the intersected grant, `exchangeCode` and `verifyAccessToken` re-intersect with the client's current scope. Operator paths (`registerClientManual`, CLI, admin API) do not use this store method and accept every canonical scope. Pinned in-process by `test/oauth-consent-security.test.ts` (live SDK `/register` with a foreign `redirect_uri`), against the real server by `test/e2e/serve-http-consent.test.ts`, and for the ceiling by `test/oauth-dcr-scope-ceiling.test.ts` + `test/oauth-authorize-scope-default.test.ts` (DCR client: `/authorize` `read write admin` -> code `['read','write']`, `admin` alone -> `[]`).
diff --git a/docs/mcp/ADMIN.md b/docs/mcp/ADMIN.md
index 2ccd312e73..e2bc4fa8ed 100644
--- a/docs/mcp/ADMIN.md
+++ b/docs/mcp/ADMIN.md
@@ -220,6 +220,35 @@ requests. Added scopes require a fresh token; refresh cannot widen the original
token's scope ceiling. Native OAuth clients must reconnect and obtain fresh
owner approval. TTL changes affect future tokens only.
+### Access-token lifetime
+
+An access token lives at most 90 days (7,776,000 seconds), whatever a
+client's stored lifetime or the server's `serve --http --token-ttl` says.
+`--token-ttl` and every grant editor accept 60 to 7,776,000 seconds; `serve`
+refuses anything else at startup.
+
+Upgrading to this release brings older settings inside that range once:
+
+- A stored client lifetime above 90 days becomes 90 days. One below 60 seconds
+ becomes 60 seconds, and a zero or negative one becomes the server default.
+ Each change bumps the client's grant revision and writes an audit row.
+- Access tokens already issued expire no later than 90 days after they were
+ issued. A token older than that stops working. No expiry is extended.
+ Refresh tokens and legacy bearer tokens are unchanged.
+
+`gbrain auth clients` marks each affected client (`token_lifetime_clamped` in
+`--json`). A client with a refresh token or machine credentials gets a new
+access token on its next refresh. A native OAuth client whose token has
+expired and whose refresh token is gone must reconnect and get owner approval
+again. Restart every running `gbrain serve --http` process after upgrading so
+it issues tokens under the new limit.
+
+When `whoami` reports `token_ttl_invalid`, the stored lifetime is outside the
+range and every grant change is refused until it is fixed. Add the
+`--token-ttl <APPROVED_TTL_SECONDS>` choice from its repair template, for
+example `gbrain auth rescope-client CLIENT_ID --token-ttl 7776000 --dry-run --json`,
+then apply the same flags without `--dry-run`.
+
## Dashboard API keys
**Say to your agent:** *"Make a read-only API key for my notes app."* The
diff --git a/src/cli.ts b/src/cli.ts
index a8396d1fae..2a8c82527a 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -3124,7 +3124,7 @@ ADMIN
On --http this is the per-client CEILING.
--access read-only|full stdio: list and dispatch only read operations
serve --http [--port N] HTTP MCP server with OAuth 2.1
- --token-ttl N Access token TTL in seconds (default: 3600)
+ --token-ttl N Access token TTL in seconds, 60-7776000 (default: 3600)
--enable-dcr Enable Dynamic Client Registration (DCR clients default to authorization_code)
--enable-dcr-insecure Also allow the consent-bypassing client_credentials grant on DCR (implies --enable-dcr)
--public-url URL Public issuer URL (required behind proxy/tunnel)
diff --git a/src/commands/auth.ts b/src/commands/auth.ts
index ca2eb8d1a7..885749fca4 100644
--- a/src/commands/auth.ts
+++ b/src/commands/auth.ts
@@ -30,7 +30,7 @@ import { normalizeTokenScopes } from '../core/legacy-token-scope.ts';
import { sqlQueryForEngine, type SqlQuery } from '../core/sql-query.ts';
import { readClientGrant, rescopeClientGrant, resolveGrantProfile, type GrantPatch } from '../core/grants/service.ts';
import { parseClientRescopeArgs, parseRescopeGrantArgs, splitRescopeTarget, type RescopeGrantArgs } from '../core/grants/cli.ts';
-import { GRANT_PROFILES, GrantError, grantFromClient } from '../core/grants/model.ts';
+import { GRANT_PROFILES, GrantError, TOKEN_TTL_MAX_SECONDS, TOKEN_TTL_MIN_SECONDS, grantFromClient } from '../core/grants/model.ts';
import { cliRenderContext, renderAction, type RenderedAction } from '../core/agent-output.ts';
import { migrateLegacyTokens, parseRescopeTokenArgs, renderLegacyGrantAxis, rescopeLegacyToken, resolveRescopeTarget, type MigrateLegacyResult, type RescopeTokenResult } from '../core/grants/legacy-token.ts';
@@ -384,11 +384,10 @@ export interface RegisterClientArgs {
tokenTtlSeconds: number | undefined;
}
-/** --token-ttl bounds: 1 minute .. 90 days. The SERVER default for CLI-minted
+/** --token-ttl bounds: 1 minute .. 90 days (defined in src/core/grants/model.ts). The SERVER default for CLI-minted
* access tokens is 3600s (oauth-provider.ts tokenTtl) — NOT 30 days; callers
* that promise long-lived tokens must write oauth_clients.token_ttl. */
-export const TOKEN_TTL_MIN_SECONDS = 60;
-export const TOKEN_TTL_MAX_SECONDS = 7_776_000;
+export { TOKEN_TTL_MIN_SECONDS, TOKEN_TTL_MAX_SECONDS };
/**
* Shared --token-ttl value parser (auth register-client + agent register).
@@ -1039,6 +1038,19 @@ export async function listClientRows(engine: BrainEngine): Promise<ClientRow[]>
return bare.map(r => ({ ...r, surface: null, surface_set_by: null, source_id: null, federated_read: null }));
}
+/** Clients whose stored or outstanding access-token lifetime an upgrade brought inside the 90-day maximum. */
+export async function tokenLifetimeClampedClients(engine: BrainEngine): Promise<Set<string>> {
+ try {
+ const rows = await engine.executeRaw<{ client_id: string }>(
+ `SELECT DISTINCT client_id FROM oauth_grant_audit WHERE actor = 'migration' AND action IN ('clamp_token_ttl', 'shorten_access_tokens')`,
+ );
+ return new Set(rows.map(r => r.client_id));
+ } catch (e) {
+ if (isUndefinedTableError(e)) return new Set();
+ throw e;
+ }
+}
+
async function clientsCmd(args: string[]) {
const usageLine = 'Usage: auth clients [--usage] [--days N] [--json]';
let parsed: { usage: boolean; days: number; json: boolean };
@@ -1054,6 +1066,7 @@ async function clientsCmd(args: string[]) {
// Degrade ladder lives in listClientRows: a pre-migration brain still
// gets the listing (missing columns render as null) instead of an error.
const clients = await listClientRows(engine);
+ const lifetimeClamped = await tokenLifetimeClampedClients(engine);
const { readClientOpUsage } = await import('../core/mcp-usage.ts');
const usage = parsed.usage ? await readClientOpUsage(engine, { days: parsed.days }) : [];
@@ -1075,6 +1088,7 @@ async function clientsCmd(args: string[]) {
federated_read: c.federated_read,
...clientOperationsView(c),
revoked_at: c.deleted_at ?? null,
+ token_lifetime_clamped: lifetimeClamped.has(c.client_id),
usage: usageByToken.get(c.client_id) ?? null,
})),
// Legacy bearer tokens seen in the window (no oauth_clients row).
@@ -1098,6 +1112,7 @@ async function clientsCmd(args: string[]) {
console.log(` scopes: ${c.scope ?? '<none>'} surface: ${surfaceStr}`);
console.log(` write source: ${c.source_id ?? '<none>'} federated reads: ${(c.federated_read ?? []).join(', ') || '<none>'}`);
for (const line of clientOperationsLines(c)) console.log(line);
+ if (lifetimeClamped.has(c.client_id)) console.log(' access-token lifetime: clamped to the 90-day maximum by an upgrade (docs/mcp/ADMIN.md#access-token-lifetime)');
if (parsed.usage) {
if (u) {
const auto = u.likely_automation ? ' [automation-shaped: >90% context_pack/delta]' : '';
diff --git a/src/commands/serve.ts b/src/commands/serve.ts
index 466aee0e85..630367046a 100644
--- a/src/commands/serve.ts
+++ b/src/commands/serve.ts
@@ -5,6 +5,7 @@ export { serveFailFastRequested, writeServeFailFastEnvelope } from '../core/serv
import { isEngineDegraded as isEngineDegradedForServe } from '../core/degraded-marker.ts';
import { startMcpServer, stdioRpcsInFlightCount, resolveMcpStdioSourceScope } from '../mcp/server.ts';
import { VERB_NAMES } from '../core/verbs.ts';
+import { parseTokenTtl } from './auth.ts';
import { RESIDENT_POOL_FLOOR } from '../core/pg-access-classify.ts';
import { redirectStdoutLoggingToStderr } from '../core/console-prefix.ts';
import { startFactsDrainScheduler, type FactsDrainScheduler, type FactsDrainSchedulerOpts } from '../core/facts/drain-scheduler.ts';
@@ -272,7 +273,7 @@ export async function runServe(
const port = portIdx >= 0 ? parseInt(args[portIdx + 1]) || 3131 : 3131;
const ttlIdx = args.indexOf('--token-ttl');
- const tokenTtl = ttlIdx >= 0 ? parseInt(args[ttlIdx + 1]) || 3600 : 3600;
+ const tokenTtl = ttlIdx >= 0 ? parseTokenTtl(args[ttlIdx + 1] ?? '', 'Omit the flag for the 3600-second default.') : 3600;
// #1353: --enable-dcr-insecure opts into the consent-bypassing
// client_credentials grant on the DCR path. It implies --enable-dcr (you
diff --git a/src/core/harness/capabilities.ts b/src/core/harness/capabilities.ts
index 36337a7acc..98e171e8b7 100644
--- a/src/core/harness/capabilities.ts
+++ b/src/core/harness/capabilities.ts
@@ -2,7 +2,7 @@ import type { AuthInfo } from '../ops/contract.ts';
import { hasScope, operationScopesAllowed } from '../scope.ts';
import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
-import { normalizeGrantBrain, validGrantPrefixes } from '../grants/model.ts';
+import { TOKEN_TTL_MAX_SECONDS, TOKEN_TTL_MIN_SECONDS, normalizeGrantBrain, validGrantPrefixes } from '../grants/model.ts';
import { shellQuote } from '../mcp-registration.ts';
/** Keep valid bindings implicit so a repair preview cannot replace unrelated
@@ -39,6 +39,8 @@ function delegationRepair(auth: AuthInfo, reasons: readonly string[]) {
if (reasons.includes('delegated_concurrency_invalid')) change(() => choose('--bound-max-concurrent', '<POSITIVE_CONCURRENCY>', 'Choose a positive concurrency limit.'));
if (reasons.some(r => ['delegated_tools_not_granted', 'submit_agent_not_granted'].includes(r))) change(() => choose('--allowed-operations', '<APPROVED_OPERATION_SNAPSHOT>',
'Explicitly review the complete operation snapshot, including submit_agent and the chosen delegated tools. Do not refresh an existing snapshot implicitly.'));
+ if (reasons.includes('token_ttl_invalid')) change(() => choose('--token-ttl', '<APPROVED_TTL_SECONDS>',
+ `Choose an access-token lifetime from ${TOKEN_TTL_MIN_SECONDS} to ${TOKEN_TTL_MAX_SECONDS} seconds (90 days). Every grant change is refused while the stored lifetime is outside that range.`));
if (reasons.includes('submit_agent_not_visible')) checks.push('Inspect the selected surface and host publish gates; a client repair cannot override a server gate.');
if (reasons.includes('grant_projection_unavailable')) checks.push('Repair the host schema/authentication projection before deriving a grant change.');
return {
@@ -84,6 +86,7 @@ export function describeAuthCapabilities(auth: AuthInfo, options: { surface?: st
if (auth.delegatedSlugPrefixes != null) reasons.push('delegated_namespace_ambiguous');
} else if (!validGrantPrefixes(auth.delegatedSlugPrefixes ?? null)) reasons.push('delegated_path_policy_missing');
if (!Number.isSafeInteger(auth.boundMaxConcurrent) || (auth.boundMaxConcurrent ?? 0) < 1) reasons.push('delegated_concurrency_invalid');
+ if (auth.tokenTtlSeconds != null && (!Number.isSafeInteger(auth.tokenTtlSeconds) || auth.tokenTtlSeconds < TOKEN_TTL_MIN_SECONDS || auth.tokenTtlSeconds > TOKEN_TTL_MAX_SECONDS)) reasons.push('token_ttl_invalid');
// Delegated authority is agent + explicit tool bindings, independently of
// direct read/write scopes. The operation snapshot still caps those tools.
const effectiveTools = (auth.boundTools ?? []).filter(name =>
diff --git a/src/core/oauth-grants.ts b/src/core/oauth-grants.ts
index e8397a9cc5..4f3dbc4dce 100644
--- a/src/core/oauth-grants.ts
+++ b/src/core/oauth-grants.ts
@@ -7,7 +7,7 @@ import { InvalidClientError, InvalidGrantError, InvalidRequestError, InvalidTarg
import type { SqlQuery } from './sql-query.ts';
import { generateToken, hashToken } from './utils.ts';
import { hasScope, parseScopeString } from './scope.ts';
-import { intersectGrantedScopes } from './grants/model.ts';
+import { TOKEN_TTL_MAX_SECONDS, intersectGrantedScopes } from './grants/model.ts';
import { safeHexEqual } from './timing-safe.ts';
export type OAuthTransaction = <T>(fn: (sql: SqlQuery) => Promise<T>) => Promise<T>;
@@ -322,7 +322,7 @@ export class OAuthGrants {
private async issue(sql: SqlQuery, client: ClientRow, scopes: string[], resource: URL | undefined, refresh: boolean): Promise<OAuthTokens> {
const clientId = client.client_id as string;
const override = Number(client.token_ttl);
- const ttl = Number.isFinite(override) && override > 0 ? override : this.options.tokenTtl;
+ const ttl = Math.min(Number.isFinite(override) && override > 0 ? override : this.options.tokenTtl, TOKEN_TTL_MAX_SECONDS);
const now = Math.floor(this.now() / 1000);
const access = generateToken('gbrain_at_');
await sql`INSERT INTO oauth_tokens (token_hash, token_type, client_id, scopes, expires_at, resource)
diff --git a/src/core/oauth-provider.ts b/src/core/oauth-provider.ts
index 75fcb03de6..9529328f36 100644
--- a/src/core/oauth-provider.ts
+++ b/src/core/oauth-provider.ts
@@ -37,7 +37,7 @@ import {
dcrScopeViolation,
} from './scope.ts';
import type { AuthInfo as CoreAuthInfo } from './operations.ts';
-import { authSourcesFromGrant, grantFromRow, normalizeGrantBrain, intersectGrantedScopes, type GrantPatch } from './grants/model.ts';
+import { TOKEN_TTL_MAX_SECONDS, authSourcesFromGrant, grantFromRow, normalizeGrantBrain, intersectGrantedScopes, type GrantPatch } from './grants/model.ts';
import { assertValidSlugPrefixes, pgArray } from './grants/encoding.ts';
import { rescopeOAuthClient, type RescopeClientOptions, type RescopeClientResult } from './grants/rescope.ts';
import { grantValidationContext, validateClientGrant, insertClientGrant, assertGrantPatch } from './grants/service.ts';
@@ -566,8 +566,8 @@ export class GBrainOAuthProvider implements OAuthServerProvider {
// token TTL — never a fixed permissive ceiling — so a self-registering
// client cannot elect a longer-lived token than the server default
// unless the admin explicitly configured a wider window.
- const dcrTtlMin = options.dcrTtlMinSeconds ?? DEFAULT_DCR_TTL_MIN_SECONDS;
- const dcrTtlMax = options.dcrTtlMaxSeconds ?? Math.max(this.tokenTtl, dcrTtlMin);
+ const dcrTtlMin = Math.min(options.dcrTtlMinSeconds ?? DEFAULT_DCR_TTL_MIN_SECONDS, TOKEN_TTL_MAX_SECONDS);
+ const dcrTtlMax = Math.min(options.dcrTtlMaxSeconds ?? Math.max(this.tokenTtl, dcrTtlMin), TOKEN_TTL_MAX_SECONDS);
this._clientsStore = new GBrainClientsStore(
this.sql,
options.allowClientCredentialsDcr === true,
@@ -869,6 +869,7 @@ export class GBrainOAuthProvider implements OAuthServerProvider {
grantRevision: Number(row.grant_revision ?? 0),
grantProfile: typeof row.grant_profile === 'string' ? row.grant_profile : null,
grantRepairReasons: Array.isArray(row.grant_repair_reasons) ? row.grant_repair_reasons as string[] : [],
+ tokenTtlSeconds: currentGrant.token_ttl == null ? null : Number(currentGrant.token_ttl),
boundTools: Array.isArray(row.bound_tools) ? row.bound_tools as string[] : null,
boundSourceId: typeof row.bound_source_id === 'string' ? row.bound_source_id : null,
boundBrainId: typeof row.bound_brain_id === 'string' ? row.bound_brain_id : null,
diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.ts
index e3b6389b24..45f440422e 100644
--- a/src/core/ops/contract.ts
+++ b/src/core/ops/contract.ts
@@ -268,6 +268,8 @@ export interface AuthInfo {
grantRevision?: number;
grantProfile?: string | null;
grantRepairReasons?: string[];
+ /** The client's stored access-token lifetime override (`oauth_clients.token_ttl`); null = server default. */
+ tokenTtlSeconds?: number | null;
delegatedSlugPrefixes?: string[] | null;
/** Missing grant projection on a profile client is fail-closed. */
grantProjectionDegraded?: boolean;
diff --git a/test/e2e/oauth-token-ttl-clamp-postgres.test.ts b/test/e2e/oauth-token-ttl-clamp-postgres.test.ts
new file mode 100644
index 0000000000..c7cd087874
--- /dev/null
+++ b/test/e2e/oauth-token-ttl-clamp-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../oauth-token-ttl-clamp.test.ts'));
diff --git a/test/fixtures/goldens/cli/help-and-errors.json b/test/fixtures/goldens/cli/help-and-errors.json
index 05da7cc873..0a6120c7d3 100644
--- a/test/fixtures/goldens/cli/help-and-errors.json
+++ b/test/fixtures/goldens/cli/help-and-errors.json
@@ -192,7 +192,7 @@
" On --http this is the per-client CEILING.",
" --access read-only|full stdio: list and dispatch only read operations",
" serve --http [--port N] HTTP MCP server with OAuth 2.1",
- " --token-ttl N Access token TTL in seconds (default: 3600)",
+ " --token-ttl N Access token TTL in seconds, 60-7776000 (default: 3600)",
" --enable-dcr Enable Dynamic Client Registration (DCR clients default to authorization_code)",
" --enable-dcr-insecure Also allow the consent-bypassing client_credentials grant on DCR (implies --enable-dcr)",
" --public-url URL Public issuer URL (required behind proxy/tunnel)",
@@ -403,7 +403,7 @@
" On --http this is the per-client CEILING.",
" --access read-only|full stdio: list and dispatch only read operations",
" serve --http [--port N] HTTP MCP server with OAuth 2.1",
- " --token-ttl N Access token TTL in seconds (default: 3600)",
+ " --token-ttl N Access token TTL in seconds, 60-7776000 (default: 3600)",
" --enable-dcr Enable Dynamic Client Registration (DCR clients default to authorization_code)",
" --enable-dcr-insecure Also allow the consent-bypassing client_credentials grant on DCR (implies --enable-dcr)",
" --public-url URL Public issuer URL (required behind proxy/tunnel)",
@@ -614,7 +614,7 @@
" On --http this is the per-client CEILING.",
" --access read-only|full stdio: list and dispatch only read operations",
" serve --http [--port N] HTTP MCP server with OAuth 2.1",
- " --token-ttl N Access token TTL in seconds (default: 3600)",
+ " --token-ttl N Access token TTL in seconds, 60-7776000 (default: 3600)",
" --enable-dcr Enable Dynamic Client Registration (DCR clients default to authorization_code)",
" --enable-dcr-insecure Also allow the consent-bypassing client_credentials grant on DCR (implies --enable-dcr)",
" --public-url URL Public issuer URL (required behind proxy/tunnel)",
diff --git a/test/oauth-token-ttl-clamp.test.ts b/test/oauth-token-ttl-clamp.test.ts
new file mode 100644
index 0000000000..c8e5058e31
--- /dev/null
+++ b/test/oauth-token-ttl-clamp.test.ts
@@ -0,0 +1,175 @@
+/**
+ * #5040: access tokens never outlive the 90-day maximum. Authoring gate:
+ * (1) protects issuance (per-client override and server default), the
+ * upgrade clamp of stored client lifetimes and outstanding access tokens
+ * (audited, never lengthening, refresh tokens untouched, re-runnable), the
+ * rescope of a formerly out-of-range client, the whoami repair template and
+ * the `serve --token-ttl` bounds; (2) fails when a stored or configured
+ * lifetime above the maximum is honored, or an upgraded brain keeps a
+ * 10-year token valid; (3) the existing DCR TTL tests only cover in-range
+ * overrides; (4) no production seam. Both engines: PGLite here, PostgreSQL
+ * through test/e2e/oauth-token-ttl-clamp-postgres.test.ts.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../src/core/sql-query.ts';
+import { hashToken } from '../src/core/utils.ts';
+import { MIGRATIONS, runMigrations } from '../src/core/migrate.ts';
+import { readClientGrant, rescopeClientGrant } from '../src/core/grants/service.ts';
+import { describeAuthCapabilities } from '../src/core/harness/capabilities.ts';
+import * as auth from '../src/commands/auth.ts';
+import { runServe } from '../src/commands/serve.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const TEN_YEARS = 315_360_000;
+const DAY = 86_400;
+const NINETY_DAYS = 7_776_000;
+
+for (const kind of testBackends()) {
+ describe(`OAuth access-token lifetime ceiling (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ let provider: GBrainOAuthProvider;
+ const providerFor = (tokenTtl?: number) => new GBrainOAuthProvider({
+ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))), tokenTtl,
+ });
+ beforeAll(async () => {
+ if (kind === 'postgres') {
+ ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ } else {
+ const pglite = new PGLiteEngine();
+ await pglite.connect({});
+ await pglite.initSchema();
+ engine = pglite;
+ close = () => pglite.disconnect();
+ }
+ provider = providerFor();
+ }, 120_000);
+ afterAll(async () => { await close?.(); });
+
+ const machineClient = (name: string) => provider.registerClientManual(name, ['client_credentials'], 'read', [], 'default');
+ const storeTtl = (clientId: string, ttl: number | null) =>
+ engine.executeRaw('UPDATE oauth_clients SET token_ttl = $1 WHERE client_id = $2', [ttl, clientId]);
+ const seedToken = async (clientId: string, type: 'access' | 'refresh', ageSeconds: number, expiresIn: number) => {
+ const token = `gbrain_${type === 'access' ? 'at' : 'rt'}_fixture_${crypto.randomUUID()}`;
+ const now = Math.floor(Date.now() / 1000);
+ await engine.executeRaw(
+ `INSERT INTO oauth_tokens (token_hash, token_type, client_id, scopes, expires_at, created_at)
+ VALUES ($1, $2, $3, ARRAY['read'], $4, to_timestamp($5))`,
+ [hashToken(token), type, clientId, now + expiresIn, now - ageSeconds],
+ );
+ return { token, createdAt: now - ageSeconds, expiresAt: now + expiresIn };
+ };
+ const expiryOf = async (token: string) =>
+ Number((await engine.executeRaw<{ expires_at: string }>('SELECT expires_at FROM oauth_tokens WHERE token_hash = $1', [hashToken(token)]))[0]!.expires_at);
+ const auditRows = (clientId: string) => engine.executeRaw<{ action: string; actor: string; before_grant: any; after_grant: any }>(
+ 'SELECT action, actor, before_grant, after_grant FROM oauth_grant_audit WHERE client_id = $1 AND actor = $2 ORDER BY id', [clientId, 'migration']);
+ const clampMigration = MIGRATIONS.find(m => m.name.endsWith('clamp_oauth_token_ttl'));
+ const rerunClamp = async () => {
+ expect(clampMigration).toBeDefined();
+ await engine.setConfig('version', String(clampMigration!.version - 1));
+ await runMigrations(engine);
+ };
+
+ test('a stored override above the maximum issues a 90-day token', async () => {
+ const { clientId, clientSecret } = await machineClient('ttl-override-example');
+ await storeTtl(clientId, TEN_YEARS);
+ const tokens = await provider.exchangeClientCredentials(clientId, clientSecret!, 'read');
+ expect(tokens.expires_in).toBe(NINETY_DAYS);
+ const auth = await provider.verifyAccessToken(tokens.access_token);
+ expect(auth.expiresAt! - Math.floor(Date.now() / 1000)).toBeLessThanOrEqual(NINETY_DAYS);
+ });
+
+ test('a server default above the maximum issues a 90-day token', async () => {
+ const longDefault = providerFor(TEN_YEARS);
+ const { clientId, clientSecret } = await longDefault.registerClientManual('ttl-default-example', ['client_credentials'], 'read', [], 'default');
+ const tokens = await longDefault.exchangeClientCredentials(clientId, clientSecret!, 'read');
+ expect(tokens.expires_in).toBe(NINETY_DAYS);
+ });
+
+ test('upgrade clamps stored lifetimes and outstanding access tokens, audited and re-runnable', async () => {
+ const over = await machineClient('ttl-over-example');
+ const under = await machineClient('ttl-under-example');
+ const zero = await machineClient('ttl-zero-example');
+ const valid = await machineClient('ttl-valid-example');
+ await storeTtl(over.clientId, TEN_YEARS);
+ await storeTtl(under.clientId, 30);
+ await storeTtl(zero.clientId, 0);
+ await storeTtl(valid.clientId, 3600);
+ const old = await seedToken(over.clientId, 'access', 100 * DAY, 9 * 365 * DAY);
+ const recent = await seedToken(over.clientId, 'access', DAY, 9 * 365 * DAY);
+ const shorter = await seedToken(over.clientId, 'access', DAY, 3600);
+ const refresh = await seedToken(over.clientId, 'refresh', 100 * DAY, 9 * 365 * DAY);
+ const validToken = await seedToken(valid.clientId, 'access', DAY, 3600);
+ const revisions = new Map<string, number>();
+ for (const c of [over, under, zero, valid]) revisions.set(c.clientId, (await readClientGrant(engine, c.clientId)).revision);
+
+ const beforeAuth = await provider.verifyAccessToken(old.token);
+ const whoami = describeAuthCapabilities(beforeAuth);
+ expect(whoami.remediation.map(r => r.reason)).toContain('token_ttl_invalid');
+ expect(whoami.delegation_repair?.preview_command).toContain('--token-ttl');
+ expect(whoami.delegation_repair?.missing_choices.map(c => c.placeholder)).toContain('<APPROVED_TTL_SECONDS>');
+
+ await rerunClamp();
+
+ expect((await readClientGrant(engine, over.clientId)).tokenTtlSeconds).toBe(NINETY_DAYS);
+ expect((await readClientGrant(engine, under.clientId)).tokenTtlSeconds).toBe(60);
+ expect((await readClientGrant(engine, zero.clientId)).tokenTtlSeconds).toBeNull();
+ expect((await readClientGrant(engine, valid.clientId)).tokenTtlSeconds).toBe(3600);
+ for (const c of [over, under, zero]) expect((await readClientGrant(engine, c.clientId)).revision).toBe(revisions.get(c.clientId)! + 1);
+ expect((await readClientGrant(engine, valid.clientId)).revision).toBe(revisions.get(valid.clientId)!);
+
+ await expect(provider.verifyAccessToken(old.token)).rejects.toThrow('Token expired');
+ expect(await expiryOf(recent.token)).toBe(recent.createdAt + NINETY_DAYS);
+ expect((await provider.verifyAccessToken(recent.token)).expiresAt).toBe(recent.createdAt + NINETY_DAYS);
+ expect(await expiryOf(shorter.token)).toBe(shorter.expiresAt);
+ expect(await expiryOf(refresh.token)).toBe(refresh.expiresAt);
+ expect(await expiryOf(validToken.token)).toBe(validToken.expiresAt);
+
+ const overAudit = await auditRows(over.clientId);
+ expect(overAudit.map(r => r.action)).toEqual(['clamp_token_ttl', 'shorten_access_tokens']);
+ expect(overAudit[0]!.before_grant.tokenTtlSeconds).toBe(TEN_YEARS);
+ expect(overAudit[0]!.after_grant.tokenTtlSeconds).toBe(NINETY_DAYS);
+ expect(overAudit[1]!.after_grant.shortenedAccessTokens).toBe(2);
+ expect((await auditRows(under.clientId))[0]!.before_grant.tokenTtlSeconds).toBe(30);
+ expect(await auditRows(valid.clientId)).toEqual([]);
+ const marked = await auth.tokenLifetimeClampedClients(engine);
+ expect([over, under, zero, valid].map(c => marked.has(c.clientId))).toEqual([true, true, true, false]);
+
+ await rerunClamp();
+ expect((await auditRows(over.clientId)).length).toBe(2);
+ expect(await expiryOf(recent.token)).toBe(recent.createdAt + NINETY_DAYS);
+ expect((await readClientGrant(engine, over.clientId)).revision).toBe(revisions.get(over.clientId)! + 1);
+
+ const rescoped = await rescopeClientGrant(engine, over.clientId, { surface: 'verbs' }, { actor: 'test' });
+ expect(rescoped.after.surface).toBe('verbs');
+ expect(rescoped.after.tokenTtlSeconds).toBe(NINETY_DAYS);
+ }, 60_000);
+
+ test('issuance racing the upgrade never leaves a token past the maximum', async () => {
+ const { clientId, clientSecret } = await machineClient('ttl-race-example');
+ await storeTtl(clientId, TEN_YEARS);
+ await engine.setConfig('version', String(clampMigration!.version - 1));
+ await Promise.all([
+ runMigrations(engine),
+ ...Array.from({ length: 4 }, () => provider.exchangeClientCredentials(clientId, clientSecret!, 'read')),
+ ]);
+ const rows = await engine.executeRaw<{ over: string }>(
+ `SELECT count(*) AS over FROM oauth_tokens WHERE client_id = $1 AND token_type = 'access'
+ AND expires_at > FLOOR(EXTRACT(EPOCH FROM created_at))::bigint + $2`, [clientId, NINETY_DAYS]);
+ expect(Number(rows[0]!.over)).toBe(0);
+ }, 60_000);
+ });
+}
+
+describe('serve --token-ttl bounds', () => {
+ for (const value of [String(TEN_YEARS), 'abc', '0', '']) {
+ test(`--token-ttl ${JSON.stringify(value)} is refused before the server starts`, async () => {
+ await expect(runServe({} as BrainEngine, ['--http', '--token-ttl', value])).rejects.toThrow(
+ '--token-ttl must be an integer number of seconds between 60 and 7776000 (90 days)');
+ });
+ }
+});