Skip to content

Commit 16a6474

Browse files
committed
feat(auth): MCP approval codes set the sign-in lifetime and remote agents get a copyable link
MCP sign-ins expired after a fixed 30 days with no refresh tokens, and every approval needed a fresh one-time code. After approval, a loopback callback sent the browser to localhost even when the agent (mcp-remote on another machine) listened somewhere else, leaving a dead page. `t3 auth pairing create` now takes `--session-ttl` and `--reusable`. Either flag makes an MCP-only code, stored in the pairing link's subject so no migration is needed; device pairing refuses it. The connect-agent page now shows Continue on this computer and Copy link for loopback callbacks instead of redirecting.
1 parent e38b376 commit 16a6474

10 files changed

Lines changed: 288 additions & 15 deletions

File tree

‎apps/server/src/auth/EnvironmentAuth.ts‎

Lines changed: 36 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
3939
import * as ServerConfig from "../config.ts";
4040
import * as EnvironmentAuthPolicy from "./EnvironmentAuthPolicy.ts";
4141
import * as PairingGrantStore from "./PairingGrantStore.ts";
42+
import { decodeMcpApprovalSubject } from "./mcpApprovalCode.ts";
4243
import * as ServerSecretStore from "./ServerSecretStore.ts";
4344
import * as SessionStore from "./SessionStore.ts";
4445
import { REUSABLE_DEV_SESSION_EXPIRES_AT, resolveReusableDevAuth } from "./ReusableDevAuth.ts";
@@ -556,6 +557,7 @@ export class EnvironmentAuth extends Context.Service<
556557
readonly issueMcpClientSession: (input: {
557558
readonly label: string;
558559
readonly access: AuthMcpClientAccess;
560+
readonly ttl?: Duration.Duration;
559561
readonly client: AuthClientMetadata;
560562
}) => Effect.Effect<
561563
{ readonly token: string; readonly expiresAt: DateTime.DateTime },
@@ -565,12 +567,16 @@ export class EnvironmentAuth extends Context.Service<
565567
* Spends a one-time pairing code as approval for an MCP client with the
566568
* given access; the code must hold every scope that access grants.
567569
* Proof-bound codes (T3 Connect) are refused without being spent, and
568-
* desktop bootstrap grants never qualify.
570+
* desktop bootstrap grants never qualify. A reusable MCP approval code is
571+
* checked without being spent, and its session TTL is returned.
569572
*/
570573
readonly consumeMcpApprovalCode: (
571574
code: string,
572575
access: AuthMcpClientAccess,
573-
) => Effect.Effect<void, ServerAuthMcpApprovalCodeError | ServerAuthInternalError>;
576+
) => Effect.Effect<
577+
{ readonly sessionTtl?: Duration.Duration },
578+
ServerAuthMcpApprovalCodeError | ServerAuthInternalError
579+
>;
574580
readonly authenticateBrowserSession: (
575581
request: HttpServerRequest.HttpServerRequest,
576582
) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
@@ -1287,7 +1293,7 @@ export const make = Effect.gen(function* () {
12871293
subject: MCP_CLIENT_SUBJECT,
12881294
method: "bearer-access-token",
12891295
scopes: mcpClientScopes(input.access),
1290-
ttl: MCP_CLIENT_SESSION_TTL,
1296+
ttl: input.ttl ?? MCP_CLIENT_SESSION_TTL,
12911297
...(input.access === "read-only" ? {} : { runtimeModeCeiling: input.access }),
12921298
client: { ...input.client, label: input.label, deviceType: "bot" },
12931299
})
@@ -1313,11 +1319,36 @@ export const make = Effect.gen(function* () {
13131319
);
13141320
};
13151321

