@devries-cameron20 / t3code-1 / commits / dd0737d3e2
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

feat: approve agent sign-ins with T3 Connect instead of a code (#33600)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 9, 2026 at 15:16 UTC dd0737d3e2029da533f1c430a10869a060396b63
16 files changed +774 -58
apps/server/src/auth/McpOAuth.test.ts
+40 -2
@@ -4,6 +4,7 @@ import {
4 AuthMcpClientAccess,
5 AuthStandardClientScopes,
6 type AuthCreatePairingCredentialInput,
7 + type EnvironmentCloudLinkStateResult,
8 EnvironmentHttpApi,
9 MCP_PEER_LINK_SOFTWARE_ID,
10 mcpClientScopes,
@@ -21,6 +22,7 @@ import * as HttpApi from "effect/http-api/HttpApi";
22 import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
23 import * as Schema from "effect/Schema";
24
25 +import * as CloudLink from "../cloud/CloudLink.ts";
26 import * as ServerConfig from "../config.ts";
27 import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
28 import * as ServerSettings from "../serverSettings.ts";
@@ -44,7 +46,17 @@ const layerEnvironmentAuth = EnvironmentAuth.layer.pipe(
46 Layer.provideMerge(ServerEnvironment.layerIdentity),
47 Layer.provide(layerConfig),
48 );
47 -const makeLayerRoutes = (capture: (auth: EnvironmentAuth.EnvironmentAuth["Service"]) => void) =>
49 +const notLinked: EnvironmentCloudLinkStateResult = {
50 + linked: false,
51 + cloudUserId: null,
52 + relayUrl: null,
53 + relayIssuer: null,
54 + publishAgentActivity: false,
55 +};
56 +const makeLayerRoutes = (
57 + capture: (auth: EnvironmentAuth.EnvironmentAuth["Service"]) => void,
58 + linkState: EnvironmentCloudLinkStateResult,
59 +) =>
60 Layer.mergeAll(
61 Layer.effectDiscard(
62 EnvironmentAuth.EnvironmentAuth.pipe(Effect.tap((auth) => Effect.sync(() => capture(auth)))),
@@ -55,6 +67,9 @@ const makeLayerRoutes = (capture: (auth: EnvironmentAuth.EnvironmentAuth["Servic
67 McpOAuthHttp.layer.pipe(
68 Layer.provide(McpOAuth.layer),
69 Layer.provide(ServerSettings.layerTest({ linkedEnvironmentsEnabled: true })),
70 + Layer.provide(
71 + Layer.mock(CloudLink.CloudLink)({ linkState: () => Effect.succeed(linkState) }),
72 + ),
73 ),
74 ),
75 Layer.provide(AuthHttp.layerAuthenticatedAuth),
@@ -92,6 +107,7 @@ type Handler = (request: Request) => Effect.Effect<Response>;
107
108 const withRoutes = <A, E>(
109 use: (handler: Handler, auth: EnvironmentAuth.EnvironmentAuth["Service"]) => Effect.Effect<A, E>,
110 + linkState = notLinked,
111 ) =>
112 Effect.gen(function* () {
113 const random = yield* SecureRandom.SecureRandom;
@@ -99,7 +115,7 @@ const withRoutes = <A, E>(
115 let routerAuth: EnvironmentAuth.EnvironmentAuth["Service"] | undefined;
116 const layerRoutes = makeLayerRoutes((auth) => {
117 routerAuth = auth;
102 - });
118 + }, linkState);
119 return yield* Effect.acquireUseRelease(
120 Effect.sync(() => HttpRouter.toWebHandler(layerRoutes, { disableLogger: true })),
121 (web) =>
@@ -594,6 +610,28 @@ it.live("an app approval code approves only an app sign-in, at its own level", (
610 ),
611 );
612
613 +it.live("offers T3 Connect approval only on the linked tunnel's own host", () =>
614 + Effect.gen(function* () {
615 + const connectSignIn = (tunnelHostname: string) =>
616 + withRoutes(
617 + (handler) =>
618 + Effect.gen(function* () {
619 + const params = authorizeParams(yield* registeredClientId(handler));
620 + const details = yield* handler(postJson("/oauth/mcp/approval", params)).pipe(
621 + Effect.flatMap(json<{ connectSignIn?: unknown }>),
622 + );
623 + return details.connectSignIn;
624 + }),
625 + { ...notLinked, linked: true, cloudUserId: "user_1", tunnelHostname },
626 + );
627 + expect(yield* connectSignIn("box.example.ts.net")).toEqual({
628 + environmentId: expect.any(String),
629 + hostedAppUrl: "https://app.t3.codes",
630 + });
631 + expect(yield* connectSignIn("other.t3coderelay.com")).toBeUndefined();
632 + }),
633 +);
634 +
635 it.live("one-click approves only access the browser session holds the scopes for", () =>
636 withRoutes((handler, auth) =>
637 Effect.gen(function* () {
apps/server/src/auth/mcpOAuthHttp.ts
+28
@@ -6,12 +6,18 @@ import {
6 mcpClientScopes,
7 } from "@t3tools/contracts";
8 import * as Effect from "effect/Effect";
9 +import * as Option from "effect/Option";
10 import * as Result from "effect/Result";
11 import * as Schema from "effect/Schema";
12 import { HttpServerRequest, HttpServerResponse } from "effect/http";
13 import * as HttpEffect from "effect/http/HttpEffect";
14 import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
15
16 +import { DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth";
17 +
18 +import * as CloudLink from "../cloud/CloudLink.ts";
19 +import { hostedAppUrlConfig } from "../cloud/publicConfig.ts";
20 +import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
21 import * as McpOAuth from "./McpOAuth.ts";
22 import { renderErrorPage } from "./mcpOAuthHtml.ts";
23
@@ -62,6 +68,23 @@ export const layer = HttpApiBuilder.group(
68 "mcpOAuth",
69 Effect.fnUntraced(function* (handlers) {
70 const oauth = yield* McpOAuth.McpOAuth;
71 + const cloudLink = yield* CloudLink.CloudLink;
72 + const serverEnvironment = yield* ServerEnvironment.ServerEnvironmentIdentity;
73 + const hostedAppUrl = yield* hostedAppUrlConfig.pipe(
74 + Effect.orElseSucceed(() => DEFAULT_HOSTED_APP_URL),
75 + );
76 + // The hosted app returns a code only to the tunnel address, so other origins keep the code field.
77 + const connectSignIn = (issuer: string) =>
78 + cloudLink.linkState().pipe(
79 + Effect.flatMap((state) =>
80 + state.linked && !state.linkRevoked && state.tunnelHostname === new URL(issuer).hostname
81 + ? serverEnvironment.getEnvironmentId.pipe(
82 + Effect.map((environmentId) => Option.some({ environmentId, hostedAppUrl })),
83 + )
84 + : Effect.succeedNone,
85 + ),
86 + Effect.orElseSucceed(Option.none),
87 + );
88 const protectedResource = () =>
89 requestUrls.pipe(Effect.map(McpOAuth.protectedResourceMetadata));
90
@@ -116,6 +139,10 @@ export const layer = HttpApiBuilder.group(
139 if ("redirectTo" in resolved) return resolved;
140 const urls = yield* requestUrls;
141 const session = yield* oauth.approvingBrowserSession(request, resolved);
142 + // A link needs a plain pairing code, which T3 Connect does not mint.
143 + const connect = resolved.client.peerLink
144 + ? Option.none()
145 + : yield* connectSignIn(urls.issuer);
146 yield* noStore;
147 return {
148 clientName: resolved.client.name,
@@ -124,6 +151,7 @@ export const layer = HttpApiBuilder.group(
151 ...(oauth.runtimeModeCeiling === undefined
152 ? {}
153 : { runtimeModeCeiling: oauth.runtimeModeCeiling }),
154 + ...(Option.isSome(connect) ? { connectSignIn: connect.value } : {}),
155 ...(session === undefined
156 ? {}
157 : {
apps/server/src/peer/PeerLinks.testkit.ts
+18 -1
@@ -23,6 +23,7 @@ import * as McpOAuth from "../auth/McpOAuth.ts";
23 import * as McpOAuthHttp from "../auth/mcpOAuthHttp.ts";
24 import type * as SqlClient from "effect/sql/SqlClient";
25 import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
26 +import * as CloudLink from "../cloud/CloudLink.ts";
27 import * as ServerConfig from "../config.ts";
28 import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
29 import * as ServerHttp from "../http.ts";
@@ -101,7 +102,23 @@ export const servePeer = <E, R>(
102 );
103 const layerRoutes = Layer.mergeAll(
104 HttpApiBuilder.layer(PeerTestApi).pipe(
104 - Layer.provide(McpOAuthHttp.layer.pipe(Layer.provide(McpOAuth.layer))),
105 + Layer.provide(
106 + McpOAuthHttp.layer.pipe(
107 + Layer.provide(McpOAuth.layer),
108 + Layer.provide(
109 + Layer.mock(CloudLink.CloudLink)({
110 + linkState: () =>
111 + Effect.succeed({
112 + linked: false,
113 + cloudUserId: null,
114 + relayUrl: null,
115 + relayIssuer: null,
116 + publishAgentActivity: false,
117 + }),
118 + }),
119 + ),
120 + ),
121 + ),
122 Layer.provide(ServerHttp.layerServerEnvironmentHttpApi),
123 Layer.provide(AuthHttp.layerAuthenticatedAuth),
124 ),
apps/web/src/cloud/connectAgentApproval.test.ts new
+71
@@ -0,0 +1,71 @@
1 +import { EnvironmentId } from "@t3tools/contracts";
2 +import { describe, expect, it } from "vite-plus/test";
3 +
4 +import {
5 + approveAgentUrl,
6 + approvedReturnUrl,
7 + pendingValue,
8 + readApproveAgentRequest,
9 + readConnectApprovalReturn,
10 +} from "./connectAgentApproval";
11 +
12 +const SIGN_IN = "https://prod-abc.t3coderelay.com/connect-agent?client_id=c&state=s";
13 +const NONCE = "abcdefghijklmnopqrstuvwx";
14 +const approveAt = (overrides: Record<string, string>) => {
15 + const url = new URL(
16 + approveAgentUrl("https://app.t3.codes", {
17 + environmentId: EnvironmentId.make("env-1"),
18 + access: "auto",
19 + nonce: NONCE,
20 + returnTo: SIGN_IN,
21 + }),
22 + );
23 + for (const [name, value] of Object.entries(overrides)) url.searchParams.set(name, value);
24 + return url;
25 +};
26 +
27 +describe("readApproveAgentRequest", () => {
28 + it("returns a code only to an https /connect-agent page with a well-formed request", () => {
29 + const request = readApproveAgentRequest(approveAt({}));
30 + expect(request).not.toBeNull();
31 + expect(approvedReturnUrl(request!, "T3-AUTO-CODE")).toBe(
32 + `${SIGN_IN}#t3-connect-code=T3-AUTO-CODE&t3-connect-nonce=${NONCE}`,
33 + );
34 +
35 + for (const overrides of [
36 + { return_to: "http://prod-abc.t3coderelay.com/connect-agent?state=s" },
37 + { return_to: "https://prod-abc.t3coderelay.com/somewhere-else" },
38 + { return_to: "https://user:pass@prod-abc.t3coderelay.com/connect-agent" },
39 + { return_to: "not a url" },
40 + { access: "everything" },
41 + { nonce: "short" },
42 + { environment: "" },
43 + ]) {
44 + expect(readApproveAgentRequest(approveAt(overrides)), JSON.stringify(overrides)).toBeNull();
45 + }
46 + });
47 +});
48 +
49 +describe("readConnectApprovalReturn", () => {
50 + const code = "AUTO-Q8RZ3NWD5KTC";
51 + const hash = `#t3-connect-code=${code}&t3-connect-nonce=${NONCE}`;
52 + const search = "?client_id=c&state=s";
53 +
54 + it("uses a code only in the tab that started this request at its level", () => {
55 + expect(readConnectApprovalReturn(hash, search, pendingValue(NONCE, "auto", search))).toEqual({
56 + status: "approved",
57 + code,
58 + });
59 + for (const pending of [
60 + null,
61 + pendingValue("another-nonce-value-xyz", "auto", search),
62 + pendingValue(NONCE, "auto", "?state=other"),
63 + pendingValue(NONCE, "read-only", search),
64 + ]) {
65 + expect(readConnectApprovalReturn(hash, search, pending)).toEqual({ status: "discarded" });
66 + }
67 + expect(readConnectApprovalReturn("", search, pendingValue(NONCE, "auto", search))).toEqual({
68 + status: "none",
69 + });
70 + });
71 +});
apps/web/src/cloud/connectAgentApproval.ts new
+133
@@ -0,0 +1,133 @@
1 +import { AuthMcpClientAccess, EnvironmentId, parseMcpApprovalCode } from "@t3tools/contracts";
2 +import * as Schema from "effect/Schema";
3 +
4 +/**
5 + * T3 Connect approval of an app sign-in. The sign-in page on an environment's relay address
6 + * sends the user to the hosted app, which mints a one-use app approval code there with the
7 + * account's own access and returns it in the fragment. The nonce stays in the page's tab, and
8 + * only the tab that asked may use the code.
9 + */
10 +const APPROVE_AGENT_PATH = "/approve-agent";
11 +const CONNECT_AGENT_PATH = "/connect-agent";
12 +const CODE_PARAM = "t3-connect-code";
13 +const NONCE_PARAM = "t3-connect-nonce";
14 +const PENDING_KEY = "t3code:connect-agent:pending";
15 +const NONCE_PATTERN = /^[A-Za-z0-9_-]{16,64}$/;
16 +
17 +const isAccess = Schema.is(AuthMcpClientAccess);
18 +
19 +export interface ApproveAgentRequest {
20 + readonly environmentId: EnvironmentId;
21 + readonly access: AuthMcpClientAccess;
22 + readonly nonce: string;
23 + /** The sign-in page to return to, without a fragment. */
24 + readonly returnTo: URL;
25 +}
26 +
27 +export function approveAgentUrl(
28 + hostedAppUrl: string,
29 + request: Omit<ApproveAgentRequest, "returnTo"> & { readonly returnTo: string },
30 +): string {
31 + const url = new URL(APPROVE_AGENT_PATH, hostedAppUrl);
32 + url.searchParams.set("environment", request.environmentId);
33 + url.searchParams.set("access", request.access);
34 + url.searchParams.set("nonce", request.nonce);
35 + url.searchParams.set("return_to", request.returnTo);
36 + return url.toString();
37 +}
38 +
39 +/** Null unless every field is present and `return_to` is an https sign-in page. */
40 +export function readApproveAgentRequest(url: URL): ApproveAgentRequest | null {
41 + const environment = url.searchParams.get("environment");
42 + const access = url.searchParams.get("access");
43 + const nonce = url.searchParams.get("nonce");
44 + const returnTo = parseUrl(url.searchParams.get("return_to"));
45 + if (
46 + !environment ||
47 + !isAccess(access) ||
48 + nonce === null ||
49 + !NONCE_PATTERN.test(nonce) ||
50 + returnTo === null ||
51 + returnTo.protocol !== "https:" ||
52 + returnTo.pathname !== CONNECT_AGENT_PATH ||
53 + returnTo.username !== "" ||
54 + returnTo.password !== ""
55 + ) {
56 + return null;
57 + }
58 + returnTo.hash = "";
59 + return { environmentId: EnvironmentId.make(environment), access, nonce, returnTo };
60 +}
61 +
62 +export function approvedReturnUrl(request: ApproveAgentRequest, code: string): string {
63 + const url = new URL(request.returnTo);
64 + url.hash = new URLSearchParams({ [CODE_PARAM]: code, [NONCE_PARAM]: request.nonce }).toString();
65 + return url.toString();
66 +}
67 +
68 +export type ConnectApprovalReturn =
69 + | { readonly status: "none" }
70 + /** A code this tab did not ask for, as from someone else's link; never used. */
71 + | { readonly status: "discarded" }
72 + | { readonly status: "approved"; readonly code: string };
73 +
74 +/**
75 + * A returned code is used only when this tab started the approval for this same sign-in request
76 + * at the code's own level, so a code minted through someone else's link is never offered.
77 + */
78 +export function readConnectApprovalReturn(
79 + hash: string,
80 + search: string,
81 + pending: string | null,
82 +): ConnectApprovalReturn {
83 + const params = new URLSearchParams(hash.replace(/^#/, ""));
84 + const code = params.get(CODE_PARAM)?.trim();
85 + if (!code) return { status: "none" };
86 + const nonce = params.get(NONCE_PARAM);
87 + const access = parseMcpApprovalCode(code)?.access;
88 + return nonce !== null && access !== undefined && pending === pendingValue(nonce, access, search)
89 + ? { status: "approved", code }
90 + : { status: "discarded" };
91 +}
92 +
93 +export function pendingValue(nonce: string, access: AuthMcpClientAccess, search: string): string {
94 + return `${nonce} ${access} ${search}`;
95 +}
96 +
97 +export function newApprovalNonce(): string {
98 + const bytes = crypto.getRandomValues(new Uint8Array(24));
99 + return btoa(String.fromCharCode(...bytes))
100 + .replaceAll("+", "-")
101 + .replaceAll("/", "_")
102 + .replace(/=+$/, "");
103 +}
104 +
105 +// Storage can throw in private windows; without it the returned code is discarded.
106 +export function rememberPendingApproval(value: string): void {
107 + try {
108 + window.sessionStorage.setItem(PENDING_KEY, value);
109 + } catch {}
110 +}
111 +
112 +export function readPendingApproval(): string | null {
113 + try {
114 + return window.sessionStorage.getItem(PENDING_KEY);
115 + } catch {
116 + return null;
117 + }
118 +}
119 +
120 +export function clearPendingApproval(): void {
121 + try {
122 + window.sessionStorage.removeItem(PENDING_KEY);
123 + } catch {}
124 +}
125 +
126 +function parseUrl(value: string | null): URL | null {
127 + if (value === null) return null;
128 + try {
129 + return new URL(value);
130 + } catch {
131 + return null;
132 + }
133 +}
apps/web/src/components/auth/ApproveAgentSurface.tsx new
+120
@@ -0,0 +1,120 @@
1 +import { useAuth, useClerk } from "@clerk/react";
2 +import { useAtomValue } from "@effect/atom-react";
3 +import { managedRelaySessionAtom } from "@t3tools/client-runtime/relay";
4 +import { ConnectApprovalCodeError } from "@t3tools/client-runtime/state/peerPairingCode";
5 +import * as Result from "effect/Result";
6 +import * as Schema from "effect/Schema";
7 +import { useEffect, useEffectEvent, useRef, useState } from "react";
8 +
9 +import { approvedReturnUrl, readApproveAgentRequest } from "../../cloud/connectAgentApproval";
10 +import { isElectron } from "../../env";
11 +import { mintConnectMcpApprovalCode } from "../../state/peerPairingCode";
12 +import { resolveClerkSignInProps } from "../clerk/authRedirect";
13 +import { Button } from "../ui/button";
14 +import { Spinner } from "../ui/spinner";
15 +import { StandalonePage, StandalonePageHeader } from "../ui/standalone-page";
16 +
17 +const isConnectApprovalCodeError = Schema.is(ConnectApprovalCodeError);
18 +
19 +/** Signs in to T3 Connect, mints an app approval code, and returns it to the sign-in page. */
20 +export function ApproveAgentSurface() {
21 + const [request] = useState(() => readApproveAgentRequest(new URL(window.location.href)));
22 + const clerk = useClerk();
23 + const { isLoaded, isSignedIn } = useAuth();
24 + const session = useAtomValue(managedRelaySessionAtom);
25 + const [failure, setFailure] = useState<string | null>(null);
26 + const signInOpened = useRef(false);
27 + const started = useRef(false);
28 +
29 + const openSignIn = () =>
30 + clerk.openSignIn(resolveClerkSignInProps(window.location.href, isElectron));
31 + const openSignInOnLoad = useEffectEvent(openSignIn);
32 +
33 + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- opens Clerk sign-in, then mints the code once the relay session is ready and navigates the window back
34 + useEffect(() => {
35 + if (!request || !isLoaded) return;
36 + if (!isSignedIn) {
37 + if (!signInOpened.current) {
38 + signInOpened.current = true;
39 + openSignInOnLoad();
40 + }
41 + return;
42 + }
43 + if (session === null || started.current) return;
44 + started.current = true;
45 + void mintConnectMcpApprovalCode({
46 + environmentId: request.environmentId,
47 + pageOrigin: request.returnTo.origin,
48 + access: request.access,
49 + }).then((result) => {
50 + if (Result.isSuccess(result)) {
51 + window.location.replace(approvedReturnUrl(request, result.success));
52 + return;
53 + }
54 + setFailure(
55 + isConnectApprovalCodeError(result.failure)
56 + ? result.failure.message
57 + : "Could not approve the sign-in. Try again from the app.",
58 + );
59 + });
60 + }, [isLoaded, isSignedIn, request, session]);
61 +
62 + if (!request) {
63 + return (
64 + <StandalonePage>
65 + <StandalonePageHeader
66 + context="Agent sign-in"
67 + title="This sign-in link is incomplete"
68 + description="Close this page and start the sign-in again from your agent."
69 + />
70 + </StandalonePage>
71 + );
72 + }
73 +
74 + if (failure !== null) {
75 + return (
76 + <StandalonePage>
77 + <StandalonePageHeader
78 + context="Agent sign-in"
79 + title="This sign-in cannot continue"
80 + description={failure}
81 + />
82 + <p className="mt-4 text-sm text-muted-foreground">
83 + You can still go back and paste a sign-in code instead.
84 + </p>
85 + <div className="mt-6">
86 + <Button
87 + type="button"
88 + variant="outline"
89 + onClick={() => void clerk.signOut({ redirectUrl: window.location.href })}
90 + >
91 + Use another account
92 + </Button>
93 + </div>
94 + </StandalonePage>
95 + );
96 + }
97 +
98 + return (
99 + <StandalonePage>
100 + <StandalonePageHeader
101 + context="Agent sign-in"
102 + title={`Approving on ${request.returnTo.host}`}
103 + description={
104 + isLoaded && !isSignedIn
105 + ? "Sign in to T3 Connect with the account this environment is linked to."
106 + : "Checking that this environment belongs to your account…"
107 + }
108 + />
109 + {isLoaded && !isSignedIn ? (
110 + <div className="mt-6">
111 + <Button type="button" onClick={openSignIn}>
112 + Sign in
113 + </Button>
114 + </div>
115 + ) : (
116 + <Spinner className="mt-6" size="lg" tone="muted" />
117 + )}
118 + </StandalonePage>
119 + );
120 +}
apps/web/src/components/auth/ConnectAgentSurface.tsx
+129 -50
@@ -16,6 +16,15 @@ import * as Effect from "effect/Effect";
16 import * as Schema from "effect/Schema";
17 import { type ReactNode, useEffect, useState } from "react";
18
19 +import {
20 + approveAgentUrl,
21 + clearPendingApproval,
22 + newApprovalNonce,
23 + pendingValue,
24 + readConnectApprovalReturn,
25 + readPendingApproval,
26 + rememberPendingApproval,
27 +} from "~/cloud/connectAgentApproval";
28 import { PrimaryEnvironmentHttpClient } from "~/environments/primary/httpClient";
29 import { runPrimaryHttp } from "~/lib/runtime";
30 import { cn } from "~/lib/utils";
@@ -80,6 +89,21 @@ function runApproval<A>(
89 ).catch((): Answer<A> => ({ kind: "error", message: UNREACHABLE }));
90 }
91
92 +/** Sends the decision and follows its redirect; otherwise the message to show. */
93 +async function submitDecision(
94 + authorization: AuthMcpAuthorizationRequest,
95 + decision: AuthMcpApprovalDecision,
96 +): Promise<string | null> {
97 + const answer = await runApproval((client) =>
98 + client.mcpOAuth.decision({ payload: { authorization, decision } }),
99 + );
100 + if (answer.kind === "redirect") {
101 + window.location.replace(answer.url);
102 + return null;
103 + }
104 + return answer.kind === "error" ? answer.message : "The sign-in could not continue.";
105 +}
106 +
107 const decodeAuthorizationRequest = Schema.decodeSync(AuthMcpAuthorizationRequest);
108
109 function readAuthorizationRequest(): AuthMcpAuthorizationRequest {
@@ -88,6 +112,9 @@ function readAuthorizationRequest(): AuthMcpAuthorizationRequest {
112
113 export function ConnectAgentSurface() {
114 const [authorization] = useState(readAuthorizationRequest);
115 + const [connectReturn] = useState(() =>
116 + readConnectApprovalReturn(window.location.hash, window.location.search, readPendingApproval()),
117 + );
118 const [loaded, setLoaded] = useState<Loaded>({ status: "loading" });
119 const [requestedAccess, setAccess] = useState<AuthMcpClientAccess | null>(null);
120 const [pairingCode, setPairingCode] = useState("");
@@ -96,12 +123,21 @@ export function ConnectAgentSurface() {
123 loaded.status === "ready" ? loaded.details.runtimeModeCeiling : undefined,
124 pairingCode.trim().length > 0,
125 );
99 - const [errorMessage, setErrorMessage] = useState("");
126 + const [errorMessage, setErrorMessage] = useState(
127 + connectReturn.status === "discarded"
128 + ? "The T3 Connect approval did not come back to the tab that started it, so it was not used. Try again here, or paste a sign-in code."
129 + : "",
130 + );
131 const [pending, setPending] = useState<"approve" | "deny" | null>(null);
132
133 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- fetches the MCP OAuth approval and redirects the window or stores details, ignoring stale answers
134 useEffect(() => {
135 let cancelled = false;
136 + // The code is one-use; keep it out of history, bookmarks and a reload.
137 + if (connectReturn.status !== "none") {
138 + clearPendingApproval();
139 + window.history.replaceState(null, "", `${window.location.pathname}${window.location.search}`);
140 + }
141 void runApproval((client) => client.mcpOAuth.approval({ payload: authorization })).then(
142 (answer) => {
143 if (cancelled) return;
@@ -109,36 +145,59 @@ export function ConnectAgentSurface() {
145 window.location.replace(answer.url);
146 return;
147 }
112 - setLoaded(
113 - answer.kind === "error"
114 - ? { status: "invalid", message: answer.message }
115 - : { status: "ready", details: answer.value },
116 - );
148 + if (answer.kind === "error") {
149 + setLoaded({ status: "invalid", message: answer.message });
150 + return;
151 + }
152 + setLoaded({ status: "ready", details: answer.value });
153 + // This tab chose the app and level before leaving for T3 Connect, so that was the approval.
154 + const decision =
155 + connectReturn.status === "approved"
156 + ? resolveApprovalDecision({
157 + code: connectReturn.code,
158 + access: "read-only",
159 + details: answer.value,
160 + })
161 + : null;
162 + if (decision === null) return;
163 + setPending("approve");
164 + void submitDecision(authorization, decision).then((message) => {
165 + if (cancelled || message === null) return;
166 + setPending(null);
167 + setErrorMessage(message);
168 + });
169 },
170 );
171 return () => {
172 cancelled = true;
173 };
122 - }, [authorization]);
174 + }, [authorization, connectReturn]);
175
124 - const decide = async (choice: "approve" | "deny") => {
125 - if (loaded.status !== "ready") return;
176 + const continueWithConnect = (connect: NonNullable<AuthMcpApprovalDetails["connectSignIn"]>) => {
177 + const nonce = newApprovalNonce();
178 + rememberPendingApproval(pendingValue(nonce, access, window.location.search));
179 + window.location.assign(
180 + approveAgentUrl(connect.hostedAppUrl, {
181 + environmentId: connect.environmentId,
182 + access,
183 + nonce,
184 + returnTo: `${window.location.origin}${window.location.pathname}${window.location.search}`,
185 + }),
186 + );
187 + };
188 +
189 + const decide = async (choice: "approve" | "deny", details: AuthMcpApprovalDetails) => {
190 const decision: AuthMcpApprovalDecision | null =
191 choice === "deny"
192 ? { _tag: "deny" }
129 - : resolveApprovalDecision({ code: pairingCode, access, details: loaded.details });
193 + : resolveApprovalDecision({ code: pairingCode, access, details });
194 if (decision === null) return;
195 setPending(choice);
196 setErrorMessage("");
133 - const answer = await runApproval((client) =>
134 - client.mcpOAuth.decision({ payload: { authorization, decision } }),
135 - );
136 - if (answer.kind === "redirect") {
137 - window.location.replace(answer.url);
138 - return;
139 - }
197 + const message = await submitDecision(authorization, decision);
198 + if (message === null) return;
199 setPending(null);
141 - setErrorMessage(answer.kind === "error" ? answer.message : "The sign-in could not continue.");
200 + setErrorMessage(message);
201 };
202
203 if (loaded.status === "loading") {
@@ -165,10 +224,36 @@ export function ConnectAgentSurface() {
224 }
225
226 const { details } = loaded;
168 - const canApprove =
169 - pending === null && resolveApprovalDecision({ code: pairingCode, access, details }) !== null;
227 + const canDecide = resolveApprovalDecision({ code: pairingCode, access, details }) !== null;
228 + const canApprove = pending === null && canDecide;
229 + // A typed code or a browser session that can approve takes precedence.
230 + const connectSignIn =
231 + pairingCode.trim().length === 0 && !canDecide ? details.connectSignIn : undefined;
232 // A code from "Use T3 Code in another app" names its level, so the page does not ask again.
233 const codeAccess = parseMcpApprovalCode(pairingCode)?.access;
234 + const codeField = (
235 + <div className="space-y-2">
236 + <label className="text-sm font-medium" htmlFor="connect-agent-pairing-code">
237 + {details.connectSignIn ? "Or paste a sign-in code" : "Sign-in code"}
238 + </label>
239 + <Input
240 + id="connect-agent-pairing-code"
241 + autoCapitalize="none"
242 + autoComplete="one-time-code"
243 + autoCorrect="off"
244 + disabled={pending !== null}
245 + nativeInput
246 + onChange={(event) => setPairingCode(event.currentTarget.value)}
247 + placeholder="Paste a code"
248 + spellCheck={false}
249 + value={pairingCode}
250 + />
251 + <p className="text-xs text-muted-foreground">
252 + Get one from Use T3 Code in another app (MCP), Settings → Sharing & access, or{" "}
253 + <code>t3 auth pairing create</code> on this machine.
254 + </p>
255 + </div>
256 + );
257
258 return (
259 <StandalonePage>
@@ -203,30 +288,10 @@ export function ConnectAgentSurface() {
288 className="mt-6 space-y-5"
289 onSubmit={(event) => {
290 event.preventDefault();
206 - if (canApprove) void decide("approve");
291 + if (canApprove) void decide("approve", details);
292 }}
293 >
209 - <div className="space-y-2">
210 - <label className="text-sm font-medium" htmlFor="connect-agent-pairing-code">
211 - Sign-in code
212 - </label>
213 - <Input
214 - id="connect-agent-pairing-code"
215 - autoCapitalize="none"
216 - autoComplete="one-time-code"
217 - autoCorrect="off"
218 - disabled={pending !== null}
219 - nativeInput
220 - onChange={(event) => setPairingCode(event.currentTarget.value)}
221 - placeholder="Paste a code"
222 - spellCheck={false}
223 - value={pairingCode}
224 - />
225 - <p className="text-xs text-muted-foreground">
226 - Get one from Use T3 Code in another app (MCP), Settings → Sharing & access, or{" "}
227 - <code>t3 auth pairing create</code> on this machine.
228 - </p>
229 - </div>
294 + {details.connectSignIn ? null : codeField}
295
296 {codeAccess ? (
297 <p className="text-sm">
@@ -266,22 +331,36 @@ export function ConnectAgentSurface() {
331 ) : null}
332
333 <div className="flex flex-wrap gap-2">
269 - <Button disabled={!canApprove} type="submit">
270 - {pending === "approve"
271 - ? "Approving…"
272 - : codeAccess
273 - ? `Approve ${accessConfig[codeAccess].label}`
274 - : "Approve"}
275 - </Button>
334 + {connectSignIn ? (
335 + <Button
336 + disabled={pending !== null}
337 + onClick={() => continueWithConnect(connectSignIn)}
338 + type="button"
339 + >
340 + {pending === "approve"
341 + ? "Approving…"
342 + : `Approve ${accessConfig[access].label} with T3 Connect`}
343 + </Button>
344 + ) : (
345 + <Button disabled={!canApprove} type="submit">
346 + {pending === "approve"
347 + ? "Approving…"
348 + : codeAccess
349 + ? `Approve ${accessConfig[codeAccess].label}`
350 + : "Approve"}
351 + </Button>
352 + )}
353 <Button
354 disabled={pending !== null}
278 - onClick={() => void decide("deny")}
355 + onClick={() => void decide("deny", details)}
356 type="button"
357 variant="outline"
358 >
359 {pending === "deny" ? "Denying…" : "Deny"}
360 </Button>
361 </div>
362 +
363 + {details.connectSignIn ? codeField : null}
364 </form>
365 </StandalonePage>
366 );
apps/web/src/routeTree.gen.ts
+21
@@ -14,6 +14,7 @@ import { Route as PairRouteImport } from './routes/pair'
14 import { Route as GuestRouteImport } from './routes/guest'
15 import { Route as ConnectAgentRouteImport } from './routes/connect-agent'
16 import { Route as ConnectRouteImport } from './routes/connect'
17 +import { Route as ApproveAgentRouteImport } from './routes/approve-agent'
18 import { Route as ChatRouteImport } from './routes/_chat'
19 import { Route as ChatIndexRouteImport } from './routes/_chat.index'
20 import { Route as ProjectsProjectKeyRouteImport } from './routes/projects.$projectKey'
@@ -77,6 +78,11 @@ const ConnectRoute = ConnectRouteImport.update({
78 path: '/connect',
79 getParentRoute: () => rootRouteImport,
80 } as any)
81 +const ApproveAgentRoute = ApproveAgentRouteImport.update({
82 + id: '/approve-agent',
83 + path: '/approve-agent',
84 + getParentRoute: () => rootRouteImport,
85 +} as any)
86 const ChatRoute = ChatRouteImport.update({
87 id: '/_chat',
88 getParentRoute: () => rootRouteImport,
@@ -270,6 +276,7 @@ const ChatEnvironmentIdThreadIdRoute =
276
277 export interface FileRoutesByFullPath {
278 '/': typeof ChatIndexRoute
279 + '/approve-agent': typeof ApproveAgentRoute
280 '/connect': typeof ConnectRoute
281 '/connect-agent': typeof ConnectAgentRoute
282 '/guest': typeof GuestRoute
@@ -312,6 +319,7 @@ export interface FileRoutesByFullPath {
319 '/threads/$environmentId/$threadId': typeof ThreadsEnvironmentIdThreadIdRoute
320 }
321 export interface FileRoutesByTo {
322 + '/approve-agent': typeof ApproveAgentRoute
323 '/connect': typeof ConnectRoute
324 '/connect-agent': typeof ConnectAgentRoute
325 '/guest': typeof GuestRoute
@@ -357,6 +365,7 @@ export interface FileRoutesByTo {
365 export interface FileRoutesById {
366 __root__: typeof rootRouteImport
367 '/_chat': typeof ChatRouteWithChildren
368 + '/approve-agent': typeof ApproveAgentRoute
369 '/connect': typeof ConnectRoute
370 '/connect-agent': typeof ConnectAgentRoute
371 '/guest': typeof GuestRoute
@@ -403,6 +412,7 @@ export interface FileRouteTypes {
412 fileRoutesByFullPath: FileRoutesByFullPath
413 fullPaths:
414 | '/'
415 + | '/approve-agent'
416 | '/connect'
417 | '/connect-agent'
418 | '/guest'
@@ -445,6 +455,7 @@ export interface FileRouteTypes {
455 | '/threads/$environmentId/$threadId'
456 fileRoutesByTo: FileRoutesByTo
457 to:
458 + | '/approve-agent'
459 | '/connect'
460 | '/connect-agent'
461 | '/guest'
@@ -489,6 +500,7 @@ export interface FileRouteTypes {
500 id:
501 | '__root__'
502 | '/_chat'
503 + | '/approve-agent'
504 | '/connect'
505 | '/connect-agent'
506 | '/guest'
@@ -534,6 +546,7 @@ export interface FileRouteTypes {
546 }
547 export interface RootRouteChildren {
548 ChatRoute: typeof ChatRouteWithChildren
549 + ApproveAgentRoute: typeof ApproveAgentRoute
550 ConnectRoute: typeof ConnectRoute
551 ConnectAgentRoute: typeof ConnectAgentRoute
552 GuestRoute: typeof GuestRoute
@@ -580,6 +593,13 @@ declare module '@tanstack/react-router' {
593 preLoaderRoute: typeof ConnectRouteImport
594 parentRoute: typeof rootRouteImport
595 }
596 + '/approve-agent': {
597 + id: '/approve-agent'
598 + path: '/approve-agent'
599 + fullPath: '/approve-agent'
600 + preLoaderRoute: typeof ApproveAgentRouteImport
601 + parentRoute: typeof rootRouteImport
602 + }
603 '/_chat': {
604 id: '/_chat'
605 path: ''
@@ -930,6 +950,7 @@ const ChatRouteWithChildren = ChatRoute._addFileChildren(ChatRouteChildren)
950
951 const rootRouteChildren: RootRouteChildren = {
952 ChatRoute: ChatRouteWithChildren,
953 + ApproveAgentRoute: ApproveAgentRoute,
954 ConnectRoute: ConnectRoute,
955 ConnectAgentRoute: ConnectAgentRoute,
956 GuestRoute: GuestRoute,
apps/web/src/routes/__root.tsx
+6 -1
@@ -156,7 +156,12 @@ function RootRouteBranch() {
156
157 if (pathname === GUEST_PAGE_PATH) return <Outlet />;
158
159 - if (pathname === "/pair" || pathname === "/connect" || pathname === "/connect-agent") {
159 + if (
160 + pathname === "/pair" ||
161 + pathname === "/connect" ||
162 + pathname === "/connect-agent" ||
163 + pathname === "/approve-agent"
164 + ) {
165 return <Outlet />;
166 }
167
apps/web/src/routes/approve-agent.tsx new
+14
@@ -0,0 +1,14 @@
1 +import { createFileRoute, redirect } from "@tanstack/react-router";
2 +
3 +import { hasCloudPublicConfig } from "../cloud/publicConfig";
4 +import { ApproveAgentSurface } from "../components/auth/ApproveAgentSurface";
5 +import { isHostedStaticApp } from "../hostedPairing";
6 +
7 +export const Route = createFileRoute("/approve-agent")({
8 + beforeLoad: () => {
9 + if (!isHostedStaticApp() || !hasCloudPublicConfig()) {
10 + throw redirect({ to: "/", replace: true });
11 + }
12 + },
13 + component: ApproveAgentSurface,
14 +});
apps/web/src/state/peerPairingCode.ts
+17
@@ -1,4 +1,5 @@
1 import {
2 + createConnectMcpApprovalCodeCommand,
3 createMcpApprovalCodeCommand,
4 createPeerPairingCodeCommand,
5 } from "@t3tools/client-runtime/state/peerPairingCode";
@@ -15,6 +16,7 @@ import { appAtomRegistry } from "../rpc/atomRegistry";
16
17 const mintPairingCode = createPeerPairingCodeCommand(connectionAtomRuntime);
18 const mintMcpApprovalCode = createMcpApprovalCodeCommand(connectionAtomRuntime);
19 +const connectMcpApprovalCodeCommand = createConnectMcpApprovalCodeCommand(connectionAtomRuntime);
20
21 /**
22 * A fresh pairing code minted on `environmentId` with this client's session
@@ -41,3 +43,18 @@ export async function mintMcpApprovalCodeOn(
43 ? Result.succeed(result.value)
44 : Result.fail(squashAtomCommandFailure(result));
45 }
46 +
47 +/**
48 + * A fresh app approval code on an environment this T3 Connect account owns, for the sign-in
49 + * page at `pageOrigin`; fails with `ConnectApprovalCodeError` when that is not its relay address.
50 + */
51 +export async function mintConnectMcpApprovalCode(input: {
52 + readonly environmentId: EnvironmentId;
53 + readonly pageOrigin: string;
54 + readonly access: AuthMcpClientAccess;
55 +}): Promise<Result.Result<string, unknown>> {
56 + const result = await connectMcpApprovalCodeCommand.run(appAtomRegistry, input);
57 + return result._tag === "Success"
58 + ? Result.succeed(result.value)
59 + : Result.fail(squashAtomCommandFailure(result));
60 +}
docs/user/outside-agents.md
+4
@@ -64,6 +64,10 @@ Only approve a sign-in you just started. To approve, enter a code from
64 `t3 auth pairing create` on the host. A browser already signed in to the
65 environment with permission to manage access can approve without a code.
66
67 +When the page opens on the environment's T3 Connect address, choose the level
68 +and select **Approve with T3 Connect** instead. Sign in with the T3 Connect
69 +account the environment is linked to, and the sign-in completes without a code.
70 +
71 A code from **Use T3 Code in another app (MCP)** already carries the level you
72 picked there. With another code, choose what the agent may do here: **Auto** is
73 selected by default, or the closest lower mode allowed by your organization’s
packages/client-runtime/src/state/environmentHttpAuth.ts
+4 -1
@@ -145,7 +145,10 @@ const executeEnvironmentRequest = Effect.fnUntraced(function* <
145 E,
146 R,
147 >(input: {
148 - readonly prepared: PreparedConnection;
148 + readonly prepared: Pick<
149 + PreparedConnection,
150 + "environmentId" | "httpBaseUrl" | "httpAuthorization" | "target"
151 + >;
152 readonly signer: Option.Option<ManagedRelay.ManagedRelayDpopSigner["Service"]>;
153 readonly remoteAuthorization?: Option.Option<
154 RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]
packages/client-runtime/src/state/peerPairingCode.test.ts new
+86
@@ -0,0 +1,86 @@
1 +import { describe, expect, it } from "@effect/vitest";
2 +import { EnvironmentId } from "@t3tools/contracts";
3 +import * as Effect from "effect/Effect";
4 +import * as Result from "effect/Result";
5 +import type { HttpClient } from "effect/http";
6 +
7 +import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
8 +import * as ManagedRelay from "../relay/managedRelay.ts";
9 +import * as RpcHttp from "../rpc/http.ts";
10 +import { mintConnectMcpApprovalCode } from "./peerPairingCode.ts";
11 +
12 +const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
13 +const RELAY_ORIGIN = "https://prod-abc.t3coderelay.test";
14 +
15 +function harness() {
16 + const calls: Array<{ readonly url: string; readonly body: unknown }> = [];
17 + const fetchFn: typeof fetch = async (request, init) => {
18 + calls.push({ url: String(request), body: JSON.parse(String(init?.body)) });
19 + return Response.json({
20 + id: "grant-1",
21 + credential: "T3-AUTO-CODE",
22 + expiresAt: "2026-11-09T12:05:00.000Z",
23 + access: "auto",
24 + });
25 + };
26 + const provide = <A, E>(
27 + effect: Effect.Effect<
28 + A,
29 + E,
30 + | RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization
31 + | ManagedRelay.ManagedRelayDpopSigner
32 + | HttpClient.HttpClient
33 + >,
34 + ) =>
35 + effect.pipe(
36 + Effect.provide(RpcHttp.layerRemoteHttpClient(fetchFn)),
37 + Effect.provideService(
38 + RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
39 + RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization.of({
40 + authorizeBearer: () => Effect.die("unexpected bearer authorization"),
41 + authorizeDpop: () => Effect.die("unexpected socket authorization"),
42 + authorizeDpopHttp: () =>
43 + Effect.succeed({
44 + environmentId: ENVIRONMENT_ID,
45 + label: "Box",
46 + httpBaseUrl: RELAY_ORIGIN,
47 + httpAuthorization: { _tag: "Dpop", accessToken: "token", expiresAtEpochMs: 1 },
48 + }),
49 + rememberCheckedDescriptor: () => Effect.void,
50 + renewDpopBeforeExpiry: () => Effect.die("unexpected renewal"),
51 + }),
52 + ),
53 + Effect.provideService(
54 + ManagedRelay.ManagedRelayDpopSigner,
55 + ManagedRelay.ManagedRelayDpopSigner.of({
56 + thumbprint: Effect.succeed("thumbprint"),
57 + createProof: () => Effect.succeed("proof"),
58 + }),
59 + ),
60 + );
61 + return { calls, provide };
62 +}
63 +
64 +describe("mintConnectMcpApprovalCode", () => {
65 + it.effect("mints only for a sign-in page on the environment's relay address", () =>
66 + Effect.gen(function* () {
67 + const { calls, provide } = harness();
68 + const mint = (pageOrigin: string) =>
69 + provide(
70 + mintConnectMcpApprovalCode({ environmentId: ENVIRONMENT_ID, pageOrigin, access: "auto" }),
71 + ).pipe(Effect.result);
72 +
73 + const elsewhere = yield* mint("https://attacker.example");
74 + expect(Result.isFailure(elsewhere) && elsewhere.failure.reason).toBe("other_address");
75 + expect(calls).toEqual([]);
76 +
77 + expect(yield* mint(RELAY_ORIGIN)).toEqual(Result.succeed("T3-AUTO-CODE"));
78 + expect(calls).toEqual([
79 + {
80 + url: `${RELAY_ORIGIN}/api/auth/pairing-token`,
81 + body: { label: "App sign-in", access: "auto" },
82 + },
83 + ]);
84 + }),
85 + );
86 +});
packages/client-runtime/src/state/peerPairingCode.ts
+78 -3
@@ -8,6 +8,7 @@ import {
8 type AuthCreatePairingCredentialInput,
9 type AuthMcpClientAccess,
10 type AuthPairingCredentialResult,
11 + type EnvironmentId,
12 mcpClientScopes,
13 } from "@t3tools/contracts";
14 import * as Schema from "effect/Schema";
@@ -18,12 +19,12 @@ import type { Atom } from "effect/reactivity";
19 import * as SubscriptionRef from "effect/SubscriptionRef";
20
21 import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
21 -import type { PreparedConnection } from "../connection/model.ts";
22 +import { type PreparedConnection, RelayConnectionTarget } from "../connection/model.ts";
23 import type { EnvironmentRegistry } from "../connection/registry.ts";
24 import * as EnvironmentSupervisor from "../connection/supervisor.ts";
25 import * as ManagedRelay from "../relay/managedRelay.ts";
26 import { executeAuthenticatedEnvironmentHttpRequest } from "./environmentHttpAuth.ts";
26 -import { createEnvironmentCommand } from "./runtime.ts";
27 +import { createEnvironmentCommand, createRuntimeCommand } from "./runtime.ts";
28
29 const MINT_TIMEOUT_MS = 8_000;
30 const PEER_PAIRING_CODE_LABEL = "T3 Code link";
@@ -44,8 +45,30 @@ export class PeerPairingCodeError extends Schema.TaggedError<PeerPairingCodeErro
45 }
46 }
47
48 +export class ConnectApprovalCodeError extends Schema.TaggedError<ConnectApprovalCodeError>()(
49 + "ConnectApprovalCodeError",
50 + {
51 + reason: Schema.Literals(["other_address", "not_allowed", "unavailable"]),
52 + cause: Schema.Defect(),
53 + },
54 +) {
55 + override get message(): string {
56 + switch (this.reason) {
57 + case "other_address":
58 + return "This sign-in did not start on that environment's T3 Connect address.";
59 + case "not_allowed":
60 + return "This account cannot approve app sign-ins on that environment.";
61 + case "unavailable":
62 + return "Could not reach that environment through T3 Connect with this account.";
63 + }
64 + }
65 +}
66 +
67 const mintPairingCredential = Effect.fn("clientRuntime.state.mintPairingCredential")(function* (
48 - prepared: PreparedConnection,
68 + prepared: Pick<
69 + PreparedConnection,
70 + "environmentId" | "httpBaseUrl" | "httpAuthorization" | "target"
71 + >,
72 payload: AuthCreatePairingCredentialInput,
73 ): Effect.fn.Return<AuthPairingCredentialResult, PeerPairingCodeError, HttpClient.HttpClient> {
74 const signer = yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner);
@@ -119,3 +142,55 @@ export function createMcpApprovalCodeCommand<R, E>(
142 mintOnEnvironment({ label: MCP_APPROVAL_CODE_LABEL, access }),
143 });
144 }
145 +
146 +/**
147 + * Mints an app approval code on an environment the T3 Connect account owns, for the sign-in
148 + * page at `pageOrigin`. It refuses before minting unless that page is the environment's own
149 + * relay address, so a crafted link cannot send the code anywhere else.
150 + */
151 +export const mintConnectMcpApprovalCode = Effect.fn(
152 + "clientRuntime.state.mintConnectMcpApprovalCode",
153 +)(function* (input: {
154 + readonly environmentId: EnvironmentId;
155 + readonly pageOrigin: string;
156 + readonly access: AuthMcpClientAccess;
157 +}) {
158 + const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
159 + // The relay grants this only for an environment linked to the signed-in account.
160 + const authorized = yield* remote
161 + .authorizeDpopHttp({ expectedEnvironmentId: input.environmentId })
162 + .pipe(
163 + Effect.mapError((cause) => new ConnectApprovalCodeError({ reason: "unavailable", cause })),
164 + );
165 + if (new URL(authorized.httpBaseUrl).origin !== input.pageOrigin) {
166 + return yield* new ConnectApprovalCodeError({
167 + reason: "other_address",
168 + cause: input.pageOrigin,
169 + });
170 + }
171 + const minted = yield* mintPairingCredential(
172 + {
173 + environmentId: input.environmentId,
174 + httpBaseUrl: authorized.httpBaseUrl,
175 + httpAuthorization: authorized.httpAuthorization,
176 + target: new RelayConnectionTarget({
177 + environmentId: input.environmentId,
178 + label: authorized.label,
179 + }),
180 + },
181 + { label: MCP_APPROVAL_CODE_LABEL, access: input.access },
182 + ).pipe(Effect.mapError((cause) => new ConnectApprovalCodeError({ reason: cause.reason, cause })));
183 + return minted.credential;
184 +});
185 +
186 +export function createConnectMcpApprovalCodeCommand<R, E>(
187 + runtime: Atom.AtomRuntime<
188 + RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization | HttpClient.HttpClient | R,
189 + E
190 + >,
191 +) {
192 + return createRuntimeCommand(runtime, {
193 + label: "environment-data:connect-mcp-approval-code:mint",
194 + execute: mintConnectMcpApprovalCode,
195 + });
196 +}
packages/contracts/src/auth.ts
+5
@@ -6,6 +6,7 @@ import {
6 ForwardCompatibleArray,
7 ClientSurface,
8 ClientWebDeployment,
9 + EnvironmentId,
10 TrimmedNonEmptyString,
11 } from "./baseSchemas.ts";
12 import { RuntimeMode } from "./providerPolicy.ts";
@@ -543,6 +544,10 @@ export const AuthMcpApprovalDetails = Schema.Struct({
544 csrfToken: Schema.optionalKey(Schema.String),
545 /** Only scopes held by this session qualify; others need a pairing code. Absent with `csrfToken`. */
546 oneClickAccess: Schema.optionalKey(Schema.Array(AuthMcpClientAccess)),
547 + /** Set when the page is on this environment's T3 Connect address, so its owner can approve there. */
548 + connectSignIn: Schema.optionalKey(
549 + Schema.Struct({ environmentId: EnvironmentId, hostedAppUrl: Schema.String }),
550 + ),
551 /** A managed policy's runtime-mode ceiling; the page loads without the server's config. */
552 runtimeModeCeiling: Schema.optionalKey(
553 Schema.Struct({ organization: Schema.String, maxRuntimeMode: RuntimeMode }),