Skip to content

Commit 327f91d

Browse files
committed
fix(auth): record an MCP token as used only after the door admits the call
IAuthService gains an optional recordMcpAccessTokenUse(principal). The plugin-auth verifier no longer schedules the consent last-use stamp; it remembers the principal object it returned, and the new member stamps only that object, once. The runtime MCP door calls it after the ban read and after the request context resolves, so a refused call (banned subject, grant-read outage) is never recorded as a use. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5pERdWox6UVMyKRjPq
1 parent fe97d85 commit 327f91d

8 files changed

Lines changed: 328 additions & 57 deletions

File tree

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
'@objectstack/spec': patch
3+
'@objectstack/plugin-auth': patch
4+
'@objectstack/runtime': patch
5+
---
6+
7+
fix(auth): an MCP access token is recorded as used only once the MCP door admits the call, so a banned person's refused calls no longer show their AI assistant as used
8+
9+
Clause-②: yes (widening)
10+
Metadata-protocol: none
11+
12+
`IAuthService` gains one optional member, `recordMcpAccessTokenUse(principal)`. Verifying a token is not admitting the call: the MCP door (`@objectstack/runtime`) refuses a banned subject after `verifyMcpAccessToken` answers, and a call whose authorization store cannot be read is a 503. Before this change `AuthManager.verifyMcpAccessToken` itself scheduled the coarse last-use stamp (`sys_oauth_consent.last_used_at`), so an administrator reading `GET /admin/authorized-clients?userId=` for a banned person saw the assistant as used in an hour when every call was refused.
13+
14+
Now `verifyMcpAccessToken` records nothing. The door calls `recordMcpAccessTokenUse` once, after its ban read and after the request context resolves, with the very object the verifier returned; `AuthManager` stamps only a principal object its own verifier returned, once, so a hand-built principal or a copy records nothing. The member returns nothing and never throws. The stamp's bound is unchanged: at most one write per consent per hour in each process.
15+
16+
A custom `IAuthService` needs nothing: the member is optional, and a door whose auth service lacks it admits the call exactly as before. A host that calls `AuthManager.verifyMcpAccessToken` itself and wants the call shown as used calls `recordMcpAccessTokenUse(principal)` with the verifier's result once it has admitted the call.

