Skip to content

Commit f7c520e

Browse files
feat(web): approve agent sign-ins on a /connect-agent page
The MCP authorize step rendered its own bare HTML form, which looked nothing like the rest of T3 Code. A valid sign-in request now redirects to /connect-agent in the web app, styled like /pair. The page posts the request back to /oauth/mcp/approval for what to show and to /oauth/mcp/decision to approve or deny; the server re-validates the request on every call. An untrusted client or redirect still gets a plain server error page and is never redirected. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent f537fe9 commit f7c520e

8 files changed

Lines changed: 533 additions & 223 deletions

File tree

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

Lines changed: 90 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,23 @@ const withRoutes = <A, E>(
104104
}).pipe(Effect.provide(NodeServices.layer));
105105

106106
const json = <A>(response: Response) => Effect.promise(() => response.json() as Promise<A>);
107-
const text = (response: Response) => Effect.promise(() => response.text());
107+
108+
/** What the approval page posts: the agent's request plus the user's choice. */
109+
const postJson = (path: string, body: Record<string, string>, cookie?: string) =>
110+
at(path, {
111+
method: "POST",
112+
headers: { "content-type": "application/json", ...(cookie ? { cookie } : {}) },
113+
body: encodeJson(body),
114+
});
115+
116+
const decide = (handler: Handler, body: Record<string, string>, cookie?: string) =>
117+
handler(postJson("/oauth/mcp/decision", body, cookie)).pipe(
118+
Effect.flatMap((response) =>
119+
json<{ redirectTo?: string; error?: string }>(response).pipe(
120+
Effect.map((payload) => ({ status: response.status, ...payload })),
121+
),
122+
),
123+
);
108124

