Skip to content

Commit a6e995a

Browse files
committed
feat(auth): withdraw an authorized AI assistant, own and admin doors
POST /api/v1/auth/authorized-clients/withdraw { id } withdraws one of the session user's own OAuth consents; POST /api/v1/auth/admin/authorized-clients/withdraw { userId, id } does the same for a platform administrator behind the admin read's gate. Both revoke the grant the way /oauth2/revoke does (consent row, then the client's refresh family), so the assistant's token is refused on its next MCP call. Unknown and not-yours answer one 404. Ledgered as sdk with oauth.authorizedClients.withdraw / withdrawForUser on the client. Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L9qibxU7nr4BXM7e8qMfwq
1 parent 23cf11a commit a6e995a

10 files changed

Lines changed: 690 additions & 18 deletions

‎packages/client/src/index.ts‎

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1240,7 +1240,7 @@ export interface OAuthConsentResult {
12401240
* secret, no session.
12411241
*/
12421242
export interface AuthorizedClient {
1243-
/** The consent's own id — the key `POST /oauth2/delete-consent` takes to withdraw it. */
1243+
/** The consent's own id — the key `oauth.authorizedClients.withdraw()` takes to withdraw it. */
12441244
id: string;
12451245
/** The OAuth client the grant is for. */
12461246
clientId: string;
@@ -1269,6 +1269,12 @@ export interface AuthorizedClientsList {
12691269
truncated: boolean;
12701270
}
12711271

1272+
/** What both `oauth.authorizedClients` withdraws answer: the consent that was withdrawn. */
1273+
export interface AuthorizedClientWithdrawal {
1274+
/** The consent id the request named. */
1275+
id: string;
1276+
}
1277+
12721278
/**
12731279
* The user object better-auth puts on the wire from the `auth.*` routes that
12741280
* echo one — `changePassword`, `verifyEmail` (on a change-email verification),
@@ -5003,8 +5009,7 @@ export class ObjectStackClient {
50035009
*
50045010
* Keyed by the session and nothing else: the route takes no parameter,
50055011
* 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`.
5012+
* none. Withdraw a grant with `withdraw()` and the row's `id`.
50085013
*/
50095014
list: async (): Promise<AuthorizedClientsList> => {
50105015
const route = this.getRoute('auth');
@@ -5028,6 +5033,44 @@ export class ObjectStackClient {
50285033
);
50295034
return this.unwrapResponse<AuthorizedClientsList>(res);
50305035
},
5036+
5037+
/**
5038+
* Withdraw one of the signed-in person's own authorized assistants, by
5039+
* the `id` `list()` answers on its row.
5040+
* POST /api/v1/auth/authorized-clients/withdraw
5041+
*
5042+
* The grant is revoked: the assistant's token is refused on its next
5043+
* call, and it must be authorized again to reconnect. Only the person's
5044+
* own grant is withdrawn: an id that names another person's grant
5045+
* answers `404` exactly as one that names none, and changes nothing.
5046+
*/
5047+
withdraw: async (id: string): Promise<AuthorizedClientWithdrawal> => {
5048+
const route = this.getRoute('auth');
5049+
const res = await this.fetch(`${this.baseUrl}${route}/authorized-clients/withdraw`, {
5050+
method: 'POST',
5051+
body: JSON.stringify({ id }),
5052+
});
5053+
return this.unwrapResponse<AuthorizedClientWithdrawal>(res);
5054+
},
5055+
5056+
/**
5057+
* Withdraw one of another person's authorized assistants, by the `id`
5058+
* `listForUser()` answers on its row.
5059+
* POST /api/v1/auth/admin/authorized-clients/withdraw
5060+
*
5061+
* Platform administrators only, behind the same gate as
5062+
* `listForUser()`: anyone else is refused `403` whoever the request
5063+
* names. A `userId` that names no user, or an `id` that is not that
5064+
* person's grant, answers `404`.
5065+
*/
5066+
withdrawForUser: async (userId: string, id: string): Promise<AuthorizedClientWithdrawal> => {
5067+
const route = this.getRoute('auth');
5068+
const res = await this.fetch(`${this.baseUrl}${route}/admin/authorized-clients/withdraw`, {
5069+
method: 'POST',
5070+
body: JSON.stringify({ userId, id }),
5071+
});
5072+
return this.unwrapResponse<AuthorizedClientWithdrawal>(res);
5073+
},
50315074
},
50325075
};
50335076

‎packages/client/src/oauth-authorized-clients.test.ts‎

Lines changed: 50 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
22

33
/**
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.
4+
* [#30918, #31048] `oauth.authorizedClients` — the URL each method builds and
5+
* the answer it hands back. The server half (who may read and withdraw whose
6+
* grants) is pinned in plugin-auth's `authorized-clients-read.real-plugin.test.ts`;
7+
* this file pins only what the SDK puts on the wire and what it returns.
88
*/
99

1010
import { describe, it, expect, expectTypeOf, vi } from 'vitest';
11-
import { ObjectStackClient, type AuthorizedClientsList } from './index';
11+
import { ObjectStackClient, type AuthorizedClientsList, type AuthorizedClientWithdrawal } from './index';
1212

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

@@ -70,3 +70,48 @@ describe('#30918 oauth.authorizedClients', () => {
7070
expectTypeOf(client.oauth.authorizedClients.listForUser).returns.toEqualTypeOf<Promise<AuthorizedClientsList>>();
7171
});
7272
});
73+
74+
describe('#31048 oauth.authorizedClients withdraws', () => {
75+
const WITHDRAWN: AuthorizedClientWithdrawal = { id: 'consent_1' };
76+
77+
it('withdraw(id) posts exactly { id } to the own door and unwraps the envelope', async () => {
78+
const { client, fetchMock } = clientAnswering({ success: true, data: WITHDRAWN });
79+
const answer = await client.oauth.authorizedClients.withdraw('consent_1');
80+
expect(answer).toEqual(WITHDRAWN);
81+
expect(fetchMock).toHaveBeenCalledTimes(1);
82+
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
83+
expect(url).toBe(`${BASE}/api/v1/auth/authorized-clients/withdraw`);
84+
expect(init.method).toBe('POST');
85+
// The route refuses any other body key, so the method sends only the id.
86+
expect(JSON.parse(String(init.body))).toEqual({ id: 'consent_1' });
87+
});
88+
89+
it('withdrawForUser(userId, id) posts exactly { userId, id } to the admin door', async () => {
90+
const { client, fetchMock } = clientAnswering({ success: true, data: WITHDRAWN });
91+
const answer = await client.oauth.authorizedClients.withdrawForUser('user_2', 'consent_1');
92+
expect(answer).toEqual(WITHDRAWN);
93+
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
94+
expect(url).toBe(`${BASE}/api/v1/auth/admin/authorized-clients/withdraw`);
95+
expect(init.method).toBe('POST');
96+
expect(JSON.parse(String(init.body))).toEqual({ userId: 'user_2', id: 'consent_1' });
97+
});
98+
99+
it('a not-found or refused withdraw reaches the caller as a throw, never as a withdrawn answer', async () => {
100+
const notFound = clientAnswering(
101+
{ success: false, error: { code: 'RESOURCE_NOT_FOUND', message: 'No authorized assistant you may withdraw matches the supplied id.' } },
102+
404,
103+
);
104+
await expect(notFound.client.oauth.authorizedClients.withdraw('consent_x')).rejects.toThrow();
105+
const refused = clientAnswering(
106+
{ success: false, error: { code: 'PERMISSION_DENIED', message: 'Platform administrator access required.' } },
107+
403,
108+
);
109+
await expect(refused.client.oauth.authorizedClients.withdrawForUser('user_2', 'consent_1')).rejects.toThrow();
110+
});
111+
112+
it('both withdraws are typed with the answer they unwrap', () => {
113+
const client = new ObjectStackClient({ baseUrl: BASE, fetch: vi.fn() as never });
114+
expectTypeOf(client.oauth.authorizedClients.withdraw).returns.toEqualTypeOf<Promise<AuthorizedClientWithdrawal>>();
115+
expectTypeOf(client.oauth.authorizedClients.withdrawForUser).returns.toEqualTypeOf<Promise<AuthorizedClientWithdrawal>>();
116+
});
117+
});

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4509,7 +4509,8 @@ export class AuthManager {
45094509
* read, and when the read fails (fail closed). So revocation takes effect
45104510
* on the next request: `/oauth2/revoke` deletes the consent and the
45114511
* client's refresh family for that user (`answerOAuthTokenRevocation`), and
4512-
* the Console's `/oauth2/delete-consent` deletes the same row. A server-only
4512+
* the Console's withdraw (`authorized-clients-withdraw.ts`) revokes the same
4513+
* grant the same way. A server-only
45134514
* `skip_consent` client has no consent row and is admitted without one.
45144515
*
45154516
* The caller (runtime dispatcher) maps the returned principal through

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

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3896,6 +3896,29 @@ export class AuthPlugin implements Plugin {
38963896
}
38973897
});
38983898