1322+
// Fork: MCP approval goes through `useMcpApprovalCode`, which leaves a
1323+
// reusable MCP approval code unspent.
1324+
const resolveMcpApprovalGrant = (
1325+
credential: string,
1326+
): Effect.Effect<
1327+
ResolvedBootstrapGrant,
1328+
ServerAuthInvalidCredentialError | ServerAuthInternalError | ServerAuthScopeNotGrantedError
1329+
> =>
1330+
devAuth?.matches(credential)
1331+
? resolveBootstrapGrant(credential)
1332+
: bootstrapCredentials
1333+
.useMcpApprovalCode(credential)
1334+
.pipe(
1335+
Effect.mapError((cause) =>
1336+
cause._tag === "BootstrapCredentialScopeNotGrantedError"
1337+
? new ServerAuthScopeNotGrantedError({})
1338+
: toBootstrapExchangeError(cause),
1339+
),
1340+
);
1341+
1342+
const mcpApprovalSessionTtl = (subject: string) => {
1343+
const sessionTtl = decodeMcpApprovalSubject(subject)?.sessionTtl;
1344+
return sessionTtl === undefined ? {} : { sessionTtl };
1345+
};
1346+
13161347
const consumeMcpApprovalCode: EnvironmentAuth["Service"]["consumeMcpApprovalCode"] = (
13171348
code,
13181349
access,
13191350
) =>
1320-
resolveBootstrapGrant(code.trim()).pipe(
1351+
resolveMcpApprovalGrant(code.trim()).pipe(
13211352
Effect.catchTags({
13221353
ServerAuthInvalidCredentialError: () =>
13231354
Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "unknown_or_used" })),
@@ -1328,7 +1359,7 @@ export const make = Effect.gen(function* () {
13281359
grant.method !== "one-time-token" && grant.method !== "reusable-dev-token"
13291360
? Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "not_a_pairing_code" }))
13301361
: mcpClientScopes(access).every((scope) => grant.scopes.includes(scope))
1331-
? Effect.void
1362+
? Effect.succeed(mcpApprovalSessionTtl(grant.subject))
13321363
: Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "insufficient_scope" })),
13331364
),
13341365
Effect.withSpan("EnvironmentAuth.consumeMcpApprovalCode"),

‎apps/server/src/auth/McpOAuth.test.ts‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
import { expect, it } from "@effect/vitest";
88
import * as Context from "effect/Context";
99
import * as Crypto from "effect/Crypto";
10+
import * as Duration from "effect/Duration";
1011
import * as Effect from "effect/Effect";
1112
import * as Layer from "effect/Layer";
1213
import * as Etag from "effect/http/Etag";
@@ -22,6 +23,7 @@ import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
2223
import * as Sqlite from "../persistence/Sqlite.ts";
2324
import * as EnvironmentAuth from "./EnvironmentAuth.ts";
2425
import * as McpOAuth from "./McpOAuth.ts";
26+
import { encodeMcpApprovalSubject } from "./mcpApprovalCode.ts";
2527
import * as McpOAuthHttp from "./mcpOAuthHttp.ts";
2628
import * as ServerSecretStore from "./ServerSecretStore.ts";
2729
import * as AuthHttp from "./http.ts";
@@ -307,6 +309,65 @@ it.live("signs in with a pairing code and issues a token only /mcp accepts", ()
307309
),
308310
);
309311

