Skip to content

Commit a0ec7b1

Browse files
committed
wip(plugin-auth): authorized-clients reads and coarse MCP last-use stamp
Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016WV4d1LNDAUs8pz7DNjQFC
1 parent 6ff27b3 commit a0ec7b1

10 files changed

Lines changed: 866 additions & 3 deletions

‎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/identity/sys-oauth-consent.object.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,24 @@ export const SysOauthConsent = ObjectSchema.create({
110110
defaultValue: 'NOW()',
111111
readonly: true,
112112
}),
113+
114+
// [#30918] ObjectStack's own column on this better-auth table: the
115+
// oauth-provider neither reads nor writes it (plugin-auth's
116+
// `oauth-provider-schema-parity.test.ts` pins that it is not one of the
117+
// provider's columns). Its one writer is plugin-auth, server-side, after
118+
// it has verified an MCP access token minted under this consent
119+
// (`mcp-client-last-use.ts`), and the value is the start of that hour, so
120+
// the column moves at most once an hour per consent. Nothing a client
121+
// sends reaches it: the object is not on the data API, the provider's
122+
// consent doors do not carry it, and the value is the server's clock.
123+
// A withdrawn or revoked consent takes its stamp with it.
124+
last_used_at: Field.datetime({
125+
label: 'Last Used At',
126+
required: false,
127+
readonly: true,
128+
description:
129+
'Start of the most recent hour in which the client made a verified MCP call under this consent; empty when none has been recorded',
130+
}),
113131
},
114132

