Skip to content

Commit 965ddc1

Browse files
t3dotggclaude
andauthored
feat(web,server): use T3 Code in another app (MCP) (#33196)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent dc3fdc6 commit 965ddc1

49 files changed

Lines changed: 2201 additions & 226 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

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

Lines changed: 47 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import {
22
AuthAccessTokenType,
33
AuthAccessWriteScope,
4+
AuthMcpClientAccess,
45
AuthOrchestrationOperateScope,
56
AuthStandardClientScopes,
67
type AuthAccessTokenResult,
@@ -9,7 +10,6 @@ import {
910
type AuthClientSession,
1011
type AuthCreatePairingCredentialInput,
1112
type AuthEnvironmentScope,
12-
type AuthMcpClientAccess,
1313
type AuthPairingLink,
1414
type AuthPairingCredentialResult,
1515
type AuthSessionId,
@@ -48,6 +48,7 @@ import { DESKTOP_RENDERER_ORIGINS } from "../httpCors.ts";
4848
import * as SqlitePersistence from "../persistence/Sqlite.ts";
4949
import * as ManagedLimits from "../policy/managedLimits.ts";
5050
import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
51+
import { MCP_APPROVAL_SUBJECT_PREFIX } from "../persistence/AuthPairingLinks.ts";
5152
import { requestUrl } from "../requestUrl.ts";
5253

5354
const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
@@ -488,6 +489,7 @@ export class EnvironmentAuth extends Context.Service<
488489
readonly subject?: string;
489490
readonly proofKeyThumbprint?: string;
490491
readonly purpose?: "startup";
492+
readonly mcpApproval?: AuthMcpClientAccess;
491493
}) => Effect.Effect<
492494
IssuedPairingLink,
493495
ServerAuthInternalError | ManagedLimits.ManagedPolicyRefusedError
@@ -559,11 +561,17 @@ export class EnvironmentAuth extends Context.Service<
559561
},
560562
ServerAuthInternalError
561563
>;
562-
/** Spends a code covering all granted scopes. Rejects desktop grants and leaves refused proof-bound codes unspent. */
564+
/**
565+
* Spends a code covering all granted scopes and returns the level it approves. A level-bound
566+
* code must name `access`. Rejects desktop grants and leaves refused codes unspent.
567+
*/
563568
readonly consumeMcpApprovalCode: (
564569
code: string,
565570
access: AuthMcpClientAccess,
566-
) => Effect.Effect<void, ServerAuthMcpApprovalCodeError | ServerAuthInternalError>;
571+
) => Effect.Effect<
572+
AuthMcpClientAccess,
573+
ServerAuthMcpApprovalCodeError | ServerAuthInternalError
574+
>;
567575
readonly authenticateBrowserSession: (
568576
request: HttpServerRequest.HttpServerRequest,
569577
) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
@@ -918,6 +926,8 @@ export const make = Effect.gen(function* () {
918926
readonly proofKeyThumbprint?: string;
919927
readonly requestedScopes?: ReadonlyArray<AuthEnvironmentScope>;
920928
readonly requiredScopes?: ReadonlyArray<AuthEnvironmentScope>;
929+
/** Only an agent sign-in opts in to spending a code issued for it. */
930+
readonly mcpApproval?: AuthMcpClientAccess;
921931
},
922932
): Effect.Effect<
923933
ResolvedBootstrapGrant,
@@ -1032,6 +1042,7 @@ export const make = Effect.gen(function* () {
10321042
...(input?.label ? { label: input.label } : {}),
10331043
...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
10341044
...(input?.purpose ? { purpose: input.purpose } : {}),
1045+
...(input?.mcpApproval ? { mcpApproval: input.mcpApproval } : {}),
10351046
});
10361047
return {
10371048
id: issued.id,
@@ -1066,7 +1077,11 @@ export const make = Effect.gen(function* () {
10661077
INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
10671078
];
10681079
return pairingLinks
1069-
.filter((pairingLink) => !excludedSubjects.includes(pairingLink.subject))
1080+
.filter(
1081+
(pairingLink) =>
1082+
!excludedSubjects.includes(pairingLink.subject) &&
1083+
!pairingLink.subject.startsWith(MCP_APPROVAL_SUBJECT_PREFIX),
1084+
)
10701085
.map((link) => ({ ...link, ...authScopeResponse(link.scopes) }))
10711086
.toSorted(
10721087
(left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds,
@@ -1132,11 +1147,17 @@ export const make = Effect.gen(function* () {
11321147

11331148
const issuePairingCredential: EnvironmentAuth["Service"]["issuePairingCredential"] = (input) =>
11341149
createPairingLink({
1135-
scopes: input?.scopes ?? AuthStandardClientScopes,
1150+
scopes: input?.access
1151+
? mcpClientScopes(input.access)
1152+
: (input?.scopes ?? AuthStandardClientScopes),
11361153
subject: "one-time-token",
11371154
...(input?.label ? { label: input.label } : {}),
1155+
...(input?.access ? { mcpApproval: input.access } : {}),
11381156
}).pipe(
1139-
Effect.map(toPairingCredential),
1157+
Effect.map((issued) => ({
1158+
...toPairingCredential(issued),
1159+
...(input?.access ? { access: input.access } : {}),
1160+
})),
11401161
Effect.withSpan("EnvironmentAuth.issuePairingCredential"),
11411162
);
11421163

@@ -1361,7 +1382,10 @@ export const make = Effect.gen(function* () {
13611382
code,
13621383
access,
13631384
) =>
1364-
resolveBootstrapGrant(code.trim(), { requiredScopes: mcpClientScopes(access) }).pipe(
1385+
resolveBootstrapGrant(code.trim(), {
1386+
requiredScopes: mcpClientScopes(access),
1387+
mcpApproval: access,
1388+
}).pipe(
13651389
Effect.catchTags({
13661390
ServerAuthInvalidCredentialError: () =>
13671391
Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "unknown_or_used" })),
@@ -1371,7 +1395,7 @@ export const make = Effect.gen(function* () {
13711395
Effect.flatMap((grant) =>
13721396
grant.method !== "one-time-token" && grant.method !== "reusable-dev-token"
13731397
? Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "not_a_pairing_code" }))
1374-
: Effect.void,
1398+
: Effect.succeed(mcpApprovalLevel(grant.subject) ?? access),
13751399
),
13761400
Effect.withSpan("EnvironmentAuth.consumeMcpApprovalCode"),
13771401
);
@@ -1410,6 +1434,16 @@ export const make = Effect.gen(function* () {
14101434
});
14111435
});
14121436

1437+
const isMcpClientAccess = Schema.is(AuthMcpClientAccess);
1438+
1439+
/** The level an approval code's subject names, or undefined for any other code. */
1440+
const mcpApprovalLevel = (subject: string): AuthMcpClientAccess | undefined => {
1441+
const level = subject.startsWith(MCP_APPROVAL_SUBJECT_PREFIX)
1442+
? subject.slice(MCP_APPROVAL_SUBJECT_PREFIX.length)
1443+
: undefined;
1444+
return isMcpClientAccess(level) ? level : undefined;
1445+
};
1446+
14131447
/** Subjects of sessions and links a pairing link created, keyed by how the client paired. */
14141448
const LINK_PAIRED_SUBJECTS = { link: "one-time-token", connect: "cloud-connect" } as const;
14151449

@@ -1440,8 +1474,11 @@ const revokePairedClientsThePolicyDisallows = Effect.fn(
14401474
session.client.ipAddress !== undefined &&
14411475
!isLocalLoopbackHost(session.client.ipAddress)),
14421476
);
1443-
const links = (yield* stores.pairingLinks.listActive()).filter((link) =>
1444-
disallowed.has(link.subject),
1477+
const links = (yield* stores.pairingLinks.listActive()).filter(
1478+
(link) =>
1479+
disallowed.has(link.subject) ||
1480+
// Approval codes let an agent elsewhere sign in, as plain codes do.
1481+
(!remoteAllowed && link.subject.startsWith(MCP_APPROVAL_SUBJECT_PREFIX)),
14451482
);
14461483
yield* Effect.forEach(sessions, (session) => stores.sessions.revoke(session.sessionId), {
14471484
discard: true,

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))(
8585
const startupPhone = yield* startup("192.168.1.20");
8686
const startupBrowser = yield* startup("127.0.0.1");
8787
yield* environmentAuth.createPairingLink({ subject: "one-time-token" });
88+
yield* environmentAuth.issuePairingCredential({ access: "auto" });
8889

8990
yield* EnvironmentAuth.make.pipe(
9091
Effect.provide(
@@ -135,6 +136,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))(
135136
subject: "one-time-token",
136137
label: "CI phone",
137138
});
139+
// An app approval code is never listed.
140+
yield* environmentAuth.issuePairingCredential({ access: "auto" });
138141
const listedBeforeRevoke = yield* environmentAuth.listPairingLinks();
139142
const revoked = yield* environmentAuth.revokePairingLink(created.id);
140143
const listedAfterRevoke = yield* environmentAuth.listPairingLinks();

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

Lines changed: 86 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
AuthStandardClientScopes,
66
type AuthCreatePairingCredentialInput,
77
EnvironmentHttpApi,
8+
MCP_PEER_LINK_SOFTWARE_ID,
89
mcpClientScopes,
910
} from "@t3tools/contracts";
1011
import { expect, it } from "@effect/vitest";
@@ -53,7 +54,7 @@ const makeLayerRoutes = (capture: (auth: EnvironmentAuth.EnvironmentAuth["Servic
5354
Layer.provide(
5455
McpOAuthHttp.layer.pipe(
5556
Layer.provide(McpOAuth.layer),
56-
Layer.provide(ServerSettings.layerTest()),
57+
Layer.provide(ServerSettings.layerTest({ linkedEnvironmentsEnabled: true })),
5758
),
5859
),
5960
Layer.provide(AuthHttp.layerAuthenticatedAuth),
@@ -509,6 +510,90 @@ it.live("a code minted with an access level's scopes approves that access", () =
509510
),
510511
);
511512

513+
it.live("an app approval code approves only an app sign-in, at its own level", () =>
514+
withRoutes((handler, auth) =>
515+
Effect.gen(function* () {
516+
const clientId = yield* registeredClientId(handler);
517+
const params = authorizeParams(clientId);
518+
const issued = yield* auth.issuePairingCredential({ access: "approval-required" });
519+
expect(issued.access).toBe("approval-required");
520+
const code = issued.credential;
521+
expect(code).toMatch(/^SUPERVISED-[2-9A-HJ-NP-Z]{12}$/);
522+
523+
// Signing in a browser, a token exchange and linking all refuse it and leave it unspent.
524+
const browser = yield* handler(
525+
at("/api/auth/browser-session", {
526+
method: "POST",
527+
headers: { "content-type": "application/json" },
528+
body: encodeJson({ credential: code }),
529+
}),
530+
);
531+
expect(browser.status).toBe(401);
532+
const exchanged = yield* auth
533+
.exchangeBootstrapCredentialForAccessToken(code, undefined, { deviceType: "bot" })
534+
.pipe(Effect.flip);
535+
expect(exchanged._tag).toBe("ServerAuthInvalidCredentialError");
536+
const peer = yield* handler(
537+
at("/oauth/mcp/register", {
538+
method: "POST",
539+
headers: { "content-type": "application/json" },
540+
body: encodeJson({
541+
client_name: "Studio",
542+
software_id: MCP_PEER_LINK_SOFTWARE_ID,
543+
redirect_uris: [REDIRECT],
544+
}),
545+
}),
546+
).pipe(Effect.flatMap(json<{ client_id: string }>));
547+
const linked = yield* decide(handler, authorizeParams(peer.client_id), {
548+
_tag: "pairing-code",
549+
access: "approval-required",
550+
code,
551+
});
552+
expect(linked.status).toBe(400);
553+
554+
// Supervised and Auto share scopes, so only the code's own level may spend it.
555+
const otherLevel = yield* decide(handler, params, {
556+
_tag: "pairing-code",
557+
access: "auto",
558+
code,
559+
});
560+
expect(otherLevel.status).toBe(400);
561+
562+
const approved = yield* decide(handler, params, {
563+
_tag: "pairing-code",
564+
access: "approval-required",
565+
code: code.toLowerCase(),
566+
});
567+
expect(approved.status).toBe(200);
568+
const token = yield* handler(
569+
at(
570+
"/oauth/mcp/token",
571+
form({
572+
grant_type: "authorization_code",
573+
code: new URL(approved.redirectTo!).searchParams.get("code")!,
574+
redirect_uri: params.redirect_uri,
575+
client_id: clientId,
576+
code_verifier: verifier,
577+
}),
578+
),
579+
).pipe(Effect.flatMap(json<{ access_token: string }>));
580+
const signedIn = yield* auth.authenticateMcpClient(
581+
HttpServerRequest.fromWeb(
582+
at("/mcp", { headers: { authorization: `Bearer ${token.access_token}` } }),
583+
),
584+
);
585+
expect(signedIn.access).toBe("approval-required");
586+
expect(
587+
(yield* decide(handler, params, {
588+
_tag: "pairing-code",
589+
access: "approval-required",
590+
code,
591+
})).status,
592+
).toBe(400);
593+
}),
594+
),
595+
);
596+
512597
it.live("one-click approves only access the browser session holds the scopes for", () =>
513598
withRoutes((handler, auth) =>
514599
Effect.gen(function* () {

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

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
AuthOrchestrationReadScope,
1616
MCP_PEER_LINK_SOFTWARE_ID,
1717
mcpClientScopes,
18+
parseMcpApprovalCode,
1819
type RuntimeMode,
1920
} from "@t3tools/contracts";
2021
import { DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth";
@@ -447,8 +448,15 @@ const make = Effect.gen(function* () {
447448

448449
const approve: McpOAuth["Service"]["approve"] = Effect.fn("McpOAuth.approve")(function* (input) {
449450
const { decision } = input;
451+
let access = decision.access;
450452
if (decision._tag === "pairing-code") {
451-
yield* environmentAuth.consumeMcpApprovalCode(decision.code, decision.access).pipe(
453+
// An approval code is for one app's sign-in, never for linking another environment.
454+
if (input.authorization.client.peerLink && parseMcpApprovalCode(decision.code)) {
455+
return yield* new McpOAuthPageError({
456+
description: "Linking needs a plain pairing code, not an app approval code.",
457+
});
458+
}
459+
access = yield* environmentAuth.consumeMcpApprovalCode(decision.code, decision.access).pipe(
452460
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (cause) =>
453461
Effect.logError("MCP approval code check failed.", { cause }).pipe(
454462
Effect.andThen(
@@ -473,10 +481,10 @@ const make = Effect.gen(function* () {
473481
});
474482
}
475483
}
476-
const code = yield* mintCode(input.authorization, decision.access);
484+
const code = yield* mintCode(input.authorization, access);
477485
yield* Effect.logInfo("Approved an MCP client sign-in.", {
478486
client: input.authorization.client.name,
479-
access: decision.access,
487+
access,
480488
method: decision._tag,
481489
});
482490
return redirectWith(input.authorization.redirectUri, {

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,9 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("PairingGrantStor
218218
Stream.runForEach((change) => Queue.offer(changes, change)),
219219
Effect.forkScoped({ startImmediately: true }),
220220
);
221+
// An app approval code sends no update, issued or spent; the next belongs to a plain code.
222+
const approval = yield* grants.issueOneTimeToken({ mcpApproval: "auto" });
223+
yield* grants.consume(approval.credential, { mcpApproval: "auto" });
221224
for (const input of [{}, { label: "Synthetic phone" }]) {
222225
const issued = yield* grants.issueOneTimeToken(input);
223226
const change = yield* Queue.take(changes);

0 commit comments

Comments
 (0)