3899+
// ────────────────────────────────────────────────────────────────────
3900+
// [#31048] admin: withdraw one of the AI assistants another person
3901+
// authorized, by the consent id the read above answers. The read's own
3902+
// gate first, ahead of any body read, so a caller outside a platform
3903+
// administrator's reach gets one refusal whoever the body names and
3904+
// whether or not the person or the consent exists (authorized-clients-withdraw.ts).
3905+
rawApp.post(`${basePath}/admin/authorized-clients/withdraw`, async (c: any) => {
3906+
try {
3907+
const actor = await gateAdmin(c);
3908+
if (actor instanceof Response) return actor;
3909+
const { authorizedClientWithdrawDepsFor, runAdminAuthorizedClientWithdraw } = await import('./authorized-clients-withdraw.js');
3910+
const answer = await runAdminAuthorizedClientWithdraw(authorizedClientWithdrawDepsFor(this.authManager!), actor, {
3911+
raw: c.req.raw,
3912+
queries: (c.req.queries() ?? {}) as Record<string, string[]>,
3913+
});
3914+
return c.json(answer.body, answer.status as any, answer.headers);
3915+
} catch (error) {
3916+
const err = error instanceof Error ? error : new Error(String(error));
3917+
ctx.logger.error('[AuthPlugin] admin/authorized-clients/withdraw failed', err);
3918+
return c.json({ success: false, error: { code: 'INTERNAL_ERROR', message: 'The authorized client could not be withdrawn.' } }, 500);
3919+
}
3920+
});
3921+
38993922
// ────────────────────────────────────────────────────────────────────
39003923
// [#30958] ADR-0134 — admin: mint and revoke the bearer credentials SCIM
39013924
// connections authenticate with. The SCIM plugin verifies against
@@ -4781,6 +4804,28 @@ export class AuthPlugin implements Plugin {
47814804
}
47824805
});
47834806

