The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 09:45 UTC
fix(auth): bind automatic pairing codes to peer links (#37825)
Julius Marminge committed
Nov 16, 2026 at 17:15 UTC
27411651a495724715c623e73d092f2b0699f494
11 files changed
+115
-39
apps/server/src/auth/EnvironmentAuth.test.ts
+30
@@ -513,6 +513,36 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodePlatformCrypto.layer))(
513
}).pipe(Effect.provide(layerEnvironmentAuth())),
514
);
515
516
+ it.effect("spends peer-link pairing codes only for the chosen link access", () =>
517
+ Effect.gen(function* () {
518
+ const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
519
+ const pairing = yield* serverAuth.issuePairingCredential({
520
+ access: "approval-required",
521
+ purpose: "peer-link",
522
+ });
523
+ expect(pairing.purpose).toBe("peer-link");
524
+
525
+ const ordinarySession = yield* serverAuth
526
+ .exchangeBootstrapCredentialForAccessToken(pairing.credential, undefined, requestMetadata)
527
+ .pipe(Effect.flip);
528
+ expect(ordinarySession._tag).toBe("ServerAuthInvalidCredentialError");
529
+
530
+ for (const input of [
531
+ { access: "approval-required", peerLink: false },
532
+ { access: "auto", peerLink: true },
533
+ ] as const) {
534
+ const rejected = yield* serverAuth
535
+ .consumeMcpApprovalCode(pairing.credential, input.access, input.peerLink)
536
+ .pipe(Effect.flip);
537
+ expect(rejected._tag).toBe("ServerAuthMcpApprovalCodeError");
538
+ }
539
+
540
+ expect(
541
+ yield* serverAuth.consumeMcpApprovalCode(pairing.credential, "approval-required", true),
542
+ ).toBe("approval-required");
543
+ }).pipe(Effect.provide(layerEnvironmentAuth())),
544
+ );
545
+
546
it.effect("narrows seeded desktop grants to the requested scopes", () =>
547
Effect.gen(function* () {
548
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
apps/server/src/auth/EnvironmentAuth.ts
+14
-6
@@ -50,7 +50,10 @@ import { DESKTOP_RENDERER_ORIGINS } from "../httpCors.ts";
50
import * as SqlitePersistence from "../persistence/Sqlite.ts";
51
import * as ManagedLimits from "../policy/managedLimits.ts";
52
import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
53
-import { MCP_APPROVAL_SUBJECT_PREFIX } from "../persistence/AuthPairingLinks.ts";
53
+import {
54
+ MCP_APPROVAL_SUBJECT_PREFIX,
55
+ PEER_LINK_PAIRING_SUBJECT_PREFIX,
56
+} from "../persistence/AuthPairingLinks.ts";
57
import { requestUrl } from "../requestUrl.ts";
58
59
const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
@@ -628,6 +631,7 @@ export class EnvironmentAuth extends Context.Service<
631
readonly consumeMcpApprovalCode: (
632
code: string,
633
access: AuthMcpClientAccess,
634
+ peerLink?: boolean,
635
) => Effect.Effect<
636
AuthMcpClientAccess,
637
ServerAuthMcpApprovalCodeError | ServerAuthInternalError
@@ -983,8 +987,7 @@ export const make = Effect.gen(function* () {
987
readonly proofKeyThumbprint?: string;
988
readonly requestedScopes?: ReadonlyArray<AuthEnvironmentScope>;
989
readonly requiredScopes?: ReadonlyArray<AuthEnvironmentScope>;
986
- /** Only an agent sign-in opts in to spending a code issued for it. */
987
- readonly mcpApproval?: AuthMcpClientAccess;
990
+ readonly allowedSubject?: string;
991
/** Shown to approvers when the credential waits on T3 Connect device approval. */
992
readonly requestMetadata?: AuthClientMetadata;
993
},
@@ -1337,13 +1340,17 @@ export const make = Effect.gen(function* () {
1340
scopes: input?.access
1341
? mcpClientScopes(input.access)
1342
: (input?.scopes ?? AuthStandardClientScopes),
1340
- subject: "one-time-token",
1343
+ subject:
1344
+ input?.purpose === "peer-link" && input.access
1345
+ ? `${PEER_LINK_PAIRING_SUBJECT_PREFIX}${input.access}`
1346
+ : "one-time-token",
1347
...(input?.label ? { label: input.label } : {}),
1342
- ...(input?.access ? { mcpApproval: input.access } : {}),
1348
+ ...(input?.access && input.purpose !== "peer-link" ? { mcpApproval: input.access } : {}),
1349
}).pipe(
1350
Effect.map((issued) => ({
1351
...toPairingCredential(issued),
1352
...(input?.access ? { access: input.access } : {}),
1353
+ ...(input?.access && input.purpose === "peer-link" ? { purpose: input.purpose } : {}),
1354
})),
1355
Effect.withSpan("EnvironmentAuth.issuePairingCredential"),
1356
);
@@ -1570,10 +1577,11 @@ export const make = Effect.gen(function* () {
1577
const consumeMcpApprovalCode: EnvironmentAuth["Service"]["consumeMcpApprovalCode"] = (
1578
code,
1579
access,
1580
+ peerLink = false,
1581
) =>
1582
resolveBootstrapGrant(code.trim(), {
1583
requiredScopes: mcpClientScopes(access),
1576
- mcpApproval: access,
1584
+ allowedSubject: `${peerLink ? PEER_LINK_PAIRING_SUBJECT_PREFIX : MCP_APPROVAL_SUBJECT_PREFIX}${access}`,
1585
}).pipe(
1586
Effect.catchTags({
1587
ServerAuthInvalidCredentialError: () =>
apps/server/src/auth/McpOAuth.ts
+12
-10
@@ -474,19 +474,21 @@ const make = Effect.gen(function* () {
474
description: "Linking needs a plain pairing code, not an app approval code.",
475
});
476
}
477
- access = yield* environmentAuth.consumeMcpApprovalCode(decision.code, decision.access).pipe(
478
- Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (cause) =>
479
- Effect.logError("MCP approval code check failed.", { cause }).pipe(
480
- Effect.andThen(
481
- Effect.fail(
482
- new McpOAuthPageError({
483
- description: "The code could not be checked. Try again.",
484
- }),
477
+ access = yield* environmentAuth
478
+ .consumeMcpApprovalCode(decision.code, decision.access, input.authorization.client.peerLink)
479
+ .pipe(
480
+ Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (cause) =>
481
+ Effect.logError("MCP approval code check failed.", { cause }).pipe(
482
+ Effect.andThen(
483
+ Effect.fail(
484
+ new McpOAuthPageError({
485
+ description: "The code could not be checked. Try again.",
486
+ }),
487
+ ),
488
),
489
),
490
),
488
- ),
489
- );
491
+ );
492
} else {
493
const session = yield* approvingSession(input.request, input.authorization);
494
if (
apps/server/src/auth/PairingGrantStore.test.ts
+4
-1
@@ -15,6 +15,7 @@ import {
15
} from "@t3tools/shared/desktopBootstrapToken";
16
17
import * as ServerConfig from "../config.ts";
18
+import { MCP_APPROVAL_SUBJECT_PREFIX } from "../persistence/AuthPairingLinks.ts";
19
import * as SqlitePersistence from "../persistence/Sqlite.ts";
20
import * as PairingGrantStore from "./PairingGrantStore.ts";
21
@@ -236,7 +237,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("PairingGrantStor
237
);
238
// An app approval code sends no update, issued or spent; the next belongs to a plain code.
239
const approval = yield* grants.issueOneTimeToken({ mcpApproval: "auto" });
239
- yield* grants.consume(approval.credential, { mcpApproval: "auto" });
240
+ yield* grants.consume(approval.credential, {
241
+ allowedSubject: `${MCP_APPROVAL_SUBJECT_PREFIX}auto`,
242
+ });
243
for (const input of [{}, { label: "Synthetic phone" }]) {
244
const issued = yield* grants.issueOneTimeToken(input);
245
const change = yield* Queue.take(changes);
apps/server/src/auth/PairingGrantStore.ts
+4
-9
@@ -301,8 +301,7 @@ export class PairingGrantStore extends Context.Service<
301
readonly requestedScopes?: ReadonlyArray<AuthEnvironmentScope>;
302
/** All scopes must be granted; requestedScopes only requires an overlap for OAuth. */
303
readonly requiredScopes?: ReadonlyArray<AuthEnvironmentScope>;
304
- /** Also spends a code issued for an agent sign-in at this level; others refuse them. */
305
- readonly mcpApproval?: AuthMcpClientAccess;
304
+ readonly allowedSubject?: string;
305
},
306
) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;
307
}
@@ -509,8 +508,8 @@ const make = Effect.gen(function* () {
508
}),
509
),
510
);
512
- // Approval codes stay out of the pairing links and QR codes that clients show.
513
- if (!mcpApproval) {
511
+ // Purpose-bound codes stay out of the pairing links and QR codes that clients show.
512
+ if (!subject.startsWith(AuthPairingLinks.MCP_APPROVAL_SUBJECT_PREFIX)) {
513
yield* emitUpsert({
514
id,
515
scopes: input?.scopes ?? AuthStandardClientScopes,
@@ -652,11 +651,7 @@ const make = Effect.gen(function* () {
651
? { requestedScopes: input.requestedScopes }
652
: {}),
653
...(input?.requiredScopes !== undefined ? { requiredScopes: input.requiredScopes } : {}),
655
- ...(input?.mcpApproval
656
- ? {
657
- mcpApprovalSubject: `${AuthPairingLinks.MCP_APPROVAL_SUBJECT_PREFIX}${input.mcpApproval}`,
658
- }
659
- : {}),
654
+ ...(input?.allowedSubject ? { allowedSubject: input.allowedSubject } : {}),
655
consumedAt: now,
656
now,
657
})
apps/server/src/environment/ServerEnvironment.ts
+1
@@ -294,6 +294,7 @@ export const make = Effect.gen(function* () {
294
mcpModeLimitHeader: true,
295
linkFence: true,
296
mcpApprovalCodes: true,
297
+ peerLinkPairingCodes: true,
298
mcpHostedApproval: true,
299
shellThreadFamilies: true,
300
shellOlderSettled: true,
apps/server/src/peer/PeerLinks.test.ts
+4
-1
@@ -173,7 +173,10 @@ it.effect("links with a pairing code, and the peer holds its agents to the limit
173
expect(refused.reason).toBe("pairing_rejected");
174
expect(yield* linkedSessions(b)).toEqual([]);
175
176
- const pairing = yield* b.auth.issuePairingCredential();
176
+ const pairing = yield* b.auth.issuePairingCredential({
177
+ access: "auto",
178
+ purpose: "peer-link",
179
+ });
180
const linked = yield* a.links.link({
181
url: b.url,
182
pairingCode: pairing.credential,
apps/server/src/persistence/AuthPairingLinks.ts
+7
-6
@@ -17,10 +17,11 @@ import {
17
} from "./Errors.ts";
18
19
/**
20
- * Subjects of codes that approve one agent sign-in at a set level, as `mcp-approval:<level>`.
21
- * Only that sign-in may spend one, so every other use of a pairing code refuses them.
20
+ * These subjects are reserved for one kind and level of MCP authorization.
21
+ * Keep peer-link subjects under the same prefix so older servers refuse them too.
22
*/
23
export const MCP_APPROVAL_SUBJECT_PREFIX = "mcp-approval:";
24
+export const PEER_LINK_PAIRING_SUBJECT_PREFIX = `${MCP_APPROVAL_SUBJECT_PREFIX}peer-link:`;
25
26
const SqliteFlag = Schema.Literals([0, 1]);
27
@@ -62,8 +63,8 @@ export const ConsumeAuthPairingLinkInput = Schema.Struct({
63
proofKeyThumbprint: Schema.NullOr(Schema.String),
64
requestedScopes: Schema.optionalKey(AuthEnvironmentScopes),
65
requiredScopes: Schema.optionalKey(AuthEnvironmentScopes),
65
- /** Also spends a code with exactly this `mcp-approval:` subject. Others are always refused. */
66
- mcpApprovalSubject: Schema.optionalKey(Schema.String),
66
+ /** Allow a purpose-bound code only when its subject matches the request. */
67
+ allowedSubject: Schema.optionalKey(Schema.String),
68
consumedAt: Schema.DateTimeUtcFromString,
69
now: Schema.DateTimeUtcFromString,
70
});
@@ -227,7 +228,7 @@ export const make = Effect.gen(function* () {
228
proofKeyThumbprint,
229
requestedScopes,
230
requiredScopes,
230
- mcpApprovalSubject,
231
+ allowedSubject,
232
consumedAt,
233
now,
234
}) =>
@@ -240,7 +241,7 @@ export const make = Effect.gen(function* () {
241
AND expires_at > ${now}
242
AND (
243
subject NOT LIKE ${`${MCP_APPROVAL_SUBJECT_PREFIX}%`}
243
- OR subject = ${mcpApprovalSubject ?? null}
244
+ OR subject = ${allowedSubject ?? null}
245
)
246
AND (
247
proof_key_thumbprint IS NULL
packages/client-runtime/src/state/peerPairingCode.ts
+22
-2
@@ -8,7 +8,6 @@ import {
8
type AuthCreatePairingCredentialInput,
9
type AuthMcpClientAccess,
10
type AuthPairingCredentialResult,
11
- mcpClientScopes,
11
} from "@t3tools/contracts";
12
import * as Schema from "effect/Schema";
13
import * as Effect from "effect/Effect";
@@ -87,6 +86,15 @@ const mintOnEnvironment = Effect.fnUntraced(function* (payload: AuthCreatePairin
86
cause: "The environment is not connected.",
87
});
88
}
89
+ if (
90
+ payload.purpose === "peer-link" &&
91
+ prepared.value.descriptor?.capabilities.peerLinkPairingCodes !== true
92
+ ) {
93
+ return yield* new PeerPairingCodeError({
94
+ reason: "unavailable",
95
+ cause: "The environment does not support peer-link pairing codes.",
96
+ });
97
+ }
98
return yield* mintPairingCredential(prepared.value, payload);
99
});
100
@@ -100,7 +108,19 @@ export function createPeerPairingCodeCommand<R, E>(
108
return createEnvironmentCommand(runtime, {
109
label: "environment-data:peer-pairing-code:mint",
110
execute: (access: AuthMcpClientAccess) =>
103
- mintOnEnvironment({ label: PEER_PAIRING_CODE_LABEL, scopes: mcpClientScopes(access) }).pipe(
111
+ mintOnEnvironment({
112
+ label: PEER_PAIRING_CODE_LABEL,
113
+ access,
114
+ purpose: "peer-link",
115
+ }).pipe(
116
+ Effect.filterOrFail(
117
+ (minted) => minted.purpose === "peer-link" && minted.access === access,
118
+ () =>
119
+ new PeerPairingCodeError({
120
+ reason: "unavailable",
121
+ cause: "The environment did not issue a peer-link code.",
122
+ }),
123
+ ),
124
Effect.map((minted) => minted.credential),
125
),
126
});
packages/contracts/src/auth.ts
+16
-4
@@ -316,6 +316,7 @@ export const AuthPairingCredentialResult = Schema.Struct({
316
credential: TrimmedNonEmptyString,
317
label: Schema.optionalKey(TrimmedNonEmptyString),
318
expiresAt: Schema.DateTimeUtc,
319
+ purpose: Schema.optionalKey(Schema.Literal("peer-link")),
320
/** Set when the code approves one agent sign-in at this level. Older servers omit it. */
321
access: Schema.optionalKey(AuthMcpClientAccess),
322
});
@@ -498,12 +499,23 @@ export const AuthRevokeConnectDeviceResult = Schema.Struct({
499
});
500
export type AuthRevokeConnectDeviceResult = typeof AuthRevokeConnectDeviceResult.Type;
501
501
-export const AuthCreatePairingCredentialInput = Schema.Struct({
502
+const pairingCredentialFields = {
503
label: Schema.optionalKey(TrimmedNonEmptyString),
504
scopes: Schema.optionalKey(AuthGrantScopes),
504
- /** Binds the code to one agent sign-in at this level. The server derives the scopes from it. */
505
- access: Schema.optionalKey(AuthMcpClientAccess),
506
-});
505
+};
506
+
507
+export const AuthCreatePairingCredentialInput = Schema.Union([
508
+ Schema.Struct({
509
+ ...pairingCredentialFields,
510
+ access: Schema.optionalKey(AuthMcpClientAccess),
511
+ purpose: Schema.optionalKey(Schema.Undefined),
512
+ }),
513
+ Schema.Struct({
514
+ ...pairingCredentialFields,
515
+ access: AuthMcpClientAccess,
516
+ purpose: Schema.Literal("peer-link"),
517
+ }),
518
+]);
519
export type AuthCreatePairingCredentialInput = typeof AuthCreatePairingCredentialInput.Type;
520
521
export const AuthSessionState = Schema.Struct({
packages/contracts/src/environment.ts
+1
@@ -185,6 +185,7 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
185
linkFence: Schema.optionalKey(Schema.Boolean),
186
/** Mints pairing codes that approve one agent sign-in at a set level (`AUTO-…`). */
187
mcpApprovalCodes: Schema.optionalKey(Schema.Boolean),
188
+ peerLinkPairingCodes: Schema.optionalKey(Schema.Boolean),
189
/** Agent sign-ins on its T3 Connect address are approved on the hosted app, without a code. */
190
mcpHostedApproval: Schema.optionalKey(Schema.Boolean),
191
/** Server answers server.prepareTriage. */