Skip to content

Commit 6bd00d2

Browse files
feat(plugin-auth): read the AI assistants a person has authorized, and when each was last used (#30946)
<!-- claude-projects-attribution: {"github_login":"os-elon-musk"} --> _Requested by **Elon** · [project thread](https://claude.ai/code/project/chan_01WedDzV26nniwxv7jC88B9D?thread=cmsg_01WedDzV26nniwxv7jC88B9DN53GvpyR9kuEwj3GGM9RrE)_ domain:server#1 · os-elon-musk · session_016WV4d1LNDAUs8pz7DNjQFC Fixes #30918 Clause-②: yes (widening) Metadata-protocol: none Claim: 6683953156 (the full re-post of 6683760626 with this branch, the stamp's home and the dogfood classification rows) · Branch: `claude/project-thread-tmgp4d` · Access boundary: security#1's 6683642288, rules 1 to 7, with the seat's rule-2 reading 6683944651 · Draft: owes a `CONTRACT_REVIEW_TIER` review against those rules, arranged by the seat. How the two lines were derived. **Clause-②: yes (widening)**: two new served reads (`AUTH_ROUTE_LEDGER` rows, `sdk`), two new `@objectstack/client` methods with two new exported types, and one new nullable column; nothing existing is removed or tightened. **Metadata-protocol: none**: the new `sys_oauth_consent.last_used_at` is a data column on a shipped, better-auth-managed object (`lock: 'full'`, `apiEnabled: false`), declared as an ordinary `Field.datetime({ readonly: true, required: false })` in `packages/platform-objects/src/identity/sys-oauth-consent.object.ts`. No metadata author can write it, and no key, accepted value or metadata type changes. ## 维护者速读 - 改了什么:新增两个只读接口。`GET /api/v1/auth/authorized-clients` 让本人看到自己授权过的 AI 助手(Claude Desktop、IDE 助手等 MCP 客户端)及每个最近一次使用的时间。`GET /api/v1/auth/admin/authorized-clients?userId=` 让平台管理员查看某个人的授权,逐行标明所属组织。`@objectstack/client` 对应新增 `oauth.authorizedClients.list()` / `.listForUser()`。服务端在 MCP 令牌验证通过后记录“最近使用时间”,精确到小时,且只记在放行这次调用的那条授权上(与 #30879 撤销后的验证规则一致:已撤销或重新授权后的旧令牌一律不记)。 - 为什么改:同意页告诉用户“可随时撤回授权”,但用户和管理员都看不到有哪些 AI 助手能以他的身份行事、最近还在不在用。控制台页面 #30894 需要这两个接口。 - 风险与回滚:本人接口只按会话本人取数,带任何参数都直接 400,不会读别人的。管理员接口与管理端会话接口同一道平台管理员门槛:组织所有者、组织管理员和普通成员都拿到同一个 403,目标人是否存在不影响回答。回答里没有任何令牌、授权码或密钥。时间戳每个进程内每个授权每小时最多写一次,写在请求结束之后,写失败不影响 MCP 调用,每种不同的失败在每个进程里报一次。回滚即撤 PR,新增的那一列为空列,可以留着不管。 - 先看:`packages/plugins/plugin-auth/src/authorized-clients-read.ts`(两个接口的拒绝顺序和返回字段),`packages/plugins/plugin-auth/src/auth-plugin.ts` 里 `admin/authorized-clients` 那段(门槛在读参数之前),`packages/plugins/plugin-auth/src/mcp-client-last-use.ts` 的 `record`(每小时一次的判断)。 - 两分钟验证:`pnpm --filter @objectstack/plugin-auth exec vitest run src/authorized-clients-read.real-plugin.test.ts src/mcp-client-last-use.real-engine.test.ts`,预期 20/20 通过。 - 需要你做的:无,席位落地。 ## What changes **Two reads** (`authorized-clients-read.ts`, mounted in `auth-plugin.ts` ahead of the better-auth catch-all): - `GET /api/v1/auth/authorized-clients` (rule 1): the session user's own OAuth consents. The query set is closed and empty, so `?userId=` or any other parameter is refused `400 VALIDATION_ERROR` naming the parameter. It is never ignored, because an ignored selector reads exactly like an honoured one, which is what better-auth's own `get-consents` does with a `userId`. Order: `401` with no session, then a held session's `403`, then the query check, then the read. - `GET /api/v1/auth/admin/authorized-clients?userId=ID` (rules 2 to 4): gated by `gateAdmin(c)`, the ADR-0068 D2 `judgePlatformAdmin` judge with a held session refused per ADR-0069 D3. That is the gate every ObjectStack `/admin/*` mount and `sys-session/revoke` use; the reading is in 6683944651. The gate runs before the query is read, so a caller outside reach gets one byte-identical refusal whoever `userId` names and whether that person exists. An organization owner or admin is not a platform admin and is refused. Rows span every organization the person granted in, and each names its `organizationId` (rule 3). Read only: there is no withdraw door here (rule 4). Past the gate, a missing, empty or repeated `userId` or an unknown parameter is `400`, and an id naming no user is `404 RESOURCE_NOT_FOUND`. - The answer (rule 5): `{ success: true, data: { clients, truncated } }`, `Cache-Control: no-store`, newest grant first. Each row carries exactly `id` (the consent id, the key `/oauth2/delete-consent` takes), `clientId`, `name`, `scopes`, `organizationId`, `authorizedAt` and `lastUsedAt`. Nothing identifies or reconstructs a token: the consent and client reads name their columns, so no secret column is ever loaded. At most 200 rows, with `truncated: true` past that. **The last-use stamp** (rule 6; `mcp-client-last-use.ts`, wired in `AuthManager.verifyMcpAccessToken`): - Home: `sys_oauth_consent.last_used_at` (option A of the claim). A consent is the grant the person sees and withdraws, it is held per organization, and a withdrawn or revoked consent is a deleted row, so no usage record outlives its grant. - Writer: only after `verifyMcpAccessToken` admits a token, from the verified token (`sub`, `azp`, `organization_id`, `iat`) and the server clock. The consent is chosen by the rule the verifier admits the token by since #30879 (`mcpConsentAdmits`): the provider's `findConsent` row for the token's organization, created no later than the token's `iat`. So the stamp can only land on the consent that admitted the call. A revoked consent refuses the call and stamps nothing, and a consent granted again is never stamped with a token of the earlier grant, even when the re-grant lands between the verdict and the after-response stamp. A token with no `azp` is refused by the verifier. No request field reaches it, and the provider's consent doors do not carry it: `update-consent`'s zod body strips it, which is pinned. - Coarse, one clock hour: the value is the hour's start, and a row is written only when its stored hour is older than the current one. Each process also remembers the hour it settled per (client, user, organization), so a busy assistant costs no I/O inside an hour: at most one read and one write per consent per hour per process. The hour is the granularity that answers "is this laptop's assistant still acting as me?" and that an administrator can be shown without exposing a minute-by-minute activity trail. - Off the request path (`runAfterResponse`): the verdict never waits on the stamp. Each distinct failure (by message, at most 16) is logged once per process at `error` (with `console.error` when the manager has no logger) and retried next hour, never next call. A consent withdrawn between the stamp's read and its write is not a failure: the engine's by-id `RECORD_NOT_FOUND` on that write counts as done, so the race cannot use up the report a real outage needs. **Around them:** two `AUTH_ROUTE_LEDGER` rows (`sdk`, `oauth.authorizedClients.list` / `.listForUser`) and the conformance own-list pin. `@objectstack/client` gets `oauth.authorizedClients.list()` / `.listForUser(userId)` and the exported `AuthorizedClient` / `AuthorizedClientsList` types. The field is declared in `platform-objects` and its four regenerated translation bundles carry hand-written zh-CN / ja-JP / es-ES text. The two `/admin/` dogfood sweeps get classification rows only: `objectstack-gate` with `?userId=`, and `ADMITTED` with its query, as #30398 did for `client-address`. `oauth-provider-schema-parity.test.ts` gains a pin that no provider consent field resolves to `last_used_at`. The tenant audit census counts the stamp's one system-context write: 261 → 262, regenerated by its own script, with the page's prose numbers moved to match. ## Tests On the real plugin. A real `AuthManager` (real better-auth, real `customSession`, real sign-ups and sessions) serves the real `AuthPlugin` routes on a Hono app. Consents are written through better-auth's own adapter, so the read decodes exactly what the provider stores. `authorized-clients-read.real-plugin.test.ts`, 10 cases: - a member reads exactly their own grants, newest first, exact key set, no client secret, access/refresh token or session token in the text (the card's first; rules 1 and 5); - a member's `?userId=<other>` is `400` and carries none of the other's rows (rule 7, first clause); - every other parameter is `400` (closed set); - anonymous is `401` on both doors; - `truncated` past the cap, newest first; - a platform admin reads a person's grants across two organizations plus one with none, each naming its organization (the card's second; rule 3); - **rule 7**: a member, an organization OWNER and an organization ADMIN of the target's organization, and the target themself, each get `403 PERMISSION_DENIED` byte-identical for an existing id, a nonexistent id and no id (the card's third); - **rule 7, outside their organizations**: the organization owner and admin of Acme, naming a person who is only in Beta, get the same `403` bytes as for a person inside Acme, with none of the person's rows; - admin `400` for missing, empty, whitespace, repeated and unknown parameters, `404` for an id naming no user; - an empty list, not a refusal, for a person with no grants. `mcp-client-last-use.real-engine.test.ts`, 10 cases, on ObjectQL + better-sqlite3, so the column is the one schema sync creates and tokens are minted by the real jwt plugin: - 25 verified calls in one hour make 1 write and 1 read with the hour's start; later in the same hour, 0 I/O; the next hour, 1 more write; the admin read answers that hour start; - a second process on the same store makes 1 read and 0 writes in an hour already stamped; - the stamp follows the token's organization claim and touches no sibling consent; - wrong audience, an unpublished key, an expired token, garbage and a `client_id`-only token (refused by the verifier since #30879) stamp nothing, against a positive control in the same process; - `update-consent` with `lastUsedAt` / `last_used_at` in its body moves the scopes and leaves the stamp `null`, and the next verified call writes the server's hour; - a failing store: 16 calls over two hours, every verdict still answered, 2 attempts, 1 `error` report naming the column; - two different failures over three hours (locked store, missing column, locked store again) give 3 attempts and 2 reports, one per distinct message; - the withdrawal race on the real engine: the consent is deleted after the stamp's read, the write meets `RECORD_NOT_FOUND`, and nothing is reported; a later missing-column outage in the same process is still reported; - with #30879: a withdrawn consent refuses its token and stamps nothing in this hour or the next; after a re-grant the old token is refused and the new consent stays unstamped until a token of its own grant is used, which stamps it; - the re-grant race on the real engine: the verdict admits the old token, the consent is revoked and granted again before the stamp reads, and nothing is written. Plus `oauth-authorized-clients.test.ts` (client URLs, encoding, unwrap, throw on refusal, types), the parity pin and the ledger conformance pin. <details><summary>Ablations: one-shot, uncommitted, through <code>scripts/ablation-replace.mjs</code>, each restored to the HEAD blob</summary> - **Subject keying, honoured selector**: the own read answers `request.queries.userId?.[0] ?? subject` with the closed-query check removed. Red: "a member who names another person with ?userId= is REFUSED 400", "any other parameter is refused the same way". 2 failed, 7 passed. - **Subject keying, filter dropped**: the consent read's `where: { user_id: userId }` becomes `where: {}`. Red: "a member reads exactly their own grants". 1 failed, 8 passed. - **Admin reach check removed**: `const actor = await gateAdmin(c); if (actor instanceof Response) return actor;` becomes `const actor = {} as any;`. Red: "anonymous is 401 UNAUTHENTICATED on both doors", "rule 7: a member, an organization OWNER and an organization ADMIN are refused with ONE answer". 2 failed, 7 passed. - **Coarseness removed**: the per-process hour memo is deleted and the stored-hour check is replaced by a per-call write of the precise time. Red: all 6 stamp cases (`expected '2026-11-06T10:17:00.050Z' to be '2026-11-06T10:00:00.000Z'`; the failure case `one attempt per hour: expected 16 to be 2`). - **Withdrawn consent counted as a failure** (the `RECORD_NOT_FOUND` no-op deleted): red, "a consent withdrawn between the stamp's read and its write is no failure" (`expected … to have a length of +0 but got 1`). 1 failed, 7 passed. - **First failure only** (`reportedFailures.has(message)` becomes `reportedFailures.size > 0`): red, "reports each DISTINCT failure once" (`expected [ Array(1) ] to deeply equal [ …(2) ]`). 1 failed, 7 passed. - **Stamp ignores the token's age** (`consentForToken` returns the organization's row without the `createdAt ≤ iat` check): red, "a re-grant that lands between the verdict and the stamp is not stamped with the old token's use" (`expected 1 to be +0`). 1 failed, 9 passed. - **`iat` not handed to the stamp** (`stamper.record(principal)` without `issuedAt`): red, 9 of the 10 stamp cases, since no consent admits a token without one. 9 failed, 1 passed. - **An organization-admin lane** (the admin door also admits any caller holding an `owner` or `admin` membership anywhere): red, both rule 7 cases, the new one with Acme's admin answered `200` with Beta's `client_beta_only`. 2 failed, 8 passed. Each run printed `ok mutation landed` (anchor 1 → 0, blob changed) and `ok restored: blob == HEAD and git diff HEAD is empty`. </details> ## Acceptance notes - **Rule 2 reading.** `/admin/list-user-sessions` is better-auth's, gated on the legacy `role = 'admin'` scalar, and refuses a real ObjectStack platform admin by design (#9969), so its gate cannot be copied literally. This PR uses the gate ObjectStack's admin session door `sys-session/revoke` uses (`judgePlatformAdmin`), as recorded in 6683944651 for security#1 to confirm or correct. A platform admin's reach crosses the tenant wall on better-auth objects (ADR-0095 D1), so the admin read is not bounded to one organization, and every row names its organization instead. - **Extension field mechanism.** The claim names ADR-0105 D7's `MANAGED_EXTENSION_FIELDS`. That guard's own test excludes every `sys_oauth_*` object with "covered by `oauth-provider-schema-parity.test.ts`", so the collision pin (no provider field may resolve to `last_used_at`) is written there instead, and `MANAGED_EXTENSION_FIELDS` is unchanged. - **#30879 (revoke) is merged, and this branch is merged with it** (`e4655063a1`, a plain merge commit). The `auth-manager.ts` conflict is resolved by keeping both import blocks, main's `verifyMcpAccessToken` host (with `getAuthContext`) with this branch's `.then`, and main's `answerOAuthTokenRevocation` unchanged. The commit after it makes the stamp pick its consent by the verifier's rule (above). The verifier's per-call consent read and the stamp's hourly read could share one read; not done here. One edge remains: in the re-grant race, that process's hour stays claimed, so the new consent's first stamp waits for the next hour. - **A banned subject's verified token still stamps.** The ban refusal runs after `verifyMcpAccessToken`, in the runtime's MCP door. The stamp then records an attempt the door refused, still at most once an hour. Moving the ban check is outside this card, and the seat filed it as #30949. - **Deployments without schema sync** lack the column: both reads answer `500 INTERNAL_ERROR` and the stamp logs that error naming the column, once per process. Existing consent rows read `lastUsedAt: null`; a consent older than the provider's `createdAt` reads `authorizedAt: null`. - **Docs.** No page lists these routes or claims there is no such read, so no sentence had to change. The console page is #30894. - **Outside the claimed file surface: two generated census files.** `content/docs/permissions/tenant-audit-census.mdx` (a `content/docs` page, but its prose counts are not route sentences) and `docs/audits/2026-08-tenant-audit-write-call-sites.counts.md`. `check-tenant-audit-census` is a derived gate and goes red on any new engine write, so both were regenerated by `node scripts/tenant-audit-census.mjs --write`, and the page's six prose numbers were moved to match. Reported to the seat. ## Verification **Head `0bed2ac5df`**: `e4655063a1` merges `origin/main` at `1aeeafd9d3` (#30879) and resolves `auth-manager.ts`; `0bed2ac5df` makes the stamp pick its consent by the verifier's rule (5 files, +161 / -33). The delta against `main` is 24 files, +2150 / -32. This was run after `pnpm install --frozen-lockfile` and a whole-tree `turbo run build --filter=!@objectstack/docs` (118/118 tasks, lock VERDICT command-exit 0): - `pnpm --filter @objectstack/plugin-auth test`: Test Files 231 passed (231), Tests 4168 passed, 10 skipped (4178), exit 0; - `pnpm --filter @objectstack/client test`: 55 files, 708 tests, exit 0; - `pnpm --filter @objectstack/platform-objects test`: 117 files, 1591 tests, exit 0; - plugin-auth `typecheck` (with `check:test-typecheck`): exit 0; - `dispatch-gates.mjs --commands` re-derived 98 families on this tree, each run sequentially with its exit code captured, all 98 exit 0; `--ran`: "98 derived famil(ies) accounted for — 98 run, 0 NOT-MEASURED"; `pnpm lint`: exit 0. **Delta on head `9688e17ce3`** (contract review 6686013581: should-fix 1, 3 and 4; 5 files, +170 / -23, all in plugin-auth and its changeset): the two real-plugin files 18/18; `auth-manager.mcp-oauth`, `-mcp-verifier-keyring`, `-mcp-oauth-resource`, `oauth-provider-schema-parity` and the ledger conformance test 114/114; plugin-auth `typecheck` (with `check:test-typecheck`) exit 0; `eslint` on the four changed source and test files exit 0; `check-tenant-audit-census`, `check-changeset-no-major`, `check-empty-changeset`, `check-issue-citations`, `check:auth-mount-ledger` and `check-comment-mask-corpus` exit 0. Should-fix 2 (one undecodable `scopes` row answers `500`) is left as built, as the seat directed. The rest of this section is the original run, on head `121bdd35a4`: All on head `121bdd35a4` (this branch merged with `origin/main` `4d56914aa`; the delta against `main` is 24 files, +1874 / -31, of which 891 lines are the two real-plugin test files), after a whole-tree `turbo run build --filter=!@objectstack/docs` (118/118 tasks, lock VERDICT command-exit 0). - `pnpm --filter @objectstack/plugin-auth test`: Test Files 230 passed (230), Tests 4112 passed, 10 skipped (4122), VERDICT command-exit 0. - `pnpm --filter @objectstack/client test`: Test Files 55 passed (55), Tests 708 passed (708), including `client-url-conformance.test.ts` (both new methods driven and matched to their ledger rows) and `auth-route-ledger-coverage.test.ts`. - `pnpm --filter @objectstack/platform-objects test`: Test Files 117 passed (117), Tests 1591 passed (1591). - `typecheck` for plugin-auth, client, platform-objects and dogfood, plus `check:test-typecheck` for plugin-auth and client: all exit 0. - The two `/admin/` dogfood sweeps, run locally against the booted stack: `admin-route-nonadmin-refusal` and `admin-platform-admin-standing`, Test Files 2 passed (2), Tests 15 passed (15). Positive control: with the `ADMITTED` entry deleted, the standing sweep goes red naming `GET /api/v1/auth/admin/authorized-clients` as unclassified (1 failed, 7 passed), so the sweep derives the new mount. - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 98 families on this head. Each ran sequentially with its exit code captured before any pipe: all 98 exit 0. `--ran`: "98 derived famil(ies) accounted for — 98 run, 0 NOT-MEASURED". `pnpm lint`: exit 0. On the first pass, `check-tenant-audit-census` (and its self-test, which reads the live tree) went red on the stamp's new write site, which is fixed by the census commit. `check:skill-examples` and `check:dual-build-cjs-loads` exited 3 (no build output) until the whole-tree build ran. - `check:i18n` exit 0 after `check-i18n-bundles.mjs --write` plus the three hand translations; `check:i18n-stale-fill` exit 0. `check:i18n-coverage` is not in the derived set and was not measured (it needs the examples' build closure). - Every family CI runs on this PR is read from the PR's check runs, not re-run here. ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (No `packages/spec` change.) - [x] 2. Every name I added uses the casing for its kind. (`last_used_at` snake_case column; camelCase wire members.) - [x] 3. No formatter ran; `pnpm lint` passes. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. (Three `patch` changesets: plugin-auth, client, platform-objects.) - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (Not touched.) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. --- _Generated by [Claude Code](https://claude.ai/code/session_016WV4d1LNDAUs8pz7DNjQFC)_ <!-- signed: domain:server#1 · os-elon-musk · session_016WV4d1LNDAUs8pz7DNjQFC --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 5cb7d7e commit 6bd00d2

25 files changed

Lines changed: 2152 additions & 30 deletions
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/client': patch
3+
---
4+
5+
feat(client): `client.oauth.authorizedClients.list()` and `.listForUser(userId)` read the AI assistants a person has authorized and when each was last used
6+
7+
Clause-②: yes (widening)
8+
Metadata-protocol: none
9+
10+
`list()` calls `GET /api/v1/auth/authorized-clients` with no parameter: the caller's own grants. `listForUser(userId)` calls `GET /api/v1/auth/admin/authorized-clients?userId=...` and is answered for a platform administrator only. Both unwrap the `{ success, data }` envelope to the new exported `AuthorizedClientsList` type, `{ clients: AuthorizedClient[]; truncated: boolean }`. `AuthorizedClient.lastUsedAt` is an hour start, `null` when no use has been recorded. A refusal throws, as every other method does. Nothing existing changes.
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/platform-objects': patch
3+
---
4+
5+
feat(platform-objects): `sys_oauth_consent` gains `last_used_at`, the start of the most recent hour in which the client made a verified MCP call under the consent
6+
7+
Clause-②: yes (widening)
8+
Metadata-protocol: none
9+
10+
A nullable, read-only datetime on the better-auth-managed consent table, owned by ObjectStack. The OAuth provider neither reads nor writes it. Its one writer is plugin-auth, server-side, after it verifies an MCP access token minted under the consent. The object stays off the data API (`apiEnabled: false`), so no client reaches the column. A withdrawn or revoked consent takes the stamp with it. Schema sync adds the column, and existing rows read `null`.
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
'@objectstack/plugin-auth': patch
3+
---
4+
5+
feat(plugin-auth): a person can read the AI assistants they have authorized and when each was last used, and a platform administrator can read another person's
6+
7+
Clause-②: yes (widening)
8+
Metadata-protocol: none
9+
10+
Two new reads, both ObjectStack mounts ahead of the better-auth catch-all and both in `AUTH_ROUTE_LEDGER`:
11+
12+
- `GET /api/v1/auth/authorized-clients` answers the signed-in person's own OAuth consents (Claude Desktop, an IDE agent, any MCP client). It is keyed by the session and nothing else: it takes no query parameter, and one that is sent (`?userId=` included) is refused `400 VALIDATION_ERROR` rather than ignored.
13+
- `GET /api/v1/auth/admin/authorized-clients?userId=ID` answers another person's, for a platform administrator only. It is gated exactly as the admin session doors are (ADR-0068 D2, a held session refused per ADR-0069 D3). The gate runs before the query is read, so anyone else (an organization owner or admin included) gets one `403 PERMISSION_DENIED` whether or not the person exists. It lists every organization the person granted in. A missing, empty or repeated `userId` is `400`, and an id naming no user is `404 RESOURCE_NOT_FOUND`. It is read only.
14+
15+
Each row carries exactly `id` (the consent id, the key `POST /oauth2/delete-consent` takes), `clientId`, `name`, `scopes`, `organizationId`, `authorizedAt` and `lastUsedAt`. Nothing in it identifies or reconstructs a token. The answer is newest first, at most 200 rows, with `truncated: true` when the person holds more, and it is sent with `Cache-Control: no-store`.
16+
17+
`lastUsedAt` is the start of the most recent clock hour in which the client made a verified MCP call under that consent, or `null` when none has been recorded. The server writes it after `verifyMcpAccessToken` admits a token, and only on the consent that admitted it: the consent for the token's client, person and organization, created no later than the token was issued, the rule the verifier's own consent read applies. So a revoked consent, or a token of an earlier grant, stamps nothing. The write is off the request path, at most once per consent per hour in each process (several processes may each write the same hour start), from the verified token and the server clock alone. A store failure never fails the MCP call, and each distinct failure is logged once per process at `error`; a consent withdrawn between the stamp's read and its write is not a failure. It lands in the new `sys_oauth_consent.last_used_at` column, so a deployment picks it up at its next schema sync. Until then the reads answer `500` and the stamp logs that error once per process.

‎content/docs/permissions/tenant-audit-census.mdx‎

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ are reported as `undecidable` rather than assumed either way.
132132

133133
The same holds twice over for the context. An options argument spelled as a
134134
literal can be read; one spelled `options`, `{ ...opts }`, or handed through a
135-
forwarding shim cannot, and **55 of the 263 sites are spelled that way**. A
135+
forwarding shim cannot, and **55 of the 264 sites are spelled that way**. A
136136
context resolved from an inline literal or a local `const` can be tested for
137137
`isSystem`; one arriving from a helper call cannot.
138138

@@ -197,10 +197,10 @@ reproduce them. Where it disagrees, it disagrees on the page:
197197

198198
| carried figure | where it survives | this census |
199199
| :--- | :--- | ---: |
200-
| 175 write call sites | quoted in the merged changeset | **263** |
200+
| 175 write call sites | quoted in the merged changeset | **264** |
201201
| 24 carrying no tenant context | quoted in the merged changeset | **2** provable and tenancy-enabled; **29** more whose options argument is unreadable |
202-
| 127 of 175 statically decidable, 48 runtime-parameter-name sites | restated on the `isSystem`-scoping card | **186 of 263** decidable, **77** undecidable |
203-
| 135 (77%) silenced by the `isSystem` guard before the posture gate | the lost issue body — **no surviving corroboration** | **not reproduced**: 146 decidably elevated, 0 decidably not, 109 undecidable |
202+
| 127 of 175 statically decidable, 48 runtime-parameter-name sites | restated on the `isSystem`-scoping card | **187 of 264** decidable, **77** undecidable |
203+
| 135 (77%) silenced by the `isSystem` guard before the posture gate | the lost issue body — **no surviving corroboration** | **not reproduced**: 147 decidably elevated, 0 decidably not, 109 undecidable |
204204
| 141 and 132, two independent re-derivations | the card that filed this work | — |
205205

206206
**The differences are not reconciled, and deliberately so.** The old census's
@@ -217,11 +217,11 @@ would report a smaller number and would not say so.
217217

218218
The fourth row is the one worth flagging to anyone citing it. **The 135 / 77%
219219
figure has no surviving corroboration anywhere in the tree.** This census reads
220-
146 of 263 (56%) as decidably elevated, with 109 more whose elevation is a
220+
147 of 264 (56%) as decidably elevated, with 109 more whose elevation is a
221221
run-time fact — so the claim is neither confirmed nor refuted, and the honest
222222
answer is that a static reading cannot settle it.
223223

224-
⇒ **Cite `2 / 263`, and say what it is**: the sites whose options argument was
224+
⇒ **Cite `2 / 264`, and say what it is**: the sites whose options argument was
225225
READ and holds no tenant context, against a decidably tenancy-enabled object.
226226
That is the control's provable yield surface. ⛔ Do not cite it as "the sites
227227
without tenant context" — **29 further sites** have an options argument this
@@ -233,28 +233,28 @@ cannot read, and they are neither in nor out.
233233

234234
| what | count |
235235
| :--- | ---: |
236-
| write call sites on the application surface | **263** |
237-
| …whose object name is statically decidable | 186 |
236+
| write call sites on the application surface | **264** |
237+
| …whose object name is statically decidable | 187 |
238238
| …whose object name is chosen at run time | 77 |
239-
| …against an object with tenancy ENABLED | 180 |
239+
| …against an object with tenancy ENABLED | 181 |
240240
| …against an object that declares tenancy off | 6 |
241-
| threading a tenant context | 200 |
241+
| threading a tenant context | 201 |
242242
| PROVABLY carrying none (options read, no context key) | **8** |
243243
| …of those, against a decidably tenancy-enabled object | **2** |
244244
| options argument UNREADABLE — may or may not carry one | 55 |
245245
| …of those, against a decidably tenancy-enabled object | 29 |
246-
| threading a decidably ELEVATED (`isSystem`) context | 146 |
246+
| threading a decidably ELEVATED (`isSystem`) context | 147 |
247247
| threading a context that is decidably NOT elevated | 0 |
248248
| threading a context whose elevation is a run-time fact | 109 |
249249

250250
| how the instrument reached the site | count |
251251
| :--- | ---: |
252-
| receiver carried a readable engine type | 201 |
252+
| receiver carried a readable engine type | 202 |
253253
| receiver erased, placed by the object NAME | 52 |
254254
| receiver erased, placed by an `object: string` PARAMETER | 5 |
255255
| receiver erased, placed by an `UNTYPED_RECEIVERS` row | 5 |
256256

257-
| object name spelled inline | 117 |
257+
| object name spelled inline | 118 |
258258
| object name spelled through a `const` | 69 |
259259
| object name is an `object: string` parameter | 7 |
260260
| object name is some other run-time expression | 70 |
@@ -307,13 +307,13 @@ holds still. They are required to be HERE and to say WHEN they were true;
307307
their values are not compared. The reasoning, and the measurement behind it,
308308
are in `scripts/check-tenant-audit-census.mjs`.
309309

310-
Measured on 2026-11-06 at `ac688f409`.
310+
Measured on 2026-11-06 at `19cadde19`.
311311

312312
| corpus scale (not enforced) | count |
313313
| :--- | ---: |
314-
| tracked non-test sources scanned | 1037 |
315-
| engine-shaped types recognised | 111 |
314+
| tracked non-test sources scanned | 1044 |
315+
| engine-shaped types recognised | 112 |
316316
| declared objects in the registry | 130 |
317-
| same-named calls subtracted as non-engine | 230 |
317+
| same-named calls subtracted as non-engine | 234 |
318318

319319
{/* END GENERATED: tenant-audit-census */}

‎docs/audits/2026-08-tenant-audit-write-call-sites.counts.md‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -33,17 +33,17 @@ silent, and `node scripts/tenant-audit-census.mjs --write` is the resolution.
3333

3434
| Measure | Value |
3535
|---|---:|
36-
| Write call sites | 263 |
37-
| Object name statically decidable | 186 |
36+
| Write call sites | 264 |
37+
| Object name statically decidable | 187 |
3838
| Object name chosen at run time | 77 |
39-
| Against a tenancy-enabled object | 180 |
39+
| Against a tenancy-enabled object | 181 |
4040
| Against an object declaring tenancy off | 6 |
41-
| Threading a tenant context | 200 |
41+
| Threading a tenant context | 201 |
4242
| Provably carrying none | 8 |
4343
| …and decidably tenancy-enabled | 2 |
4444
| Options argument unreadable | 55 |
4545
| …and decidably tenancy-enabled | 29 |
46-
| Threading a decidably elevated context | 146 |
46+
| Threading a decidably elevated context | 147 |
4747
| Threading a decidably non-elevated context | 0 |
4848
| Threading a context of undecidable elevation | 109 |
4949

@@ -90,14 +90,14 @@ holds still. They are required to be HERE and to say WHEN they were true;
9090
their values are not compared. The reasoning, and the measurement behind it,
9191
are in `scripts/check-tenant-audit-census.mjs`.
9292

93-
Measured on 2026-11-06 at `ac688f409`.
93+
Measured on 2026-11-06 at `19cadde19`.
9494

9595
| corpus scale (not enforced) | count |
9696
| :--- | ---: |
97-
| tracked non-test sources scanned | 1037 |
98-
| engine-shaped types recognised | 111 |
97+
| tracked non-test sources scanned | 1044 |
98+
| engine-shaped types recognised | 112 |
9999
| declared objects in the registry | 130 |
100-
| same-named calls subtracted as non-engine | 230 |
100+
| same-named calls subtracted as non-engine | 234 |
101101

102102
## Every site
103103

@@ -153,6 +153,7 @@ Measured on 2026-11-06 at `ac688f409`.
153153
| `packages/plugins/plugin-auth/src/forced-reset-revocation.ts` | `update` | `SystemObjectName.API_KEY` | undecidable | elevated | 1 |
154154
| `packages/plugins/plugin-auth/src/forced-reset-revocation.ts` | `update` | `SystemObjectName.SESSION` | undecidable | elevated | 1 |
155155
| `packages/plugins/plugin-auth/src/idp-locale-claim.ts` | `update` | `sys_user` | enabled | elevated | 1 |
156+
| `packages/plugins/plugin-auth/src/mcp-client-last-use.ts` | `update` | `sys_oauth_consent` | enabled | elevated | 1 |
156157
| `packages/plugins/plugin-auth/src/member-role-canonical.ts` | `update` | `MEMBER_OBJECT` | undecidable | elevated | 1 |
157158
| `packages/plugins/plugin-auth/src/membership-backfill-ledger.ts` | `insert` | `DATA_MIGRATION_FLAG_OBJECT` | undecidable | elevated | 1 |
158159
| `packages/plugins/plugin-auth/src/membership-ended-session.ts` | `update` | `SystemObjectName.SESSION` | undecidable | elevated | 2 |

‎packages/client/src/index.ts‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1230,6 +1230,45 @@ export interface OAuthConsentResult {
12301230
url: string;
12311231
}
12321232

1233+
/**
1234+
* One AI assistant (OAuth client) a person has authorized: a consent they
1235+
* granted on the consent page, as `oauth.authorizedClients.list()` and
1236+
* `oauth.authorizedClients.listForUser()` answer it.
1237+
*
1238+
* Exactly these members. Nothing here identifies or reconstructs a token: no
1239+
* access-token, refresh-token or authorization-code value or id, no client
1240+
* secret, no session.
1241+
*/
1242+
export interface AuthorizedClient {
1243+
/** The consent's own id — the key `POST /oauth2/delete-consent` takes to withdraw it. */
1244+
id: string;
1245+
/** The OAuth client the grant is for. */
1246+
clientId: string;
1247+
/** The client's display name; `null` when it declares none. */
1248+
name: string | null;
1249+
/** What the person granted. */
1250+
scopes: string[];
1251+
/** The organization the grant is held in; `null` when none was active when it was granted. */
1252+
organizationId: string | null;
1253+
/** When the grant was made (ISO 8601); `null` when the row carries no readable time. */
1254+
authorizedAt: string | null;
1255+
/**
1256+
* The START of the most recent clock hour in which the client made a
1257+
* verified MCP call under this grant (ISO 8601) — the server records it at
1258+
* hour granularity, so it means "used during the hour starting at", never a
1259+
* precise moment. `null` when no use has been recorded.
1260+
*/
1261+
lastUsedAt: string | null;
1262+
}
1263+
1264+
/** What both `oauth.authorizedClients` reads answer. */
1265+
export interface AuthorizedClientsList {
1266+
/** Newest grant first. */
1267+
clients: AuthorizedClient[];
1268+
/** `true` when the person holds more grants than the server answers in one read (200). */
1269+
truncated: boolean;
1270+
}
1271+
12331272
/**
12341273
* The user object better-auth puts on the wire from the `auth.*` routes that
12351274
* echo one — `changePassword`, `verifyEmail` (on a change-email verification),
@@ -4951,6 +4990,45 @@ export class ObjectStackClient {
49514990
});
49524991
return res.json();
49534992
},
4993+
4994+
/**
4995+
* The AI assistants (OAuth clients) a person has authorized, and when each
4996+
* was last used. ObjectStack routes under the auth route, answered in the
4997+
* `{ success, data }` envelope this unwraps.
4998+
*/
4999+
authorizedClients: {
5000+
/**
5001+
* The signed-in person's own authorized assistants.
5002+
* GET /api/v1/auth/authorized-clients
5003+
*
5004+
* Keyed by the session and nothing else: the route takes no parameter,
5005+
* and refuses one (`400`) rather than ignoring it, so this method sends
5006+
* none. Withdraw a grant with `POST /oauth2/delete-consent` and the row's
5007+
* `id`.
5008+
*/
5009+
list: async (): Promise<AuthorizedClientsList> => {
5010+
const route = this.getRoute('auth');
5011+
const res = await this.fetch(`${this.baseUrl}${route}/authorized-clients`);
5012+
return this.unwrapResponse<AuthorizedClientsList>(res);
5013+
},
5014+
5015+
/**
5016+
* Another person's authorized assistants, in every organization they
5017+
* granted in (each row names its `organizationId`).
5018+
* GET /api/v1/auth/admin/authorized-clients?userId=...
5019+
*
5020+
* Platform administrators only, gated as the admin session doors are:
5021+
* anyone else is refused `403` whoever `userId` names. A `userId` that
5022+
* names no user answers `404`. Read only.
5023+
*/
5024+
listForUser: async (userId: string): Promise<AuthorizedClientsList> => {
5025+
const route = this.getRoute('auth');
5026+
const res = await this.fetch(
5027+
`${this.baseUrl}${route}/admin/authorized-clients?userId=${encodeURIComponent(userId)}`,
5028+
);
5029+
return this.unwrapResponse<AuthorizedClientsList>(res);
5030+
},
5031+
},
49545032
};
49555033

49565034
/**
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#30918] `oauth.authorizedClients` — the URL each method builds and the
5+
* answer it hands back. The server half (who may read whose grants) is pinned
6+
* in plugin-auth's `authorized-clients-read.real-plugin.test.ts`; this file
7+
* pins only what the SDK puts on the wire and what it returns.
8+
*/
9+
10+
import { describe, it, expect, expectTypeOf, vi } from 'vitest';
11+
import { ObjectStackClient, type AuthorizedClientsList } from './index';
12+
13+
const BASE = 'http://localhost:3000';
14+
15+
const LIST: AuthorizedClientsList = {
16+
clients: [
17+
{
18+
id: 'consent_1',
19+
clientId: 'client_1',
20+
name: 'Desk Assistant',
21+
scopes: ['openid', 'mcp:read'],
22+
organizationId: 'org_1',
23+
authorizedAt: '2026-11-01T09:12:00.000Z',
24+
lastUsedAt: '2026-11-06T10:00:00.000Z',
25+
},
26+
],
27+
truncated: false,
28+
};
29+
30+
function clientAnswering(body: unknown, status = 200) {
31+
const fetchMock = vi.fn(async () =>
32+
new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }),
33+
);
34+
const client = new ObjectStackClient({ baseUrl: BASE, fetch: fetchMock as never });
35+
return { client, fetchMock };
36+
}
37+
38+
describe('#30918 oauth.authorizedClients', () => {
39+
it('list() reads the caller\'s own grants with NO parameter and unwraps the envelope', async () => {
40+
const { client, fetchMock } = clientAnswering({ success: true, data: LIST });
41+
const answer = await client.oauth.authorizedClients.list();
42+
expect(answer).toEqual(LIST);
43+
expect(fetchMock).toHaveBeenCalledTimes(1);
44+
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit | undefined];
45+
// The route refuses any parameter, so the method sends none.
46+
expect(url).toBe(`${BASE}/api/v1/auth/authorized-clients`);
47+
expect(init?.method ?? 'GET').toBe('GET');
48+
});
49+
50+
it('listForUser(id) names the person in the one parameter the admin route takes, encoded', async () => {
51+
const { client, fetchMock } = clientAnswering({ success: true, data: LIST });
52+
const answer = await client.oauth.authorizedClients.listForUser('user a&b');
53+
expect(answer).toEqual(LIST);
54+
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit | undefined];
55+
expect(url).toBe(`${BASE}/api/v1/auth/admin/authorized-clients?userId=user%20a%26b`);
56+
expect(init?.method ?? 'GET').toBe('GET');
57+
});
58+
59+
it('a refusal reaches the caller as a throw, not as an empty list', async () => {
60+
const { client } = clientAnswering(
61+
{ success: false, error: { code: 'PERMISSION_DENIED', message: 'Platform administrator access required.' } },
62+
403,
63+
);
64+
await expect(client.oauth.authorizedClients.listForUser('user_2')).rejects.toThrow();
65+
});
66+
67+
it('both methods are typed with the answer they unwrap', () => {
68+
const client = new ObjectStackClient({ baseUrl: BASE, fetch: vi.fn() as never });
69+
expectTypeOf(client.oauth.authorizedClients.list).returns.toEqualTypeOf<Promise<AuthorizedClientsList>>();
70+
expectTypeOf(client.oauth.authorizedClients.listForUser).returns.toEqualTypeOf<Promise<AuthorizedClientsList>>();
71+
});
72+
});