4807+
// ────────────────────────────────────────────────────────────────────
4808+
// [#31048] Withdraw one of the caller's own authorized AI assistants, by
4809+
// the consent id the read above answers: the consent and the client's
4810+
// refresh family go, so the assistant's token is refused on its next MCP
4811+
// call. Only the session subject's own consent is withdrawn; an id naming
4812+
// no consent and one naming another person's read the same 404. Another
4813+
// person's grant is the admin door above. See authorized-clients-withdraw.ts.
4814+
rawApp.post(`${basePath}/authorized-clients/withdraw`, async (c: any) => {
4815+
try {
4816+
const { authorizedClientWithdrawDepsFor, runOwnAuthorizedClientWithdraw } = await import('./authorized-clients-withdraw.js');
4817+
const answer = await runOwnAuthorizedClientWithdraw(authorizedClientWithdrawDepsFor(this.authManager!), {
4818+
raw: c.req.raw,
4819+
queries: (c.req.queries() ?? {}) as Record<string, string[]>,
4820+
});
4821+
return c.json(answer.body, answer.status as any, answer.headers);
4822+
} catch (error) {
4823+
const err = error instanceof Error ? error : new Error(String(error));
4824+
ctx.logger.error('[AuthPlugin] authorized-clients/withdraw failed', err);
4825+
return c.json({ success: false, error: { code: 'INTERNAL_ERROR', message: 'The authorized client could not be withdrawn.' } }, 500);
4826+
}
4827+
});
4828+
47844829
// ────────────────────────────────────────────────────────────────────
47854830
// Self-service resend of the email-verification link. SHADOWS better-auth's
47864831
// 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
@@ -248,6 +248,14 @@ describe('auth route ledger hygiene', () => {
248248
// holds it to the same proof — better-auth's own read is
249249
// `/organization/get-invitation`, a different path.
250250
'GET /api/v1/auth/organization/invitation-preview',
251+
// [#31048] Both withdraws, on this pin's own terms: `auth-plugin.ts`
252+
// mounts each itself (a `rawApp.post` on the
253+
// `${basePath}/admin/authorized-clients/withdraw` and
254+
// `${basePath}/authorized-clients/withdraw` templates, ahead of the
255+
// catch-all), and the `live.has(route)` loop below holds them to the same
256+
// proof — better-auth's own withdraw is `/oauth2/delete-consent`, a
257+
// different path.
258+
'POST /api/v1/auth/admin/authorized-clients/withdraw',
251259
'POST /api/v1/auth/admin/import-users',
252260
// On this pin's own terms: `auth-plugin.ts` mounts it itself (a
253261
// `rawApp.post` on the `${basePath}/admin/list-platform-admins`
@@ -274,6 +282,7 @@ describe('auth route ledger hygiene', () => {
274282
'POST /api/v1/auth/admin/sso/request-domain-verification',
275283
'POST /api/v1/auth/admin/sso/verify-domain',
276284
'POST /api/v1/auth/admin/unlock-user',
285+
'POST /api/v1/auth/authorized-clients/withdraw',
277286
'POST /api/v1/auth/organization/add-member',
278287
'POST /api/v1/auth/set-initial-password',
279288
'POST /api/v1/auth/sys-oauth-application/register',

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,7 @@ export const AUTH_ROUTE_LEDGER: readonly AuthRouteLedgerEntry[] = [
173173
{ route: 'POST /api/v1/auth/oauth2/consent', family: 'oauth-provider', source: 'better-auth', disposition: 'sdk', client: 'oauth.consent', requires: 'oidcProvider' },
174174
{ route: 'POST /api/v1/auth/oauth2/create-client', family: 'oauth-provider', source: 'better-auth', disposition: 'sdk', client: 'oauth.applications.register', requires: 'oidcProvider' },
175175
{ route: 'POST /api/v1/auth/oauth2/delete-client', family: 'oauth-provider', source: 'better-auth', disposition: 'sdk', client: 'oauth.applications.delete', requires: 'oidcProvider' },
176+
{ route: 'POST /api/v1/auth/oauth2/delete-consent', family: 'oauth-provider', source: 'better-auth', disposition: 'server-only', requires: 'oidcProvider', note: 'no SDK method builds this URL — the withdraw door is POST /authorized-clients/withdraw. Measured on @better-auth/oauth-provider 1.7.12: the vendor route does check the consent is the session user\'s, but answers an unknown id 404 and another person\'s id 401, so the two can be told apart, and it leaves the client\'s refresh family in place; the ObjectStack door answers both the same 404 and revokes the whole grant' },
176177
{ route: 'GET /api/v1/auth/oauth2/get-client', family: 'oauth-provider', source: 'better-auth', disposition: 'sdk', client: 'oauth.applications.get', requires: 'oidcProvider' },
177178
{ route: 'GET /api/v1/auth/oauth2/get-clients', family: 'oauth-provider', source: 'better-auth', disposition: 'sdk', client: 'oauth.applications.list', requires: 'oidcProvider' },
178179
{ route: 'GET /api/v1/auth/oauth2/public-client', family: 'oauth-provider', source: 'better-auth', disposition: 'sdk', client: 'oauth.applications.getPublic', requires: 'oidcProvider' },
@@ -196,7 +197,9 @@ export const AUTH_ROUTE_LEDGER: readonly AuthRouteLedgerEntry[] = [
196197
// is registered whether or not it is enabled, so both are unconditional
197198
// mounts and carry no `requires`.
198199
{ route: 'GET /api/v1/auth/admin/authorized-clients', family: 'objectstack-mount', source: 'objectstack', disposition: 'sdk', client: 'oauth.authorizedClients.listForUser', note: 'another person\'s authorized AI assistants, ?userId=ID: platform-admin gated exactly as the admin session doors are (ADR-0068 D2, a held session refused per ADR-0069 D3), the gate run before the query is read, so a caller outside that reach is refused once whether or not the person exists; an organization owner or admin is not a platform admin and is refused. Every organization the person granted in, each row naming its organizationId. Read only. Closed query set {userId}: missing, empty or repeated is 400, an id naming no user is 404' },
199-
{ route: 'GET /api/v1/auth/authorized-clients', family: 'objectstack-mount', source: 'objectstack', disposition: 'sdk', client: 'oauth.authorizedClients.list', note: 'the caller\'s own authorized AI assistants (OAuth consents), keyed by the session\'s subject and nothing else: the query set is closed and empty, so a userId or any other parameter is refused 400 rather than ignored. Each row: consent id (the key /oauth2/delete-consent takes), clientId, name, scopes, organizationId, authorizedAt, lastUsedAt (start of the most recent hour with a verified MCP call, null when none is recorded); no token, code, secret or session value. Newest first, at most 200 rows with truncated saying when there are more; Cache-Control: no-store' },
200+
{ route: 'POST /api/v1/auth/admin/authorized-clients/withdraw', family: 'objectstack-mount', source: 'objectstack', disposition: 'sdk', client: 'oauth.authorizedClients.withdrawForUser', note: 'withdraw one of another person\'s authorized AI assistants, body { userId, id }: behind the same gate as GET /admin/authorized-clients (ADR-0068 D2, a held session refused per ADR-0069 D3), run before the body is read, so a caller outside that reach is refused once whether or not the person or the consent exists; an organization owner or admin is not a platform admin and is refused. A userId naming no user is 404 with the read\'s message; a consent that is not that person\'s reads the same 404 as one that does not exist. The same revoke as the own door' },
201+
{ route: 'GET /api/v1/auth/authorized-clients', family: 'objectstack-mount', source: 'objectstack', disposition: 'sdk', client: 'oauth.authorizedClients.list', note: 'the caller\'s own authorized AI assistants (OAuth consents), keyed by the session\'s subject and nothing else: the query set is closed and empty, so a userId or any other parameter is refused 400 rather than ignored. Each row: consent id (the key POST /authorized-clients/withdraw takes), clientId, name, scopes, organizationId, authorizedAt, lastUsedAt (start of the most recent hour with a verified MCP call, null when none is recorded); no token, code, secret or session value. Newest first, at most 200 rows with truncated saying when there are more; Cache-Control: no-store' },
202+
{ route: 'POST /api/v1/auth/authorized-clients/withdraw', family: 'objectstack-mount', source: 'objectstack', disposition: 'sdk', client: 'oauth.authorizedClients.withdraw', note: 'withdraw one of the caller\'s own authorized AI assistants by the consent id the authorized-clients read answers, body { id } and nothing else (the query set is closed and empty, an unknown body key is 400): keyed by the session\'s subject, so an id naming no consent and an id naming another person\'s consent read the same 404 RESOURCE_NOT_FOUND and the other row stays. Revokes the grant as /oauth2/revoke does (cloud#3606 ruling A): the consent row, then the client\'s refresh family, so the assistant\'s token is refused on its next MCP call. Answers { id }; Cache-Control: no-store' },
200203
// ─────────────────────────────────────────────────────────────────────
201204
// #10534 — the remaining ObjectStack raw-app mounts, ledgered.
202205
//

0 commit comments

Comments
 (0)