Skip to content
Open
10 changes: 10 additions & 0 deletions .changeset/30918-client-authorized-clients.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@objectstack/client': patch
---

feat(client): `client.oauth.authorizedClients.list()` and `.listForUser(userId)` read the AI assistants a person has authorized and when each was last used

Clause-②: yes (widening)
Metadata-protocol: none

`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.
10 changes: 10 additions & 0 deletions .changeset/30918-platform-objects-consent-last-used.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@objectstack/platform-objects': patch
---

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

Clause-②: yes (widening)
Metadata-protocol: none

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`.
17 changes: 17 additions & 0 deletions .changeset/30918-plugin-auth-authorized-clients.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
'@objectstack/plugin-auth': patch
---

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

Clause-②: yes (widening)
Metadata-protocol: none

Two new reads, both ObjectStack mounts ahead of the better-auth catch-all and both in `AUTH_ROUTE_LEDGER`:

- `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.
- `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.

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`.

`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.
36 changes: 18 additions & 18 deletions content/docs/permissions/tenant-audit-census.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ are reported as `undecidable` rather than assumed either way.

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

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

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

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

The fourth row is the one worth flagging to anyone citing it. **The 135 / 77%
figure has no surviving corroboration anywhere in the tree.** This census reads
144 of 261 (55%) as decidably elevated, with 109 more whose elevation is a
145 of 262 (55%) as decidably elevated, with 109 more whose elevation is a
run-time fact — so the claim is neither confirmed nor refuted, and the honest
answer is that a static reading cannot settle it.

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

| what | count |
| :--- | ---: |
| write call sites on the application surface | **261** |
| …whose object name is statically decidable | 184 |
| write call sites on the application surface | **262** |
| …whose object name is statically decidable | 185 |
| …whose object name is chosen at run time | 77 |
| …against an object with tenancy ENABLED | 178 |
| …against an object with tenancy ENABLED | 179 |
| …against an object that declares tenancy off | 6 |
| threading a tenant context | 198 |
| threading a tenant context | 199 |
| PROVABLY carrying none (options read, no context key) | **8** |
| …of those, against a decidably tenancy-enabled object | **2** |
| options argument UNREADABLE — may or may not carry one | 55 |
| …of those, against a decidably tenancy-enabled object | 29 |
| threading a decidably ELEVATED (`isSystem`) context | 144 |
| threading a decidably ELEVATED (`isSystem`) context | 145 |
| threading a context that is decidably NOT elevated | 0 |
| threading a context whose elevation is a run-time fact | 109 |

| how the instrument reached the site | count |
| :--- | ---: |
| receiver carried a readable engine type | 199 |
| receiver carried a readable engine type | 200 |
| receiver erased, placed by the object NAME | 52 |
| receiver erased, placed by an `object: string` PARAMETER | 5 |
| receiver erased, placed by an `UNTYPED_RECEIVERS` row | 5 |

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

Measured on 2026-11-05 at `e40e04854`.
Measured on 2026-11-06 at `2ca181937`.

| corpus scale (not enforced) | count |
| :--- | ---: |
| tracked non-test sources scanned | 871 |
| engine-shaped types recognised | 105 |
| declared objects in the registry | 127 |
| same-named calls subtracted as non-engine | 229 |
| tracked non-test sources scanned | 1034 |
| engine-shaped types recognised | 111 |
| declared objects in the registry | 130 |
| same-named calls subtracted as non-engine | 232 |

{/* END GENERATED: tenant-audit-census */}
21 changes: 11 additions & 10 deletions docs/audits/2026-08-tenant-audit-write-call-sites.counts.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,17 +33,17 @@ silent, and `node scripts/tenant-audit-census.mjs --write` is the resolution.

| Measure | Value |
|---|---:|
| Write call sites | 261 |
| Object name statically decidable | 184 |
| Write call sites | 262 |
| Object name statically decidable | 185 |
| Object name chosen at run time | 77 |
| Against a tenancy-enabled object | 178 |
| Against a tenancy-enabled object | 179 |
| Against an object declaring tenancy off | 6 |
| Threading a tenant context | 198 |
| Threading a tenant context | 199 |
| Provably carrying none | 8 |
| …and decidably tenancy-enabled | 2 |
| Options argument unreadable | 55 |
| …and decidably tenancy-enabled | 29 |
| Threading a decidably elevated context | 144 |
| Threading a decidably elevated context | 145 |
| Threading a decidably non-elevated context | 0 |
| Threading a context of undecidable elevation | 109 |

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

