@devries-cameron20 / t3code Mirror · read-only / commits / 9a0d02723c
Fork 0

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 22, 00:45 UTC

feat: approve agent sign-ins on app.t3.codes with T3 Connect (#33632)

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

Julius Marminge committed Nov 9, 2026 at 17:09 UTC 9a0d02723c182cd9da01973b30c2b38b299bdbc6
24 files changed +666 -707
apps/server/src/auth/EnvironmentAuth.ts
-20
@@ -572,9 +572,6 @@ export class EnvironmentAuth extends Context.Service<
572 AuthMcpClientAccess,
573 ServerAuthMcpApprovalCodeError | ServerAuthInternalError
574 >;
575 - readonly authenticateBrowserSession: (
576 - request: HttpServerRequest.HttpServerRequest,
577 - ) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
575 }
576 >()("t3/auth/EnvironmentAuth") {}
577
@@ -1362,22 +1359,6 @@ export const make = Effect.gen(function* () {
1359 Effect.withSpan("EnvironmentAuth.issueMcpClientSession"),
1360 );
1361
1365 - const authenticateBrowserSession: EnvironmentAuth["Service"]["authenticateBrowserSession"] = (
1366 - request,
1367 - ) => {
1368 - const credential = resolveRequestCredential(request);
1369 - if (!credential || !isBrowserCookieCredential(credential.source)) {
1370 - return Effect.fail(new ServerAuthMissingCredentialError({}));
1371 - }
1372 - return authenticateRequest(request).pipe(
1373 - Effect.filterOrFail(
1374 - (session) => session.method === "browser-session-cookie",
1375 - () => new ServerAuthInvalidCredentialError({ diagnostic: "Not a browser session." }),
1376 - ),
1377 - Effect.withSpan("EnvironmentAuth.authenticateBrowserSession"),
1378 - );
1379 - };
1380 -
1362 const consumeMcpApprovalCode: EnvironmentAuth["Service"]["consumeMcpApprovalCode"] = (
1363 code,
1364 access,
@@ -1430,7 +1411,6 @@ export const make = Effect.gen(function* () {
1411 authenticateMcpClient,
1412 issueMcpClientSession,
1413 consumeMcpApprovalCode,
1433 - authenticateBrowserSession,
1414 });
1415 });
1416
apps/server/src/auth/McpOAuth.test.ts
+63 -22
@@ -130,10 +130,18 @@ const withRoutes = <A, E>(
130
131 const json = <A>(response: Response) => Effect.promise(() => response.json() as Promise<A>);
132
133 -const postJson = (path: string, body: unknown, cookie?: string) =>
133 +/** `credential` is a browser cookie, or `Bearer <token>` for a session such as T3 Connect's. */
134 +const postJson = (path: string, body: unknown, credential?: string) =>
135 at(path, {
136 method: "POST",
136 - headers: { "content-type": "application/json", ...(cookie ? { cookie } : {}) },
137 + headers: {
138 + "content-type": "application/json",
139 + ...(credential === undefined
140 + ? {}
141 + : credential.startsWith("Bearer ")
142 + ? { authorization: credential }
143 + : { cookie: credential }),
144 + },
145 body: encodeJson(body),
146 });
147
@@ -610,26 +618,47 @@ it.live("an app approval code approves only an app sign-in, at its own level", (
618 ),
619 );
620
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 - }),
621 +it.live(
622 + "sends an app sign-in on the linked tunnel to the hosted app, and a link to its own page",
623 + () =>
624 + Effect.gen(function* () {
625 + const handoff = (tunnelHostname: string, peerLink = false) =>
626 + withRoutes(
627 + (handler) =>
628 + Effect.gen(function* () {
629 + const registered = yield* handler(
630 + at("/oauth/mcp/register", {
631 + method: "POST",
632 + headers: { "content-type": "application/json" },
633 + body: encodeJson({
634 + client_name: "Agent",
635 + redirect_uris: [REDIRECT],
636 + token_endpoint_auth_method: "none",
637 + ...(peerLink ? { software_id: MCP_PEER_LINK_SOFTWARE_ID } : {}),
638 + }),
639 + }),
640 + ).pipe(Effect.flatMap(json<{ client_id: string }>));
641 + const query = new URLSearchParams(
642 + authorizeParams(registered.client_id, "http://localhost:51234/callback"),
643 + );
644 + const response = yield* handler(at(`/oauth/mcp/authorize?${query}`));
645 + return { location: response.headers.get("location")!, query: query.toString() };
646 + }),
647 + { ...notLinked, linked: true, cloudUserId: "user_1", tunnelHostname },
648 + );
649 +
650 + const onTunnel = yield* handoff("box.example.ts.net");
651 + const hosted = new URL(onTunnel.location);
652 + expect(`${hosted.origin}${hosted.pathname}`).toBe("https://app.t3.codes/approve-agent");
653 + expect(hosted.searchParams.get("environment")).toEqual(expect.any(String));
654 + hosted.searchParams.delete("environment");
655 + expect(hosted.searchParams.toString()).toBe(onTunnel.query);
656 +
657 + const elsewhere = yield* handoff("other.t3coderelay.com");
658 + expect(elsewhere.location).toBe(`/connect-agent?${elsewhere.query}`);
659 + const peerLink = yield* handoff("box.example.ts.net", true);
660 + expect(peerLink.location).toBe(`/connect-agent?${peerLink.query}`);
661 + }),
662 );
663
664 it.live("one-click approves only access the browser session holds the scopes for", () =>
@@ -701,6 +730,18 @@ it.live("one-click approves only access the browser session holds the scopes for
730 reader,
731 );
732 expect(new URL(readOnly.redirectTo!).searchParams.get("code")).toEqual(expect.any(String));
733 +
734 + // The hosted app approves with the owner's T3 Connect session, which sends no cookie.
735 + const connect = `Bearer ${(yield* auth.issueSession({ scopes: [...AuthStandardClientScopes] })).token}`;
736 + const connectDetails = yield* details(connect);
737 + expect(connectDetails.oneClickAccess).toContain("full-access");
738 + const viaConnect = yield* decide(
739 + handler,
740 + params,
741 + { _tag: "browser-session", access: "auto", csrfToken: connectDetails.csrfToken! },
742 + connect,
743 + );
744 + expect(new URL(viaConnect.redirectTo!).searchParams.get("code")).toEqual(expect.any(String));
745 }),
746 ),
747 );
apps/server/src/auth/McpOAuth.ts
+6 -8
@@ -206,7 +206,8 @@ export class McpOAuth extends Context.Service<
206 readonly urls: McpOAuthUrls;
207 readonly request: AuthMcpAuthorizationRequest;
208 }) => Effect.Effect<AuthorizationRequest, McpOAuthPageError | McpOAuthRedirectError>;
209 - readonly approvingBrowserSession: (
209 + /** A browser cookie session, or a T3 Connect session from the hosted app, that may approve. */
210 + readonly approvingSession: (
211 request: HttpServerRequest.HttpServerRequest,
212 authorization: AuthorizationRequest,
213 ) => Effect.Effect<
@@ -406,11 +407,8 @@ const make = Effect.gen(function* () {
407 } satisfies AuthorizationRequest;
408 });
409
409 - const approvingBrowserSession: McpOAuth["Service"]["approvingBrowserSession"] = (
410 - request,
411 - authorization,
412 - ) =>
413 - environmentAuth.authenticateBrowserSession(request).pipe(
410 + const approvingSession: McpOAuth["Service"]["approvingSession"] = (request, authorization) =>
411 + environmentAuth.authenticateHttpRequest(request).pipe(
412 Effect.flatMap((session) =>
413 // Approving manages access, and a session may only hand out scopes it holds.
414 session.scopes.includes(AuthAccessWriteScope) &&
@@ -470,7 +468,7 @@ const make = Effect.gen(function* () {
468 ),
469 );
470 } else {
473 - const session = yield* approvingBrowserSession(input.request, input.authorization);
471 + const session = yield* approvingSession(input.request, input.authorization);
472 if (
473 session === undefined ||
474 !timingSafeEqualBase64Url(decision.csrfToken, session.csrfToken) ||
@@ -574,7 +572,7 @@ const make = Effect.gen(function* () {
572 : { organization: managedPolicy.organization, maxRuntimeMode },
573 register,
574 validateAuthorization,
577 - approvingBrowserSession,
575 + approvingSession,
576 approve,
577 deny,
578 exchangeCode,
apps/server/src/auth/mcpOAuthHttp.ts
+20 -12
@@ -16,12 +16,13 @@ import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
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";
19 +import { agentApprovalAppUrlConfig } 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
24 const APPROVAL_PAGE_PATH = "/connect-agent";
25 +const HOSTED_APPROVAL_PATH = "/approve-agent";
26
27 const PAGE_HEADERS = {
28 "content-security-policy":
@@ -70,16 +71,21 @@ export const layer = HttpApiBuilder.group(
71 const oauth = yield* McpOAuth.McpOAuth;
72 const cloudLink = yield* CloudLink.CloudLink;
73 const serverEnvironment = yield* ServerEnvironment.ServerEnvironmentIdentity;
73 - const hostedAppUrl = yield* hostedAppUrlConfig.pipe(
74 + const hostedAppUrl = yield* agentApprovalAppUrlConfig.pipe(
75 Effect.orElseSucceed(() => DEFAULT_HOSTED_APP_URL),
76 );
76 - // The hosted app returns a code only to the tunnel address, so other origins keep the code field.
77 - const connectSignIn = (issuer: string) =>
77 + // T3 Connect serves this host, so the owner can approve on the hosted app by signing in there.
78 + const hostedApprovalUrl = (issuer: string, search: string) =>
79 cloudLink.linkState().pipe(
80 Effect.flatMap((state) =>
81 state.linked && !state.linkRevoked && state.tunnelHostname === new URL(issuer).hostname
82 ? serverEnvironment.getEnvironmentId.pipe(
82 - Effect.map((environmentId) => Option.some({ environmentId, hostedAppUrl })),
83 + Effect.map((environmentId) => {
84 + const url = new URL(HOSTED_APPROVAL_PATH, hostedAppUrl);
85 + url.search = search;
86 + url.searchParams.set("environment", environmentId);
87 + return Option.some(url.toString());
88 + }),
89 )
90 : Effect.succeedNone,
91 ),
@@ -119,7 +125,14 @@ export const layer = HttpApiBuilder.group(
125 .pipe(Effect.result);
126 const headers = { "cache-control": "no-store", "referrer-policy": "no-referrer" };
127 if (Result.isSuccess(authorization)) {
122 - return HttpServerResponse.redirect(`${APPROVAL_PAGE_PATH}${url.search}`, { headers });
128 + // A link needs a plain pairing code, so it stays on this environment's own page.
129 + const hosted = authorization.success.client.peerLink
130 + ? Option.none()
131 + : yield* hostedApprovalUrl(urls.issuer, url.search);
132 + return HttpServerResponse.redirect(
133 + Option.getOrElse(hosted, () => `${APPROVAL_PAGE_PATH}${url.search}`),
134 + { headers },
135 + );
136 }
137 const error = authorization.failure;
138 return error._tag === "McpOAuthPageError"
@@ -138,11 +151,7 @@ export const layer = HttpApiBuilder.group(
151 const resolved = yield* forwardedAuthorization(oauth, payload);
152 if ("redirectTo" in resolved) return resolved;
153 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);
154 + const session = yield* oauth.approvingSession(request, resolved);
155 yield* noStore;
156 return {
157 clientName: resolved.client.name,
@@ -151,7 +160,6 @@ export const layer = HttpApiBuilder.group(
160 ...(oauth.runtimeModeCeiling === undefined
161 ? {}
162 : { runtimeModeCeiling: oauth.runtimeModeCeiling }),
154 - ...(Option.isSome(connect) ? { connectSignIn: connect.value } : {}),
163 ...(session === undefined
164 ? {}
165 : {
apps/server/src/cloud/publicConfig.ts
+14
@@ -13,6 +13,7 @@ import * as Schema from "effect/Schema";
13 import * as SchemaIssue from "effect/SchemaIssue";
14
15 declare const __T3CODE_BUILD_RELAY_URL__: string | undefined;
16 +declare const __T3CODE_BUILD_CHANNEL__: "nightly" | "latest" | undefined;
17 declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
18 declare const __T3CODE_BUILD_CLERK_CLI_OAUTH_CLIENT_ID__: string | undefined;
19 declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_URL__: string | undefined;
@@ -114,6 +115,19 @@ export const hostedAppUrlConfig = makePublicValueConfig(
115 DEFAULT_HOSTED_APP_URL,
116 ).pipe(Config.mapEffect(validateHostedAppUrl));
117
118 +const NIGHTLY_HOSTED_APP_URL = "https://nightly.app.t3.codes";
119 +
120 +/**
121 + * Where agent sign-ins on the T3 Connect address are approved. A nightly build defaults to the
122 + * nightly hosted app, which ships the same approval page; app.t3.codes serves stable.
123 + */
124 +export const agentApprovalAppUrlConfig = makePublicValueConfig(
125 + "T3CODE_HOSTED_APP_URL",
126 + typeof __T3CODE_BUILD_CHANNEL__ !== "undefined" && __T3CODE_BUILD_CHANNEL__ === "nightly"
127 + ? NIGHTLY_HOSTED_APP_URL
128 + : DEFAULT_HOSTED_APP_URL,
129 +).pipe(Config.mapEffect(validateHostedAppUrl));
130 +
131 function validateHostedAppUrl(value: string) {
132 try {
133 const url = new URL(value);
apps/server/src/environment/ServerEnvironment.ts
+1
@@ -289,6 +289,7 @@ export const make = Effect.gen(function* () {
289 mcpModeLimitHeader: true,
290 linkFence: true,
291 mcpApprovalCodes: true,
292 + mcpHostedApproval: true,
293 },
294 };
295
apps/server/src/peer/PeerLinks.ts
+1
@@ -309,6 +309,7 @@ const make = Effect.gen(function* () {
309 const resource = `${origin}/mcp`;
310 const decided = yield* client.mcpOAuth
311 .decision({
312 + headers: {},
313 payload: {
314 authorization: {
315 response_type: "code",
apps/web/src/cloud/connectAgentApproval.test.ts deleted
-71
@@ -1,71 +0,0 @@
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 deleted
-133
@@ -1,133 +0,0 @@
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
+151 -72
@@ -1,120 +1,199 @@
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";
4 +import {
5 + type ConnectMcpApprovalCall,
6 + ConnectMcpApprovalUnavailableError,
7 +} from "@t3tools/client-runtime/state/connectMcpApproval";
8 +import { type AuthMcpApprovalDetails, EnvironmentId } from "@t3tools/contracts";
9 import * as Result from "effect/Result";
10 import * as Schema from "effect/Schema";
7 -import { useEffect, useEffectEvent, useRef, useState } from "react";
11 +import { type ReactNode, useEffect, useEffectEvent, useRef, useState } from "react";
12
9 -import { approvedReturnUrl, readApproveAgentRequest } from "../../cloud/connectAgentApproval";
13 import { isElectron } from "../../env";
11 -import { mintConnectMcpApprovalCode } from "../../state/peerPairingCode";
14 +import { runConnectMcpApproval } from "../../state/connectMcpApproval";
15 import { resolveClerkSignInProps } from "../clerk/authRedirect";
16 import { Button } from "../ui/button";
17 import { Spinner } from "../ui/spinner";
18 import { StandalonePage, StandalonePageHeader } from "../ui/standalone-page";
19 +import {
20 + type McpApprovalAnswer,
21 + type McpApprovalTransport,
22 + McpConsent,
23 + readAuthorizationRequest,
24 +} from "./ConnectAgentSurface";
25
17 -const isConnectApprovalCodeError = Schema.is(ConnectApprovalCodeError);
26 +const isUnavailable = Schema.is(ConnectMcpApprovalUnavailableError);
27
19 -/** Signs in to T3 Connect, mints an app approval code, and returns it to the sign-in page. */
28 +function readEnvironmentId(): EnvironmentId | null {
29 + const value = new URL(window.location.href).searchParams.get("environment");
30 + return value ? EnvironmentId.make(value) : null;
31 +}
32 +
33 +/** Sends each call with the owner's T3 Connect session and remembers where the environment is. */
34 +function connectTransport(
35 + environmentId: EnvironmentId,
36 + onEnvironment: (environment: { readonly url: string; readonly label: string }) => void,
37 +): McpApprovalTransport {
38 + const send = async (
39 + call: ConnectMcpApprovalCall,
40 + ): Promise<McpApprovalAnswer<AuthMcpApprovalDetails>> => {
41 + const result = await runConnectMcpApproval(environmentId, call);
42 + if (Result.isFailure(result)) {
43 + return {
44 + kind: "error",
45 + message: isUnavailable(result.failure)
46 + ? result.failure.message
47 + : "Could not reach this environment. Try again.",
48 + };
49 + }
50 + onEnvironment({
51 + url: result.success.environmentUrl,
52 + label: result.success.environmentLabel,
53 + });
54 + const { answer } = result.success;
55 + switch (answer.kind) {
56 + case "details":
57 + return { kind: "ok", value: answer.details };
58 + case "redirect":
59 + return { kind: "redirect", url: answer.url };
60 + case "refused":
61 + return { kind: "error", message: answer.message };
62 + }
63 + };
64 + return {
65 + load: (authorization) => send({ kind: "approval", payload: authorization }),
66 + decide: (authorization, decision) =>
67 + send({ kind: "decision", payload: { authorization, decision } }),
68 + };
69 +}
70 +
71 +/**
72 + * The consent screen for an agent sign-in on a T3 Connect environment: the owner signs in to
73 + * T3 Connect here and approves with that session, so no sign-in code is needed.
74 + */
75 export function ApproveAgentSurface() {
21 - const [request] = useState(() => readApproveAgentRequest(new URL(window.location.href)));
76 + const [environmentId] = useState(readEnvironmentId);
77 + const [authorization] = useState(readAuthorizationRequest);
78 + // Another site could frame this page and steer a click onto Approve.
79 + const [framed] = useState(() => window.top !== window.self);
80 + const [environment, setEnvironment] = useState<{
81 + readonly url: string;
82 + readonly label: string;
83 + } | null>(null);
84 + const [transport] = useState(() =>
85 + environmentId === null ? null : connectTransport(environmentId, setEnvironment),
86 + );
87 const clerk = useClerk();
88 const { isLoaded, isSignedIn } = useAuth();
89 const session = useAtomValue(managedRelaySessionAtom);
25 - const [failure, setFailure] = useState<string | null>(null);
90 const signInOpened = useRef(false);
27 - const started = useRef(false);
91
92 const openSignIn = () =>
93 clerk.openSignIn(resolveClerkSignInProps(window.location.href, isElectron));
94 const openSignInOnLoad = useEffectEvent(openSignIn);
95
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
96 + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- opens Clerk sign-in once Clerk has loaded and nobody is signed in
97 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]);
98 + if (!isLoaded || isSignedIn || signInOpened.current || framed) return;
99 + signInOpened.current = true;
100 + openSignInOnLoad();
101 + }, [framed, isLoaded, isSignedIn]);
102
62 - if (!request) {
103 + if (environmentId === null || transport === null) {
104 + return (
105 + <Message
106 + title="This sign-in link is incomplete"
107 + description="Close this page and start the sign-in again from your agent."
108 + />
109 + );
110 + }
111 +
112 + if (framed) {
113 + return (
114 + <Message
115 + title="Open this page in its own window"
116 + description="For your safety, agent sign-ins cannot be approved inside another site."
117 + />
118 + );
119 + }
120 +
121 + if (!isLoaded || (isSignedIn && session === null)) {
122 return (
123 <StandalonePage>
124 <StandalonePageHeader
125 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."
126 + title="Connecting to T3 Connect"
127 + description="One moment while your account loads."
128 />
129 + <Spinner className="mt-6" size="lg" tone="muted" />
130 </StandalonePage>
131 );
132 }
133
74 - if (failure !== null) {
134 + if (!isSignedIn) {
135 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>
136 + <Message
137 + title="Sign in to approve"
138 + description="Sign in to T3 Connect with the account this environment is linked to."
139 + >
140 <div className="mt-6">
141 + <Button type="button" onClick={openSignIn}>
142 + Sign in
143 + </Button>
144 + </div>
145 + </Message>
146 + );
147 + }
148 +
149 + const search = new URLSearchParams(window.location.search);
150 + search.delete("environment");
151 + return (
152 + <McpConsent
153 + authorization={authorization}
154 + transport={transport}
155 + requireLevelChoice
156 + environmentLabel={environment?.label}
157 + footer={
158 + <div className="mt-6 flex flex-wrap gap-2">
159 + {environment ? (
160 + <Button
161 + size="sm"
162 + variant="link"
163 + render={
164 + <a href={`${new URL("/connect-agent", environment.url).toString()}?${search}`} />
165 + }
166 + >
167 + Use a sign-in code instead
168 + </Button>
169 + ) : null}
170 <Button
87 - type="button"
88 - variant="outline"
171 + size="sm"
172 + variant="link"
173 onClick={() => void clerk.signOut({ redirectUrl: window.location.href })}
174 + type="button"
175 >
176 Use another account
177 </Button>
178 </div>
94 - </StandalonePage>
95 - );
96 - }
179 + }
180 + />
181 + );
182 +}
183
184 +function Message({
185 + title,
186 + description,
187 + children,
188 +}: {
189 + readonly title: string;
190 + readonly description: string;
191 + readonly children?: ReactNode;
192 +}) {
193 return (
194 <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 - )}
195 + <StandalonePageHeader context="Agent sign-in" title={title} description={description} />
196 + {children}
197 </StandalonePage>
198 );
199 }
apps/web/src/components/auth/ConnectAgentSurface.logic.test.ts
+22 -1
@@ -1,7 +1,11 @@
1 import { expect, it } from "vite-plus/test";
2 import { AuthMcpClientAccess, RuntimeMode } from "@t3tools/contracts";
3
4 -import { resolveApprovalDecision, resolveMcpAccess } from "./ConnectAgentSurface.logic";
4 +import {
5 + agentRedirectUrl,
6 + resolveApprovalDecision,
7 + resolveMcpAccess,
8 +} from "./ConnectAgentSurface.logic";
9
10 it.each(RuntimeMode.literals)("keeps MCP access within the %s policy ceiling", (maxRuntimeMode) => {
11 const ceiling = { organization: "Example", maxRuntimeMode };
@@ -41,3 +45,20 @@ it("checks a typed code even in a signed-in browser, and approves without one at
45 });
46 expect(resolveApprovalDecision({ code: "", access, details: signedOut })).toBeNull();
47 });
48 +
49 +it("follows only https or loopback http redirects to an agent", () => {
50 + expect(agentRedirectUrl("https://www.cursor.com/cb?code=x")).toBe(
51 + "https://www.cursor.com/cb?code=x",
52 + );
53 + expect(agentRedirectUrl("http://localhost:51234/callback?code=x")).toBe(
54 + "http://localhost:51234/callback?code=x",
55 + );
56 + for (const url of [
57 + "javascript:alert(document.domain)",
58 + "data:text/html,hi",
59 + "http://evil.example/cb",
60 + "not a url",
61 + ]) {
62 + expect(agentRedirectUrl(url), url).toBeNull();
63 + }
64 +});
apps/web/src/components/auth/ConnectAgentSurface.logic.ts
+18
@@ -5,6 +5,7 @@ import {
5 isRuntimeModeAbove,
6 parseMcpApprovalCode,
7 } from "@t3tools/contracts";
8 +import { isLoopbackHost } from "@t3tools/shared/preview";
9
10 /**
11 * The picker's access, lowered to a managed ceiling: the user's choice, else Auto for a typed
@@ -45,3 +46,20 @@ export function resolveApprovalDecision(input: {
46 ? { _tag: "browser-session", access: input.access, csrfToken }
47 : null;
48 }
49 +
50 +/**
51 + * The address to send the window to after a decision, or null. Only https, or http on this
52 + * computer, can carry a sign-in to an agent; anything else, such as `javascript:`, is refused.
53 + */
54 +export function agentRedirectUrl(url: string): string | null {
55 + let parsed: URL;
56 + try {
57 + parsed = new URL(url);
58 + } catch {
59 + return null;
60 + }
61 + return parsed.protocol === "https:" ||
62 + (parsed.protocol === "http:" && isLoopbackHost(parsed.hostname))
63 + ? parsed.toString()
64 + : null;
65 +}
apps/web/src/components/auth/ConnectAgentSurface.tsx
+163 -147
@@ -16,19 +16,14 @@ 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";
19 import { PrimaryEnvironmentHttpClient } from "~/environments/primary/httpClient";
20 import { runPrimaryHttp } from "~/lib/runtime";
21 import { cn } from "~/lib/utils";
31 -import { resolveApprovalDecision, resolveMcpAccess } from "./ConnectAgentSurface.logic";
22 +import {
23 + agentRedirectUrl,
24 + resolveApprovalDecision,
25 + resolveMcpAccess,
26 +} from "./ConnectAgentSurface.logic";
27 import { runtimeModeConfig } from "../chat/runtimeModeConfig";
28 import { Alert, AlertDescription } from "../ui/alert";
29 import { Button } from "../ui/button";
@@ -49,6 +44,15 @@ export const accessConfig: Record<
44 ...runtimeModeConfig,
45 };
46
47 +const ARM_DELAY_MS = 700;
48 +const UNSAFE_REDIRECT = "The environment returned an address this page will not open.";
49 +
50 +function followRedirect(url: string): boolean {
51 + const safe = agentRedirectUrl(url);
52 + if (safe !== null) window.location.replace(safe);
53 + return safe !== null;
54 +}
55 +
56 function redirectsToThisComputer(redirectHost: string): boolean {
57 return isLoopbackHost(new URL(`http://${redirectHost}`).hostname);
58 }
@@ -61,143 +65,159 @@ type Loaded =
65 const UNREACHABLE = "Could not reach this environment. Try again.";
66 const isApprovalError = Schema.is(AuthMcpApprovalError);
67
64 -type Answer<A> =
68 +export type McpApprovalAnswer<A> =
69 | { readonly kind: "ok"; readonly value: A }
70 | { readonly kind: "redirect"; readonly url: string }
71 | { readonly kind: "error"; readonly message: string };
72
73 +/** Where the consent page reads the sign-in request and sends the decision. */
74 +export interface McpApprovalTransport {
75 + readonly load: (
76 + authorization: AuthMcpAuthorizationRequest,
77 + ) => Promise<McpApprovalAnswer<AuthMcpApprovalDetails>>;
78 + readonly decide: (
79 + authorization: AuthMcpAuthorizationRequest,
80 + decision: AuthMcpApprovalDecision,
81 + ) => Promise<McpApprovalAnswer<unknown>>;
82 +}
83 +
84 function runApproval<A>(
85 call: (
86 client: Context.Service.Shape<typeof PrimaryEnvironmentHttpClient>,
87 ) => Effect.Effect<A | { readonly redirectTo: string }, unknown>,
73 -): Promise<Answer<A>> {
88 +): Promise<McpApprovalAnswer<A>> {
89 return runPrimaryHttp(
90 PrimaryEnvironmentHttpClient.pipe(
91 Effect.flatMap(call),
77 - Effect.map((value): Answer<A> =>
92 + Effect.map((value): McpApprovalAnswer<A> =>
93 typeof value === "object" && value !== null && "redirectTo" in value
94 ? { kind: "redirect", url: value.redirectTo }
95 : { kind: "ok", value: value as A },
96 ),
97 Effect.catch((error) =>
83 - Effect.succeed<Answer<A>>({
98 + Effect.succeed<McpApprovalAnswer<A>>({
99 kind: "error",
100 message: isApprovalError(error) ? error.message : UNREACHABLE,
101 }),
102 ),
103 ),
89 - ).catch((): Answer<A> => ({ kind: "error", message: UNREACHABLE }));
104 + ).catch((): McpApprovalAnswer<A> => ({ kind: "error", message: UNREACHABLE }));
105 }
106
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 -}
107 +/** This environment's own page, approving with a code or this browser's session. */
108 +const primaryTransport: McpApprovalTransport = {
109 + load: (authorization) =>
110 + runApproval((client) => client.mcpOAuth.approval({ headers: {}, payload: authorization })),
111 + decide: (authorization, decision) =>
112 + runApproval((client) =>
113 + client.mcpOAuth.decision({ headers: {}, payload: { authorization, decision } }),
114 + ),
115 +};
116
117 const decodeAuthorizationRequest = Schema.decodeSync(AuthMcpAuthorizationRequest);
118
109 -function readAuthorizationRequest(): AuthMcpAuthorizationRequest {
119 +/** The agent's OAuth request from this page's query; other parameters are ignored. */
120 +export function readAuthorizationRequest(): AuthMcpAuthorizationRequest {
121 return decodeAuthorizationRequest(Object.fromEntries(new URL(window.location.href).searchParams));
122 }
123
124 export function ConnectAgentSurface() {
125 const [authorization] = useState(readAuthorizationRequest);
115 - const [connectReturn] = useState(() =>
116 - readConnectApprovalReturn(window.location.hash, window.location.search, readPendingApproval()),
117 - );
126 + return <McpConsent authorization={authorization} transport={primaryTransport} acceptsCode />;
127 +}
128 +
129 +/**
130 + * The consent screen for one agent sign-in. `acceptsCode` shows the sign-in code field;
131 + * `requireLevelChoice` starts with no level picked; `footer` sits under the actions.
132 + */
133 +export function McpConsent({
134 + authorization,
135 + transport,
136 + acceptsCode = false,
137 + requireLevelChoice = false,
138 + environmentLabel,
139 + footer,
140 +}: {
141 + readonly authorization: AuthMcpAuthorizationRequest;
142 + readonly transport: McpApprovalTransport;
143 + readonly acceptsCode?: boolean;
144 + readonly requireLevelChoice?: boolean;
145 + readonly environmentLabel?: string | undefined;
146 + readonly footer?: ReactNode;
147 +}) {
148 const [loaded, setLoaded] = useState<Loaded>({ status: "loading" });
149 const [requestedAccess, setAccess] = useState<AuthMcpClientAccess | null>(null);
150 const [pairingCode, setPairingCode] = useState("");
121 - const access = resolveMcpAccess(
122 - requestedAccess,
123 - loaded.status === "ready" ? loaded.details.runtimeModeCeiling : undefined,
124 - pairingCode.trim().length > 0,
125 - );
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 - );
151 + const [armed, setArmed] = useState(false);
152 + const access =
153 + requireLevelChoice && requestedAccess === null
154 + ? null
155 + : resolveMcpAccess(
156 + requestedAccess,
157 + loaded.status === "ready" ? loaded.details.runtimeModeCeiling : undefined,
158 + pairingCode.trim().length > 0,
159 + );
160 + const [errorMessage, setErrorMessage] = useState("");
161 const [pending, setPending] = useState<"approve" | "deny" | null>(null);
162
163 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- fetches the MCP OAuth approval and redirects the window or stores details, ignoring stale answers
164 useEffect(() => {
165 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;
144 - if (answer.kind === "redirect") {
145 - window.location.replace(answer.url);
146 - return;
147 - }
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 - );
166 + void transport.load(authorization).then((answer) => {
167 + if (cancelled) return;
168 + if (answer.kind === "redirect") {
169 + if (!followRedirect(answer.url)) setLoaded({ status: "invalid", message: UNSAFE_REDIRECT });
170 + return;
171 + }
172 + setLoaded(
173 + answer.kind === "error"
174 + ? { status: "invalid", message: answer.message }
175 + : { status: "ready", details: answer.value },
176 + );
177 + });
178 return () => {
179 cancelled = true;
180 };
174 - }, [authorization, connectReturn]);
181 + }, [authorization, transport]);
182
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 - };
183 + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps Approve off briefly after the page shows or regains focus, so a click aimed at another window cannot land on it
184 + useEffect(() => {
185 + if (loaded.status !== "ready") return;
186 + let timer = window.setTimeout(() => setArmed(true), ARM_DELAY_MS);
187 + const rearm = () => {
188 + setArmed(false);
189 + window.clearTimeout(timer);
190 + timer = window.setTimeout(() => setArmed(true), ARM_DELAY_MS);
191 + };
192 + window.addEventListener("focus", rearm);
193 + document.addEventListener("visibilitychange", rearm);
194 + return () => {
195 + window.clearTimeout(timer);
196 + window.removeEventListener("focus", rearm);
197 + document.removeEventListener("visibilitychange", rearm);
198 + };
199 + }, [loaded.status]);
200
201 const decide = async (choice: "approve" | "deny", details: AuthMcpApprovalDetails) => {
202 const decision: AuthMcpApprovalDecision | null =
203 choice === "deny"
204 ? { _tag: "deny" }
193 - : resolveApprovalDecision({ code: pairingCode, access, details });
205 + : access === null
206 + ? null
207 + : resolveApprovalDecision({ code: pairingCode, access, details });
208 if (decision === null) return;
209 setPending(choice);
210 setErrorMessage("");
197 - const message = await submitDecision(authorization, decision);
198 - if (message === null) return;
211 + const answer = await transport.decide(authorization, decision);
212 + if (answer.kind === "redirect" && followRedirect(answer.url)) return;
213 setPending(null);
200 - setErrorMessage(message);
214 + setErrorMessage(
215 + answer.kind === "error"
216 + ? answer.message
217 + : answer.kind === "redirect"
218 + ? UNSAFE_REDIRECT
219 + : "The sign-in could not continue.",
220 + );
221 };
222
223 if (loaded.status === "loading") {
@@ -219,41 +239,20 @@ export function ConnectAgentSurface() {
239 <p className="mt-4 text-sm text-muted-foreground">
240 Close this page and start the sign-in again from your agent.
241 </p>
242 + {footer}
243 </StandalonePage>
244 );
245 }
246
247 const { details } = loaded;
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;
248 + const canApprove =
249 + armed &&
250 + pending === null &&
251 + access !== null &&
252 + resolveApprovalDecision({ code: pairingCode, access, details }) !== null;
253 // A code from "Use T3 Code in another app" names its level, so the page does not ask again.
254 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 - );
255 + const approveLevel = codeAccess ?? access;
256
257 return (
258 <StandalonePage>
@@ -262,7 +261,10 @@ export function ConnectAgentSurface() {
261 description={
262 <>
263 This agent wants to use the threads in every project on{" "}
265 - <span className="font-medium text-foreground">{details.environmentHost}</span>.
264 + <span className="font-medium text-foreground">
265 + {environmentLabel ?? details.environmentHost}
266 + </span>
267 + {environmentLabel ? ` (${details.environmentHost})` : null}.
268 </>
269 }
270 />
@@ -279,7 +281,12 @@ export function ConnectAgentSurface() {
281 {" "}
282 on the computer that opened this page
283 </span>
282 - ) : null}
284 + ) : (
285 + <span className="font-normal text-muted-foreground">
286 + {" "}
287 + · whoever runs it gets this access
288 + </span>
289 + )}
290 </dd>
291 </dl>
292 <p className="mt-2 text-xs text-muted-foreground">Only approve a sign-in you just started.</p>
@@ -291,7 +298,29 @@ export function ConnectAgentSurface() {
298 if (canApprove) void decide("approve", details);
299 }}
300 >
294 - {details.connectSignIn ? null : codeField}
301 + {acceptsCode ? (
302 + <div className="space-y-2">
303 + <label className="text-sm font-medium" htmlFor="connect-agent-pairing-code">
304 + Sign-in code
305 + </label>
306 + <Input
307 + id="connect-agent-pairing-code"
308 + autoCapitalize="none"
309 + autoComplete="one-time-code"
310 + autoCorrect="off"
311 + disabled={pending !== null}
312 + nativeInput
313 + onChange={(event) => setPairingCode(event.currentTarget.value)}
314 + placeholder="Paste a code"
315 + spellCheck={false}
316 + value={pairingCode}
317 + />
318 + <p className="text-xs text-muted-foreground">
319 + Get one from Use T3 Code in another app (MCP), Settings → Sharing & access, or{" "}
320 + <code>t3 auth pairing create</code> on this machine.
321 + </p>
322 + </div>
323 + ) : null}
324
325 {codeAccess ? (
326 <p className="text-sm">
@@ -331,25 +360,13 @@ export function ConnectAgentSurface() {
360 ) : null}
361
362 <div className="flex flex-wrap gap-2">
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 - )}
363 + <Button disabled={!canApprove} type="submit">
364 + {pending === "approve"
365 + ? "Approving…"
366 + : approveLevel === null
367 + ? "Choose what it may do"
368 + : `Approve ${accessConfig[approveLevel].label}`}
369 + </Button>
370 <Button
371 disabled={pending !== null}
372 onClick={() => void decide("deny", details)}
@@ -359,9 +376,8 @@ export function ConnectAgentSurface() {
376 {pending === "deny" ? "Denying…" : "Deny"}
377 </Button>
378 </div>
362 -
363 - {details.connectSignIn ? codeField : null}
379 </form>
380 + {footer}
381 </StandalonePage>
382 );
383 }
apps/web/src/components/mcp/UseInAnotherAppDialog.tsx
+34 -21
@@ -103,6 +103,7 @@ function UseInAnotherAppDialog({ requested }: { readonly requested: EnvironmentI
103 }
104
105 const STEPS = ["App", "Access", "Connect"] as const;
106 +const HOSTED_APPROVAL_STEPS = ["App", "Connect"] as const;
107 type Step = 0 | 1 | 2;
108 type Choice = McpApp | "other";
109
@@ -120,16 +121,22 @@ function Wizard({
121 const [picked, setPicked] = useState<AuthMcpClientAccess | null>(null);
122 const access = picked ?? DEFAULT_LEVELS.find((level) => levels.get(level) === undefined) ?? null;
123 const open = gate.gate.kind === "open";
124 + // The level is picked on the sign-in page, so the wizard neither asks for it nor needs a code.
125 + const hostedApproval =
126 + environment.serverConfig?.environment.capabilities.mcpHostedApproval === true;
127 + const steps = hostedApproval ? HOSTED_APPROVAL_STEPS : STEPS;
128 + const shownStep = hostedApproval && step === 2 ? 1 : step;
129 + const next = () => setStep(step === 0 ? (hostedApproval ? 2 : 1) : 2);
130 const appName = choice === null || choice === "other" ? "the app" : choice.name;
131 return (
132 <>
133 <WizardHeader title={title}>
134 {open ? (
135 <WizardSteps
129 - steps={STEPS}
130 - currentStep={step}
131 - isStepDisabled={(index) => index > step}
132 - onStepChange={(index) => setStep(index as Step)}
136 + steps={steps}
137 + currentStep={shownStep}
138 + isStepDisabled={(index) => index > shownStep}
139 + onStepChange={(index) => setStep(hostedApproval && index === 1 ? 2 : (index as Step))}
140 />
141 ) : null}
142 </WizardHeader>
@@ -159,12 +166,12 @@ function Wizard({
166 ))}
167 </RadioGroup>
168 </section>
162 - ) : choice !== null && access !== null ? (
169 + ) : choice !== null && (hostedApproval || access !== null) ? (
170 <ConnectStep
171 environment={environment}
172 mcpUrl={gate.gate.mcpUrl}
173 choice={choice}
167 - access={access}
174 + access={hostedApproval ? null : access}
175 />
176 ) : null}
177 </WizardPanel>
@@ -180,10 +187,7 @@ function Wizard({
187 {step === 2 ? (
188 <Button onClick={close}>Done</Button>
189 ) : (
183 - <Button
184 - disabled={step === 0 ? choice === null : access === null}
185 - onClick={() => setStep(step === 0 ? 1 : 2)}
186 - >
190 + <Button disabled={step === 0 ? choice === null : access === null} onClick={next}>
191 Next
192 </Button>
193 )}
@@ -554,18 +558,25 @@ function ConnectStep({
558 readonly environment: EnvironmentPresentation;
559 readonly mcpUrl: string;
560 readonly choice: Choice;
557 - readonly access: AuthMcpClientAccess;
561 + /** Null when the sign-in page asks for the level, so no code is needed. */
562 + readonly access: AuthMcpClientAccess | null;
563 }) {
564 const [anotherWay, setAnotherWay] = useState(choice === "other");
565 const app = choice === "other" ? null : choice;
561 - const code = (
562 - <ApprovalCode
563 - key={access}
564 - environmentId={environment.environmentId}
565 - name={environment.label}
566 - access={access}
567 - />
568 - );
566 + const code =
567 + access === null ? (
568 + <p className="text-sm text-muted-foreground">
569 + When {app?.name ?? "the app"} opens the sign-in page, choose what it may do and approve with
570 + your T3 Connect account.
571 + </p>
572 + ) : (
573 + <ApprovalCode
574 + key={access}
575 + environmentId={environment.environmentId}
576 + name={environment.label}
577 + access={access}
578 + />
579 + );
580 if (anotherWay || app === null) {
581 const message = app?.handoff.kind === "copy-message" ? app.handoff.message(mcpUrl) : null;
582 return (
@@ -773,7 +784,8 @@ function LinkedLine({
784 access,
785 }: {
786 readonly environment: EnvironmentPresentation;
776 - readonly access: AuthMcpClientAccess;
787 + /** Null when the level is picked later; each link then shows its own. */
788 + readonly access: AuthMcpClientAccess | null;
789 }) {
790 const offered = offersLinkedEnvironments(environment.serverConfig);
791 const links = useEnvironmentQuery(
@@ -788,7 +800,8 @@ function LinkedLine({
800 identities.find((identity) => identity.environmentId === link.environmentId)?.label ??
801 link.label;
802 // A forwarded call keeps the lower of the app's level and the link's own.
791 - const level = levelRank(link.access) < levelRank(access) ? link.access : access;
803 + const level =
804 + access === null || levelRank(link.access) < levelRank(access) ? link.access : access;
805 return `${name} · ${link.status === "expired" ? "Expired" : accessConfig[level].label}`;
806 });
807 return <p className="text-xs text-muted-foreground">Linked: {named.join(", ")}</p>;
apps/web/src/state/connectMcpApproval.ts new
+23
@@ -0,0 +1,23 @@
1 +import {
2 + type ConnectMcpApprovalCall,
3 + createConnectMcpApprovalCommand,
4 +} from "@t3tools/client-runtime/state/connectMcpApproval";
5 +import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
6 +import type { EnvironmentId } from "@t3tools/contracts";
7 +import * as Result from "effect/Result";
8 +
9 +import { connectionAtomRuntime } from "../connection/runtime";
10 +import { appAtomRegistry } from "../rpc/atomRegistry";
11 +
12 +const connectMcpApproval = createConnectMcpApprovalCommand(connectionAtomRuntime);
13 +
14 +/** One agent sign-in call to `environmentId`, sent with this account's T3 Connect session. */
15 +export async function runConnectMcpApproval(
16 + environmentId: EnvironmentId,
17 + call: ConnectMcpApprovalCall,
18 +) {
19 + const result = await connectMcpApproval.run(appAtomRegistry, { environmentId, call });
20 + return result._tag === "Success"
21 + ? Result.succeed(result.value)
22 + : Result.fail(squashAtomCommandFailure(result));
23 +}
apps/web/src/state/peerPairingCode.ts
-17
@@ -1,5 +1,4 @@
1 import {
2 - createConnectMcpApprovalCodeCommand,
2 createMcpApprovalCodeCommand,
3 createPeerPairingCodeCommand,
4 } from "@t3tools/client-runtime/state/peerPairingCode";
@@ -16,7 +15,6 @@ import { appAtomRegistry } from "../rpc/atomRegistry";
15
16 const mintPairingCode = createPeerPairingCodeCommand(connectionAtomRuntime);
17 const mintMcpApprovalCode = createMcpApprovalCodeCommand(connectionAtomRuntime);
19 -const connectMcpApprovalCodeCommand = createConnectMcpApprovalCodeCommand(connectionAtomRuntime);
18
19 /**
20 * A fresh pairing code minted on `environmentId` with this client's session
@@ -43,18 +41,3 @@ export async function mintMcpApprovalCodeOn(
41 ? Result.succeed(result.value)
42 : Result.fail(squashAtomCommandFailure(result));
43 }
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
+15 -14
@@ -10,15 +10,16 @@ in once, and you choose what it may do.
10
11 Open the command palette (`Cmd/Ctrl+K`) and choose **Use T3 Code in another
12 app (MCP)**, or use the button in **Settings → Sharing & access**. Pick the
13 -app, choose what it may do, and follow the step for that app. Assistants like
13 +app and follow the step for that app. Assistants like
14 Poke and Claude run in the cloud, so the wizard first asks you to sign in to T3
15 Connect and turn it on for the environment. To reach your other machines through
16 the same connection, turn on **Linked environments** in Labs and
17 [link them](./remote-access.md#link-another-environment).
18
19 -When the app opens the sign-in page, choose **Get code** in the wizard and paste
20 -the code there. A code works once, for 5 minutes, and approves only the level
21 -you chose.
19 +When the app opens the sign-in page, choose what it may do and approve with your
20 +T3 Connect account. On an older environment, the wizard asks for the level and
21 +gives you a code to paste instead. A code works once, for 5 minutes, and
22 +approves only that level.
23
24 For an app that is not listed, choose **Something else…**, add a remote MCP
25 server with OAuth in that app, and paste the URL. Apps that require their own
@@ -51,22 +52,22 @@ device is connected over, so an agent on the same device can reach it.
52
53 ## Approve a sign-in
54
54 -The first time an agent connects, it opens a sign-in page on the environment.
55 -The page names the agent and where its access goes:
55 +The first time an agent connects, it opens a sign-in page. When the agent
56 +reaches the environment through T3 Connect, the page opens on the T3 Code web
57 +app: sign in with the T3 Connect account the environment is linked to and
58 +approve there, without a code. Otherwise the page opens on the environment.
59 +Either page names the agent and where its access goes:
60
61 - For an agent on your computer, approval returns to a `localhost` address on
62 the computer that opened the page.
63 - For a hosted agent, approval goes to that service, such as `chatgpt.com`.
64 Anyone who runs that service gets the access.
65
62 -Only approve a sign-in you just started. To approve, enter a code from
63 -**Use T3 Code in another app (MCP)**, **Settings → Sharing & access**, or
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.
66 +Only approve a sign-in you just started. On the environment's own page, enter a
67 +code from **Use T3 Code in another app (MCP)**, **Settings → Sharing & access**,
68 +or `t3 auth pairing create` on the host. A browser already signed in to the
69 +environment with permission to manage access can approve without a code. On the
70 +web app, **Use a sign-in code instead** opens the environment's own page.
71
72 A code from **Use T3 Code in another app (MCP)** already carries the level you
73 picked there. With another code, choose what the agent may do here: **Auto** is
packages/client-runtime/package.json
+4
@@ -243,6 +243,10 @@
243 "types": "./src/state/environmentHttpAuth.ts",
244 "default": "./src/state/environmentHttpAuth.ts"
245 },
246 + "./state/connectMcpApproval": {
247 + "types": "./src/state/connectMcpApproval.ts",
248 + "default": "./src/state/connectMcpApproval.ts"
249 + },
250 "./state/peerPairingCode": {
251 "types": "./src/state/peerPairingCode.ts",
252 "default": "./src/state/peerPairingCode.ts"
packages/client-runtime/src/state/connectMcpApproval.ts new
+122
@@ -0,0 +1,122 @@
1 +/**
2 + * The hosted app's side of an agent sign-in on a T3 Connect environment: it reads the request
3 + * and sends the decision with the owner's own Connect session there, so no code is needed.
4 + */
5 +import type {
6 + AuthMcpApprovalDecisionRequest,
7 + AuthMcpApprovalDetails,
8 + AuthMcpAuthorizationRequest,
9 + EnvironmentId,
10 +} from "@t3tools/contracts";
11 +import * as Effect from "effect/Effect";
12 +import type * as HttpClient from "effect/http/HttpClient";
13 +import type { Atom } from "effect/reactivity";
14 +import * as Schema from "effect/Schema";
15 +
16 +import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
17 +import { RelayConnectionTarget } from "../connection/model.ts";
18 +import * as ManagedRelay from "../relay/managedRelay.ts";
19 +import { executeAuthenticatedEnvironmentHttpRequest } from "./environmentHttpAuth.ts";
20 +import { createRuntimeCommand } from "./runtime.ts";
21 +
22 +const REQUEST_TIMEOUT_MS = 10_000;
23 +
24 +/** The environment cannot be reached through T3 Connect with this account. */
25 +export class ConnectMcpApprovalUnavailableError extends Schema.TaggedError<ConnectMcpApprovalUnavailableError>()(
26 + "ConnectMcpApprovalUnavailableError",
27 + { cause: Schema.Defect() },
28 +) {
29 + override get message(): string {
30 + return "Could not reach that environment through T3 Connect with this account.";
31 + }
32 +}
33 +
34 +export type ConnectMcpApprovalAnswer =
35 + | { readonly kind: "details"; readonly details: AuthMcpApprovalDetails }
36 + | { readonly kind: "redirect"; readonly url: string }
37 + /** The environment refused the request, with a message for the user. */
38 + | { readonly kind: "refused"; readonly message: string };
39 +
40 +export type ConnectMcpApprovalCall =
41 + | { readonly kind: "approval"; readonly payload: AuthMcpAuthorizationRequest }
42 + | { readonly kind: "decision"; readonly payload: AuthMcpApprovalDecisionRequest };
43 +
44 +const answerFrom = (
45 + value: AuthMcpApprovalDetails | { readonly redirectTo: string },
46 +): ConnectMcpApprovalAnswer =>
47 + "redirectTo" in value
48 + ? { kind: "redirect", url: value.redirectTo }
49 + : { kind: "details", details: value };
50 +
51 +const refused = (error: { readonly message: string }) =>
52 + Effect.succeed<ConnectMcpApprovalAnswer>({ kind: "refused", message: error.message });
53 +
54 +/**
55 + * Sends one approval call to `environmentId` with this account's T3 Connect session. Its
56 + * address comes from the relay, which only grants access to the environment's owner.
57 + */
58 +const callConnectMcpApproval = Effect.fn("clientRuntime.state.connectMcpApproval")(
59 + function* (input: {
60 + readonly environmentId: EnvironmentId;
61 + readonly call: ConnectMcpApprovalCall;
62 + }) {
63 + const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
64 + const authorized = yield* remote.authorizeDpopHttp({
65 + expectedEnvironmentId: input.environmentId,
66 + });
67 + const common = {
68 + prepared: {
69 + environmentId: input.environmentId,
70 + httpBaseUrl: authorized.httpBaseUrl,
71 + httpAuthorization: authorized.httpAuthorization,
72 + target: new RelayConnectionTarget({
73 + environmentId: input.environmentId,
74 + label: authorized.label,
75 + }),
76 + },
77 + signer: yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner),
78 + remoteAuthorization: yield* Effect.serviceOption(
79 + RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,
80 + ),
81 + group: "mcpOAuth",
82 + method: "POST",
83 + timeoutMs: REQUEST_TIMEOUT_MS,
84 + } as const;
85 + const { call } = input;
86 + const answer =
87 + call.kind === "approval"
88 + ? yield* executeAuthenticatedEnvironmentHttpRequest({
89 + ...common,
90 + url: (urls) => urls.approval(),
91 + request: ({ client, headers }) =>
92 + client
93 + .approval({ headers, payload: call.payload })
94 + .pipe(Effect.map(answerFrom), Effect.catchTags({ AuthMcpApprovalError: refused })),
95 + // The owner's session can always approve; no CSRF token means a stale credential.
96 + isUnauthorizedResponse: (answer) =>
97 + answer.kind === "details" && answer.details.csrfToken === undefined,
98 + })
99 + : yield* executeAuthenticatedEnvironmentHttpRequest({
100 + ...common,
101 + url: (urls) => urls.decision(),
102 + request: ({ client, headers }) =>
103 + client
104 + .decision({ headers, payload: call.payload })
105 + .pipe(Effect.map(answerFrom), Effect.catchTags({ AuthMcpApprovalError: refused })),
106 + });
107 + return { answer, environmentUrl: authorized.httpBaseUrl, environmentLabel: authorized.label };
108 + },
109 + Effect.mapError((cause) => new ConnectMcpApprovalUnavailableError({ cause })),
110 +);
111 +
112 +export function createConnectMcpApprovalCommand<R, E>(
113 + runtime: Atom.AtomRuntime<
114 + RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization | HttpClient.HttpClient | R,
115 + E
116 + >,
117 +) {
118 + return createRuntimeCommand(runtime, {
119 + label: "environment-data:connect-mcp-approval",
120 + execute: callConnectMcpApproval,
121 + });
122 +}
packages/client-runtime/src/state/peerPairingCode.test.ts deleted
-86
@@ -1,86 +0,0 @@
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
+3 -78
@@ -8,7 +8,6 @@ import {
8 type AuthCreatePairingCredentialInput,
9 type AuthMcpClientAccess,
10 type AuthPairingCredentialResult,
11 - type EnvironmentId,
11 mcpClientScopes,
12 } from "@t3tools/contracts";
13 import * as Schema from "effect/Schema";
@@ -19,12 +18,12 @@ import type { Atom } from "effect/reactivity";
18 import * as SubscriptionRef from "effect/SubscriptionRef";
19
20 import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
22 -import { type PreparedConnection, RelayConnectionTarget } from "../connection/model.ts";
21 +import type { PreparedConnection } from "../connection/model.ts";
22 import type { EnvironmentRegistry } from "../connection/registry.ts";
23 import * as EnvironmentSupervisor from "../connection/supervisor.ts";
24 import * as ManagedRelay from "../relay/managedRelay.ts";
25 import { executeAuthenticatedEnvironmentHttpRequest } from "./environmentHttpAuth.ts";
27 -import { createEnvironmentCommand, createRuntimeCommand } from "./runtime.ts";
26 +import { createEnvironmentCommand } from "./runtime.ts";
27
28 const MINT_TIMEOUT_MS = 8_000;
29 const PEER_PAIRING_CODE_LABEL = "T3 Code link";
@@ -45,30 +44,8 @@ export class PeerPairingCodeError extends Schema.TaggedError<PeerPairingCodeErro
44 }
45 }
46
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 -
47 const mintPairingCredential = Effect.fn("clientRuntime.state.mintPairingCredential")(function* (
68 - prepared: Pick<
69 - PreparedConnection,
70 - "environmentId" | "httpBaseUrl" | "httpAuthorization" | "target"
71 - >,
48 + prepared: PreparedConnection,
49 payload: AuthCreatePairingCredentialInput,
50 ): Effect.fn.Return<AuthPairingCredentialResult, PeerPairingCodeError, HttpClient.HttpClient> {
51 const signer = yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner);
@@ -142,55 +119,3 @@ export function createMcpApprovalCodeCommand<R, E>(
119 mintOnEnvironment({ label: MCP_APPROVAL_CODE_LABEL, access }),
120 });
121 }
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,7 +6,6 @@ import {
6 ForwardCompatibleArray,
7 ClientSurface,
8 ClientWebDeployment,
9 - EnvironmentId,
9 TrimmedNonEmptyString,
10 } from "./baseSchemas.ts";
11 import { RuntimeMode } from "./providerPolicy.ts";
@@ -544,10 +543,6 @@ export const AuthMcpApprovalDetails = Schema.Struct({
543 csrfToken: Schema.optionalKey(Schema.String),
544 /** Only scopes held by this session qualify; others need a pairing code. Absent with `csrfToken`. */
545 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 - ),
546 /** A managed policy's runtime-mode ceiling; the page loads without the server's config. */
547 runtimeModeCeiling: Schema.optionalKey(
548 Schema.Struct({ organization: Schema.String, maxRuntimeMode: RuntimeMode }),
packages/contracts/src/environment.ts
+2
@@ -171,6 +171,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
171 linkFence: Schema.optionalKey(Schema.Boolean),
172 /** Mints pairing codes that approve one agent sign-in at a set level (`AUTO-…`). */
173 mcpApprovalCodes: Schema.optionalKey(Schema.Boolean),
174 + /** Agent sign-ins on its T3 Connect address are approved on the hosted app, without a code. */
175 + mcpHostedApproval: Schema.optionalKey(Schema.Boolean),
176 /** Server answers server.prepareTriage. */
177 triage: Schema.optionalKey(Schema.Boolean),
178 /** Server accepts `{ type: "once" }` scheduled tasks; older servers reject them on save. */
packages/contracts/src/environmentHttp.ts
+4
@@ -653,6 +653,8 @@ class EnvironmentMcpOAuthHttpApi extends HttpApiGroup.make("mcpOAuth")
653 .add(HttpApiEndpoint.get("authorize", "/oauth/mcp/authorize"))
654 .add(
655 HttpApiEndpoint.post("approval", "/oauth/mcp/approval", {
656 + // The hosted app sends the owner's T3 Connect credential; the environment's own page uses its cookie.
657 + headers: OptionalBearerHeaders,
658 payload: AuthMcpAuthorizationRequest,
659 success: [AuthMcpApprovalDetails, AuthMcpApprovalRedirect],
660 error: AuthMcpApprovalError,
@@ -660,6 +662,8 @@ class EnvironmentMcpOAuthHttpApi extends HttpApiGroup.make("mcpOAuth")
662 )
663 .add(
664 HttpApiEndpoint.post("decision", "/oauth/mcp/decision", {
665 + // The hosted app sends the owner's T3 Connect credential; the environment's own page uses its cookie.
666 + headers: OptionalBearerHeaders,
667 payload: AuthMcpApprovalDecisionRequest,
668 success: AuthMcpApprovalRedirect,
669 error: AuthMcpApprovalError,