109125
const register = (handler: Handler, redirect = REDIRECT) =>
110126
handler(
@@ -187,12 +203,26 @@ it.live("registers only loopback clients and never redirects for an unverified c
187203
expect(unregistered.status).toBe(400);
188204
expect(unregistered.headers.get("location")).toBeNull();
189205

190-
const page = yield* handler(
191-
at(`/oauth/mcp/authorize?${new URLSearchParams(authorizeParams(clientId))}`),
206+
// A valid request is handed to the web app's approval page, query intact.
207+
const query = new URLSearchParams(authorizeParams(clientId)).toString();
208+
const handoff = yield* handler(at(`/oauth/mcp/authorize?${query}`));
209+
expect(handoff.status).toBe(302);
210+
expect(handoff.headers.get("location")).toBe(`/connect-agent?${query}`);
211+
const details = yield* handler(
212+
postJson("/oauth/mcp/approval", authorizeParams(clientId)),
213+
).pipe(Effect.flatMap(json<Record<string, unknown>>));
214+
expect(details).toEqual({
215+
clientName: "Claude Code",
216+
redirectHost: "localhost:51234",
217+
environmentHost: "box.example.ts.net",
218+
});
219+
220+
// The approval endpoints re-check the request: a forged client gets a message, not a URL.
221+
const forgedDetails = yield* handler(
222+
postJson("/oauth/mcp/approval", authorizeParams(`${clientId.split(".")[0]}.forged`)),
192223
);
193-
expect(page.status).toBe(200);
194-
expect(page.headers.get("content-security-policy")).toContain("frame-ancestors 'none'");
195-
expect(yield* text(page)).toContain("Pairing code");
224+
expect(forgedDetails.status).toBe(400);
225+
expect(yield* json<Record<string, unknown>>(forgedDetails)).not.toHaveProperty("redirectTo");
196226
}),
197227
),
198228
);
@@ -204,28 +234,23 @@ it.live("signs in with a pairing code and issues a token only /mcp accepts", ()
204234
const pairing = yield* auth.issuePairingCredential();
205235
const params = authorizeParams(clientId);
206236

207-
const wrongCode = yield* handler(
208-
at(
209-
"/oauth/mcp/authorize",
210-
form({ ...params, decision: "approve", runtime_mode: "auto", pairing_code: "nope" }),
211-
),
212-
);
237+
const wrongCode = yield* decide(handler, {
238+
...params,
239+
decision: "approve",
240+
runtime_mode: "auto",
241+
pairing_code: "nope",
242+
});
213243
expect(wrongCode.status).toBe(400);
214-
expect(yield* text(wrongCode)).toContain("unknown, expired, or already used");
244+
expect(wrongCode.error).toContain("unknown, expired, or already used");
215245

216-
const approved = yield* handler(
217-
at(
218-
"/oauth/mcp/authorize",
219-
form({
220-
...params,
221-
decision: "approve",
222-
runtime_mode: "auto",
223-
pairing_code: pairing.credential,
224-
}),
225-
),
226-
);
227-
expect(approved.status).toBe(302);
228-
const callback = new URL(approved.headers.get("location")!);
246+
const approved = yield* decide(handler, {
247+
...params,
248+
decision: "approve",
249+
runtime_mode: "auto",
250+
pairing_code: pairing.credential,
251+
});
252+
expect(approved.status).toBe(200);
253+
const callback = new URL(approved.redirectTo!);
229254
expect(callback.origin).toBe("http://localhost:51234");
230255
expect(callback.searchParams.get("state")).toBe("state-1");
231256
expect(callback.searchParams.get("iss")).toBe(ORIGIN);
@@ -285,18 +310,13 @@ it.live("rejects a wrong PKCE verifier and spends the code", () =>
285310
const clientId = yield* registeredClientId(handler);
286311
const pairing = yield* auth.issuePairingCredential();
287312
const params = authorizeParams(clientId);
288-
const approved = yield* handler(
289-
at(
290-
"/oauth/mcp/authorize",
291-
form({
292-
...params,
293-
decision: "approve",
294-
runtime_mode: "approval-required",
295-
pairing_code: pairing.credential,
296-
}),
297-
),
298-
);
299-
const code = new URL(approved.headers.get("location")!).searchParams.get("code")!;
313+
const approved = yield* decide(handler, {
314+
...params,
315+
decision: "approve",
316+
runtime_mode: "approval-required",
317+
pairing_code: pairing.credential,
318+
});
319+
const code = new URL(approved.redirectTo!).searchParams.get("code")!;
300320
const exchange = (codeVerifier: string) =>
301321
handler(
302322
at(
@@ -324,21 +344,18 @@ it.live("denies and refuses codes bound to another client's key or without threa
324344
const clientId = yield* registeredClientId(handler);
325345
const params = authorizeParams(clientId);
326346

327-
const denied = yield* handler(
328-
at("/oauth/mcp/authorize", form({ ...params, decision: "deny" })),
329-
);
330-
expect(denied.status).toBe(302);
331-
const deniedUrl = new URL(denied.headers.get("location")!);
347+
const denied = yield* decide(handler, { ...params, decision: "deny" });
348+
const deniedUrl = new URL(denied.redirectTo!);
332349
expect(deniedUrl.searchParams.get("error")).toBe("access_denied");
333350
expect(deniedUrl.searchParams.get("state")).toBe("state-1");
334351

335352
const approveWith = (code: string) =>
336-
handler(
337-
at(
338-
"/oauth/mcp/authorize",
339-
form({ ...params, decision: "approve", runtime_mode: "auto", pairing_code: code }),
340-
),
341-
);
353+
decide(handler, {
354+
...params,
355+
decision: "approve",
356+
runtime_mode: "auto",
357+
pairing_code: code,
358+
});
342359

343360
// A T3 Connect code is bound to a device key: refused, and still usable by its device.
344361
const bound = yield* auth.createPairingLink({ proofKeyThumbprint: "device-key-thumbprint" });
@@ -359,7 +376,7 @@ it.live("denies and refuses codes bound to another client's key or without threa
359376
const readOnly = yield* auth.issuePairingCredential({ scopes: ["orchestration:read"] });
360377
const readOnlyResponse = yield* approveWith(readOnly.credential);
361378
expect(readOnlyResponse.status).toBe(400);
362-
expect(yield* text(readOnlyResponse)).toContain("cannot control threads");
379+
expect(readOnlyResponse.error).toContain("cannot control threads");
363380
}),
364381
),
365382
);
@@ -382,28 +399,36 @@ it.live("offers one-click only to a browser session that holds the scopes it wou
382399
);
383400
return response.headers.getSetCookie()[0]!.split(";", 1)[0]!;
384401
});
385-
const page = (cookie: string) =>
386-
handler(
387-
at(`/oauth/mcp/authorize?${new URLSearchParams(params)}`, { headers: { cookie } }),
388-
).pipe(Effect.flatMap(text));
402+
const details = (cookie: string) =>
403+
handler(postJson("/oauth/mcp/approval", params, cookie)).pipe(
404+
Effect.flatMap(json<{ csrfToken?: string }>),
405+
);
389406