Measured on 2026-11-05 at `e40e04854`.
Measured on 2026-11-06 at `2ca181937`.

| corpus scale (not enforced) | count |
| :--- | ---: |
| tracked non-test sources scanned | 871 |
| engine-shaped types recognised | 105 |
| declared objects in the registry | 127 |
| same-named calls subtracted as non-engine | 229 |
| tracked non-test sources scanned | 1034 |
| engine-shaped types recognised | 111 |
| declared objects in the registry | 130 |
| same-named calls subtracted as non-engine | 232 |

## Every site

Expand Down Expand Up @@ -153,6 +153,7 @@ Measured on 2026-11-05 at `e40e04854`.
| `packages/plugins/plugin-auth/src/forced-reset-revocation.ts` | `update` | `SystemObjectName.API_KEY` | undecidable | elevated | 1 |
| `packages/plugins/plugin-auth/src/forced-reset-revocation.ts` | `update` | `SystemObjectName.SESSION` | undecidable | elevated | 1 |
| `packages/plugins/plugin-auth/src/idp-locale-claim.ts` | `update` | `sys_user` | enabled | elevated | 1 |
| `packages/plugins/plugin-auth/src/mcp-client-last-use.ts` | `update` | `sys_oauth_consent` | enabled | elevated | 1 |
| `packages/plugins/plugin-auth/src/member-role-canonical.ts` | `update` | `MEMBER_OBJECT` | undecidable | elevated | 1 |
| `packages/plugins/plugin-auth/src/membership-backfill-ledger.ts` | `insert` | `DATA_MIGRATION_FLAG_OBJECT` | undecidable | elevated | 1 |
| `packages/plugins/plugin-auth/src/membership-ended-session.ts` | `update` | `SystemObjectName.SESSION` | undecidable | elevated | 2 |
Expand Down
78 changes: 78 additions & 0 deletions packages/client/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1230,6 +1230,45 @@ export interface OAuthConsentResult {
url: string;
}

/**
* One AI assistant (OAuth client) a person has authorized: a consent they
* granted on the consent page, as `oauth.authorizedClients.list()` and
* `oauth.authorizedClients.listForUser()` answer it.
*
* Exactly these members. Nothing here identifies or reconstructs a token: no
* access-token, refresh-token or authorization-code value or id, no client
* secret, no session.
*/
export interface AuthorizedClient {
/** The consent's own id — the key `POST /oauth2/delete-consent` takes to withdraw it. */
id: string;
/** The OAuth client the grant is for. */
clientId: string;
/** The client's display name; `null` when it declares none. */
name: string | null;
/** What the person granted. */
scopes: string[];
/** The organization the grant is held in; `null` when none was active when it was granted. */
organizationId: string | null;
/** When the grant was made (ISO 8601); `null` when the row carries no readable time. */
authorizedAt: string | null;
/**
* The START of the most recent clock hour in which the client made a
* verified MCP call under this grant (ISO 8601) — the server records it at
* hour granularity, so it means "used during the hour starting at", never a
* precise moment. `null` when no use has been recorded.
*/
lastUsedAt: string | null;
}

/** What both `oauth.authorizedClients` reads answer. */
export interface AuthorizedClientsList {
/** Newest grant first. */
clients: AuthorizedClient[];
/** `true` when the person holds more grants than the server answers in one read (200). */
truncated: boolean;
}

/**
* The user object better-auth puts on the wire from the `auth.*` routes that
* echo one — `changePassword`, `verifyEmail` (on a change-email verification),
Expand Down Expand Up @@ -4951,6 +4990,45 @@ export class ObjectStackClient {
});
return res.json();
},

/**
* The AI assistants (OAuth clients) a person has authorized, and when each
* was last used. ObjectStack routes under the auth route, answered in the
* `{ success, data }` envelope this unwraps.
*/
authorizedClients: {
/**
* The signed-in person's own authorized assistants.
* GET /api/v1/auth/authorized-clients
*
* Keyed by the session and nothing else: the route takes no parameter,
* and refuses one (`400`) rather than ignoring it, so this method sends
* none. Withdraw a grant with `POST /oauth2/delete-consent` and the row's
* `id`.
*/
list: async (): Promise<AuthorizedClientsList> => {
const route = this.getRoute('auth');
const res = await this.fetch(`${this.baseUrl}${route}/authorized-clients`);
return this.unwrapResponse<AuthorizedClientsList>(res);
},

/**
* Another person's authorized assistants, in every organization they
* granted in (each row names its `organizationId`).
* GET /api/v1/auth/admin/authorized-clients?userId=...
*
* Platform administrators only, gated as the admin session doors are:
* anyone else is refused `403` whoever `userId` names. A `userId` that
* names no user answers `404`. Read only.
*/
listForUser: async (userId: string): Promise<AuthorizedClientsList> => {
const route = this.getRoute('auth');
const res = await this.fetch(
`${this.baseUrl}${route}/admin/authorized-clients?userId=${encodeURIComponent(userId)}`,
);
return this.unwrapResponse<AuthorizedClientsList>(res);
},
},
};