115133
indexes: [

‎packages/plugins/plugin-auth/src/auth-manager-mcp-access-token.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,9 @@
2626
* keeps both methods — the published `dist/*.d.ts` lists each one — and each
2727
* body is one literal of exactly the {@link McpAccessTokenHost} members that
2828
* method reads, plus a `.call`. `verifyMcpAccessToken` is no longer `async`:
29-
* it returns the moved function's own promise, so a caller awaits the same
30-
* promise the body settles, with no extra wrapper.
29+
* it returns the moved function's own promise with one `.then` on it, which
30+
* hands a verified principal to the coarse last-use stamp
31+
* (`mcp-client-last-use.ts`, #30918) and resolves to the same value.
3132
*
3233
* A method goes as a closure that calls it on the manager at call time, so a
3334
* test double or spy set on the manager is still the one a body reaches —

‎packages/plugins/plugin-auth/src/auth-manager.ts‎

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,9 @@ import {
187187
verifyMcpAccessToken,
188188
type McpAccessTokenHost,
189189
} from './auth-manager-mcp-access-token.js';
190+
// [#30918] The coarse last-use stamp a verified MCP call writes on its consent.
191+
import { McpClientLastUseStamper, mcpClientLastUseStoreFor } from './mcp-client-last-use.js';
192+
import { runAfterResponse } from './run-after-response.js';
190193
// [#25224 cut 10] The request routing — the seam every better-auth request
191194
// passes through, route ownership and the endpoint path both key on; the
192195
// methods of the same names below hand each body the members it reads
@@ -4417,6 +4420,13 @@ export class AuthManager {
44174420
* caller vets it on every request by the rule that vets a session's active
44184421
* organization (`vetOrganizationClaim`, `@objectstack/core`), as the
44194422
* `IAuthService` contract states.
4423+
*
4424+
* [#30918] A token that verifies also schedules, AFTER the verdict and off
4425+
* the request's path, the coarse last-use stamp on the consent it was minted
4426+
* under (`mcp-client-last-use.ts`): at most one write per consent per hour,
4427+
* from this verified principal and the server's clock. The stamp reads and
4428+
* writes nothing the verdict depends on, and its failure is never this
4429+
* method's failure.
44204430
*/
44214431
verifyMcpAccessToken(
44224432
token: string,
@@ -4429,7 +4439,47 @@ export class AuthManager {
44294439
isMcpOAuthEnabled: (...a) => this.isMcpOAuthEnabled(...a),
44304440
rereadKeyringForUnknownKey: (...a) => this.rereadKeyringForUnknownKey(...a),
44314441
};
4432-
return verifyMcpAccessToken.call(host, token);
4442+
// [#30918] A token that verified is a verified MCP call: its consent's
4443+
// coarse last-use stamp is settled after the response, never awaited here,
4444+
// and from the verified principal only (`mcp-client-last-use.ts`).
4445+
return verifyMcpAccessToken.call(host, token).then((principal) => {
4446+
if (principal) this.scheduleMcpClientLastUse(principal);
4447+
return principal;
4448+
});
4449+
}
4450+
4451+
/** [#30918] The per-manager stamper, built on first use. */
4452+
private mcpClientLastUse?: McpClientLastUseStamper;
4453+
4454+
/**
4455+
* [#30918] Settle the last-use stamp of the consent `principal`'s token was
4456+
* minted under, after the response (`run-after-response.ts`). At most one
4457+
* write per consent per hour, from the verified principal and the server's
4458+
* clock alone; the first failure in this process is reported at `error`
4459+
* (`error` when the host logger carries it, else `warn`, called through the
4460+
* property — see {@link audienceLogError}).
4461+
*/
4462+
private scheduleMcpClientLastUse(principal: { userId: string; clientId?: string; organizationId?: string }): void {
4463+
if (!principal.clientId) return;
4464+
const stamper = (this.mcpClientLastUse ??= new McpClientLastUseStamper(
4465+
mcpClientLastUseStoreFor(() => this.getDataEngine()),
4466+
{
4467+
onFirstFailure: (error) =>
4468+
this.audienceLogError(
4469+
'[AuthManager] The last-use time of authorized AI assistants could not be recorded: '
4470+
+ 'the authorized-clients reads keep answering the last stamp that landed as if it were current. '
4471+
+ 'Check that schema sync has added sys_oauth_consent.last_used_at and that the data engine is reachable; '
4472+
+ 'each consent is retried once an hour, and only this first failure is reported.',
4473+
{ error: error instanceof Error ? error.message : String(error) },
4474+
),
4475+
},
4476+
));
4477+
runAfterResponse(
4478+
() => stamper.record(principal),
4479+
() => {
4480+
// `record` never rejects; its own failure report is above.
4481+
},
4482+
);
44334483
}
44344484

44354485
/**

‎packages/plugins/plugin-auth/src/auth-plugin.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3807,6 +3807,28 @@ export class AuthPlugin implements Plugin {
38073807
}
38083808
});
38093809

3810+
// ────────────────────────────────────────────────────────────────────
3811+
// [#30918] admin: the AI assistants (OAuth clients) another person has
3812+
// authorized, per organization, and when each was last used. Read only.
3813+
// The shared gate first, so a caller outside a platform administrator's
3814+
// reach gets one refusal whoever `userId` names and whether or not that
3815+
// person exists; then the closed query set { userId } (authorized-clients-read.ts).
3816+
rawApp.get(`${basePath}/admin/authorized-clients`, async (c: any) => {
3817+
try {
3818+
const actor = await gateAdmin(c);
3819+
if (actor instanceof Response) return actor;
3820+
const { authorizedClientsDepsFor, runAdminAuthorizedClientsRead } = await import('./authorized-clients-read.js');
3821+
const answer = await runAdminAuthorizedClientsRead(authorizedClientsDepsFor(this.authManager!), actor, {
3822+
queries: (c.req.queries() ?? {}) as Record<string, string[]>,
3823+
});
3824+
return c.json(answer.body, answer.status as any, answer.headers);
3825+
} catch (error) {
3826+
const err = error instanceof Error ? error : new Error(String(error));
3827+
ctx.logger.error('[AuthPlugin] admin/authorized-clients failed', err);
3828+
return c.json({ success: false, error: { code: 'INTERNAL_ERROR', message: 'The authorized clients could not be read.' } }, 500);
3829+
}
3830+
});
3831+
38103832
// ────────────────────────────────────────────────────────────────────
38113833
// #2766 V1 — admin direct user management. `sys_user` CRUD is suppressed
38123834
// (managedBy better-auth), and until now the only add-a-teammate path was
@@ -4625,6 +4647,28 @@ export class AuthPlugin implements Plugin {
46254647
}
46264648
});
46274649

4650+
// ────────────────────────────────────────────────────────────────────
4651+
// [#30918] The caller's own authorized AI assistants (OAuth consents),
4652+
// with each one's display name, scopes, organization, grant time and last
4653+
// verified MCP call. Keyed by the session's subject and nothing else: the
4654+
// query set is closed and empty, so `?userId=` is refused, never ignored.
4655+
// Outside `/admin/` because it admits every signed-in person; another
4656+
// person's grants are the admin door above. See authorized-clients-read.ts.
4657+
rawApp.get(`${basePath}/authorized-clients`, async (c: any) => {
4658+
try {
4659+
const { authorizedClientsDepsFor, runOwnAuthorizedClientsRead } = await import('./authorized-clients-read.js');
4660+
const answer = await runOwnAuthorizedClientsRead(authorizedClientsDepsFor(this.authManager!), {
4661+
headers: c.req.raw.headers,
4662+
queries: (c.req.queries() ?? {}) as Record<string, string[]>,
4663+
});
4664+
return c.json(answer.body, answer.status as any, answer.headers);
4665+
} catch (error) {
4666+
const err = error instanceof Error ? error : new Error(String(error));
4667+
ctx.logger.error('[AuthPlugin] authorized-clients failed', err);
4668+
return c.json({ success: false, error: { code: 'INTERNAL_ERROR', message: 'The authorized clients could not be read.' } }, 500);
4669+
}
4670+
});
4671+
46284672
// ────────────────────────────────────────────────────────────────────
46294673
// Self-service resend of the email-verification link. SHADOWS better-auth's
46304674
// native `/send-verification-email` (registered before the catch-all below).

‎packages/plugins/plugin-auth/src/auth-route-ledger.conformance.test.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,11 +220,20 @@ describe('auth route ledger hygiene', () => {
220220
// ruling of 2026-08-23).
221221
const own = AUTH_ROUTE_LEDGER.filter((e) => e.source === 'objectstack').map((e) => e.route).sort();
222222
expect(own).toEqual([
223+
// [#30918] Both authorized-clients reads, on this pin's own terms:
224+
// `auth-plugin.ts` mounts each itself (a `rawApp.get` on the
225+
// `${basePath}/admin/authorized-clients` and
226+
// `${basePath}/authorized-clients` templates, ahead of the catch-all),
227+
// and the `live.has(route)` loop below holds them to the same proof —
228+
// better-auth's own consent read is `/oauth2/get-consents`, a different
229+
// path.
230+
'GET /api/v1/auth/admin/authorized-clients',
223231
// [#30398] On this pin's own terms: `auth-plugin.ts` mounts it itself (a
224232
// `rawApp.get` on the `${basePath}/admin/client-address` template, ahead
225233
// of the catch-all), and the `live.has(route)` loop below holds it to the
226234
// same proof — better-auth serves no address read.
227235
'GET /api/v1/auth/admin/client-address',
236+
'GET /api/v1/auth/authorized-clients',
228237
'GET /api/v1/auth/bootstrap-status',
229238
'GET /api/v1/auth/config',
230239
// On this pin's own terms: `auth-plugin.ts` mounts it itself (a

0 commit comments

Comments
 (0)