390407
const admin = yield* browserCookie([...AuthAdministrativeScopes]);
391-
expect(yield* page(admin)).toContain('name="csrf_token"');
408+
const adminDetails = yield* details(admin);
409+
expect(adminDetails.csrfToken).toEqual(expect.any(String));
410+
const oneClick = yield* decide(
411+
handler,
412+
{
413+
...params,
414+
decision: "approve",
415+
runtime_mode: "auto",
416+
csrf_token: adminDetails.csrfToken!,
417+
},
418+
admin,
419+
);
420+
expect(new URL(oneClick.redirectTo!).searchParams.get("code")).toEqual(expect.any(String));
392421

393422
// access:write alone cannot hand an agent thread control it does not hold.
394423
const accessOnly = yield* browserCookie(["access:read", "access:write"]);
395-
expect(yield* page(accessOnly)).not.toContain('name="csrf_token"');
396-
const forged = yield* handler(
397-
at("/oauth/mcp/authorize", {
398-
...form({ ...params, decision: "approve", runtime_mode: "auto", csrf_token: "forged" }),
399-
headers: {
400-
"content-type": "application/x-www-form-urlencoded",
401-
cookie: accessOnly,
402-
},
403-
}),
424+
expect((yield* details(accessOnly)).csrfToken).toBeUndefined();
425+
const forged = yield* decide(
426+
handler,
427+
{ ...params, decision: "approve", runtime_mode: "auto", csrf_token: "forged" },
428+
accessOnly,
404429
);
405430
expect(forged.status).toBe(400);
406-
expect(yield* text(forged)).toContain("Enter a pairing code instead");
431+
expect(forged.error).toContain("Enter a pairing code instead");
407432
}),
408433
),
409434
);

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