/**
Expand Down
72 changes: 72 additions & 0 deletions packages/client/src/oauth-authorized-clients.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* [#30918] `oauth.authorizedClients` — the URL each method builds and the
* answer it hands back. The server half (who may read whose grants) is pinned
* in plugin-auth's `authorized-clients-read.real-plugin.test.ts`; this file
* pins only what the SDK puts on the wire and what it returns.
*/

import { describe, it, expect, expectTypeOf, vi } from 'vitest';
import { ObjectStackClient, type AuthorizedClientsList } from './index';

const BASE = 'http://localhost:3000';

const LIST: AuthorizedClientsList = {
clients: [
{
id: 'consent_1',
clientId: 'client_1',
name: 'Desk Assistant',
scopes: ['openid', 'mcp:read'],
organizationId: 'org_1',
authorizedAt: '2026-11-01T09:12:00.000Z',
lastUsedAt: '2026-11-06T10:00:00.000Z',
},
],
truncated: false,
};

function clientAnswering(body: unknown, status = 200) {
const fetchMock = vi.fn(async () =>
new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }),
);
const client = new ObjectStackClient({ baseUrl: BASE, fetch: fetchMock as never });
return { client, fetchMock };
}

describe('#30918 oauth.authorizedClients', () => {
it('list() reads the caller\'s own grants with NO parameter and unwraps the envelope', async () => {
const { client, fetchMock } = clientAnswering({ success: true, data: LIST });
const answer = await client.oauth.authorizedClients.list();
expect(answer).toEqual(LIST);
expect(fetchMock).toHaveBeenCalledTimes(1);
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit | undefined];
// The route refuses any parameter, so the method sends none.
expect(url).toBe(`${BASE}/api/v1/auth/authorized-clients`);
expect(init?.method ?? 'GET').toBe('GET');
});

it('listForUser(id) names the person in the one parameter the admin route takes, encoded', async () => {
const { client, fetchMock } = clientAnswering({ success: true, data: LIST });
const answer = await client.oauth.authorizedClients.listForUser('user a&b');
expect(answer).toEqual(LIST);
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit | undefined];
expect(url).toBe(`${BASE}/api/v1/auth/admin/authorized-clients?userId=user%20a%26b`);
expect(init?.method ?? 'GET').toBe('GET');
});

it('a refusal reaches the caller as a throw, not as an empty list', async () => {
const { client } = clientAnswering(
{ success: false, error: { code: 'PERMISSION_DENIED', message: 'Platform administrator access required.' } },
403,
);
await expect(client.oauth.authorizedClients.listForUser('user_2')).rejects.toThrow();
});

it('both methods are typed with the answer they unwrap', () => {
const client = new ObjectStackClient({ baseUrl: BASE, fetch: vi.fn() as never });
expectTypeOf(client.oauth.authorizedClients.list).returns.toEqualTypeOf<Promise<AuthorizedClientsList>>();
expectTypeOf(client.oauth.authorizedClients.listForUser).returns.toEqualTypeOf<Promise<AuthorizedClientsList>>();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -1873,6 +1873,10 @@ export const enObjects: NonNullable<TranslationData['objects']> = {
},
updated_at: {
label: "Updated At"
},
last_used_at: {
label: "Last Used At",
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"
}
}
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1873,6 +1873,10 @@ export const esESObjects: NonNullable<TranslationData['objects']> = {
},
updated_at: {
label: "Actualizado el"
},
last_used_at: {
label: "Último uso",
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"
}
}
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1873,6 +1873,10 @@ export const jaJPObjects: NonNullable<TranslationData['objects']> = {
},
updated_at: {
label: "更新日時"
},
last_used_at: {
label: "最終使用日時",
help: "この同意のもとでクライアントが検証済みの MCP 呼び出しを最後に行った時間帯の開始時刻。記録がない場合は空です"
}
}
},
Expand Down
Loading
Loading