Skip to content

Commit a8edf49

Browse files
feat: approve agent sign-ins on app.t3.codes with T3 Connect
An agent sign-in that reaches an environment through its T3 Connect address now goes straight to a consent page on the hosted app. The owner signs in to T3 Connect there, sees the app, where its access goes and the environment, picks a level, and approves; the hosted app sends the decision to the environment through the relay with the owner's Connect credential, and the browser returns to the agent. No code, no round-trip. The environment accepts that credential the way it accepts a browser session with access:write. The "Use T3 Code in another app" wizard drops the level step and code when the server supports this. Tailscale, LAN and localhost keep sign-in codes. Replaces the code round-trip from #33600. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent bbdc7dc commit a8edf49

24 files changed

Lines changed: 666 additions & 707 deletions

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

Lines changed: 0 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -572,9 +572,6 @@ export class EnvironmentAuth extends Context.Service<
572572
AuthMcpClientAccess,
573573
ServerAuthMcpApprovalCodeError | ServerAuthInternalError
574574
>;
575-
readonly authenticateBrowserSession: (
576-
request: HttpServerRequest.HttpServerRequest,
577-
) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
578575
}
579576
>()("t3/auth/EnvironmentAuth") {}
580577

@@ -1362,22 +1359,6 @@ export const make = Effect.gen(function* () {
13621359
Effect.withSpan("EnvironmentAuth.issueMcpClientSession"),
13631360
);
13641361

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-
13811362
const consumeMcpApprovalCode: EnvironmentAuth["Service"]["consumeMcpApprovalCode"] = (
13821363
code,
13831364
access,
@@ -1430,7 +1411,6 @@ export const make = Effect.gen(function* () {
14301411
authenticateMcpClient,
14311412
issueMcpClientSession,
14321413
consumeMcpApprovalCode,
1433-
authenticateBrowserSession,
14341414
});
14351415
});
14361416

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

Lines changed: 63 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -130,10 +130,18 @@ const withRoutes = <A, E>(
130130

131131
const json = <A>(response: Response) => Effect.promise(() => response.json() as Promise<A>);
132132

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) =>
134135
at(path, {
135136
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+
},
137145
body: encodeJson(body),
138146
});
139147

@@ -610,26 +618,47 @@ it.live("an app approval code approves only an app sign-in, at its own level", (
610618
),
611619
);
612620

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+
}),
633662
);
634663