Lines changed: 8 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,24 @@
1-
import type { RuntimeMode } from "@t3tools/contracts";
2-
1+
/**
2+
* The page for a sign-in link that cannot be trusted (unknown client or
3+
* unregistered redirect). It is plain server HTML so it never depends on the
4+
* web app, and it must not redirect anywhere.
5+
*/
36
const escapeHtml = (value: string) =>
47
value.replace(
58
/[&<>"']/gu,
69
(character) =>
710
({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[character]!,
811
);
912

10-
// Same words as the composer's permission menu, so the choice reads the same everywhere.
11-
const RUNTIME_MODES: ReadonlyArray<{ readonly value: RuntimeMode; readonly label: string }> = [
12-
{ value: "approval-required", label: "Supervised: it asks before running commands or editing" },
13-
{ value: "auto-accept-edits", label: "Auto-accept edits" },
14-
{ value: "auto", label: "Auto" },
15-
{ value: "full-access", label: "Full access" },
16-
];
17-
1813
const STYLES = `
1914
:root { color-scheme: light dark; font-family: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
20-
* { box-sizing: border-box; }
2115
body { margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 32px 16px; background: #f6f7f9; color: #17191f; }
22-
main { width: min(100%, 480px); border: 1px solid rgba(23, 25, 31, 0.1); border-radius: 16px; background: #fff; padding: 28px; }
16+
main { width: min(100%, 440px); }
2317
h1 { margin: 0 0 8px; font-size: 20px; }
24-
p { margin: 0 0 16px; line-height: 1.5; color: #4b5060; }
25-
dl { margin: 0 0 20px; display: grid; grid-template-columns: max-content 1fr; gap: 6px 16px; font-size: 14px; }
26-
dt { color: #6b7080; }
27-
dd { margin: 0; word-break: break-word; }
28-
label { display: block; font-size: 14px; font-weight: 600; margin: 0 0 6px; }
29-
select, input { width: 100%; font: inherit; padding: 8px 10px; border-radius: 8px; border: 1px solid rgba(23, 25, 31, 0.2); margin: 0 0 16px; background: inherit; color: inherit; }
30-
.warning { padding: 10px 12px; border-radius: 8px; background: rgba(234, 179, 8, 0.12); font-size: 14px; }
31-
.error { padding: 10px 12px; border-radius: 8px; background: rgba(239, 68, 68, 0.12); color: #b91c1c; font-size: 14px; }
32-
.actions { display: flex; gap: 8px; justify-content: flex-end; }
33-
button { font: inherit; padding: 8px 16px; border-radius: 8px; border: 1px solid rgba(23, 25, 31, 0.2); background: transparent; color: inherit; cursor: pointer; }
34-
button.primary { background: #2563eb; border-color: #2563eb; color: #fff; }
35-
.hint { font-size: 13px; color: #6b7080; margin-top: -10px; }
18+
p { margin: 0 0 12px; line-height: 1.5; color: #4b5060; }
3619
@media (prefers-color-scheme: dark) {
3720
body { background: #0f1115; color: #e6e8ee; }
38-
main { background: #171a21; border-color: rgba(255, 255, 255, 0.1); }
39-
p, dt, .hint { color: #a0a6b4; }
40-
select, input, button { border-color: rgba(255, 255, 255, 0.2); }
41-
.error { color: #fca5a5; }
21+
p { color: #a0a6b4; }
4222
}
4323
`;
4424

@@ -56,61 +36,6 @@ const shell = (title: string, body: string) => `<!doctype html>
5636
</body>
5737
</html>`;
5838

59-
export interface ApprovalPageInput {
60-
readonly clientName: string;
61-
readonly redirectHost: string;
62-
readonly environmentHost: string;
63-
/** Every authorize parameter, carried through the form unchanged. */
64-
readonly hiddenParams: ReadonlyArray<readonly [string, string]>;
65-
/** Present when the owner's browser session may approve without a code. */
66-
readonly csrfToken?: string;
67-
readonly error?: string;
68-
readonly runtimeModeCeiling?: RuntimeMode;
69-
}
70-
71-
export function renderApprovalPage(input: ApprovalPageInput): string {
72-
const selected = input.runtimeModeCeiling ?? "approval-required";
73-
const hidden = input.hiddenParams
74-
.map(
75-
([name, value]) =>
76-
`<input type="hidden" name="${escapeHtml(name)}" value="${escapeHtml(value)}" />`,
77-
)
78-
.join("");
79-
const approval =
80-
input.csrfToken === undefined
81-
? `<label for="pairing_code">Pairing code</label>
82-
<input id="pairing_code" name="pairing_code" autocomplete="one-time-code" autocapitalize="off" spellcheck="false" required />
83-
<p class="hint">Create one in T3 Code under Settings → Connections, or run <code>t3 auth pairing create</code> on this machine.</p>`
84-
: `<input type="hidden" name="csrf_token" value="${escapeHtml(input.csrfToken)}" />`;
85-
return shell(
86-
"Connect an agent to T3 Code",
87-
`<h1>Connect an agent to T3 Code</h1>
88-
<p>An app wants to control threads on <strong>${escapeHtml(input.environmentHost)}</strong>.</p>
89-
<dl>
90-
<dt>App</dt><dd>${escapeHtml(input.clientName)} <span class="hint">(as the app names itself)</span></dd>
91-
<dt>Returns to</dt><dd>${escapeHtml(input.redirectHost)} on the computer that opened this page</dd>
92-
<dt>Access</dt><dd>Read, start, message and stop threads in every project</dd>
93-
</dl>
94-
<p class="warning">Only approve if you just started this sign-in from an agent you trust.</p>
95-
${input.error === undefined ? "" : `<p class="error" role="alert">${escapeHtml(input.error)}</p>`}
96-
<form method="post">
97-
${hidden}
98-
<label for="runtime_mode">Most it may allow an agent to do</label>
99-
<select id="runtime_mode" name="runtime_mode">
100-
${RUNTIME_MODES.map(
101-
(mode) =>
102-
`<option value="${mode.value}"${mode.value === selected ? " selected" : ""}>${escapeHtml(mode.label)}</option>`,
103-
).join("")}
104-
</select>
105-
${approval}
106-
<div class="actions">
107-
<button type="submit" name="decision" value="deny">Deny</button>
108-
<button type="submit" name="decision" value="approve" class="primary">Approve</button>
109-
</div>
110-
</form>`,
111-
);
112-
}
113-
11439
export function renderErrorPage(description: string): string {
11540
return shell(
11641
"Sign-in failed",

0 commit comments

Comments
 (0)