‎packages/platform-objects/src/apps/translations/en.objects.generated.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1873,6 +1873,10 @@ export const enObjects: NonNullable<TranslationData['objects']> = {
18731873
},
18741874
updated_at: {
18751875
label: "Updated At"
1876+
},
1877+
last_used_at: {
1878+
label: "Last Used At",
1879+
help: "Start of the most recent hour in which the client made a verified MCP call under this consent; empty when none has been recorded"
18761880
}
18771881
}
18781882
},

‎packages/platform-objects/src/apps/translations/es-ES.objects.generated.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1873,6 +1873,10 @@ export const esESObjects: NonNullable<TranslationData['objects']> = {
18731873
},
18741874
updated_at: {
18751875
label: "Actualizado el"
1876+
},
1877+
last_used_at: {
1878+
label: "Último uso",
1879+
help: "Inicio de la hora más reciente en la que el cliente hizo una llamada MCP verificada con este consentimiento; vacío si no se ha registrado ninguna"
18761880
}
18771881
}
18781882
},

‎packages/platform-objects/src/apps/translations/ja-JP.objects.generated.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1873,6 +1873,10 @@ export const jaJPObjects: NonNullable<TranslationData['objects']> = {
18731873
},
18741874
updated_at: {
18751875
label: "更新日時"
1876+
},
1877+
last_used_at: {
1878+
label: "最終使用日時",
1879+
help: "この同意のもとでクライアントが検証済みの MCP 呼び出しを最後に行った時間帯の開始時刻。記録がない場合は空です"
18761880
}
18771881
}
18781882
},

0 commit comments

Comments
 (0)