Skip to content

Commit 1aeeafd

Browse files
fix(plugin-auth)!: revoke an MCP access token through its OAuth consent (#30879)
security#1 · os-tesla · session_01L9qibvynRbCtMndW8EHNGc Fixes #30345 Clause-②: no (narrowing) — the MCP door refuses a bearer whose consent is gone or newer than the token, which the published contract already promises (`packages/spec/src/contracts/auth-service.ts` `verifyMcpAccessToken`: "a falsy value when the token is unknown/expired/revoked … callers fail CLOSED"), and a bearer with no `azp` claim to key that read; the revoke door's 200 for an invalid or another client's token removes a refusal RFC 7009 §2.1/§2.2 already negates. The contract text is not changed. Metadata-protocol: none Skills-docs: none — `skills/**` says nothing about revoking an MCP OAuth access token or withdrawing a consent, so no published skill text moves; the rule is documented in `mcp-token-revocation.ts` and on `AuthManager.verifyMcpAccessToken`. ## 维护者速读 - **改了什么**:MCP 访问令牌现在可以撤销。每次 MCP 请求按令牌的 (azp, sub, organization_id) 读一次 `sys_oauth_consent`,记录不在或比令牌新就拒绝;`/oauth2/revoke` 对本客户端的 MCP 令牌删掉这条同意和该用户的刷新令牌族并回 200,控制台的撤回同意也随之真正生效。 - **为什么改**:执行 objectstack-ai/cloud#3606 的方案 A。此前 `/oauth2/revoke` 对 MCP 令牌回 400,撤回同意也挡不住已签发的令牌,直到它过期。 - **风险与回滚**:每次 MCP 请求多一次带索引的读取;读失败时拒绝(fail closed,MCP 路由回 401);撤销后用户下次连接要重新同意。不新增对象、表或门禁,回滚即还原本 PR,无数据迁移。 - **先看**:`packages/plugins/plugin-auth/src/mcp-token-revocation.ts`、`packages/plugins/plugin-auth/src/auth-manager-mcp-access-token.ts`、`packages/plugins/plugin-auth/src/auth-manager-request-routing.ts` - **两分钟验证**:`pnpm --filter @objectstack/plugin-auth exec vitest run src/mcp-token-revocation.test.ts`,看 ⭐ 那条:撤销后同一令牌被拒、同意与刷新令牌行消失、刷新请求 400、再连接重新弹出同意页。 - **需要你做的**:审阅这份草稿 PR,确认下方 Acceptance notes 里 consent 存储故障回 401(而非 503)这一取舍。 ## What changes The ruling (objectstack-ai/cloud#3606, ruling A): the platform's existing OAuth consent record is the revocable record. A revoke or withdraw deletes it, every MCP request reads it, and a missing record is refused. No new object, table or gate. - **`verifyMcpAccessToken` reads the consent** (`auth-manager-mcp-access-token.ts`, `mcp-token-revocation.ts` `mcpConsentAdmits`). After the signature, issuer, audience and expiry checks that were already there, it reads `sys_oauth_consent` by the token's client (`azp`), user (`sub`) and organization (`organization_id`). This is one indexed read, matched by the same reference rule the provider's own `findConsent` uses. It refuses the token in these cases: - no matching consent; - a consent whose `createdAt` (whole seconds) is later than the token's `iat`, meaning it was revoked and then granted again; - a token with no `azp`; - a token with no `iat`, or a consent whose `createdAt` cannot be read; - a failed read (fail closed). The MCP route already answers a refused bearer `401` (`packages/runtime/src/http-dispatcher.mcp-oauth.test.ts`, "invalid/expired JWT bearer → 401"). A client marked `skip_consent` (server-only, which DCR cannot set) has no consent row: its tokens are admitted without one, which takes one extra `oauthClient` read only when no consent matched. - **`POST /oauth2/revoke` is wrapped** in the one route seam every vendor route passes through (`auth-manager-request-routing.ts`, which clones the request only for this path, then `answerMcpTokenRevocation`). The provider still runs first and still authenticates the client. Only its answer is re-read: - `400 unsupported_token_type`: the wrap verifies the MCP JWT, reads the authenticated client id in the provider's own order (assertion, then Basic, then form), and acts on the result. - **Same client:** it deletes the consent for (client, user, org) and the client's refresh family for that user, together with the access-token rows bound to that family, and answers `200`. - **Another client:** it answers `200` and changes nothing. - **A `skip_consent` client:** it keeps the honest `unsupported_token_type`. - `400 invalid_request` for an unknown or invalid token (the provider's three descriptions, pinned against the installed dist): the wrap answers `200` (RFC 7009 §2.2). - A `token_type_hint` that does not locate the token does not end the search (RFC 7009 §2.1): before the provider's "not found" is answered `200`, the wrap looks for an MCP access token, with the same three outcomes as above (same client: revoked; another client: a `200` that changes nothing; a `skip_consent` client: `400 unsupported_token_type`). - A refusal the provider makes before it looks at the token (no client, an unknown client, a malformed request) passes through unchanged. - A store error while revoking: the wrap answers `503 server_error` with `no-store` (RFC 7009 §2.2.1: the token still stands, retry later), and a retry completes the revoke. - **`POST /oauth2/delete-consent` (the Console's withdraw)** is not changed. It deletes the same row the MCP door now reads, so the agent's next request is refused. - The revocation note on `AuthManager.verifyMcpAccessToken` is rewritten to describe this. The contract in `packages/spec/src/contracts/auth-service.ts` is not edited. The `ipMatchesRange` region (#30717) is not touched. - A `patch` changeset with the BREAKING banner and its ADR-0087 disposition (`.changeset/30345-mcp-token-revocation.md`). ## Tests - **New `mcp-token-revocation.test.ts`.** A real `AuthManager` (oidcProvider + DCR) on real ObjectQL + SqlDriver (better-sqlite3), driven through `handleRequest`. Legs: - ⭐ The client revokes its token with `client_id` only. Expected: `200`; the verifier refuses the token; the consent and refresh rows are gone; the refresh grant answers `400`; the next authorize asks for consent again. - Revoke with no `token_type_hint`, then a second revoke of the same token. Expected: both `200`. - delete-consent. Expected: the token is refused. - Another client revokes the token. Expected: `200`, and the owner's token still works. - The token is sent with `token_type_hint=refresh_token`. Expected: `200`; the verifier refuses the token; the consent and refresh rows are gone. Under the same hint, another client's revoke answers `200` and changes nothing. - Re-consent after a revoke. Expected: the old token is refused and the new one is admitted. - An invalid token under every hint. Expected: `200`. - The provider's descriptions are pinned against the installed dist. - Pre-token refusals are kept: no client gives `401`, an unknown client gives `invalid_client`, an empty token gives `400`. - A consent-read store error. Expected: refused, and a green control afterwards. - A delete store error. Expected: `503` with `no-store`, and a retry gives `200`. - A `skip_consent` client. Expected: admitted with no consent row, and its revoke keeps `400 unsupported_token_type`, word for word the same under `token_type_hint=refresh_token`. - **`auth-manager.mcp-oauth.test.ts`.** A new describe, "verifyMcpAccessToken reads the consent the token was minted under (ruling A)", with 10 legs: - exactly one read; - the consent is gone; - `iat` against `createdAt` in whole seconds; - organization scoping; - client and user scoping; - `skip_consent`; - a store error; - no adapter; - no `azp`; - an unreadable `createdAt`, and no `iat`. - **The existing verifier rigs** (`mcp-verifier-keyring`, `mcp-oauth-resource`, `oauth-consent-organization`) now give the verifier a consent store. The keyring rig inserts a real consent row and mints `iat`, as the provider always does. **Ablations** (one-shot, not committed; the tree was restored and verified by blob hash and an empty `git diff HEAD`): | Ablation | Result | |---|---| | A1: the consent check returns `principal` unconditionally | 15 failed / 83 passed: all 9 consent-gate unit legs and 6 end-to-end legs go red | | A2: the route returns the provider's answer unwrapped | 6 failed / 92 passed: ⭐, no-hint, another-client, re-consent, invalid-token and revoke-500 go red | | A3 (at `49868b3174`): the provider's "not found" is answered `200` without looking for an MCP access token | 2 failed / 11 passed: the `refresh_token`-hint revoke leg and the `skip_consent` leg go red | A1 and A2 ran at `842d17a53a`. ## Acceptance notes - **Narrowing a consent's scope does not refuse old tokens.** `update-consent` touches only `updatedAt`, and the ruling keys on the record's existence and `createdAt`. A token minted under wider scopes keeps them until it expires. Only a revoke, a withdraw or a re-grant ends it. - **A consent-store outage answers `401`, not `503`.** The verifier's contract returns a falsy value and callers fail closed, so the MCP route answers `401`. The ban read answers `503` in the same outage. Changing that needs a contract change, which is out of scope here. - **The refresh family is revoked per (client, user), across organizations.** This follows the card's wording and `invalidateRefreshFamily(clientId, userId)`. The consent delete is scoped to the token's organization. - **Legacy consent rows with an unreadable `created_at` are refused** (fail closed). Every row the provider writes carries one. - **Accepted cost (from the ruling):** one indexed read per MCP request, and the consent page again on the next connect after a revoke. ## Verification Head `36d3a9fd82`: the fix commit `49868b3174` on top of `842d17a53a`, then `origin/main` `d55acb7828` merged in cleanly. The merge brings plugin-auth changes from main, among them `objectql-adapter.ts`, and every run below includes them. Diff: 10 files, +1114 / −16. - Build: exit 0. - plugin-auth tests: exit 0. Test Files 229 passed (229), Tests 4119 passed and 10 skipped (4129). Revocation file: 13 of 13. - plugin-auth typecheck: exit 0. - dogfood: exit 0. Test Files 424 passed and 3 skipped (427), Tests 3538 passed and 41 skipped (3579). - Derived gates (`dispatch-gates --commands` at this head): 63 run, every one exit 0. The derivation is one family shorter than at `842d17a53a`: `check:error-status-conformance` is no longer derived after the merge. - `--ran` reconcile: "63 derived famil(ies) accounted for — 63 run, 0 NOT-MEASURED (a DERIVED zero — all 63 recorded an exit code and none of them is 3)". - `test:repo` is left to CI. <details><summary>Gate results (63, all exit 0)</summary> ``` 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 --self-test :: exit 0 node scripts/check-closing-keyword-parity.mjs :: exit 0 node scripts/check-comment-mask-adoption.mjs --self-test :: exit 0 node scripts/check-comment-mask-adoption.mjs :: 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 --self-test :: exit 0 node scripts/check-plugin-teardown-shape.mjs :: exit 0 node scripts/check-tenant-audit-census.mjs --self-test :: exit 0 node scripts/check-tenant-audit-census.mjs :: 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:auth-mount-ledger :: 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:dispatcher-error-vocabulary :: 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:durability-log-level :: 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:watch-hint-literal :: exit 0 pnpm check:where-matcher :: exit 0 ``` </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01L9qibvynRbCtMndW8EHNGc)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent a30c4f4 commit 1aeeafd

10 files changed

Lines changed: 1114 additions & 16 deletions
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
---
2+
'@objectstack/plugin-auth': patch
3+
---
4+
5+
fix(plugin-auth)!: an MCP access token can be revoked — `/oauth2/revoke` and the Console's consent withdraw end it on the next request, through the OAuth consent it was minted under
6+
7+
Clause-②: no (narrowing) — the MCP door refuses a bearer whose consent is gone or newer than the token, which the published contract already promises (`packages/spec/src/contracts/auth-service.ts` `verifyMcpAccessToken`: "a falsy value when the token is unknown/expired/revoked … callers fail CLOSED"), and a bearer with no `azp` claim to key that read; the revoke door's 200 for an invalid or another client's token removes a refusal RFC 7009 §2.1/§2.2 already negates. The contract text is not changed.
8+
Metadata-protocol: none
9+
Skills-docs: none — `skills/**` says nothing about revoking an MCP OAuth access token or withdrawing a consent, so no published skill text moves; the rule is documented in `mcp-token-revocation.ts` and on `AuthManager.verifyMcpAccessToken`.
10+
11+
<!-- adr-0087: not-required (no-migration-prescription) no authorable key, value or export is removed or renamed; no metadata parses or saves differently, and only which OAuth bearers the MCP door admits after a revoke narrows -->
12+
13+
**BREAKING** narrowing at the MCP OAuth door and `/oauth2/revoke` (`@objectstack/plugin-auth`), executing the maintainer's ruling A of objectstack-ai/cloud#3606.
14+
15+
- **The consent is the revocable record.** An MCP access token is a JWT the authorization server never stores, so `verifyMcpAccessToken` now reads, on every MCP request, the consent the token was minted under: one indexed read of `sys_oauth_consent` by the token's client (`azp`), user (`sub`) and organization (`organization_id`). The token is refused when that consent is gone, when it was created after the token was issued (revoked, then granted again), when the token carries no `azp`, and when the read fails (fail closed). The MCP route answers a refused bearer `401`.
16+
- **`POST /oauth2/revoke`.** The provider still authenticates the client first, unchanged. For an MCP access token issued to that client, the revoke now deletes the consent and the client's refresh family for that user and answers `200`, where it answered `400 unsupported_token_type` and the token kept working until it expired. A token issued to another client answers `200` and changes nothing. An unknown or invalid token answers `200` (RFC 7009 §2.2) where it answered `400 invalid_request`. A `token_type_hint` that names another token type does not end the search (RFC 7009 §2.1): the MCP access token is revoked all the same. A request the provider refuses before it looks at the token (no client, an unknown client, a malformed request) keeps its refusal. A store error while revoking answers `503 server_error` (RFC 7009 §2.2.1: the token still stands, retry later), and a retry completes it.
17+
- **The Console's withdraw (`POST /oauth2/delete-consent`)** now ends the agent's access on its next request, with no other change: it deletes the same row the MCP door reads.
18+
- **A server-only `skip_consent` client** has no consent row: its tokens are admitted without one, and revoking one keeps the honest `unsupported_token_type`.
19+
- **The accepted cost.** After a revoke, the person sees the consent page again on the next connect.

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

Lines changed: 64 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -53,10 +53,22 @@
5353
* function declarations.
5454
*
5555
* Nothing re-exports this module, so the published surface does not move.
56+
*
57+
* ## The consent read (objectstack-ai/cloud#3606, ruling A)
58+
*
59+
* Since the move, the verifier gained one step the move did not carry: the
60+
* body is split into {@link verifyMcpAccessTokenClaims} (everything above,
61+
* unedited, now also answering the token's `iat`) and
62+
* {@link verifyMcpAccessToken}, which adds the consent read
63+
* (`mcp-token-revocation.ts` `mcpConsentAdmits`) through better-auth's own
64+
* storage adapter, reached as `getAuthContext`. `/oauth2/revoke` verifies
65+
* through the claims half alone, because it must still find the grant of a
66+
* token whose consent is already gone.
5667
*/
5768

5869
import type { JSONWebKeySet } from 'jose';
5970
import { OAUTH_ORGANIZATION_CLAIM, type AuthManager } from './auth-manager.js';
71+
import { mcpConsentAdmits, type OAuthGrantStore } from './mcp-token-revocation.js';
6072
import {
6173
retireHeldKeyrings,
6274
UNKNOWN_SIGNING_KEY_REREAD_FLOOR_MS,
@@ -90,13 +102,25 @@ export interface McpAccessTokenHost {
90102
getMcpResourceUrl: AuthManager['getMcpResourceUrl'];
91103
isMcpOAuthEnabled: AuthManager['isMcpOAuthEnabled'];
92104
rereadKeyringForUnknownKey: AuthManager['rereadKeyringForUnknownKey'];
105+
getAuthContext: AuthManager['getAuthContext'];
93106
}
94107

95-
/** The body of `AuthManager#verifyMcpAccessToken`; the method's docblock there is its contract. */
96-
export async function verifyMcpAccessToken(
97-
this: Pick<McpAccessTokenHost, 'getApi' | 'getAuthIssuer' | 'getMcpResourceUrl' | 'isMcpOAuthEnabled' | 'rereadKeyringForUnknownKey'>,
108+
/** The `this` of {@link verifyMcpAccessTokenClaims}: the members it reads. */
109+
type McpAccessTokenClaimsHost = Pick<McpAccessTokenHost, 'getApi' | 'getAuthIssuer' | 'getMcpResourceUrl' | 'isMcpOAuthEnabled' | 'rereadKeyringForUnknownKey'>;
110+
111+
/** A verified MCP access token's principal, as `IAuthService.verifyMcpAccessToken` returns it. */
112+
type McpAccessTokenPrincipal = { userId: string; scopes: string[]; clientId?: string; organizationId?: string };
113+
114+
/**
115+
* Every check of `AuthManager#verifyMcpAccessToken` but the consent read: the
116+
* signature, issuer, audience and expiry, the delegated-subject rule and the
117+
* organization claim. Answers the principal and the token's `iat` (absent
118+
* when the token carries none), or `null`.
119+
*/
120+
export async function verifyMcpAccessTokenClaims(
121+
this: McpAccessTokenClaimsHost,
98122
token: string,
99-
): Promise<{ userId: string; scopes: string[]; clientId?: string; organizationId?: string } | null> {
123+
): Promise<{ principal: McpAccessTokenPrincipal; issuedAt?: number } | null> {
100124
try {
101125
if (!token || token.split('.').length !== 3) return null; // not a JWS compact token
102126
if (!this.isMcpOAuthEnabled()) return null;
@@ -161,16 +185,48 @@ export async function verifyMcpAccessToken(
161185
) return null;
162186
const organizationId = organizationClaim as string | undefined;
163187
return {
164-
userId: subject,
165-
scopes,
166-
...(azp ? { clientId: azp } : {}),
167-
...(organizationId ? { organizationId } : {}),
188+
principal: {
189+
userId: subject,
190+
scopes,
191+
...(azp ? { clientId: azp } : {}),
192+
...(organizationId ? { organizationId } : {}),
193+
},
194+
...(typeof payload.iat === 'number' ? { issuedAt: payload.iat } : {}),
168195
};
169196
} catch {
170197
return null; // unknown/expired/wrong-audience/garbage → no principal
171198
}
172199
}
173200

201+
/**
202+
* The body of `AuthManager#verifyMcpAccessToken`; the method's docblock there
203+
* is its contract. {@link verifyMcpAccessTokenClaims}, then the consent read:
204+
* the token's grant must still stand (`mcpConsentAdmits`), read through
205+
* better-auth's storage adapter, the one the provider writes consents through.
206+
* The read is keyed by `azp`, the client the provider mints into every
207+
* access token, so a token without one is refused. A store error, or no
208+
* adapter at all, is a refusal: fail closed.
209+
*/
210+
export async function verifyMcpAccessToken(
211+
this: McpAccessTokenClaimsHost & Pick<McpAccessTokenHost, 'getAuthContext'>,
212+
token: string,
213+
): Promise<McpAccessTokenPrincipal | null> {
214+
const verified = await verifyMcpAccessTokenClaims.call(this, token);
215+
if (!verified?.principal.clientId) return null;
216+
const { principal, issuedAt } = verified;
217+
try {
218+
const store = ((await this.getAuthContext()) as { adapter?: OAuthGrantStore } | null | undefined)?.adapter;
219+
const grant = {
220+
clientId: principal.clientId!,
221+
userId: principal.userId,
222+
...(principal.organizationId ? { organizationId: principal.organizationId } : {}),
223+
};
224+
return (await mcpConsentAdmits(store, grant, issuedAt)) ? principal : null;
225+
} catch {
226+
return null; // the consent store could not answer → no principal (fail closed)
227+
}
228+
}
229+
174230
/** The body of `AuthManager#rereadKeyringForUnknownKey`; the method's docblock there is its contract. */
175231
export function rereadKeyringForUnknownKey(this: Pick<McpAccessTokenHost, 'config' | 'unknownKeyReread'>, api: unknown): Promise<JSONWebKeySet | undefined> {
176232
const last = this.unknownKeyReread;

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

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ import { ORGANIZATION_DELETE_PATH } from './organization-delete.js';
6666
import { clientAddressStateEntries } from './request-client-address.js';
6767
import { SESSION_ERASURE_PATHS } from './session-tombstone.js';
6868
import { envelopeVendorAdminRefusal } from './vendor-admin-refusal-envelope.js';
69+
import { OAUTH_REVOKE_PATH } from './mcp-token-revocation.js';
6970

7071
/**
7172
* The `AuthManager` members the functions below read — every one of them, and
@@ -83,10 +84,11 @@ export interface RequestRoutingHost {
8384
getOrCreateAuth: AuthManager['getOrCreateAuth'];
8485
resolveClientAddress: AuthManager['resolveClientAddress'];
8586
runSubjectErasureAtomically: AuthManager['runSubjectErasureAtomically'];
87+
answerOAuthTokenRevocation: AuthManager['answerOAuthTokenRevocation'];
8688
}
8789

8890
/** The body of `AuthManager#handleRequest`; the method's docblock there is its contract. */
89-
export async function handleRequest(this: Pick<RequestRoutingHost, 'betterAuthEndpointPath' | 'getOrCreateAuth' | 'resolveClientAddress' | 'runSubjectErasureAtomically'>, request: Request, transport?: { remoteAddress?: string }): Promise<Response> {
91+
export async function handleRequest(this: Pick<RequestRoutingHost, 'betterAuthEndpointPath' | 'getOrCreateAuth' | 'resolveClientAddress' | 'runSubjectErasureAtomically' | 'answerOAuthTokenRevocation'>, request: Request, transport?: { remoteAddress?: string }): Promise<Response> {
9092
// ADR-0069 D7 — the client address this request's sign-in audit stamps,
9193
// established ONCE, here, by the same trust rule the D5 allow-list judges
9294
// with (`resolveClientAddress`). Read before any rewrite below, and carried
@@ -229,16 +231,27 @@ export async function handleRequest(this: Pick<RequestRoutingHost, 'betterAuthEn
229231
return scimRequestScope.run({ scim: true }, runHandler);
230232
}
231233
: runHandler;
234+
// [objectstack-ai/cloud#3606, ruling A] `/oauth2/revoke` is answered a
235+
// second time, AFTER the provider: the provider authenticates the client
236+
// and answers first, unchanged, and the MCP access token it cannot revoke
237+
// is revoked through its consent (`mcp-token-revocation.ts`). The request is
238+
// cloned here, before the vendor reads its body, because the answer reads
239+
// the token and the client credentials off the same request.
240+
const revocationRequest =
241+
endpointPath === OAUTH_REVOKE_PATH && request.method === 'POST' ? request.clone() : undefined;
232242
// [#24948] An organization delete is one unit of work on the same terms:
233243
// better-auth clears the caller's active organization and deletes the
234244
// members and invitations before the organization row, with no
235245
// transaction, and the engine's refusal on that last row used to leave the
236246
// organization standing with no owner.
237-
const vendorResponse =
247+
const providerResponse =
238248
endpointPath !== undefined &&
239249
(SESSION_ERASURE_PATHS.has(endpointPath) || endpointPath === ORGANIZATION_DELETE_PATH)
240250
? await this.runSubjectErasureAtomically(runRequest)
241251
: await runRequest();
252+
const vendorResponse = revocationRequest
253+
? await this.answerOAuthTokenRevocation(revocationRequest, providerResponse)
254+
: providerResponse;
242255

243256
// [#10349] The better-auth-native `/admin/` routes refuse an anonymous
244257
// caller through the vendor's `adminMiddleware`

‎packages/plugins/plugin-auth/src/auth-manager.mcp-oauth-resource.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -388,6 +388,9 @@ function managerVerifyingAgainst(server: { auth: any }): AuthManager {
388388
vi.spyOn(m, 'getApi').mockResolvedValue({
389389
getJwks: async () => await server.auth.api.getJwks(),
390390
} as any);
391+
// [objectstack-ai/cloud#3606, ruling A] The consent read goes to the same
392+
// running server's storage adapter, where its provider stored the consent.
393+
vi.spyOn(m, 'getAuthContext').mockImplementation(async () => await server.auth.$context);
391394
return m;
392395
}
393396

0 commit comments

Comments
 (0)