‎content/docs/kernel/contracts/auth-service.mdx‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,9 @@ export interface IAuthService {
4141
/** Verify an OAuth 2.1 access token from the embedded AS (MCP surface); the optional `organizationId` is the organization the user's OAuth consent bound, absent for a token minted before consents bound an organization. Optional. */
4242
verifyMcpAccessToken?(token: string): Promise<{ userId: string; scopes: string[]; clientId?: string; organizationId?: string } | undefined>;
4343

44+
/** Record that the caller admitted a call made with a verified MCP access token: called once, after the caller's last refusal, with the object `verifyMcpAccessToken` returned; a principal the provider did not return records nothing. Never throws. Optional. */
45+
recordMcpAccessTokenUse?(principal: { userId: string; scopes: string[]; clientId?: string; organizationId?: string }): void;
46+
4447
/** The MCP resource identifier (RFC 8707 `resource` / token `aud`). Optional. */
4548
getMcpResourceUrl?(): string;
4649

@@ -51,10 +54,11 @@ export interface IAuthService {
5154

5255
The two required members are the core: it follows the Dependency Inversion Principle so that plugins depend on the contract rather than a concrete provider. Concrete implementations (better-auth, custom, LDAP, etc.) supply the actual logic, and `handleRequest` works directly with the standard `Request`/`Response` types.
5356

54-
Everything after `verify` is optional, and each optional member describes a capability a provider may or may not have — a caller must probe before use. Two pairs are worth reading together:
57+
Everything after `verify` is optional, and each optional member describes a capability a provider may or may not have — a caller must probe before use. Three pairs are worth reading together:
5558

5659
- **`api` and `getApi()`** are the same session handle by two routes. `api` is the legacy direct mount; `getApi()` is the lazy accessor, and it is the one to prefer — the shipped `plugin-auth` registers an `AuthManager`, which has **no `api` member at all**, so a caller that reads only `api` gets `undefined` on every current deployment. Read `api ?? await getApi?.()`.
5760
- **`getMcpResourceUrl()` and `getMcpResourceMetadataUrl()`** both describe the MCP OAuth surface; the second returns `null` (rather than being absent) when the OAuth track is off for the deployment.
61+
- **`verifyMcpAccessToken()` and `recordMcpAccessTokenUse()`** split verifying a token from admitting the call. The MCP door verifies first, then applies its own refusals (a banned subject, an authorization store it could not read), and only for a call it admits hands the verified principal back to `recordMcpAccessTokenUse()`. So a refused call is never recorded as a use of the grant (the coarse "last used" time the authorized-clients reads show).
5862

5963
---
6064

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

Lines changed: 46 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
22

33
import type { Auth, BetterAuthOptions } from 'better-auth';
4-
import { decodeJwt, type JSONWebKeySet } from 'jose';
4+
import type { JSONWebKeySet } from 'jose';
55
import type { SCIMIdentityState, SCIMTransactionContext } from '@better-auth/scim';
66
// better-auth value imports (betterAuth + plugins) are deferred via dynamic
77
// import() in getOrCreateAuth() / buildPluginList() so that disabled plugins
@@ -225,7 +225,7 @@ import {
225225
type McpAccessTokenHost,
226226
} from './auth-manager-mcp-access-token.js';
227227
// [#30918] The coarse last-use stamp a verified MCP call writes on its consent.
228-
import { McpClientLastUseStamper, mcpClientLastUseStoreFor } from './mcp-client-last-use.js';
228+
import { McpClientLastUseStamper, mcpClientLastUseStoreFor, issuedAtOf } from './mcp-client-last-use.js';
229229
import { runAfterResponse } from './run-after-response.js';
230230
// [objectstack-ai/cloud#3606, ruling A] `/oauth2/revoke` for an MCP access
231231
// token: the answer `handleRequest` gives after the provider's, through
@@ -4620,13 +4620,12 @@ export class AuthManager {
46204620
* organization (`vetOrganizationClaim`, `@objectstack/core`), as the
46214621
* `IAuthService` contract states.
46224622
*
4623-
* [#30918] A token that verifies also schedules, AFTER the verdict and off
4624-
* the request's path, the coarse last-use stamp on the consent it was minted
4625-
* under (`mcp-client-last-use.ts`): at most one write per consent per hour
4626-
* in each process, from this verified token and the server's clock, and
4627-
* only on the consent that admitted it (the consent read above, by the same
4628-
* rule). The stamp reads and writes nothing the verdict depends on, and its
4629-
* failure is never this method's failure.
4623+
* [#30918 · #31211] Verifying is not admitting: this method records NO use.
4624+
* The door that resolves the principal can still refuse the call (a banned
4625+
* subject, an authorization store it could not read), and a refused call is
4626+
* not a use. It remembers the principal object it returns, and the door
4627+
* hands that object back to {@link recordMcpAccessTokenUse} once it has
4628+
* admitted the call.
46304629
*/
46314630
verifyMcpAccessToken(
46324631
token: string,
@@ -4640,18 +4639,48 @@ export class AuthManager {
46404639
rereadKeyringForUnknownKey: (...a) => this.rereadKeyringForUnknownKey(...a),
46414640
getAuthContext: (...a) => this.getAuthContext(...a),
46424641
};
4643-
// [#30918] A token that verified is a verified MCP call: its consent's
4644-
// coarse last-use stamp is settled after the response, never awaited here,
4645-
// and from the verified token only (`mcp-client-last-use.ts`). The
4646-
// verifier has just admitted the token by its consent (#30879,
4647-
// `mcpConsentAdmits`), so a revoked consent refuses the call and stamps
4648-
// nothing; the stamp picks its consent by the same rule.
4642+
// [#31211] Remember the object this verifier answered, with the `iat` of
4643+
// the token it verified, so only that object can later be recorded as
4644+
// used. The token has just verified, so its payload is the one the
4645+
// signature covers: its `iat` is what the verifier admitted the consent
4646+
// against (#30879, `mcpConsentAdmits`).
46494647
return verifyMcpAccessToken.call(host, token).then((principal) => {
4650-
if (principal) this.scheduleMcpClientLastUse(principal, token);
4648+
if (principal) this.verifiedMcpPrincipals.set(principal, { issuedAt: issuedAtOf(token) });
46514649
return principal;
46524650
});
46534651
}
46544652

4653+
/**
4654+
* [#31211] The principal objects {@link verifyMcpAccessToken} answered and
4655+
* nobody has recorded yet, each with its token's `iat`. Weak, so a principal
4656+
* whose call was refused (never recorded) is dropped with the request.
4657+
*/
4658+
private readonly verifiedMcpPrincipals = new WeakMap<object, { issuedAt?: number }>();
4659+
4660+
/**
4661+
* [#31211] `IAuthService.recordMcpAccessTokenUse`: the MCP door admitted a
4662+
* call made with a token {@link verifyMcpAccessToken} verified, so the
4663+
* consent that token was minted under gets its coarse last-use stamp
4664+
* (`mcp-client-last-use.ts`, #30918), after the response and never awaited
4665+
* here: at most one write per consent per hour in each process, from the
4666+
* verified token and the server's clock, and only on the consent that
4667+
* admitted it.
4668+
*
4669+
* Only an object this manager's verifier returned is recorded, and only
4670+
* once; a hand-built principal, a copy, or the same object again records
4671+
* nothing. Never throws: the stamp's failure is never the call's failure.
4672+
*/
4673+
recordMcpAccessTokenUse(principal: { userId: string; scopes: string[]; clientId?: string; organizationId?: string }): void {
4674+
try {
4675+
const verified = principal !== null && typeof principal === 'object' ? this.verifiedMcpPrincipals.get(principal) : undefined;
4676+
if (!verified) return;
4677+
this.verifiedMcpPrincipals.delete(principal);
4678+
this.scheduleMcpClientLastUse(principal, verified.issuedAt);
4679+
} catch {
4680+
// Bookkeeping only: an admitted call is never refused for it.
4681+
}
4682+
}
4683+
46554684
/** [#30918] The per-manager stamper, built on first use. */
46564685
private mcpClientLastUse?: McpClientLastUseStamper;
46574686

@@ -4667,18 +4696,9 @@ export class AuthManager {
46674696
*/
46684697
private scheduleMcpClientLastUse(
46694698
principal: { userId: string; clientId?: string; organizationId?: string },
4670-
token: string,
4699+
issuedAt: number | undefined,
46714700
): void {
46724701
if (!principal.clientId) return;
4673-
// The token has just verified, so its payload is the one the signature
4674-
// covers: its `iat` is what the verifier admitted the consent against.
4675-
let issuedAt: number | undefined;
4676-
try {
4677-
const iat = decodeJwt(token).iat;
4678-
issuedAt = typeof iat === 'number' ? iat : undefined;
4679-
} catch {
4680-
issuedAt = undefined;
4681-
}
46824702
const stamper = (this.mcpClientLastUse ??= new McpClientLastUseStamper(
46834703
mcpClientLastUseStoreFor(() => this.getDataEngine()),
46844704
{

0 commit comments

Comments
 (0)