312+
it.live(
313+
"an MCP approval code sets the sign-in lifetime, may be reused, and never pairs a client",
314+
() =>
315+
withRoutes((handler, auth) =>
316+
Effect.gen(function* () {
317+
const clientId = yield* registeredClientId(handler);
318+
const approve = (code: string) =>
319+
decide(handler, authorizeParams(clientId), {
320+
_tag: "pairing-code",
321+
access: "auto-accept-edits",
322+
code,
323+
});
324+
const signInDays = (code: string) =>
325+
Effect.gen(function* () {
326+
const approved = yield* approve(code);
327+
expect(approved.status).toBe(200);
328+
const token = yield* handler(
329+
at(
330+
"/oauth/mcp/token",
331+
form({
332+
grant_type: "authorization_code",
333+
code: new URL(approved.redirectTo!).searchParams.get("code")!,
334+
redirect_uri: authorizeParams(clientId).redirect_uri,
335+
client_id: clientId,
336+
code_verifier: verifier,
337+
resource: `${ORIGIN}/mcp`,
338+
}),
339+
),
340+
).pipe(Effect.flatMap(json<{ expires_in: number }>));
341+
return Math.round(token.expires_in / 86_400);
342+
});
343+
const pairsClient = (code: string) =>
344+
auth
345+
.exchangeBootstrapCredentialForAccessToken(code, undefined, { deviceType: "desktop" })
346+
.pipe(Effect.match({ onFailure: () => false, onSuccess: () => true }));
347+
348+
const reusable = yield* auth.createPairingLink({
349+
ttl: Duration.days(7),
350+
subject: encodeMcpApprovalSubject({ sessionTtl: Duration.days(180), reusable: true }),
351+
});
352+
expect(yield* pairsClient(reusable.credential)).toBe(false);
353+
expect(yield* signInDays(reusable.credential)).toBe(180);
354+
expect(yield* signInDays(reusable.credential)).toBe(180);
355+
expect(yield* auth.revokePairingLink(reusable.id)).toBe(true);
356+
expect((yield* approve(reusable.credential)).status).toBe(400);
357+
358+
const once = yield* auth.createPairingLink({
359+
subject: encodeMcpApprovalSubject({ sessionTtl: Duration.days(90), reusable: false }),
360+
});
361+
expect(yield* pairsClient(once.credential)).toBe(false);
362+
expect(yield* signInDays(once.credential)).toBe(90);
363+
expect((yield* approve(once.credential)).status).toBe(400);
364+
365+
const plain = yield* auth.issuePairingCredential();
366+
expect(yield* signInDays(plain.credential)).toBe(30);
367+
}),
368+
),
369+
);
370+
310371
it.live("signs in a hosted agent with an https callback that asked for a client secret", () =>
311372
withRoutes((handler, auth) =>
312373
Effect.gen(function* () {

‎apps/server/src/auth/McpOAuth.ts‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
1818
import * as Clock from "effect/Clock";
1919
import * as Context from "effect/Context";
2020
import * as Crypto from "effect/Crypto";
21+
import type * as Duration from "effect/Duration";
2122
import * as Effect from "effect/Effect";
2223
import * as Layer from "effect/Layer";
2324
import * as Option from "effect/Option";
@@ -183,6 +184,7 @@ interface PendingCode {
183184
readonly codeChallenge: string;
184185
readonly resource: string;
185186
readonly access: AuthMcpClientAccess;
187+
readonly sessionTtl?: Duration.Duration;
186188
readonly expiresAtMs: number;
187189
}
188190

@@ -383,7 +385,11 @@ const make = Effect.gen(function* () {
383385
Effect.orElseSucceed(() => undefined),
384386
);
385387

386-
const mintCode = (authorization: AuthorizationRequest, access: AuthMcpClientAccess) =>
388+
const mintCode = (
389+
authorization: AuthorizationRequest,
390+
access: AuthMcpClientAccess,
391+
sessionTtl: Duration.Duration | undefined,
392+
) =>
387393
Effect.gen(function* () {
388394
const now = yield* Clock.currentTimeMillis;
389395
const code = Buffer.from(yield* crypto.randomBytes(32).pipe(Effect.orDie)).toString(
@@ -400,6 +406,7 @@ const make = Effect.gen(function* () {
400406
codeChallenge: authorization.codeChallenge,
401407
resource: authorization.resource,
402408
access,
409+
...(sessionTtl === undefined ? {} : { sessionTtl }),
403410
expiresAtMs: now + AUTHORIZATION_CODE_TTL_MS,
404411
});
405412
return next;
@@ -410,8 +417,14 @@ const make = Effect.gen(function* () {
410417
const approve: McpOAuth["Service"]["approve"] = (input) =>
411418
Effect.gen(function* () {
412419
const { decision } = input;
420+
let sessionTtl: Duration.Duration | undefined;
413421
if (decision._tag === "pairing-code") {
414422
yield* environmentAuth.consumeMcpApprovalCode(decision.code, decision.access).pipe(
423+
Effect.tap((approval) =>
424+
Effect.sync(() => {
425+
sessionTtl = approval.sessionTtl;
426+
}),
427+
),
415428
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (cause) =>
416429
Effect.logError("MCP approval code check failed.", { cause }).pipe(
417430
Effect.andThen(
@@ -438,7 +451,7 @@ const make = Effect.gen(function* () {
438451
});
439452
}
440453
}
441-
const code = yield* mintCode(input.authorization, decision.access);
454+
const code = yield* mintCode(input.authorization, decision.access, sessionTtl);
442455
yield* Effect.logInfo("Approved an MCP client sign-in.", {
443456
client: input.authorization.client.name,
444457
access: decision.access,
@@ -500,6 +513,7 @@ const make = Effect.gen(function* () {
500513
.issueMcpClientSession({
501514
label: pending.clientName,
502515
access: pending.access,
516+
...(pending.sessionTtl === undefined ? {} : { ttl: pending.sessionTtl }),
503517
client: deriveAuthClientMetadata({ request }),
504518
})
505519
.pipe(

‎apps/server/src/auth/PairingGrantStore.ts‎

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import * as Stream from "effect/Stream";
2222

2323
import * as ServerConfig from "../config.ts";
2424
import * as AuthPairingLinks from "../persistence/AuthPairingLinks.ts";
25+
import { decodeMcpApprovalSubject } from "./mcpApprovalCode.ts";
2526

2627
export interface BootstrapGrant {
2728
readonly method: ServerAuthBootstrapMethod;
@@ -228,6 +229,13 @@ export class PairingGrantStore extends Context.Service<
228229
readonly requestedScopes?: ReadonlyArray<AuthEnvironmentScope>;
229230
},
230231
) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;
232+
/**
233+
* Like `consume` for an MCP approval, except a reusable MCP approval code
234+
* is only checked, not spent.
235+
*/
236+
readonly useMcpApprovalCode: (
237+
credential: string,
238+
) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;
231239
}
232240
>()("t3/auth/PairingGrantStore") {}
233241

@@ -604,14 +612,56 @@ export const make = Effect.gen(function* () {
604612
},
605613
);
606614

615+
const storedLink = (credential: string) =>
616+
pairingLinks.getByCredential({ credential }).pipe(
617+
Effect.map(Option.getOrUndefined),
618+
Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause })),
619+
);
620+
621+
// Fork: an MCP approval code may be reusable, so it never pairs a client.
622+
const consumeForPairing: PairingGrantStore["Service"]["consume"] = (credential, input) =>
623+
storedLink(credential).pipe(
624+
Effect.flatMap((link) =>
625+
link !== undefined && decodeMcpApprovalSubject(link.subject) !== undefined
626+
? Effect.fail(new UnknownBootstrapCredentialError({}))
627+
: consume(credential, input),
628+
),
629+
);
630+
631+
const useMcpApprovalCode: PairingGrantStore["Service"]["useMcpApprovalCode"] = Effect.fn(
632+
"PairingGrantStore.useMcpApprovalCode",
633+
)(function* (credential) {
634+
const link = yield* storedLink(credential);
635+
if (link === undefined || decodeMcpApprovalSubject(link.subject)?.reusable !== true) {
636+
return yield* consume(credential);
637+
}
638+
const now = yield* DateTime.now;
639+
if (link.revokedAt !== null) return yield* new UnavailableBootstrapCredentialError({});
640+
if (link.consumedAt !== null) return yield* new UnknownBootstrapCredentialError({});
641+
if (DateTime.isGreaterThanOrEqualTo(now, link.expiresAt)) {
642+
return yield* new ExpiredBootstrapCredentialError({});
643+
}
644+
if (link.proofKeyThumbprint !== null) {
645+
return yield* new BootstrapCredentialProofKeyMismatchError({});
646+
}
647+
return {
648+
method: link.method,
649+
scopes: link.scopes,
650+
subject: link.subject,
651+
...(link.label ? { label: link.label } : {}),
652+
expiresAt: link.expiresAt,
653+
} satisfies BootstrapGrant;
654+
});
655+
607656
return PairingGrantStore.of({
608657
issueOneTimeToken,
609658
listActive,
610659
get streamChanges() {
611660
return Stream.fromPubSub(changesPubSub);
612661
},
613662
revoke,
614-
consume,
663+
consume: consumeForPairing,
664+
useMcpApprovalCode,
615665
});
616666
});
617667

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import * as Duration from "effect/Duration";
2+
3+
/**
4+
* Fork patch: a pairing code made only for MCP approvals keeps its options in
5+
* the pairing link's `subject`, because a fork migration would collide with
6+
* upstream's numbered ones.
7+
*/
8+
const SUBJECT_PREFIX = "mcp-approval";
9+
10+
export interface McpApprovalCodeOptions {
11+
/** How long sign-ins approved with the code last, instead of the MCP default. */
12+
readonly sessionTtl?: Duration.Duration;
13+
/** Approving does not spend the code; it lasts until it expires or is revoked. */
14+
readonly reusable: boolean;
15+
}
16+
17+
export const encodeMcpApprovalSubject = (options: McpApprovalCodeOptions): string =>
18+
[
19+
SUBJECT_PREFIX,
20+
...(options.sessionTtl === undefined ? [] : [`ttl=${Duration.toMillis(options.sessionTtl)}`]),
21+
...(options.reusable ? ["reusable"] : []),
22+
].join(";");
23+
24+
export const decodeMcpApprovalSubject = (subject: string): McpApprovalCodeOptions | undefined => {
25+
const [prefix, ...parts] = subject.split(";");
26+
if (prefix !== SUBJECT_PREFIX) return undefined;
27+
const ttlMillis = Number(parts.find((part) => part.startsWith("ttl="))?.slice("ttl=".length));
28+
return {
29+
...(Number.isSafeInteger(ttlMillis) && ttlMillis > 0
30+
? { sessionTtl: Duration.millis(ttlMillis) }
31+
: {}),
32+
reusable: parts.includes("reusable"),
33+
};
34+
};

0 commit comments

Comments
 (0)