Public: anyone can read this; the crew can change it.

The owner sees every MCP OAuth grant with its client and last use, and revokes one in one tap #13338

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

torque/forge:torque/13308-the-owner-sees-every-mcp-oauth-grant-wit → main 8 commits fork 3 threads · 3 unresolved

  • Merged. torque/13308-the-owner-sees-every-mcp-oauth-grant-wit was merged into main as 97489a2.

Review

Sign in to review this change.
22 files changed +672 −18
docs/design/attention-budget.json +3 −3
@@ -110,16 +110,16 @@
110110 },
111111 "settings": {
112112 "390": {
113 "words": 144,
113 "words": 146,
114114 "blocks": 32,
115115 "colours": 1
116116 },
117117 "1280": {
118 "words": 144,
118 "words": 146,
119119 "blocks": 32,
120120 "colours": 1
121121 },
122 "note": "143 words since 68efd9dd (2026-11-13, a hosted forge asks its host for a name its gate refused): that change added two words to this first view."
122 "note": "146 words since #13308 (2026-11-15, Settings › Connected agents): its side-nav entry added two words to the 144 main had."
123123 },
124124 "search": {
125125 "390": {
docs/design/audit.md +1
@@ -156,6 +156,7 @@ Machine routes are not pages and have no entry: `/audit.csv`,
156156 - `/settings` — `pages/account.ts` · my account · the rest of settings · colour 1.
157157 - `/settings/password` — `pages/account.ts` · change password · `/settings/passkeys` · colour 1.
158158 - `/settings/tokens` — `pages/account.ts` · my API tokens · `/settings/keys` (credentials of two kinds on two pages) · colour 1.
159 - `/settings/grants` — `pages/grants.ts` · the agents I let in through the MCP OAuth sign-in, with last use and Revoke · `/settings/tokens` · colour 1.
159160 - `/settings/shells` — `pages/account.ts` · the machine shells I hold, live then ended · `/settings/keys` · colour 1.
160161 - `/settings/keys` — `pages/account.ts` · my SSH keys · `/settings/tokens` · colour 1.
161162 - `/settings/passkeys` — `pages/passkeys.ts` · my passkeys · `/settings/password` · none seen.
docs/features/README.md +1
@@ -361,6 +361,7 @@ Read with the guide page [Agents: MCP, git, or the terminal](../guide-agents.md)
361361 - [Atom feeds](atom.md)
362362 - [Guest pulls](guest-pulls.md)
363363 - [How a person with no account gets in to contribute](guests.md)
364 - [Connected agents](oauth-grants.md)
364365 - [OAuth refresh](oauth-refresh.md)
365366 - [OAuth revoke](oauth-revoke.md)
366367 - [OpenAPI and OAuth](openapi-oauth.md)
docs/features/oauth-grants.md added +30
@@ -0,0 +1,30 @@
1 # Connected agents
2
3 Settings › Connected agents (`/settings/grants`) lists every agent you let in
4 through the MCP's OAuth sign-in: Claude, an editor, or another harness.
5
6 ## What a row says
7
8 - the client's registered name, as it named itself when it registered;
9 - its scope (`ro` or `rw`) and any OpenID scopes (`openid`, `profile`, `email`);
10 - when you granted it: the first consent, kept across every refresh;
11 - when it was last used, to the minute, or "never used";
12 - when its token ends or renews, for a grant that expires.
13
14 Last used is written at most once a minute per token, so a busy agent costs
15 one write a minute, not one per call. A refresh keeps both dates.
16
17 ## Revoking
18
19 Revoke is one tap: a same-origin `POST /settings/grants/<id>/revoke`. The
20 token and its refresh tokens go at once, so the agent's next call to `/mcp` or
21 `/api/v1` gets `401`, and it cannot refresh its way back. The page says what it
22 ended. A `token.deleted` event lands in the audit trail.
23
24 Only your own grants are listed and only they can be revoked here. Tokens you
25 made by hand are under Settings › Access codes.
26
27 ## In the terminal
28
29 `Connected agents` in the palette lists the same rows; `x` revokes the
30 selected one after a confirm and says the same receipt.
forge.json +2 −2
@@ -4,8 +4,8 @@
44 "api.github.com"
55 ],
66 "app": {
7 "looks": ["/", "/docs", "/explore", "/board", "/notes", "/review", "/releases", "/apps", "/security", "/system", "/maintenance", "/talk", "/flow", "/resilience", "/boards?help", "/settings/crew", "/settings/crew?help", "/settings/security/controls", "/preview-admin/sample", "/preview-admin/sample/pulls/3", "/preview-admin/sample/next?pick", "/preview-admin/sample/bets", "/preview-admin/sample/waves", "/preview-admin/sample/space"],
8 "looksAsOwner": ["/", "/board", "/flow", "/boards?help", "/settings/crew", "/settings/crew?help", "/settings/security/controls", "/talk", "/system", "/maintenance", "/resilience", "/preview-admin/sample", "/preview-admin/sample/pulls/3", "/preview-admin/sample/next?pick", "/preview-admin/sample/bets", "/preview-admin/sample/waves", "/preview-admin/sample/space"],
7 "looks": ["/", "/docs", "/explore", "/board", "/notes", "/review", "/releases", "/apps", "/security", "/system", "/maintenance", "/talk", "/flow", "/resilience", "/boards?help", "/settings/crew", "/settings/crew?help", "/settings/security/controls", "/settings/grants", "/preview-admin/sample", "/preview-admin/sample/pulls/3", "/preview-admin/sample/next?pick", "/preview-admin/sample/bets", "/preview-admin/sample/waves", "/preview-admin/sample/space"],
8 "looksAsOwner": ["/", "/board", "/flow", "/boards?help", "/settings/crew", "/settings/crew?help", "/settings/security/controls", "/settings/grants", "/talk", "/system", "/maintenance", "/resilience", "/preview-admin/sample", "/preview-admin/sample/pulls/3", "/preview-admin/sample/next?pick", "/preview-admin/sample/bets", "/preview-admin/sample/waves", "/preview-admin/sample/space"],
99 "run": "bun run src/main.ts",
1010 "install": "",
1111 "health": "/healthz",
src/actions/oauth_grants.ts added +40
@@ -0,0 +1,40 @@
1 /**
2 * A person's OAuth grants and the one act on each, revoking it (#13308).
3 * The page (`/settings/grants`) and the terminal (`screens/oauthgrants.ts`)
4 * both come through here, so the gate is one: your own grants only, and a
5 * hand-made token is not a grant (Settings › Access codes ends those).
6 * Revoking goes through `deleteToken`, so the refresh family goes with the
7 * token and `token.deleted` is emitted; the next call with it is refused,
8 * since `verifyToken` reads the row on every call.
9 */
10 import type { App } from "../app.ts";
11 import { listOAuthGrants, oauthGrantOf, type OAuthGrant } from "../core/oauth_grants.ts";
12 import type { User } from "../core/users.ts";
13 import { err, ok, type Result } from "../kernel/result.ts";
14 import { requireUser } from "./access.ts";
15 import { deleteToken } from "./users.ts";
16
17 /** The asker's grants; empty for a guest or an agent, who grant nothing. */
18 export function myOAuthGrants(app: App, actor: User | undefined): OAuthGrant[] {
19 const user = requireUser(actor);
20 if (!user.ok || user.value.kind !== "user") return [];
21 return listOAuthGrants(app.db, user.value.id);
22 }
23
24 /** End one of the asker's grants; returns what was ended, for the receipt. */
25 export function revokeOAuthGrant(
26 app: App,
27 actor: User | undefined,
28 tokenId: string,
29 ): Result<OAuthGrant, "not_found"> {
30 const user = requireUser(actor);
31 if (!user.ok || user.value.kind !== "user") return err("not_found");
32 const grant = oauthGrantOf(app.db, user.value.id, tokenId);
33 if (grant === null) return err("not_found");
34 if (!deleteToken(app, user.value, tokenId).ok) return err("not_found");
35 return ok(grant);
36 }
37
38 /** The receipt both doors say after a revoke. */
39 export const revokedWords = (grant: OAuthGrant): string =>
40 `Revoked ${grant.client} (${grant.scope}): its next call is refused, and it cannot refresh its way back.`;
src/core/migration-pins/20261115130000-oauth-grant-start.pin added +1
@@ -0,0 +1,1 @@
1 eb16615d6f102c2989a0c911e9414ef1dd86ec82584c36e0436e1573a616e2e1
src/core/migrations/20261115130000-oauth-grant-start.ts added +7
@@ -0,0 +1,7 @@
1 // When a person first granted an OAuth client its token (#13308). A refresh
2 // replaces the access token, and with it `token.created_at`, so the grant's
3 // own start is kept on its mark and carried across every rotation. Null on
4 // a mark made before this: the token's own creation stands in. Additive.
5 export default `
6 ALTER TABLE oauth_token ADD COLUMN granted_at TEXT;
7 `;
src/core/oauth.ts +28 −4
@@ -153,10 +153,16 @@ export function oauthClientNames(db: Database, userId: string): Map<string, stri
153153 return new Map(rows.map((r) => [r.token_id, r.name]));
154154 }
155155
156 /** A token as every door lists it: `oauthClient` names the harness that holds it, null for a hand-made one. */
156 /**
157 * A token as every door lists it: `oauthClient` names the harness that holds it, null for a
158 * hand-made one.
159 */
157160 export type ListedToken = TokenInfo & { readonly oauthClient: string | null };
158161
159 /** A person's tokens with the harness behind each: two reads for the whole list, whatever its length. */
162 /**
163 * A person's tokens with the harness behind each: two reads for the whole list, whatever its
164 * length.
165 */
160166 export function listTokensWithClients(db: Database, userId: string): ListedToken[] {
161167 const clients = oauthClientNames(db, userId);
162168 return listTokens(db, userId).map((t) => ({ ...t, oauthClient: clients.get(t.id) ?? null }));
@@ -420,9 +426,10 @@ export async function redeemCode(
420426 ? {}
421427 : { expiresAt: new Date(Date.now() + row.lifetime_s * 1000).toISOString() }),
422428 });
423 db.query("INSERT INTO oauth_token (token_id, client_id) VALUES (?1, ?2)").run(
429 db.query("INSERT INTO oauth_token (token_id, client_id, granted_at) VALUES (?1, ?2, ?3)").run(
424430 minted.id,
425431 row.client_id,
432 new Date().toISOString(),
426433 );
427434 const scopes = row.oidc_scopes === "" ? [] : row.oidc_scopes.split(" ");
428435 const refreshToken =
@@ -515,11 +522,28 @@ export function refreshGrant(
515522 }
516523 const spend = db.query("UPDATE oauth_refresh SET spent = 1 WHERE token_hash = ?1 AND spent = 0");
517524 if (spend.run(sha256(input.refreshToken)).changes !== 1) return err("invalid_grant");
525 // The grant outlives its rotations (#13308): read when it began and when it
526 // was last used before the old token, and its mark, are deleted.
527 const before =
528 row.token_id === null
529 ? null
530 : db
531 .query<{ granted_at: string | null; created_at: string; last_used_at: string | null }, [string]>(
532 `SELECT o.granted_at, t.created_at, t.last_used_at FROM token t
533 LEFT JOIN oauth_token o ON o.token_id = t.id WHERE t.id = ?1`,
534 )
535 .get(row.token_id);
518536 if (row.token_id !== null) db.query("DELETE FROM token WHERE id = ?1").run(row.token_id);
519537 const minted = createToken(db, row.user_id, row.name, scope, {
520538 expiresAt: new Date(Date.now() + row.lifetime_s * 1000).toISOString(),
521539 });
522 db.query("INSERT INTO oauth_token (token_id, client_id) VALUES (?1, ?2)").run(minted.id, row.client_id);
540 db.query("INSERT INTO oauth_token (token_id, client_id, granted_at) VALUES (?1, ?2, ?3)").run(
541 minted.id,
542 row.client_id,
543 before?.granted_at ?? before?.created_at ?? null,
544 );
545 if (before?.last_used_at != null)
546 db.query("UPDATE token SET last_used_at = ?1 WHERE id = ?2").run(before.last_used_at, minted.id);
523547 const scopes = row.oidc_scopes === "" ? [] : row.oidc_scopes.split(" ");
524548 if (scopes.length > 0) recordGrant(db, minted.id, scopes);
525549 const refreshToken = mintRefresh(db, {
src/core/oauth_grants.ts added +73
@@ -0,0 +1,73 @@
1 /**
2 * The OAuth grants a person has given (#13308): one per token the OAuth
3 * endpoint minted, with the client that holds it, what it may do, when it
4 * was granted and when it was last used. A refresh rotates the token but not
5 * the grant: `granted_at` and `last_used_at` are carried over (`oauth.ts`,
6 * `refreshGrant`). `last_used_at` is the token's own, written at most once a
7 * minute per token by `verifyToken` (`TOUCH_EVERY_MS`), so a busy harness
8 * costs one write a minute, not one per call.
9 */
10 import type { Database } from "bun:sqlite";
11 import type { TokenScope } from "./tokens.ts";
12
13 export interface OAuthGrant {
14 /** The access token's id: what revoking ends. */
15 readonly tokenId: string;
16 /** The client's registered name, untrusted text: escape it on every door. */
17 readonly client: string;
18 readonly scope: TokenScope;
19 /** OpenID scopes granted with it (`openid`, `profile`, `email`), empty for a plain grant. */
20 readonly oidcScopes: readonly string[];
21 readonly grantedAt: string;
22 readonly lastUsedAt: string | null;
23 readonly expiresAt: string | null;
24 /** The client holds a refresh token, so an expiring token renews itself. */
25 readonly renews: boolean;
26 }
27
28 /** A person's OAuth grants, the most recently used first; one read, whatever the count. */
29 export function listOAuthGrants(db: Database, userId: string): OAuthGrant[] {
30 const rows = db
31 .query<
32 {
33 id: string;
34 scope: TokenScope;
35 created_at: string;
36 last_used_at: string | null;
37 expires_at: string | null;
38 granted_at: string | null;
39 client: string;
40 oidc: string | null;
41 renews: number;
42 },
43 [string]
44 >(
45 `SELECT t.id, t.scope, t.created_at, t.last_used_at, t.expires_at, o.granted_at,
46 c.name AS client, d.scopes AS oidc,
47 EXISTS (SELECT 1 FROM oauth_refresh r WHERE r.token_id = t.id) AS renews
48 FROM token t
49 JOIN oauth_token o ON o.token_id = t.id
50 JOIN oauth_client c ON c.id = o.client_id
51 LEFT JOIN oidc_token d ON d.token_id = t.id
52 WHERE t.user_id = ?1
53 ORDER BY COALESCE(t.last_used_at, '') DESC, t.id`,
54 )
55 .all(userId);
56 return rows.map((r) => ({
57 tokenId: r.id,
58 client: r.client,
59 scope: r.scope,
60 oidcScopes: r.oidc === null || r.oidc === "" ? [] : r.oidc.split(" "),
61 grantedAt: r.granted_at ?? r.created_at,
62 lastUsedAt: r.last_used_at,
63 expiresAt: r.expires_at,
64 renews: r.renews === 1,
65 }));
66 }
67
68 /**
69 * One of a person's grants by its token id, or null when it is not theirs or not an OAuth grant.
70 */
71 export function oauthGrantOf(db: Database, userId: string, tokenId: string): OAuthGrant | null {
72 return listOAuthGrants(db, userId).find((g) => g.tokenId === tokenId) ?? null;
73 }
src/http/route_marks.ts +2
@@ -284,6 +284,8 @@ export const ROUTES: Readonly<Record<string, Mark>> = {
284284 "/settings/shells/:id/stop": "open",
285285 "/settings/tokens": "open",
286286 "/settings/tokens/:id/delete": "open",
287 "/settings/grants": "open",
288 "/settings/grants/:id/revoke": "open",
287289 "/settings/sessions/:id/delete": "open",
288290 "/settings/confirms": "open",
289291 "/settings/confirms/:id": "open",
src/http/settings_routes.ts +3
@@ -123,6 +123,7 @@ import {
123123 tokenDelete,
124124 tokensPage,
125125 } from "../web/pages/account.ts";
126 import { grantRevoke, grantsPage } from "../web/pages/grants.ts";
126127 import { completeBrokeredCallback, completeOAuthCallback } from "../actions/origins.ts";
127128 import { originReachAsk, originReachDismiss } from "../web/pages/origin-reach.ts";
128129 import { hostedForgesPage, reachAdd, reachRemove, reachSwitch } from "../web/pages/hosted-forges.ts";
@@ -180,6 +181,8 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea
180181 router.add("GET", "/settings/tokens", tokensPage);
181182 router.add("POST", "/settings/tokens", tokenCreate);
182183 router.add("POST", "/settings/tokens/:id/delete", tokenDelete);
184 router.add("GET", "/settings/grants", grantsPage);
185 router.add("POST", "/settings/grants/:id/revoke", grantRevoke);
183186 router.add("POST", "/settings/sessions/:id/delete", sessionDelete);
184187 router.add("GET", "/settings/confirms", confirmsList);
185188 router.add("POST", "/settings/confirms/:id", confirmYes);
src/tui/forge.ts +8
@@ -80,6 +80,7 @@ import { receiptsScreen } from "./screens/receipts.ts";
8080 import { mayTrust, trustedScreen } from "./screens/trusted.ts";
8181 import { proposalTokensPrompt } from "./screens/proposal_tokens.ts";
8282 import { signInsScreen } from "./screens/signins.ts";
83 import { oauthGrantsScreen } from "./screens/oauthgrants.ts";
8384 import { originAppsScreen } from "./screens/originapps.ts";
8485 import { addEntries } from "./screens/entries.ts";
8586 import { capacityScreen, mayCapacity } from "./screens/capacity.ts";
@@ -497,6 +498,13 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
497498 hint: "your browsers and tokens; d signs a browser out",
498499 run: () => ctx.push(signInsScreen(session, ctx)),
499500 },
501 // Settings › Connected agents: the OAuth grants you gave (#13308).
502 {
503 id: "oauth-grants",
504 title: "Connected agents",
505 hint: "the agents you let in through OAuth; x revokes one",
506 run: () => ctx.push(oauthGrantsScreen(session, ctx)),
507 },
500508 // Settings → Connected accounts' OAuth apps and MCP `origin_apps` (#7291).
501509 {
502510 id: "origin-apps",
src/tui/screens/oauthgrants.ts added +77
@@ -0,0 +1,77 @@
1 /**
2 * Settings › Connected agents in the terminal (#13308): each OAuth grant you
3 * gave, with its client, scopes, when it was granted and last used, as the
4 * page lists it. `x` revokes the selected one after a confirm, through
5 * `revokeOAuthGrant` (the page's action and gate: your own grants only) and
6 * says the page's receipt. An agent and a guest see nothing to revoke.
7 */
8 import { myOAuthGrants, revokeOAuthGrant, revokedWords } from "../../actions/oauth_grants.ts";
9 import type { OAuthGrant } from "../../core/oauth_grants.ts";
10 import type { Ctx, Screen } from "../app/app.ts";
11 import { binding } from "../app/keys.ts";
12 import { style } from "../term/style.ts";
13 import { truncate } from "../term/width.ts";
14 import type { Session } from "../session.ts";
15 import { fill, len, split } from "../ui/layout.ts";
16 import { ListState, ago, confirmScreen, drawList, type ListRow } from "./common.ts";
17
18 /** One row per grant, in the page's words. */
19 export function grantRows(grants: readonly OAuthGrant[]): ListRow[] {
20 return grants.map((g) => ({
21 title: g.client,
22 secondary: [g.scope, ...g.oidcScopes].join(" "),
23 meta: `granted ${g.grantedAt.slice(0, 10)} · ${g.lastUsedAt === null ? "never used" : `last used ${ago(g.lastUsedAt)}`}`,
24 }));
25 }
26
27 export function oauthGrantsScreen(f: Session, ctx: Ctx): Screen {
28 const state = new ListState();
29 let note = "";
30
31 const askRevoke = (picked: OAuthGrant): void => {
32 ctx.push(
33 confirmScreen(ctx, screen, {
34 title: "Revoke a connected agent",
35 body: [`Revoke ${picked.client} (${picked.scope})? Its next call is refused.`],
36 actions: [{ label: "Keep", variant: "ghost" }, { label: "Revoke", variant: "danger" }],
37 onChoose: (i) => {
38 if (i < 1) return;
39 const done = revokeOAuthGrant(f.app, f.user, picked.tokenId);
40 note = done.ok ? revokedWords(done.value) : "That grant is already gone.";
41 ctx.invalidate();
42 },
43 }),
44 );
45 };
46
47 const screen: Screen = {
48 title: "Connected agents",
49 keys: [binding(["j", "k"], "move cursor"), binding(["x"], "revoke the selected agent")],
50 render(area, s) {
51 const c = ctx.theme.c;
52 const all = myOAuthGrants(f.app, f.user);
53 const [head, body] = split(area, "v", [len(1), fill(1)]);
54 const text =
55 note !== ""
56 ? note
57 : f.user === undefined
58 ? "Sign in to see the agents you connected."
59 : all.length === 0
60 ? "No agent is connected through OAuth."
61 : "Agents you let in through the MCP's sign-in. x revokes one.";
62 s.text(head!.x, head!.y, truncate(text, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
63 drawList(s, body!, c, state, grantRows(all));
64 },
65 key(e) {
66 note = "";
67 const all = myOAuthGrants(f.app, f.user);
68 if (state.key(e, all.length)) return true;
69 if (e.ctrl || e.alt || e.key !== "x") return false;
70 const picked = all[state.index];
71 if (picked === undefined) return false;
72 askRevoke(picked);
73 return true;
74 },
75 };
76 return screen;
77 }
src/web/layout.ts +1
@@ -413,6 +413,7 @@ const STATIC_PALETTE: PaletteItem[] = [
413413 { t: "New organization", h: "/organizations/new", c: "Create" },
414414 { t: "Account settings", h: "/settings", c: "Settings" },
415415 { t: "Access codes", h: "/settings/tokens", c: "Settings" },
416 { t: "Connected agents", h: "/settings/grants", c: "Settings" },
416417 { t: "Computer keys", h: "/settings/keys", c: "Settings" },
417418 { t: "Connected accounts", h: "/settings/origins", c: "Settings" },
418419 { t: "Your shells", h: "/settings/shells", c: "Settings" },
src/web/pages/account.ts +1 −1
@@ -109,7 +109,7 @@ const help = (notes: readonly (readonly [string, string | Html])[]): Html =>
109109 </dl>
110110 </details>`;
111111
112 type Section = "profile" | "appearance" | "password" | "tokens" | "keys" | "passkeys" | "shells";
112 type Section = "profile" | "appearance" | "password" | "tokens" | "grants" | "keys" | "passkeys" | "shells";
113113
114114 // The section list lives beside the newest page that joins it, so adding one
115115 // cannot leave the others pointing at a nav that has forgotten it.
src/web/pages/grants.ts added +82
@@ -0,0 +1,82 @@
1 /**
2 * Settings › Connected agents (#13308): every OAuth grant the person has
3 * given, one row each with the client that holds it, its scopes, when it
4 * was granted and when it was last used, and Revoke. Revoke asks first on
5 * `/-/confirm` (its words are in `search.ts`), then a same-origin POST
6 * (`readForm`), then a receipt naming what was ended. The
7 * rows and the gate are `actions/oauth_grants.ts`, which the terminal's
8 * `screens/oauthgrants.ts` shares.
9 */
10 import { myOAuthGrants, revokeOAuthGrant, revokedWords } from "../../actions/oauth_grants.ts";
11 import type { OAuthGrant } from "../../core/oauth_grants.ts";
12 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
13 import type { Ctx } from "../../http/context.ts";
14 import { signInFirst } from "../chrome.ts";
15 import { readForm } from "../form.ts";
16 import { html, when, type Html } from "../html.ts";
17 import { flashTo } from "../layout.ts";
18 import { badge, confirmAction, row, time } from "../ui.ts";
19 import { accountShell } from "./account.ts";
20
21 export const GRANTS_PATH = "/settings/grants";
22
23 /** Last used, in words a glance answers: never, or the time. */
24 const lastUsed = (g: OAuthGrant): Html =>
25 g.lastUsedAt === null ? html`never used` : html`last used ${time(g.lastUsedAt)}`;
26
27 function grantRow(g: OAuthGrant): Html {
28 return row({
29 title: html`<strong>${g.client}</strong> ${badge(g.scope)} ${g.oidcScopes.map((s) => badge(s))}`,
30 meta: html`granted ${time(g.grantedAt)} · ${lastUsed(g)}${when(
31 g.expiresAt,
32 (at) => html` · ${g.renews ? "renews" : "ends"} ${time(at)}`,
33 )}`,
34 trail: confirmAction({
35 action: `${GRANTS_PATH}/${encodeURIComponent(g.tokenId)}/revoke`,
36 verb: "Revoke",
37 size: "sm",
38 label: `Revoke ${g.client}`,
39 }),
40 });
41 }
42
43 function grantsView(grants: readonly OAuthGrant[]): Html {
44 const list =
45 grants.length === 0
46 ? html`<p class="muted">No agent is connected.</p>`
outdated

Principle 1: the empty state restates the page's purpose ('an agent, an editor or another harness signs in through /mcp'). One short line is enough: 'No agent is connected.'

47 : html`<ul class="list setting-list" data-grants>
48 ${grants.map(grantRow)}
49 </ul>`;
50 return html`<section class="settings-block">
outdated

Principle 1 (nothing explains itself twice; plain words per 8): this paragraph says what Revoke does ('its next call is refused and it cannot refresh'), and the same claim is made again in the confirm page and in the receipt (revokedWords). Cut it to one confident sentence saying what the page is for, e.g. 'The agents you let in through sign-in.' Keep the pointer to Access codes only if it is one short clause. Drop 'Last used is kept to the minute'; that is a docs detail, not page copy.

51 <h2>Signed in through OAuth</h2>
52 <p class="muted small">
53 The agents you let in through sign-in; tokens you made are under <a href="/settings/tokens">Access codes</a>.
54 </p>
55 ${list}
56 </section>`;
57 }
58
59 // GET /settings/grants
60 export function grantsPage(ctx: Ctx): Response {
61 if (!ctx.auth.user) return signInFirst(ctx);
62 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
63 const grants = timePhase(ctx.request, "grants", () => myOAuthGrants(ctx.app, ctx.auth.user));
64 return timePhase(ctx.request, "render", () =>
65 accountShell(ctx, "grants", "Connected agents", grantsView(grants)),
66 );
67 }
68
69 // POST /settings/grants/:id/revoke
70 export async function grantRevoke(ctx: Ctx): Promise<Response> {
71 if (!ctx.auth.user) return signInFirst(ctx);
72 const form = await readForm(ctx, "admin");
73 if (form instanceof Response) return form;
74 const revoked = revokeOAuthGrant(ctx.app, ctx.auth.user, ctx.params.id ?? "");
75 return flashTo(
76 ctx,
77 GRANTS_PATH,
78 revoked.ok
79 ? { message: revokedWords(revoked.value) }
80 : { tone: "danger", message: "That grant is already gone." },
81 );
82 }
src/web/pages/origins.ts +19 −7
@@ -104,6 +104,7 @@ export type AccountSection =
104104 | "confirms"
105105 | "password"
106106 | "tokens"
107 | "grants"
107108 | "shells"
108109 | "keys"
109110 | "model"
@@ -160,6 +161,7 @@ const SECTION_ROWS: readonly (readonly [
160161 ["Account", "Passkeys", "/settings/passkeys", "key", (c) => c === "passkeys", false],
161162 ["Account", "Computer keys", "/settings/keys", "lock", (c) => c === "keys", false],
162163 ["Account", "Access codes", "/settings/tokens", "key", (c) => c === "tokens", false],
164 ["Account", "Connected agents", "/settings/grants", "bot", (c) => c === "grants", false],
163165 ["Account", "Confirms", "/settings/confirms", "check", (c) => c === "confirms", false],
164166 ["Crew and AI", "Model", "/settings/model", "key", (c) => c === "model", false],
165167 ["Crew and AI", "Crew", "/settings/crew", "bot", (c) => c === "crew", true],
@@ -370,7 +372,10 @@ interface ConnectValues {
370372 registerError?: string;
371373 /** Sign-in cannot work for this address, so the token path opens. */
372374 offerToken?: boolean;
373 /** The host's gate refused the address: said once, above the forms, with the button that asks the host (`origin-reach.ts`). */
375 /**
376 * The host's gate refused the address: said once, above the forms, with the button that asks the
377 * host (`origin-reach.ts`).
378 */
374379 blocked?: Blocked;
375380 trustedText?: string;
376381 trustedError?: string;
@@ -638,7 +643,9 @@ function readOnlyField(): Html {
638643
639644 const OLDER_FORGE_DOC = "docs/features/forge-origin-older.md";
640645
641 /** The one line for a forge older than 0.7.346 (#9626): it cannot start a connection, this side can. */
646 /**
647 * The one line for a forge older than 0.7.346 (#9626): it cannot start a connection, this side can.
648 */
642649 function olderForgeLine(db: Database): Html {
643650 return html`<p class="muted small" id="older-forge-line">
644651 A forge older than 0.7.346 cannot connect outward: connect it from here, and
@@ -829,7 +836,8 @@ function originsView(
829836 if (timing !== undefined) timing.rendering = performance.now();
830837 const githubConfigured = githubConnectable(ctx);
831838 const offers = knownOffers(ctx.app);
832 // The token form is the way that always works. Under a one-click button it is the quiet way, not an equal one.
839 // The token form is the way that always works. Under a one-click button it is the quiet way, not
840 // an equal one.
833841 const tokenPath = connectPath(
834842 "connect-token",
835843 "key",
@@ -999,9 +1007,11 @@ export async function originsPage(ctx: Ctx): Promise<Response> {
9991007 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
10001008 const denied = accountOnly(ctx);
10011009 if (denied) return denied;
1002 // A hosted forge learns what its parent can sign people in to (kept five minutes); a forge with no parent does not wait.
1010 // A hosted forge learns what its parent can sign people in to (kept five minutes); a forge with
1011 // no parent does not wait.
10031012 await brokerOffers(ctx.app);
1004 // ...and how the host answered what it was asked to let this forge reach, at most every few seconds.
1013 // ...and how the host answered what it was asked to let this forge reach, at most every few
1014 // seconds.
10051015 await refreshAsksSoon(ctx.app);
10061016 const params = ctx.url.searchParams;
10071017 const values = blankValues();
@@ -1064,7 +1074,8 @@ export async function originConnectToken(ctx: Ctx): Promise<Response> {
10641074 values.tokenHost = host;
10651075 const refused = connectRefusal(connected.error);
10661076 const gate = gatedHost(connected.error);
1067 // The host's gate refused it: one sentence and the ask, in place of a field error nobody here can act on.
1077 // The host's gate refused it: one sentence and the ask, in place of a field error nobody here
1078 // can act on.
10681079 if (gate !== undefined) {
10691080 values.blocked = await gateNote(ctx, gate);
10701081 values.offerToken = true;
@@ -1209,7 +1220,8 @@ export async function originOAuthStart(ctx: Ctx): Promise<Response> {
12091220 : connectMessage(started.error.error);
12101221 return shell(ctx, originsView(ctx, values), 422);
12111222 }
1212 // A parent's sign-in is one click: the browser goes straight to the parent, which sends it to the provider.
1223 // A parent's sign-in is one click: the browser goes straight to the parent, which sends it to the
1224 // provider.
12131225 if (started.value.brokered === true && started.value.flow === "code") return redirect(started.value.url);
12141226 // The flow's page knows where to go from the flow itself, not the link.
12151227 const qs = then === undefined ? "" : `?${thenQuery(then, link)}`;
src/web/pages/search.ts +11
@@ -768,6 +768,17 @@ const DESTRUCTIVE: {
768768 phrase: "",
769769 }),
770770 },
771 {
772 // Settings › Connected agents (#13308): one OAuth grant ended.
773 pattern: /^\/settings\/grants\/([^/]+)\/revoke$/,
774 describe: () => ({
775 verb: "Revoke",
776 title: "Revoke this connected agent?",
777 detail:
778 "Its next call to the forge is refused and it cannot refresh. To let it back in, sign it in again.",
779 phrase: "",
780 }),
781 },
771782 {
772783 pattern: /^\/settings\/origins\/([^/]+)\/delete$/,
773784 describe: () => ({
test/forge-looks.test.ts +1 −1
@@ -178,7 +178,7 @@ test("`/` signed out is its own look at phone and desktop, taken with no session
178178 test("a look below the top level is the preview seed's, taken as the owner", () => {
179179 const { looks, looksAsOwner } = manifest();
180180 for (const p of looks.filter((p) => !isTopLevel(p))) {
181 expect(p.startsWith("/preview-admin/sample") || p === "/settings/crew" || p === "/settings/security/controls" || isHelpLook(p)).toBe(true);
181 expect(p.startsWith("/preview-admin/sample") || p === "/settings/crew" || p === "/settings/security/controls" || p === "/settings/grants" || isHelpLook(p)).toBe(true);
182182 expect(looksAsOwner).toContain(p);
183183 }
184184 });
test/oauth-grants.test.ts added +278
@@ -0,0 +1,278 @@
1 /**
2 * Settings › Connected agents (#13308): each OAuth grant is one row with its
3 * client, scopes, granted and last used; Revoke is a same-origin POST that
4 * ends it before the next call (the MCP answers 401) and leaves a receipt.
5 * A refresh keeps the grant's start and last use; a hand-made token and
6 * another person's grant are never listed or ended here. The terminal
7 * screen reads the same rows.
8 */
9 import { afterAll, beforeAll, expect, test } from "bun:test";
10 import { mkdtempSync, rmSync } from "node:fs";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { revokeOAuthGrant } from "../src/actions/oauth_grants.ts";
14 import { createApp, type App } from "../src/app.ts";
15 import { createClient, issueCode, parseAuthRequest, redeemCode, refreshGrant } from "../src/core/oauth.ts";
16 import { listOAuthGrants } from "../src/core/oauth_grants.ts";
17 import { createToken } from "../src/core/tokens.ts";
18 import { createUser, type User } from "../src/core/users.ts";
19 import { serve, type Servers } from "../src/http/server.ts";
20 import { createAgent } from "../src/actions/crew.ts";
21 import type { Ctx, Screen } from "../src/tui/app/app.ts";
22 import { grantRows, oauthGrantsScreen } from "../src/tui/screens/oauthgrants.ts";
23 import type { Session } from "../src/tui/session.ts";
24 import { Screen as Surface } from "../src/tui/term/screen.ts";
25 import { theme } from "../src/tui/ui/theme.ts";
26 import { proveAll } from "./helpers/verified.ts";
27 import { quietLogs } from "./helpers/globals.ts";
28
29 quietLogs();
30
31 const REDIRECT = "https://claude.ai/api/mcp/auth_callback";
32 const verifier = "v".repeat(60);
33 const challenge = new Bun.CryptoHasher("sha256").update(verifier).digest("base64url");
34
35 let root = "";
36 let app: App;
37 let servers: Servers;
38 let alice: User;
39 let bob: User;
40 let cookie = "";
41
42 beforeAll(async () => {
43 root = mkdtempSync(join(tmpdir(), "forge-oauth-grants-"));
44 app = createApp({ dataDir: root, port: 0 });
45 const made = async (username: string): Promise<User> => {
46 const u = await createUser(app.db, {
47 origin: "seed",
48 trusted: true,
49 username,
50 email: `${username}@forge.local`,
51 password: "a-good-passphrase",
52 adminIfFirst: true,
53 });
54 if (!u.ok) throw new Error(u.error);
55 return u.value;
56 };
57 alice = await made("alice");
58 bob = await made("bob");
59 proveAll(app);
60 servers = await serve(app);
61 const signin = await fetch(`${servers.url}/signin`, {
62 method: "POST",
63 headers: { origin: servers.url },
64 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
65 redirect: "manual",
66 });
67 cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
68 });
69 afterAll(() => {
70 servers.stop();
71 app.close();
72 rmSync(root, { recursive: true, force: true });
73 });
74
75 async function grant(
76 user: User,
77 clientName: string,
78 lifetimeS: number | null = null,
79 ): Promise<{ token: string; refresh?: string; clientId: string }> {
80 const client = createClient(app.db, { name: clientName, redirectUris: [REDIRECT] });
81 const params: Record<string, string> = {
82 client_id: client.id,
83 redirect_uri: REDIRECT,
84 response_type: "code",
85 code_challenge_method: "S256",
86 code_challenge: challenge,
87 scope: "rw",
88 };
89 const request = parseAuthRequest(app.db, (n) => params[n] ?? "");
90 if (!request.ok) throw new Error(request.error);
91 const code = issueCode(app.db, user.id, request.value, { scope: "rw", name: clientName, lifetimeS });
92 const minted = await redeemCode(app.db, root, { code, clientId: client.id, redirectUri: REDIRECT, verifier, issuer: servers.url });
93 if (!minted.ok || minted.value.token === undefined) throw new Error("no token");
94 return {
95 token: minted.value.token,
96 clientId: client.id,
97 ...(minted.value.refreshToken === undefined ? {} : { refresh: minted.value.refreshToken }),
98 };
99 }
100
101 const mcp = (token: string) =>
102 fetch(`${servers.url}/mcp`, {
103 method: "POST",
104 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
105 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }),
106 });
107
108 const page = async (extra = ""): Promise<string> =>
109 (await fetch(`${servers.url}/settings/grants`, { headers: { cookie: extra === "" ? cookie : `${cookie}; ${extra}` } })).text();
110
111 const idOf = (user: User, client: string): string => {
112 const found = listOAuthGrants(app.db, user.id).find((g) => g.client === client);
113 if (found === undefined) throw new Error(`no grant for ${client}`);
114 return found.tokenId;
115 };
116
117 test("each grant is one row with its client, scope, granted and last used; a hand-made token is not one", async () => {
118 await grant(alice, "Claude Code");
119 createToken(app.db, alice.id, "laptop", "rw");
120 const grants = listOAuthGrants(app.db, alice.id);
121 expect(grants.map((g) => g.client)).toEqual(["Claude Code"]);
122 expect(grants[0]!.scope).toBe("rw");
123 expect(grants[0]!.lastUsedAt).toBeNull();
124 const html = await page();
125 expect(html).toContain("<strong>Claude Code</strong>");
126 expect(html).toContain("never used");
127 expect(html).not.toContain("<strong>laptop</strong>");
128 expect(html).toContain('href="/settings/grants"');
129 });
130
131 test("Revoke asks first: the row links to /-/confirm, whose form posts to the grant's revoke", async () => {
132 await grant(alice, "Claude Code");
133 const to = `/settings/grants/${idOf(alice, "Claude Code")}/revoke`;
134 const html = await page();
135 expect(html).toContain(`href="/-/confirm?to=${encodeURIComponent(to)}"`);
136 expect(html).not.toContain(`action="${to}"`);
137 const confirm = await (
138 await fetch(`${servers.url}/-/confirm?to=${encodeURIComponent(to)}`, { headers: { cookie } })
139 ).text();
140 expect(confirm).toContain("Revoke this connected agent?");
141 expect(confirm).toContain(`action="${to}"`);
142 });
143
144 test("a client name with <script> is escaped on the page", async () => {
145 await grant(alice, "<script>alert(1)</script>");
146 const html = await page();
147 expect(html).not.toContain("<script>alert(1)</script>");
148 expect(html).toContain("&lt;script&gt;alert(1)&lt;/script&gt;");
149 });
150
151 test("revoking is a same-origin POST: the next MCP call gets 401, and the page says what it ended", async () => {
152 const { token } = await grant(alice, "Grok in a car");
153 expect((await mcp(token)).status).not.toBe(401);
154 expect(listOAuthGrants(app.db, alice.id).find((g) => g.client === "Grok in a car")!.lastUsedAt).not.toBeNull();
155 const id = idOf(alice, "Grok in a car");
156
157 const forged = await fetch(`${servers.url}/settings/grants/${id}/revoke`, {
158 method: "POST",
159 headers: { cookie, origin: "https://evil.example" },
160 redirect: "manual",
161 });
162 expect(forged.status).toBe(403);
163 expect((await mcp(token)).status).not.toBe(401);
164
165 const res = await fetch(`${servers.url}/settings/grants/${id}/revoke`, {
166 method: "POST",
167 headers: { cookie, origin: servers.url },
168 redirect: "manual",
169 });
170 expect(res.status).toBe(303);
171 expect(res.headers.get("location")).toEndWith("/settings/grants");
172 expect((await mcp(token)).status).toBe(401);
173 const flash = res.headers.getSetCookie().find((c) => c.startsWith("forge_flash="))!.split(";")[0]!;
174 const after = await page(flash);
175 expect(after).toContain("Revoked Grok in a car (rw): its next call is refused");
176 expect(after).not.toContain("<strong>Grok in a car</strong>");
177 });
178
179 test("a revoked grant with a refresh token cannot refresh its way back", async () => {
180 const { refresh, clientId } = await grant(alice, "Renewing harness", 86_400);
181 revokeOAuthGrant(app, alice, idOf(alice, "Renewing harness"));
182 expect(refreshGrant(app.db, { refreshToken: refresh!, clientId, scope: "" }).ok).toBe(false);
183 });
184
185 test("a refresh keeps when the grant began and when it was last used", async () => {
186 const { token, refresh, clientId } = await grant(alice, "Rotating harness", 86_400);
187 await mcp(token);
188 const before = listOAuthGrants(app.db, alice.id).find((g) => g.client === "Rotating harness")!;
189 app.db.query("UPDATE oauth_token SET granted_at = '2026-01-02T03:04:05.000Z' WHERE token_id = ?1").run(before.tokenId);
190 const rotated = refreshGrant(app.db, { refreshToken: refresh!, clientId, scope: "" });
191 expect(rotated.ok).toBe(true);
192 const after = listOAuthGrants(app.db, alice.id).find((g) => g.client === "Rotating harness")!;
193 expect(after.tokenId).not.toBe(before.tokenId);
194 expect(after.grantedAt).toBe("2026-01-02T03:04:05.000Z");
195 expect(after.lastUsedAt).toBe(before.lastUsedAt);
196 expect(after.renews).toBe(true);
197 });
198
199 test("another person's grant and a hand-made token are not this page's to end", async () => {
200 const { token } = await grant(bob, "Bob's agent");
201 const res = await fetch(`${servers.url}/settings/grants/${idOf(bob, "Bob's agent")}/revoke`, {
202 method: "POST",
203 headers: { cookie, origin: servers.url },
204 redirect: "manual",
205 });
206 expect(res.status).toBe(303);
207 expect((await mcp(token)).status).not.toBe(401);
208 const laptop = createToken(app.db, alice.id, "desk", "rw");
209 expect(revokeOAuthGrant(app, alice, laptop.id).ok).toBe(false);
210 expect((await page()).includes("Bob&#39;s agent") || (await page()).includes("Bob's agent")).toBe(false);
211 });
212
213 test("the terminal screen reads the same rows", () => {
214 const rows = grantRows(listOAuthGrants(app.db, alice.id));
outdated

The terminal door's write is untested. Add a test that drives oauthGrantsScreen (key x, then the Revoke choice in confirmScreen) and asserts the token is gone, the next /mcp call gets 401, and a guest or agent session sees no rows and revokes nothing. The existing terminal test only covers the row formatting, so a broken x binding or gate would pass.

215 const claude = rows.find((r) => r.title === "Claude Code")!;
216 expect(claude.secondary).toBe("rw");
217 expect(claude.meta).toStartWith("granted ");
218 expect(claude.meta).toContain("never used");
219 });
220
221 /** The terminal's Connected agents for `user`, with the screens it pushes kept to drive. */
222 function terminal(user: User | undefined) {
223 const pushed: Screen[] = [];
224 const ctx = {
225 theme: theme("dark"),
226 invalidate() {},
227 toast() {},
228 push: (s: Screen) => pushed.push(s),
229 pop() {},
230 copy() {},
231 hit() {},
232 } as unknown as Ctx;
233 const f = { app, db: app.db, user } as unknown as Session;
234 const screen = oauthGrantsScreen(f, ctx);
235 const press = (key: string, on: Screen = screen) => on.key!({ type: "key", key, ctrl: false, alt: false, shift: false });
236 const draw = (): string => {
237 const s = new Surface(110, 20);
238 screen.render({ x: 0, y: 0, w: 110, h: 20 }, s);
239 return s.toText();
240 };
241 return { pushed, press, draw };
242 }
243
244 test("the terminal's x asks first; Keep ends nothing, Revoke ends the grant and the MCP answers 401", async () => {
245 for (const g of listOAuthGrants(app.db, alice.id)) revokeOAuthGrant(app, alice, g.tokenId);
246 const { token } = await grant(alice, "Terminal harness");
247 const t = terminal(alice);
248 expect(t.draw()).toContain("Terminal harness");
249
250 t.press("x");
251 expect(t.pushed).toHaveLength(1);
252 expect(t.pushed[0]!.title).toBe("Revoke a connected agent");
253 t.press("enter", t.pushed[0]!); // Keep is the first choice
254 expect(listOAuthGrants(app.db, alice.id).map((g) => g.client)).toEqual(["Terminal harness"]);
255 expect((await mcp(token)).status).not.toBe(401);
256
257 t.press("x");
258 expect(t.pushed).toHaveLength(2);
259 t.press("right", t.pushed[1]!);
260 t.press("enter", t.pushed[1]!);
261 expect(listOAuthGrants(app.db, alice.id)).toEqual([]);
262 expect((await mcp(token)).status).toBe(401);
263 expect(t.draw()).toContain("Revoked Terminal harness (rw)");
264 });
265
266 test("in the terminal a guest and an agent see no rows and x revokes nothing", async () => {
267 const { token } = await grant(alice, "Still mine");
268 const made = await createAgent(app, alice, { username: "helper" });
269 if (!made.ok) throw new Error(JSON.stringify(made.error));
270 for (const who of [undefined, made.value.user]) {
271 const t = terminal(who);
272 expect(t.draw()).not.toContain("Still mine");
273 t.press("x");
274 expect(t.pushed).toHaveLength(0);
275 }
276 expect(listOAuthGrants(app.db, alice.id).map((g) => g.client)).toContain("Still mine");
277 expect((await mcp(token)).status).not.toBe(401);
278 });
test/palette-roster.test.ts +3
@@ -117,6 +117,7 @@ test("a site-admin person is offered the whole roster", () => {
117117 ["front-milestones", "Milestones", "the biggest open milestones: how far, what landed this week"],
118118 ["forge-view", "Forge view", "the forge's counts, and Foundry when it is installed"],
119119 ["captain", "Captain", "what Talk remembers, and the check-ins it posts for you"],
120 ["oauth-grants", "Connected agents", "the agents you let in through OAuth; x revokes one"],
120121 ["origin-apps", "Connection apps", "your OAuth apps for connecting accounts; a adds, d removes"],
121122 ["system-memory", "System memory", "RSS beside the JS heap, hourly for 24 h"],
122123 ["flow", "Flow", "the pipeline's bottleneck and throughput"],
@@ -274,6 +275,7 @@ test("a site-admin agent is offered the roster without the person-only entries",
274275 ["signins", "Signed in", "your browsers and tokens; d signs a browser out"],
275276 ["sentinel", "Sentinel", "the forge's open faults"],
276277 ["resilience", "Resilience", "where snapshots go and the mirror; each protection green, red or untested"],
278 ["oauth-grants", "Connected agents", "the agents you let in through OAuth; x revokes one"],
277279 ["origin-apps", "Connection apps", "your OAuth apps for connecting accounts; a adds, d removes"],
278280 ["api", "API", "the forge's endpoints; run a GET"],
279281 ["docs", "Docs", "the forge's documentation; Enter reads one"],
@@ -382,6 +384,7 @@ test("a member person is offered the signed-in roster without the admin entries"
382384 ["passkeys", "Passkeys", "the passkeys that sign in as you"],
383385 ["account", "Account settings", undefined],
384386 ["signins", "Signed in", "your browsers and tokens; d signs a browser out"],
387 ["oauth-grants", "Connected agents", "the agents you let in through OAuth; x revokes one"],
385388 ["origin-apps", "Connection apps", "your OAuth apps for connecting accounts; a adds, d removes"],
386389 ["api", "API", "the forge's endpoints; run a GET"],
387390 ["docs", "Docs", "the forge's documentation; Enter reads one"],

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs