Skip to content

Commit 9f61e06

Browse files
fix(plugin-auth): withdrawing an AI assistant in one organization keeps its refresh tokens in the person's other organizations (#31132)
<!-- claude-projects-attribution: {"github_login":"marchtian"} --> _Requested by **田騏** · [project thread](https://claude.ai/code/project/chan_01VmuUhXU9SSUzqJYyXSmYSi?thread=cmsg_01VmuUhXU9SSUzqJYyXSmYSi9Hju7DThD7eoLKoJU9hnHj)_ Fixes #31076 Clause-②: no Metadata-protocol: none ## 维护者速读 - **改了什么**:撤回 AI 助手(控制台的两个撤回入口和 `/oauth2/revoke`)时,只删除该组织下签发的刷新令牌,以及没有记录组织的旧刷新令牌;其他组织的刷新令牌保留。 - **为什么改**:同一个人在两个组织里授权了同一个助手,在 A 组织撤回后,B 组织里的助手也会在访问令牌过期后被登出,只能重新授权。 - **风险与回滚**:失败方向是"多删"而不是"少删":撤回组织的每一行刷新令牌(含已轮换的和并发轮换出的新行)都删,没有组织的行在任何撤回时也都删。回滚即 revert 本 PR,行为回到按客户端+用户整族删除。 - **先看**:`packages/plugins/plugin-auth/src/mcp-token-revocation.ts` 的 `isRefreshFamilyRow` 与 `revokeMcpGrant`(两轮读删);`mcp-token-revocation.test.ts` 末尾新增的 describe。 - **两分钟验证**:`pnpm --filter @objectstack/plugin-auth exec vitest run src/mcp-token-revocation.test.ts`,预期 17 条全绿,其中 4 条是新增的两组织用例。 - **需要你做的**:无,席位落地。 ## What changes - `revokeMcpGrant` (shared by `/oauth2/revoke` and both console withdraws, `POST /api/v1/auth/authorized-clients/withdraw` and the admin door) no longer reads the refresh family by client + user alone. A refresh row stores the organization it was minted under (`referenceId` / `reference_id`, measured on the installed `@better-auth/oauth-provider` 1.7.12: the consent's reference is copied onto the authorization code, the refresh token it starts, and every rotation, since `handleRefreshTokenGrant` passes `refreshToken.referenceId` to `createUserTokens`). - The family a revoke deletes is: client + user AND (the row's reference is the grant's organization, by the consent rule `isConsentFor`, OR the row has no reference). Only a row that names ANOTHER organization is kept. - A row with no reference dies on every revoke of that client for that person, as before this change. Which grant it was minted under cannot be read off it (a row from before consents bound an organization, or from any path that leaves the reference unset, looks the same), so keeping it could leave the withdrawn assistant a live refresh token. This is the seat's ruling on the claim thread: fail closed. - The family is deleted by id in two read-and-delete passes. A rotation racing the first pass started from a row that pass read and wrote its successor after the read. The second read finds that successor. The provider's own filter delete catches a successor written before the delete runs, and the second read runs later than that, so no revoke deletes less than before. - `/oauth2/revoke` answers exactly as before (RFC 7009 revoke of one token). - Changeset: `@objectstack/plugin-auth` patch. ## Tests On the real plugin (`AuthManager` + `@better-auth/oauth-provider` 1.7.12 + `ObjectQL` over `driver-sql`/better-sqlite3), one person and one DCR public client, consents in organizations A and B (`mcp-token-revocation.test.ts`, new describe "a grant is revoked in its own organization only"): 1. `/oauth2/revoke` of A's access token: A's consent and refresh row are gone, A's bearer is refused and its refresh token mints nothing; B's bearer still verifies with `organizationId` B, and B's refresh token refreshes into a token that verifies in B. 2. The shared function, as the console withdraws call it: after one rotation of A (a rotated row and its live successor), revoking A deletes both and nothing of B. CONTROL: revoking the remaining organization leaves no refresh row and no consent at all. 3. A refresh row with no organization (consented with no active organization) dies on an A withdraw and mints nothing afterwards; B still refreshes. 4. A rotation of A performed between the revoke's family read and its delete: its successor is deleted too and mints nothing. The withdraw doors' own suite (`authorized-clients-read.real-plugin.test.ts`) seeds token rows through a fixture that wrote them with no `reference_id` under consents bound to an organization, a shape the provider never writes. The fixture now writes the consent's reference on both token rows, as the provider does. No assertion changed. ## Acceptance notes - **File surface:** the claim names `mcp-token-revocation.ts` and its tests. `authorized-clients-read.real-plugin.test.ts` is also touched (fixture only, see Tests). The seat accepted it as a declared deviation. - **Known nuisance kept:** a person who also has a no-organization grant of the same client loses that grant's refresh token when they withdraw the client in an organization. That is today's behaviour for those rows and is the cost of failing closed on rows whose grant cannot be identified. - The header of `authorized-clients-withdraw.ts` still says the withdraw deletes "the client's refresh family for that person". It is now that family minus other organizations' rows. That file is outside the claimed surface, so it is left unchanged and named here. ## Verification All at head `aa7a88d0ea`, worktree on origin/main `5f0037449`. <details><summary>Targeted tests</summary> - `pnpm exec vitest run src/mcp-token-revocation.test.ts src/authorized-clients-read.real-plugin.test.ts` (plugin-auth): Test Files 2 passed, Tests 35 passed. - `pnpm --filter @objectstack/plugin-auth exec vitest run`: before the fixture fix, 2 failed (the two withdraw-door tests named above) | 4191 passed | 10 skipped; full package rerun after the fix at aa7a88d: Test Files 232 passed (232), Tests 4193 passed | 10 skipped (4203). - `pnpm --filter @objectstack/plugin-auth build && pnpm --filter @objectstack/plugin-auth typecheck`: exit 0 (`check:test-typecheck: OK`). - `eslint --no-inline-config` on the two touched source/test files: exit 0. </details> <details><summary>Ablations (scripts/ablation-replace.mjs, each restored to the HEAD blob with git diff HEAD empty)</summary> - **Scoping removed** (`isRefreshFamilyRow` answers `true`, the old client + user family): 4 of the new tests red, e.g. `expected [] to deeply equal [ 'B_ORG_ID' ]` (B's row deleted). - **No-reference rule removed** (`isRefreshFamilyRow` answers `isConsentFor` only): test 3 red, `the row with no organization went with A: expected [ '(none)', … ] to deeply equal [ … ]`. - **One pass** (`REFRESH_FAMILY_PASSES = 1`): test 4 red, `its successor was deleted too: expected [ …(2) ] to deeply equal [ … ]`. </details> <details><summary>Gates</summary> Local subset, every command derived by `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` for this diff, run at aa7a88d (exit code captured before any pipe): ```text node scripts/check-adr-0087-registration.mjs --base origin/main :: exit 0 node scripts/check-adr-0087-registration.mjs --self-test :: exit 0 node scripts/check-changeset-no-major.mjs --base origin/main :: exit 0 node scripts/check-closing-keyword-parity.mjs :: exit 0 node scripts/check-closing-keyword-parity.mjs --self-test :: exit 0 node scripts/check-comment-mask-adoption.mjs :: exit 0 node scripts/check-comment-mask-adoption.mjs --self-test :: exit 0 node scripts/check-comment-mask-corpus.mjs :: exit 0 node scripts/check-dev-prereqs.mjs --self-test :: exit 0 node scripts/check-dts-emitted.mjs --self-test :: exit 0 node scripts/check-empty-changeset.mjs --base origin/main :: exit 0 node scripts/check-empty-changeset.mjs --self-test :: exit 0 node scripts/check-issue-citations.mjs :: exit 0 node scripts/check-plugin-teardown-shape.mjs :: exit 0 node scripts/check-plugin-teardown-shape.mjs --self-test :: exit 0 node scripts/check-tenant-audit-census.mjs :: exit 0 node scripts/check-tenant-audit-census.mjs --self-test :: exit 0 node scripts/ci/assert-turbo-remote-cache.mjs --self-test :: exit 0 node scripts/ci/plan-test-core-shards.mjs --self-test :: exit 0 node scripts/ci/prune-turbo-cache.mjs --self-test :: exit 0 node scripts/ci/snapshot-next.mjs --self-test :: exit 0 node scripts/docs-audit/check-affected-docs.mjs :: exit 0 node scripts/docs-audit/check-drift-comment.mjs :: exit 0 node scripts/pm/release-rehearsal-clone.mjs --self-test :: exit 0 node scripts/release-pending-publish.mjs --self-test :: exit 0 pnpm --filter @objectstack/spec run check:duration-unit-keys :: exit 0 pnpm check:changeset-gate-self-tests :: exit 0 pnpm check:ci-filter-parity :: exit 0 pnpm check:closed-ceremony-text :: exit 0 pnpm check:cross-package-test-inputs :: exit 0 pnpm check:doc-authoring :: exit 0 pnpm check:driver-memory-census :: exit 0 pnpm check:dts-closure :: exit 0 pnpm check:dual-build-cjs-loads :: exit 0 pnpm check:engine-double-contract :: exit 0 pnpm check:gitlink-declared :: exit 0 pnpm check:issue-citations :: exit 0 pnpm check:keyed-text-bounds :: exit 0 pnpm check:lean-entry-closure :: exit 0 pnpm check:logger-receiver-detach :: exit 0 pnpm check:nul-bytes :: exit 0 pnpm check:objectql-double-limit :: exit 0 pnpm check:org-identifier :: exit 0 pnpm check:page-declaration-shape :: exit 0 pnpm check:platform-object-tenancy-census :: exit 0 pnpm check:published-files :: exit 0 pnpm check:query-options-erasure :: exit 0 pnpm check:refd-timer-probe :: exit 0 pnpm check:registry-log-declared :: exit 0 pnpm check:rest-log-spy-declared :: exit 0 pnpm check:slot-lookup :: exit 0 pnpm check:sourcemap-no-sources-content :: exit 0 pnpm check:system-context-census :: exit 0 pnpm check:test-source-alias :: exit 0 pnpm check:tier-file-adoption :: exit 0 pnpm check:type-check-coverage :: exit 0 pnpm check:type-check-debt :: exit 0 pnpm check:undeclared-dep-imports :: exit 0 pnpm check:vouch-for-reference-callers :: exit 0 pnpm check:watch-hint-literal :: exit 0 pnpm check:where-matcher :: exit 0 ``` `dispatch-gates --ran`: 61 derived famil(ies) accounted for — 61 run, 0 NOT-MEASURED. Every family CI runs is read from this PR's check-runs. </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 79a0d30 commit 9f61e06

4 files changed

Lines changed: 234 additions & 27 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/plugin-auth': patch
3+
---
4+
5+
fix(plugin-auth): withdrawing an AI assistant in one organization no longer signs it out of the person's other organizations
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
A person can authorize the same AI assistant (an OAuth client such as Claude Desktop) in two organizations. Withdrawing it in one of them, from the console (`POST /api/v1/auth/authorized-clients/withdraw` or the admin door) or with `POST /oauth2/revoke`, deleted only that organization's consent but every refresh token the assistant held for that person, in every organization. The assistant then stopped working in the other organization once its access token expired, and the person had to authorize it there again. A withdraw now deletes the refresh tokens minted in the withdrawn organization only: every one of them, rotated or live, and the access tokens minted from them. The other organization's refresh token keeps refreshing. A refresh token minted with no active organization belongs to the grant with no organization and is deleted when that grant is withdrawn. `/oauth2/revoke` answers exactly as before.

‎packages/plugins/plugin-auth/src/authorized-clients-read.real-plugin.test.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,9 @@ const arrange = async () => {
219219
/**
220220
* A consent, written by better-auth's own storage adapter (the write the
221221
* provider's consent door makes), plus the token rows a real grant carries,
222-
* so an answer that leaked one would be caught.
222+
* so an answer that leaked one would be caught. The token rows carry the
223+
* consent's organization reference, as the provider writes them: a withdraw
224+
* deletes the refresh family of the withdrawn grant's organization only.
223225
*/
224226
const grant = async (
225227
userId: string,
@@ -242,12 +244,14 @@ const arrange = async () => {
242244
token: `${ACCESS_TOKEN}-${row.id}`,
243245
client_id: clientId,
244246
user_id: userId,
247+
...(opts.referenceId ? { reference_id: opts.referenceId } : {}),
245248
scopes: JSON.stringify(opts.scopes ?? ['openid', 'data:read']),
246249
});
247250
await engine.insert('sys_oauth_refresh_token', {
248251
token: `${REFRESH_TOKEN}-${row.id}`,
249252
client_id: clientId,
250253
user_id: userId,
254+
...(opts.referenceId ? { reference_id: opts.referenceId } : {}),
251255
scopes: JSON.stringify(opts.scopes ?? ['openid', 'data:read']),
252256
});
253257
return String(row.id);

‎packages/plugins/plugin-auth/src/mcp-token-revocation.test.ts‎

Lines changed: 147 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,12 @@
3333
* (RFC 7009 §2.2.1);
3434
* - a token minted before its consent was granted again stays refused;
3535
* - a server-only `skip_consent` client keeps the provider's honest
36-
* `unsupported_token_type` and is admitted without a consent row.
36+
* `unsupported_token_type` and is admitted without a consent row;
37+
* - one person, one client, consents in two organizations: revoking the
38+
* grant of one deletes that organization's whole refresh family (every
39+
* rotation of it) and leaves the other organization's family refreshing;
40+
* a refresh row with no organization dies on every withdraw (fail closed);
41+
* a rotation racing the revoke does not leave a live successor behind.
3742
*/
3843

3944
import { createRequire } from 'node:module';
@@ -44,7 +49,7 @@ import { ObjectQL } from '@objectstack/objectql';
4449
import { SqlDriver } from '@objectstack/driver-sql';
4550
import { AuthManager } from './auth-manager.js';
4651
import { authIdentityObjects } from './manifest.js';
47-
import { UNKNOWN_TOKEN_DESCRIPTIONS } from './mcp-token-revocation.js';
52+
import { revokeMcpGrant, UNKNOWN_TOKEN_DESCRIPTIONS, type OAuthGrantStore } from './mcp-token-revocation.js';
4853

4954
const BASE = 'http://localhost:3000';
5055
const AUTH = `${BASE}/api/v1/auth`;
@@ -193,7 +198,38 @@ async function rig() {
193198
const revoke = (params: Record<string, string>, headers?: Record<string, string>) =>
194199
postForm('/oauth2/revoke', params, headers);
195200

196-
return { engine, driver, manager, send, postJson, postForm, rowsAtRest, registerClient, signUp, authorize, exchange, connect, revoke };
201+
/** A refresh-token grant: the provider's own answer, status and body. */
202+
const refresh = async (clientId: string, refreshToken: string) => {
203+
const res = await postForm('/oauth2/token', {
204+
grant_type: 'refresh_token', refresh_token: refreshToken, client_id: clientId, resource: MCP_RESOURCE,
205+
});
206+
return { status: res.status, body: (await res.json().catch(() => null)) as any };
207+
};
208+
209+
/**
210+
* Makes the signed-in user a member of a new organization and that
211+
* organization the session's active one, so the next consent binds it.
212+
* (`/organization/create` is refused under this rig's single posture, so the
213+
* organization and the membership are written directly; `set-active` is the
214+
* real door, and it checks the membership.)
215+
*/
216+
async function enterOrganization(cookie: string, slug: string): Promise<string> {
217+
const [session]: any[] = (await rowsAtRest('sys_session')).filter((row) => cookie.includes(String(row.token)));
218+
const userId = session?.user_id ?? (await rowsAtRest('sys_user'))[0]?.id;
219+
const org: any = await (engine as any).insert('sys_organization', { name: slug, slug }, SYS);
220+
await (engine as any).insert('sys_member', { organization_id: org.id, user_id: userId, role: 'member' }, SYS);
221+
const res = await postJson('/organization/set-active', { organizationId: org.id }, cookie);
222+
expect(res.status, await res.clone().text()).toBe(200);
223+
return String(org.id);
224+
}
225+
226+
/** better-auth's storage adapter: the store every revoke door hands `revokeMcpGrant`. */
227+
const store = async (): Promise<OAuthGrantStore> => (await (manager as any).getAuthContext()).adapter;
228+
229+
return {
230+
engine, driver, manager, send, postJson, postForm, rowsAtRest, registerClient, signUp, authorize, exchange, connect, revoke,
231+
refresh, enterOrganization, store,
232+
};
197233
}
198234

199235
const bodyOf = async (res: Response) => ({ status: res.status, body: await res.clone().json().catch(() => res.clone().text()) });
@@ -386,3 +422,111 @@ describe('[ruling A, step 5] a server-only `skip_consent` client', () => {
386422
expect(await r.manager.verifyMcpAccessToken(access_token)).toMatchObject({ clientId });
387423
}, 60_000);
388424
});
425+
426+
describe('a grant is revoked in its own organization only', () => {
427+
/** One person, one client: consents in organizations A and B, and the tokens each earned. */
428+
async function twoOrganizations() {
429+
const r = await rig();
430+
const clientId = await r.registerClient();
431+
const cookie = await r.signUp('mia@acme.example.com');
432+
const userId = String((await r.rowsAtRest('sys_user'))[0]!.id);
433+
const orgA = await r.enterOrganization(cookie, 'org-a');
434+
const inA = await r.authorize(clientId, cookie);
435+
expect(inA.prompted, 'the first consent, in A').toBe(true);
436+
const a = await r.exchange(clientId, inA.code);
437+
const orgB = await r.enterOrganization(cookie, 'org-b');
438+
const inB = await r.authorize(clientId, cookie);
439+
expect(inB.prompted, 'B is a consent of its own').toBe(true);
440+
const b = await r.exchange(clientId, inB.code);
441+
expect((await r.manager.verifyMcpAccessToken(a.access_token))?.organizationId).toBe(orgA);
442+
expect((await r.manager.verifyMcpAccessToken(b.access_token))?.organizationId).toBe(orgB);
443+
const referencesOf = async (object: string) => (await r.rowsAtRest(object)).map((row) => row.reference_id).sort();
444+
expect(await referencesOf('sys_oauth_consent')).toEqual([orgA, orgB].sort());
445+
expect(await referencesOf('sys_oauth_refresh_token'), 'each refresh row records its organization').toEqual([orgA, orgB].sort());
446+
return { r, clientId, cookie, userId, orgA, orgB, a, b, referencesOf };
447+
}
448+
449+
it('⭐ /oauth2/revoke in A deletes A\'s consent and refresh family; B\'s token still verifies and its refresh token still refreshes', async () => {
450+
const { r, clientId, orgB, a, b, referencesOf } = await twoOrganizations();
451+
452+
const res = await r.revoke({ token: a.access_token, token_type_hint: 'access_token', client_id: clientId });
453+
expect(await bodyOf(res)).toEqual({ status: 200, body: null });
454+
455+
expect(await r.manager.verifyMcpAccessToken(a.access_token), 'A\'s bearer is refused').toBeNull();
456+
expect((await r.refresh(clientId, a.refresh_token)).status, 'A\'s refresh token mints nothing').toBe(400);
457+
expect(await referencesOf('sys_oauth_consent')).toEqual([orgB]);
458+
expect(await referencesOf('sys_oauth_refresh_token')).toEqual([orgB]);
459+
460+
expect((await r.manager.verifyMcpAccessToken(b.access_token))?.organizationId, 'B\'s bearer still verifies').toBe(orgB);
461+
const refreshed = await r.refresh(clientId, b.refresh_token);
462+
expect(refreshed.status, JSON.stringify(refreshed.body)).toBe(200);
463+
expect((await r.manager.verifyMcpAccessToken(refreshed.body.access_token))?.organizationId, 'and B refreshes in B').toBe(orgB);
464+
}, 60_000);
465+
466+
it('the shared function deletes EVERY row of the withdrawn organization\'s family — a rotated row and its live successor — and only those', async () => {
467+
const { r, clientId, userId, orgA, orgB, a, b, referencesOf } = await twoOrganizations();
468+
// Rotate A once: the family now holds the rotated row and its successor.
469+
const rotated = await r.refresh(clientId, a.refresh_token);
470+
expect(rotated.status, JSON.stringify(rotated.body)).toBe(200);
471+
expect(await referencesOf('sys_oauth_refresh_token')).toEqual([orgA, orgA, orgB].sort());
472+
473+
// The consent id's grant, as both console withdraws hand it over.
474+
await revokeMcpGrant(await r.store(), { clientId, userId, organizationId: orgA });
475+
476+
expect(await referencesOf('sys_oauth_refresh_token'), 'no row of A survives').toEqual([orgB]);
477+
expect((await r.refresh(clientId, rotated.body.refresh_token)).status, 'A\'s live successor mints nothing').toBe(400);
478+
expect(await r.manager.verifyMcpAccessToken(rotated.body.access_token)).toBeNull();
479+
expect((await r.refresh(clientId, b.refresh_token)).status, 'B still refreshes').toBe(200);
480+
481+
// CONTROL: with one organization left, its revoke leaves nothing at all.
482+
await revokeMcpGrant(await r.store(), { clientId, userId, organizationId: orgB });
483+
expect(await r.rowsAtRest('sys_oauth_refresh_token')).toEqual([]);
484+
expect(await r.rowsAtRest('sys_oauth_consent')).toEqual([]);
485+
}, 60_000);
486+
487+
it('a refresh row with NO organization dies on EVERY withdraw of the client: revoking A deletes it, and B\'s row still refreshes', async () => {
488+
const r = await rig();
489+
const clientId = await r.registerClient();
490+
const cookie = await r.signUp('mia@acme.example.com');
491+
const userId = String((await r.rowsAtRest('sys_user'))[0]!.id);
492+
// A consent made with no active organization: its refresh row has no reference.
493+
const none = await r.exchange(clientId, (await r.authorize(clientId, cookie)).code);
494+
const orgA = await r.enterOrganization(cookie, 'org-a');
495+
await r.exchange(clientId, (await r.authorize(clientId, cookie)).code);
496+
const orgB = await r.enterOrganization(cookie, 'org-b');
497+
const inB = await r.exchange(clientId, (await r.authorize(clientId, cookie)).code);
498+
const references = async () =>
499+
(await r.rowsAtRest('sys_oauth_refresh_token')).map((row) => row.reference_id ?? '(none)').sort();
500+
expect(await references()).toEqual([orgA, orgB, '(none)'].sort());
501+
502+
await revokeMcpGrant(await r.store(), { clientId, userId, organizationId: orgA });
503+
// Which grant a row with no reference was minted under cannot be read off
504+
// it, so it goes with any withdraw (fail closed); only a row naming
505+
// another organization stays.
506+
expect(await references(), 'the row with no organization went with A').toEqual([orgB]);
507+
expect((await r.refresh(clientId, none.refresh_token)).status, 'and mints nothing').toBe(400);
508+
expect((await r.refresh(clientId, inB.refresh_token)).status, 'B still refreshes').toBe(200);
509+
}, 60_000);
510+
511+
it('a rotation racing the revoke leaves no live successor in the withdrawn organization', async () => {
512+
const { r, clientId, userId, orgA, orgB, a, referencesOf } = await twoOrganizations();
513+
const real = await r.store();
514+
let raced: { status: number; body: any } | undefined;
515+
// The client refreshes A between the revoke's read of the family and its
516+
// delete: the provider marks the row it started from and writes a successor.
517+
const racing: OAuthGrantStore = {
518+
findOne: (q) => real.findOne(q),
519+
findMany: (q) => real.findMany(q),
520+
delete: (q) => real.delete(q),
521+
deleteMany: async (q) => {
522+
if (!raced && q.model === 'oauthAccessToken') raced = await r.refresh(clientId, a.refresh_token);
523+
return real.deleteMany(q);
524+
},
525+
};
526+
await revokeMcpGrant(racing, { clientId, userId, organizationId: orgA });
527+
528+
expect(raced?.status, 'the race happened: the rotation succeeded mid-revoke').toBe(200);
529+
expect(await referencesOf('sys_oauth_refresh_token'), 'its successor was deleted too').toEqual([orgB]);
530+
expect((await r.refresh(clientId, raced!.body.refresh_token)).status).toBe(400);
531+
}, 60_000);
532+
});

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