635664
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
701730
reader,
702731
);
703732
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));
704745
}),
705746
),
706747
);

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

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,8 @@ export class McpOAuth extends Context.Service<
206206
readonly urls: McpOAuthUrls;
207207
readonly request: AuthMcpAuthorizationRequest;
208208
}) => 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: (
210211
request: HttpServerRequest.HttpServerRequest,
211212
authorization: AuthorizationRequest,
212213
) => Effect.Effect<
@@ -406,11 +407,8 @@ const make = Effect.gen(function* () {
406407
} satisfies AuthorizationRequest;
407408
});
408409

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(
414412
Effect.flatMap((session) =>
415413
// Approving manages access, and a session may only hand out scopes it holds.
416414
session.scopes.includes(AuthAccessWriteScope) &&
@@ -470,7 +468,7 @@ const make = Effect.gen(function* () {
470468
),
471469
);
472470
} else {
473-
const session = yield* approvingBrowserSession(input.request, input.authorization);
471+
const session = yield* approvingSession(input.request, input.authorization);
474472
if (
475473
session === undefined ||
476474
!timingSafeEqualBase64Url(decision.csrfToken, session.csrfToken) ||
@@ -574,7 +572,7 @@ const make = Effect.gen(function* () {
574572
: { organization: managedPolicy.organization, maxRuntimeMode },
575573
register,
576574
validateAuthorization,
577-
approvingBrowserSession,
575+
approvingSession,
578576
approve,
579577
deny,
580578
exchangeCode,

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

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,13 @@ import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
1616
import { DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth";
1717

1818
import * as CloudLink from "../cloud/CloudLink.ts";
19-
import { hostedAppUrlConfig } from "../cloud/publicConfig.ts";
19+
import { agentApprovalAppUrlConfig } from "../cloud/publicConfig.ts";
2020
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
2121
import * as McpOAuth from "./McpOAuth.ts";
2222
import { renderErrorPage } from "./mcpOAuthHtml.ts";
2323

2424
const APPROVAL_PAGE_PATH = "/connect-agent";
25+
const HOSTED_APPROVAL_PATH = "/approve-agent";
2526

2627
const PAGE_HEADERS = {
2728
"content-security-policy":
@@ -70,16 +71,21 @@ export const layer = HttpApiBuilder.group(
7071
const oauth = yield* McpOAuth.McpOAuth;
7172
const cloudLink = yield* CloudLink.CloudLink;
7273
const serverEnvironment = yield* ServerEnvironment.ServerEnvironmentIdentity;
73-
const hostedAppUrl = yield* hostedAppUrlConfig.pipe(
74+
const hostedAppUrl = yield* agentApprovalAppUrlConfig.pipe(
7475
Effect.orElseSucceed(() => DEFAULT_HOSTED_APP_URL),
7576
);
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) =>
7879
cloudLink.linkState().pipe(
7980
Effect.flatMap((state) =>
8081
state.linked && !state.linkRevoked && state.tunnelHostname === new URL(issuer).hostname
8182
? 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+
}),
8389
)
8490
: Effect.succeedNone,
8591
),
@@ -119,7 +125,14 @@ export const layer = HttpApiBuilder.group(
119125
.pipe(Effect.result);
120126
const headers = { "cache-control": "no-store", "referrer-policy": "no-referrer" };
121127
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+
);
123136
}
124137
const error = authorization.failure;
125138
return error._tag === "McpOAuthPageError"
@@ -138,11 +151,7 @@ export const layer = HttpApiBuilder.group(
138151
const resolved = yield* forwardedAuthorization(oauth, payload);
139152
if ("redirectTo" in resolved) return resolved;
140153
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);
146155
yield* noStore;
147156
return {
148157
clientName: resolved.client.name,
@@ -151,7 +160,6 @@ export const layer = HttpApiBuilder.group(
151160
...(oauth.runtimeModeCeiling === undefined
152161
? {}
153162
: { runtimeModeCeiling: oauth.runtimeModeCeiling }),
154-
...(Option.isSome(connect) ? { connectSignIn: connect.value } : {}),
155163
...(session === undefined
156164
? {}
157165
: {

‎apps/server/src/cloud/publicConfig.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import * as Schema from "effect/Schema";
1313
import * as SchemaIssue from "effect/SchemaIssue";
1414

1515
declare const __T3CODE_BUILD_RELAY_URL__: string | undefined;
16+
declare const __T3CODE_BUILD_CHANNEL__: "nightly" | "latest" | undefined;
1617
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
1718
declare const __T3CODE_BUILD_CLERK_CLI_OAUTH_CLIENT_ID__: string | undefined;
1819
declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_URL__: string | undefined;
@@ -114,6 +115,19 @@ export const hostedAppUrlConfig = makePublicValueConfig(
114115
DEFAULT_HOSTED_APP_URL,
115116
).pipe(Config.mapEffect(validateHostedAppUrl));
116117

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+
117131
function validateHostedAppUrl(value: string) {
118132
try {
119133
const url = new URL(value);

‎apps/server/src/environment/ServerEnvironment.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,7 @@ export const make = Effect.gen(function* () {
289289
mcpModeLimitHeader: true,
290290
linkFence: true,
291291
mcpApprovalCodes: true,
292+
mcpHostedApproval: true,
292293
},
293294
};
294295

‎apps/server/src/peer/PeerLinks.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,7 @@ const make = Effect.gen(function* () {
309309
const resource = `${origin}/mcp`;
310310
const decided = yield* client.mcpOAuth
311311
.decision({
312+
headers: {},
312313
payload: {
313314
authorization: {
314315
response_type: "code",

‎apps/web/src/cloud/connectAgentApproval.test.ts‎

Lines changed: 0 additions & 71 deletions
This file was deleted.

0 commit comments

Comments
 (0)