From 8de6140ec28ee064573f2601ca6b6bd560327ace Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 16 Nov 2026 16:03:24 -0800 Subject: [PATCH 1/2] fix(auth): bind automatic pairing codes to peer links --- apps/server/src/auth/EnvironmentAuth.test.ts | 30 +++++++++++++++++++ apps/server/src/auth/EnvironmentAuth.ts | 20 +++++++++---- apps/server/src/auth/McpOAuth.ts | 22 +++++++------- .../server/src/auth/PairingGrantStore.test.ts | 5 +++- apps/server/src/auth/PairingGrantStore.ts | 13 +++----- apps/server/src/auth/http.ts | 3 ++ .../src/environment/ServerEnvironment.ts | 1 + apps/server/src/peer/PeerLinks.test.ts | 5 +++- .../src/persistence/AuthPairingLinks.ts | 13 ++++---- .../src/state/peerPairingCode.ts | 24 +++++++++++++-- packages/contracts/src/auth.ts | 2 ++ packages/contracts/src/environment.ts | 1 + 12 files changed, 104 insertions(+), 35 deletions(-) diff --git a/apps/server/src/auth/EnvironmentAuth.test.ts b/apps/server/src/auth/EnvironmentAuth.test.ts index 365203e03db2..40fce79a54f5 100644 --- a/apps/server/src/auth/EnvironmentAuth.test.ts +++ b/apps/server/src/auth/EnvironmentAuth.test.ts @@ -513,6 +513,36 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodePlatformCrypto.layer))( }).pipe(Effect.provide(layerEnvironmentAuth())), ); + it.effect("spends peer-link pairing codes only for the chosen link access", () => + Effect.gen(function* () { + const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; + const pairing = yield* serverAuth.issuePairingCredential({ + access: "approval-required", + purpose: "peer-link", + }); + expect(pairing.purpose).toBe("peer-link"); + + const ordinarySession = yield* serverAuth + .exchangeBootstrapCredentialForAccessToken(pairing.credential, undefined, requestMetadata) + .pipe(Effect.flip); + expect(ordinarySession._tag).toBe("ServerAuthInvalidCredentialError"); + + for (const input of [ + { access: "approval-required", peerLink: false }, + { access: "auto", peerLink: true }, + ] as const) { + const rejected = yield* serverAuth + .consumeMcpApprovalCode(pairing.credential, input.access, input.peerLink) + .pipe(Effect.flip); + expect(rejected._tag).toBe("ServerAuthMcpApprovalCodeError"); + } + + expect( + yield* serverAuth.consumeMcpApprovalCode(pairing.credential, "approval-required", true), + ).toBe("approval-required"); + }).pipe(Effect.provide(layerEnvironmentAuth())), + ); + it.effect("narrows seeded desktop grants to the requested scopes", () => Effect.gen(function* () { const serverAuth = yield* EnvironmentAuth.EnvironmentAuth; diff --git a/apps/server/src/auth/EnvironmentAuth.ts b/apps/server/src/auth/EnvironmentAuth.ts index 384afb2d72c1..3d68f07b0b8f 100644 --- a/apps/server/src/auth/EnvironmentAuth.ts +++ b/apps/server/src/auth/EnvironmentAuth.ts @@ -50,7 +50,10 @@ import { DESKTOP_RENDERER_ORIGINS } from "../httpCors.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as ManagedLimits from "../policy/managedLimits.ts"; import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; -import { MCP_APPROVAL_SUBJECT_PREFIX } from "../persistence/AuthPairingLinks.ts"; +import { + MCP_APPROVAL_SUBJECT_PREFIX, + PEER_LINK_PAIRING_SUBJECT_PREFIX, +} from "../persistence/AuthPairingLinks.ts"; import { requestUrl } from "../requestUrl.ts"; const DEFAULT_SESSION_SUBJECT = "cli-issued-session"; @@ -628,6 +631,7 @@ export class EnvironmentAuth extends Context.Service< readonly consumeMcpApprovalCode: ( code: string, access: AuthMcpClientAccess, + peerLink?: boolean, ) => Effect.Effect< AuthMcpClientAccess, ServerAuthMcpApprovalCodeError | ServerAuthInternalError @@ -983,8 +987,7 @@ export const make = Effect.gen(function* () { readonly proofKeyThumbprint?: string; readonly requestedScopes?: ReadonlyArray; readonly requiredScopes?: ReadonlyArray; - /** Only an agent sign-in opts in to spending a code issued for it. */ - readonly mcpApproval?: AuthMcpClientAccess; + readonly allowedSubject?: string; /** Shown to approvers when the credential waits on T3 Connect device approval. */ readonly requestMetadata?: AuthClientMetadata; }, @@ -1337,13 +1340,17 @@ export const make = Effect.gen(function* () { scopes: input?.access ? mcpClientScopes(input.access) : (input?.scopes ?? AuthStandardClientScopes), - subject: "one-time-token", + subject: + input?.purpose === "peer-link" && input.access + ? `${PEER_LINK_PAIRING_SUBJECT_PREFIX}${input.access}` + : "one-time-token", ...(input?.label ? { label: input.label } : {}), - ...(input?.access ? { mcpApproval: input.access } : {}), + ...(input?.access && input.purpose !== "peer-link" ? { mcpApproval: input.access } : {}), }).pipe( Effect.map((issued) => ({ ...toPairingCredential(issued), ...(input?.access ? { access: input.access } : {}), + ...(input?.access && input.purpose === "peer-link" ? { purpose: input.purpose } : {}), })), Effect.withSpan("EnvironmentAuth.issuePairingCredential"), ); @@ -1570,10 +1577,11 @@ export const make = Effect.gen(function* () { const consumeMcpApprovalCode: EnvironmentAuth["Service"]["consumeMcpApprovalCode"] = ( code, access, + peerLink = false, ) => resolveBootstrapGrant(code.trim(), { requiredScopes: mcpClientScopes(access), - mcpApproval: access, + allowedSubject: `${peerLink ? PEER_LINK_PAIRING_SUBJECT_PREFIX : MCP_APPROVAL_SUBJECT_PREFIX}${access}`, }).pipe( Effect.catchTags({ ServerAuthInvalidCredentialError: () => diff --git a/apps/server/src/auth/McpOAuth.ts b/apps/server/src/auth/McpOAuth.ts index fdb0e4044f1d..18ad10c2dbd2 100644 --- a/apps/server/src/auth/McpOAuth.ts +++ b/apps/server/src/auth/McpOAuth.ts @@ -474,19 +474,21 @@ const make = Effect.gen(function* () { description: "Linking needs a plain pairing code, not an app approval code.", }); } - access = yield* environmentAuth.consumeMcpApprovalCode(decision.code, decision.access).pipe( - Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (cause) => - Effect.logError("MCP approval code check failed.", { cause }).pipe( - Effect.andThen( - Effect.fail( - new McpOAuthPageError({ - description: "The code could not be checked. Try again.", - }), + access = yield* environmentAuth + .consumeMcpApprovalCode(decision.code, decision.access, input.authorization.client.peerLink) + .pipe( + Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (cause) => + Effect.logError("MCP approval code check failed.", { cause }).pipe( + Effect.andThen( + Effect.fail( + new McpOAuthPageError({ + description: "The code could not be checked. Try again.", + }), + ), ), ), ), - ), - ); + ); } else { const session = yield* approvingSession(input.request, input.authorization); if ( diff --git a/apps/server/src/auth/PairingGrantStore.test.ts b/apps/server/src/auth/PairingGrantStore.test.ts index 3f95ce46ec69..4d70e65caecf 100644 --- a/apps/server/src/auth/PairingGrantStore.test.ts +++ b/apps/server/src/auth/PairingGrantStore.test.ts @@ -15,6 +15,7 @@ import { } from "@t3tools/shared/desktopBootstrapToken"; import * as ServerConfig from "../config.ts"; +import { MCP_APPROVAL_SUBJECT_PREFIX } from "../persistence/AuthPairingLinks.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as PairingGrantStore from "./PairingGrantStore.ts"; @@ -236,7 +237,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("PairingGrantStor ); // An app approval code sends no update, issued or spent; the next belongs to a plain code. const approval = yield* grants.issueOneTimeToken({ mcpApproval: "auto" }); - yield* grants.consume(approval.credential, { mcpApproval: "auto" }); + yield* grants.consume(approval.credential, { + allowedSubject: `${MCP_APPROVAL_SUBJECT_PREFIX}auto`, + }); for (const input of [{}, { label: "Synthetic phone" }]) { const issued = yield* grants.issueOneTimeToken(input); const change = yield* Queue.take(changes); diff --git a/apps/server/src/auth/PairingGrantStore.ts b/apps/server/src/auth/PairingGrantStore.ts index 62d78d349501..6929cffc7eeb 100644 --- a/apps/server/src/auth/PairingGrantStore.ts +++ b/apps/server/src/auth/PairingGrantStore.ts @@ -301,8 +301,7 @@ export class PairingGrantStore extends Context.Service< readonly requestedScopes?: ReadonlyArray; /** All scopes must be granted; requestedScopes only requires an overlap for OAuth. */ readonly requiredScopes?: ReadonlyArray; - /** Also spends a code issued for an agent sign-in at this level; others refuse them. */ - readonly mcpApproval?: AuthMcpClientAccess; + readonly allowedSubject?: string; }, ) => Effect.Effect; } @@ -509,8 +508,8 @@ const make = Effect.gen(function* () { }), ), ); - // Approval codes stay out of the pairing links and QR codes that clients show. - if (!mcpApproval) { + // Purpose-bound codes stay out of the pairing links and QR codes that clients show. + if (!subject.startsWith(AuthPairingLinks.MCP_APPROVAL_SUBJECT_PREFIX)) { yield* emitUpsert({ id, scopes: input?.scopes ?? AuthStandardClientScopes, @@ -652,11 +651,7 @@ const make = Effect.gen(function* () { ? { requestedScopes: input.requestedScopes } : {}), ...(input?.requiredScopes !== undefined ? { requiredScopes: input.requiredScopes } : {}), - ...(input?.mcpApproval - ? { - mcpApprovalSubject: `${AuthPairingLinks.MCP_APPROVAL_SUBJECT_PREFIX}${input.mcpApproval}`, - } - : {}), + ...(input?.allowedSubject ? { allowedSubject: input.allowedSubject } : {}), consumedAt: now, now, }) diff --git a/apps/server/src/auth/http.ts b/apps/server/src/auth/http.ts index b8b49a1d1b34..d2221860522d 100644 --- a/apps/server/src/auth/http.ts +++ b/apps/server/src/auth/http.ts @@ -478,6 +478,9 @@ export const layer = HttpApiBuilder.group( function* (args) { yield* annotateEnvironmentRequest(args.endpoint.name); const session = yield* requireEnvironmentScope(AuthAccessWriteScope); + if (args.payload.purpose === "peer-link" && args.payload.access === undefined) { + return yield* failEnvironmentInvalidRequest("invalid_scope"); + } const delegatedScopes = args.payload.access ? mcpClientScopes(args.payload.access) : (args.payload.scopes ?? AuthStandardClientScopes); diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index 813efbe53ea3..0f3a88f5c0d9 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -294,6 +294,7 @@ export const make = Effect.gen(function* () { mcpModeLimitHeader: true, linkFence: true, mcpApprovalCodes: true, + peerLinkPairingCodes: true, mcpHostedApproval: true, shellThreadFamilies: true, shellOlderSettled: true, diff --git a/apps/server/src/peer/PeerLinks.test.ts b/apps/server/src/peer/PeerLinks.test.ts index 6923037b6f7c..855e7e29cd33 100644 --- a/apps/server/src/peer/PeerLinks.test.ts +++ b/apps/server/src/peer/PeerLinks.test.ts @@ -173,7 +173,10 @@ it.effect("links with a pairing code, and the peer holds its agents to the limit expect(refused.reason).toBe("pairing_rejected"); expect(yield* linkedSessions(b)).toEqual([]); - const pairing = yield* b.auth.issuePairingCredential(); + const pairing = yield* b.auth.issuePairingCredential({ + access: "auto", + purpose: "peer-link", + }); const linked = yield* a.links.link({ url: b.url, pairingCode: pairing.credential, diff --git a/apps/server/src/persistence/AuthPairingLinks.ts b/apps/server/src/persistence/AuthPairingLinks.ts index df513f9963ca..dc1fae88e68a 100644 --- a/apps/server/src/persistence/AuthPairingLinks.ts +++ b/apps/server/src/persistence/AuthPairingLinks.ts @@ -17,10 +17,11 @@ import { } from "./Errors.ts"; /** - * Subjects of codes that approve one agent sign-in at a set level, as `mcp-approval:`. - * Only that sign-in may spend one, so every other use of a pairing code refuses them. + * These subjects are reserved for one kind and level of MCP authorization. + * Keep peer-link subjects under the same prefix so older servers refuse them too. */ export const MCP_APPROVAL_SUBJECT_PREFIX = "mcp-approval:"; +export const PEER_LINK_PAIRING_SUBJECT_PREFIX = `${MCP_APPROVAL_SUBJECT_PREFIX}peer-link:`; const SqliteFlag = Schema.Literals([0, 1]); @@ -62,8 +63,8 @@ export const ConsumeAuthPairingLinkInput = Schema.Struct({ proofKeyThumbprint: Schema.NullOr(Schema.String), requestedScopes: Schema.optionalKey(AuthEnvironmentScopes), requiredScopes: Schema.optionalKey(AuthEnvironmentScopes), - /** Also spends a code with exactly this `mcp-approval:` subject. Others are always refused. */ - mcpApprovalSubject: Schema.optionalKey(Schema.String), + /** Allow a purpose-bound code only when its subject matches the request. */ + allowedSubject: Schema.optionalKey(Schema.String), consumedAt: Schema.DateTimeUtcFromString, now: Schema.DateTimeUtcFromString, }); @@ -227,7 +228,7 @@ export const make = Effect.gen(function* () { proofKeyThumbprint, requestedScopes, requiredScopes, - mcpApprovalSubject, + allowedSubject, consumedAt, now, }) => @@ -240,7 +241,7 @@ export const make = Effect.gen(function* () { AND expires_at > ${now} AND ( subject NOT LIKE ${`${MCP_APPROVAL_SUBJECT_PREFIX}%`} - OR subject = ${mcpApprovalSubject ?? null} + OR subject = ${allowedSubject ?? null} ) AND ( proof_key_thumbprint IS NULL diff --git a/packages/client-runtime/src/state/peerPairingCode.ts b/packages/client-runtime/src/state/peerPairingCode.ts index fe825610ea63..7b1f20639427 100644 --- a/packages/client-runtime/src/state/peerPairingCode.ts +++ b/packages/client-runtime/src/state/peerPairingCode.ts @@ -8,7 +8,6 @@ import { type AuthCreatePairingCredentialInput, type AuthMcpClientAccess, type AuthPairingCredentialResult, - mcpClientScopes, } from "@t3tools/contracts"; import * as Schema from "effect/Schema"; import * as Effect from "effect/Effect"; @@ -87,6 +86,15 @@ const mintOnEnvironment = Effect.fnUntraced(function* (payload: AuthCreatePairin cause: "The environment is not connected.", }); } + if ( + payload.purpose === "peer-link" && + prepared.value.descriptor?.capabilities.peerLinkPairingCodes !== true + ) { + return yield* new PeerPairingCodeError({ + reason: "unavailable", + cause: "The environment does not support peer-link pairing codes.", + }); + } return yield* mintPairingCredential(prepared.value, payload); }); @@ -100,7 +108,19 @@ export function createPeerPairingCodeCommand( return createEnvironmentCommand(runtime, { label: "environment-data:peer-pairing-code:mint", execute: (access: AuthMcpClientAccess) => - mintOnEnvironment({ label: PEER_PAIRING_CODE_LABEL, scopes: mcpClientScopes(access) }).pipe( + mintOnEnvironment({ + label: PEER_PAIRING_CODE_LABEL, + access, + purpose: "peer-link", + }).pipe( + Effect.filterOrFail( + (minted) => minted.purpose === "peer-link" && minted.access === access, + () => + new PeerPairingCodeError({ + reason: "unavailable", + cause: "The environment did not issue a peer-link code.", + }), + ), Effect.map((minted) => minted.credential), ), }); diff --git a/packages/contracts/src/auth.ts b/packages/contracts/src/auth.ts index 371377d5e905..87eb168d9e33 100644 --- a/packages/contracts/src/auth.ts +++ b/packages/contracts/src/auth.ts @@ -316,6 +316,7 @@ export const AuthPairingCredentialResult = Schema.Struct({ credential: TrimmedNonEmptyString, label: Schema.optionalKey(TrimmedNonEmptyString), expiresAt: Schema.DateTimeUtc, + purpose: Schema.optionalKey(Schema.Literal("peer-link")), /** Set when the code approves one agent sign-in at this level. Older servers omit it. */ access: Schema.optionalKey(AuthMcpClientAccess), }); @@ -503,6 +504,7 @@ export const AuthCreatePairingCredentialInput = Schema.Struct({ scopes: Schema.optionalKey(AuthGrantScopes), /** Binds the code to one agent sign-in at this level. The server derives the scopes from it. */ access: Schema.optionalKey(AuthMcpClientAccess), + purpose: Schema.optionalKey(Schema.Literal("peer-link")), }); export type AuthCreatePairingCredentialInput = typeof AuthCreatePairingCredentialInput.Type; diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index 603b6c6cc862..fd091152599d 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -185,6 +185,7 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ linkFence: Schema.optionalKey(Schema.Boolean), /** Mints pairing codes that approve one agent sign-in at a set level (`AUTO-…`). */ mcpApprovalCodes: Schema.optionalKey(Schema.Boolean), + peerLinkPairingCodes: Schema.optionalKey(Schema.Boolean), /** Agent sign-ins on its T3 Connect address are approved on the hosted app, without a code. */ mcpHostedApproval: Schema.optionalKey(Schema.Boolean), /** Server answers server.prepareTriage. */ From 98aa6fe10e46a723d921bb6d91fd68ad53304f35 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 16 Nov 2026 16:40:35 -0800 Subject: [PATCH 2/2] fix(auth): require an access level for peer pairing codes --- apps/server/src/auth/http.ts | 3 --- packages/contracts/src/auth.ts | 20 +++++++++++++++----- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/apps/server/src/auth/http.ts b/apps/server/src/auth/http.ts index d2221860522d..b8b49a1d1b34 100644 --- a/apps/server/src/auth/http.ts +++ b/apps/server/src/auth/http.ts @@ -478,9 +478,6 @@ export const layer = HttpApiBuilder.group( function* (args) { yield* annotateEnvironmentRequest(args.endpoint.name); const session = yield* requireEnvironmentScope(AuthAccessWriteScope); - if (args.payload.purpose === "peer-link" && args.payload.access === undefined) { - return yield* failEnvironmentInvalidRequest("invalid_scope"); - } const delegatedScopes = args.payload.access ? mcpClientScopes(args.payload.access) : (args.payload.scopes ?? AuthStandardClientScopes); diff --git a/packages/contracts/src/auth.ts b/packages/contracts/src/auth.ts index 87eb168d9e33..fd0c93025dbf 100644 --- a/packages/contracts/src/auth.ts +++ b/packages/contracts/src/auth.ts @@ -499,13 +499,23 @@ export const AuthRevokeConnectDeviceResult = Schema.Struct({ }); export type AuthRevokeConnectDeviceResult = typeof AuthRevokeConnectDeviceResult.Type; -export const AuthCreatePairingCredentialInput = Schema.Struct({ +const pairingCredentialFields = { label: Schema.optionalKey(TrimmedNonEmptyString), scopes: Schema.optionalKey(AuthGrantScopes), - /** Binds the code to one agent sign-in at this level. The server derives the scopes from it. */ - access: Schema.optionalKey(AuthMcpClientAccess), - purpose: Schema.optionalKey(Schema.Literal("peer-link")), -}); +}; + +export const AuthCreatePairingCredentialInput = Schema.Union([ + Schema.Struct({ + ...pairingCredentialFields, + access: Schema.optionalKey(AuthMcpClientAccess), + purpose: Schema.optionalKey(Schema.Undefined), + }), + Schema.Struct({ + ...pairingCredentialFields, + access: AuthMcpClientAccess, + purpose: Schema.Literal("peer-link"), + }), +]); export type AuthCreatePairingCredentialInput = typeof AuthCreatePairingCredentialInput.Type; export const AuthSessionState = Schema.Struct({