Lines changed: 72 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,9 @@
2121
* `@objectstack/spec` `IAuthService.verifyMcpAccessToken` already says
2222
* this: a falsy value when the token is revoked, and callers fail CLOSED.
2323
* - **`/oauth2/revoke` deletes it** ({@link answerMcpTokenRevocation}) and
24-
* revokes the client's refresh family for that user.
24+
* revokes the grant's refresh family: the client's refresh tokens for that
25+
* user, except those minted under another organization
26+
* ({@link revokeMcpGrant}).
2527
* - **The Console's withdraw** (`authorized-clients-withdraw.ts`, the own and
2628
* the admin door) revokes a grant through {@link revokeMcpGrant} too, keyed
2729
* by the consent id; the read above refuses on the next request.
@@ -133,8 +135,12 @@ export interface McpGrantKey {
133135
organizationId?: string;
134136
}
135137

136-
/** A consent row as the adapter answers it (camelCase, the provider's field names). */
137-
interface ConsentRow {
138+
/**
139+
* A consent or refresh-token row as the adapter answers it (camelCase, the
140+
* provider's field names). Both models store the organization reference the
141+
* grant was made under in `referenceId`.
142+
*/
143+
interface GrantRow {
138144
id?: unknown;
139145
referenceId?: unknown;
140146
createdAt?: unknown;
@@ -145,23 +151,51 @@ interface ConsentRow {
145151
* provider's own rule (`findConsent`): with a reference, the row carrying
146152
* exactly it; without one, a row whose reference is missing, null or empty.
147153
*/
148-
function isConsentFor(row: ConsentRow, organizationId: string | undefined): boolean {
154+
function isConsentFor(row: GrantRow, organizationId: string | undefined): boolean {
149155
return organizationId ? row.referenceId === organizationId : !row.referenceId;
150156
}
151157

152-
async function consentsOf(store: OAuthGrantStore, grant: McpGrantKey): Promise<ConsentRow[]> {
158+
/**
159+
* Whether a refresh-token row is in the family a revoke of this organization
160+
* reference deletes: a row of the grant's own organization (the consent rule
161+
* above: the provider copies the consent's reference onto the authorization
162+
* code, the refresh token it starts and every rotation of it), AND every row
163+
* with no reference, whatever organization is revoked.
164+
*
165+
* ⛔ A row with no reference dies on every revoke of the client for that
166+
* person. Which grant it was minted under cannot be read off it (a row from
167+
* before consents bound an organization, or from any path that leaves the
168+
* reference unset, looks the same), so keeping it alive could leave the
169+
* withdrawn assistant a live refresh token: fail closed, as every revoke did
170+
* before refresh families were scoped. Only a row that names ANOTHER
171+
* organization is kept.
172+
*/
173+
function isRefreshFamilyRow(row: GrantRow, organizationId: string | undefined): boolean {
174+
return !row.referenceId || isConsentFor(row, organizationId);
175+
}
176+
177+
/** The rows of `model` for (client, user) that `belongs` admits for the grant's organization. */
178+
async function grantRowsOf(
179+
store: OAuthGrantStore,
180+
model: string,
181+
grant: McpGrantKey,
182+
belongs: (row: GrantRow, organizationId: string | undefined) => boolean,
183+
): Promise<GrantRow[]> {
153184
const rows = await store.findMany({
154-
model: 'oauthConsent',
185+
model,
155186
where: [
156187
{ field: 'clientId', value: grant.clientId },
157188
{ field: 'userId', value: grant.userId },
158189
],
159190
});
160191
return (Array.isArray(rows) ? rows : []).filter(
161-
(row): row is ConsentRow => !!row && typeof row === 'object' && isConsentFor(row as ConsentRow, grant.organizationId),
192+
(row): row is GrantRow => !!row && typeof row === 'object' && belongs(row as GrantRow, grant.organizationId),
162193
);
163194
}
164195

196+
const consentsOf = (store: OAuthGrantStore, grant: McpGrantKey) =>
197+
grantRowsOf(store, 'oauthConsent', grant, isConsentFor);
198+
165199
/** Whether the client is a server-only `skip_consent` client: one that never has a consent row. */
166200
async function isSkipConsentClient(store: OAuthGrantStore, clientId: string): Promise<boolean> {
167201
const client = (await store.findOne({
@@ -203,34 +237,49 @@ export async function mcpConsentAdmits(
203237
return Math.floor(createdAtMs / 1000) <= issuedAt;
204238
}
205239

240+
/**
241+
* How many times {@link revokeMcpGrant} reads and deletes the refresh family.
242+
* The second read finds the row a rotation racing the first pass wrote: that
243+
* rotation started from a row the first read returned and wrote its successor
244+
* after the read. A rotation needs a live row to start from, and the first
245+
* pass deletes every row it read, so a rotation that starts after it finds
246+
* none. The provider's own family delete, by filter, catches a successor
247+
* written before its delete runs; the second read runs later than that.
248+
*/
249+
const REFRESH_FAMILY_PASSES = 2;
250+
206251
/**
207252
* Revokes the grant: deletes the consent for (client, user, organization),
208-
* then the client's refresh family for that user — the refresh tokens and the
209-
* opaque access tokens minted from them, as the provider's own
210-
* `invalidateRefreshFamily` does. The consent goes first because it is what
211-
* the MCP door reads; a failure after it leaves the access token already
212-
* refused, and the client's retry finishes the rest (every step is
213-
* idempotent).
253+
* then that grant's refresh family — the client's refresh tokens for that
254+
* user that name no other organization, and the opaque access tokens
255+
* minted from them, as the provider's own `invalidateRefreshFamily` does for
256+
* a whole (client, user) pair. The consent goes first because it is what the
257+
* MCP door reads; a failure after it leaves the access token already refused,
258+
* and the client's retry finishes the rest (every step is idempotent).
259+
*
260+
* ⛔ A person can authorize the same client in two organizations: withdrawing
261+
* it in one must not sign the client out of the other, so a refresh row that
262+
* names another organization is kept. Every row this grant minted is deleted,
263+
* and so is every row with no reference ({@link isRefreshFamilyRow}).
214264
*/
215265
export async function revokeMcpGrant(store: OAuthGrantStore, grant: McpGrantKey): Promise<void> {
216266
for (const consent of await consentsOf(store, grant)) {
217267
await store.delete({ model: 'oauthConsent', where: [{ field: 'id', value: consent.id }] });
218268
}
219-
const family = [
220-
{ field: 'clientId', value: grant.clientId },
221-
{ field: 'userId', value: grant.userId },
222-
];
223-
const refreshTokens = (await store.findMany({ model: 'oauthRefreshToken', where: family })) ?? [];
224-
const refreshIds = refreshTokens
225-
.map((row) => (row as { id?: unknown } | null)?.id)
226-
.filter((id) => id !== undefined && id !== null);
227-
if (refreshIds.length) {
269+
for (let pass = 0; pass < REFRESH_FAMILY_PASSES; pass += 1) {
270+
const refreshIds = (await grantRowsOf(store, 'oauthRefreshToken', grant, isRefreshFamilyRow))
271+
.map((row) => row.id)
272+
.filter((id) => id !== undefined && id !== null);
273+
if (!refreshIds.length) return;
228274
await store.deleteMany({
229275
model: 'oauthAccessToken',
230276
where: [{ field: 'refreshId', operator: 'in', value: refreshIds }],
231277
});
278+
await store.deleteMany({
279+
model: 'oauthRefreshToken',
280+
where: [{ field: 'id', operator: 'in', value: refreshIds }],
281+
});
232282
}
233-
await store.deleteMany({ model: 'oauthRefreshToken', where: family });
234283
}
235284

236285
/**

0 commit comments

Comments
 (0)