Public: anyone can read this; the crew can change it.
OAuth refresh-token reuse revokes the grant, with a test and a line in /settings #15987
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/15974-oauth-refresh-token-reuse-revokes-the-gr → main 0 commits fork 4 threads · 4 unresolved
9 files
changed +120
−15
docs/features/oauth-refresh.md +4 −1
| @@ -15,7 +15,10 @@ curl -X POST https://<forge>/oauth/token \ | ||
| 15 | 15 | |
| 16 | 16 | - The answer is a new `access_token` and a new `refresh_token`; the old pair stops working. |
| 17 | 17 | - A spent refresh token presented again ends the whole family (OAuth 2.1 §4.3.1) |
| 18 | and leaves a `token.deleted` event with `via: oauth_refresh_reuse`. | |
| 18 | and leaves a `token.deleted` event with `via: oauth_refresh_reuse` (RFC 9700 §4.14.2). | |
| 19 | Every replay revokes; there is no grace for a lost response. The ended grant is listed under "Revoked after a token was | |
| 20 | reused" on Settings › Connected agents (`/settings/grants`), and named on the | |
| 21 | terminal's Connected agents screen. | |
| 19 | 22 | - `scope` may only narrow (`rw` to `ro`); more is `invalid_scope` and spends nothing. |
| 20 | 23 | - `POST /oauth/revoke` with either token ends the family. |
| 21 | 24 | - Deleting the access token on Settings › Tokens (or through the API, the terminal, |
src/actions/oauth_grants.ts +12 −5
| @@ -12,19 +12,26 @@ | ||
| 12 | 12 | */ |
| 13 | 13 | import type { App } from "../app.ts"; |
| 14 | 14 | import { endGrantFamily } from "../core/oauth.ts"; |
| 15 | import { listOAuthGrants, oauthGrantOf, type OAuthGrant } from "../core/oauth_grants.ts"; | |
| 15 | import { listOAuthGrants, listReusedGrants, oauthGrantOf, type OAuthGrant, type ReusedGrant } from "../core/oauth_grants.ts"; | |
| 16 | 16 | import type { User } from "../core/users.ts"; |
| 17 | 17 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 18 | 18 | import { requireUser } from "./access.ts"; |
| 19 | 19 | import { deleteToken } from "./users.ts"; |
| 20 | 20 | |
| 21 | /** The asker's grants; empty for a guest or an agent, who grant nothing. */ | |
| 22 | export function myOAuthGrants(app: App, actor: User | undefined): OAuthGrant[] { | |
| 21 | /** What `read` finds for the asker; empty for a guest or an agent, who grant nothing. */ | |
| 22 | function ownGrants<T>(actor: User | undefined, read: (userId: string) => T[]): T[] { | |
| 23 | 23 | const user = requireUser(actor); |
| 24 | if (!user.ok || user.value.kind !== "user") return []; | |
| 25 | return listOAuthGrants(app.db, user.value.id); | |
| 24 | return !user.ok || user.value.kind !== "user" ? [] : read(user.value.id); | |
| 26 | 25 | } |
| 27 | 26 | |
| 27 | /** The asker's grants. */ | |
| 28 | export const myOAuthGrants = (app: App, actor: User | undefined): OAuthGrant[] => | |
| 29 | ownGrants(actor, (id) => listOAuthGrants(app.db, id)); | |
| 30 | ||
| 31 | /** The asker's grants ended by refresh-token reuse (#15974). */ | |
| 32 | export const myReusedGrants = (app: App, actor: User | undefined): ReusedGrant[] => | |
| 33 | ownGrants(actor, (id) => listReusedGrants(app.db, id)); | |
| 34 | ||
| 28 | 35 | /** End one of the asker's grants; returns what was ended, for the receipt. */ |
| 29 | 36 | export function revokeOAuthGrant( |
| 30 | 37 | app: App, |
src/core/migration-pins/20261123130000-oauth-reuse.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | e84ff8e3565f992a75817c098a363d621a9d72abed25c346e2fdc31bf55a8a0a |
src/core/migrations/20261123130000-oauth-reuse.ts added +12
| @@ -0,0 +1,12 @@ | ||
| 1 | // A refresh token presented twice ends its grant (#15974); the grant is kept as one line so | |
| 2 | // Settings can say so. Additive. | |
| 3 | export default ` | |
| 4 | CREATE TABLE oauth_reuse ( | |
| 5 | family TEXT PRIMARY KEY, | |
| 6 | user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE, | |
| 7 | client TEXT NOT NULL, | |
| 8 | scope TEXT NOT NULL, | |
| 9 | revoked_at TEXT NOT NULL | |
| 10 | ); | |
| 11 | CREATE INDEX oauth_reuse_user ON oauth_reuse(user_id, revoked_at); | |
| 12 | `; |
src/core/oauth.ts +15 −2
| @@ -2,6 +2,11 @@ | ||
| 2 | 2 | * OAuth for the MCP: clients (RFC 7591), the authorization request a person |
| 3 | 3 | * consents to, the one-time code, and its PKCE exchange for the same token |
| 4 | 4 | * Settings mints. |
| 5 | * | |
| 6 | * Refresh-token reuse follows RFC 9700 (OAuth 2.0 Security BCP) §4.14.2: a | |
| 7 | * rotated refresh token presented again means it leaked, so every token of | |
| 8 | * the grant is revoked, every time, with no grace, and the grant is kept as | |
| 9 | * a line in `oauth_reuse` for Settings. | |
| 5 | 10 | */ |
| 6 | 11 | import type { Database } from "bun:sqlite"; |
| 7 | 12 | import { sha256 } from "../kernel/hash.ts"; |
| @@ -513,8 +518,9 @@ const SCOPE_RANK: Readonly<Record<OAuthScope, number>> = { ro: 0, rw: 1 }; | ||
| 513 | 518 | */ |
| 514 | 519 | export function refreshGrant( |
| 515 | 520 | db: Database, |
| 516 | input: { refreshToken: string; clientId: string; scope: string }, | |
| 521 | input: { refreshToken: string; clientId: string; scope: string; now?: number }, | |
| 517 | 522 | ): Result<Minted, RefreshRefusal> & { reuse?: FamilyRevoked } { |
| 523 | const now = input.now ?? Date.now(); | |
| 518 | 524 | const row = db |
| 519 | 525 | .query< |
| 520 | 526 | { |
| @@ -534,10 +540,17 @@ export function refreshGrant( | ||
| 534 | 540 | .get(sha256(input.refreshToken)); |
| 535 | 541 | if (row === null || row.client_id !== input.clientId) return err("invalid_grant"); |
| 536 | 542 | if (row.spent === 1) { |
| 543 | const client = db | |
| 544 | .query<{ name: string }, [string]>("SELECT name FROM oauth_client WHERE id = ?1") | |
| 545 | .get(row.client_id); | |
| 537 | 546 | const ended = endFamily(db, row.family); |
| 547 | if (ended !== null) | |
| 548 | db.query( | |
| 549 | "INSERT OR REPLACE INTO oauth_reuse (family, user_id, client, scope, revoked_at) VALUES (?1, ?2, ?3, ?4, ?5)", | |
| 550 | ).run(row.family, row.user_id, client?.name ?? "", row.scope, new Date(now).toISOString()); | |
| 538 | 551 | return { ...err("invalid_grant"), ...(ended === null ? {} : { reuse: ended }) }; |
| 539 | 552 | } |
| 540 | if (Date.parse(row.expires_at) <= Date.now()) { | |
| 553 | if (Date.parse(row.expires_at) <= now) { | |
| 541 | 554 | endFamily(db, row.family); |
| 542 | 555 | return err("invalid_grant"); |
| 543 | 556 | } |
src/core/oauth_grants.ts +18
| @@ -122,3 +122,21 @@ function idleGrants(db: Database, userId: string, now: Date = new Date()): OAuth | ||
| 122 | 122 | export function oauthGrantOf(db: Database, userId: string, id: string): OAuthGrant | null { |
| 123 | 123 | return listOAuthGrants(db, userId).find((g) => g.id === id) ?? null; |
| 124 | 124 | } |
| 125 | ||
| 126 | /** A grant ended because a rotated refresh token was presented again (RFC 9700 §4.14.2). */ | |
| 127 | export interface ReusedGrant { | |
| 128 | /** The client's registered name, untrusted text: escape it. */ | |
| 129 | readonly client: string; | |
| 130 | readonly scope: TokenScope; | |
| 131 | readonly revokedAt: string; | |
| 132 | } | |
| 133 | ||
| 134 | /** A person's grants ended by refresh-token reuse, newest first, at most 20. */ | |
| 135 | export function listReusedGrants(db: Database, userId: string): ReusedGrant[] { | |
| 136 | return db | |
| 137 | .query<{ client: string; scope: TokenScope; revoked_at: string }, [string]>( | |
| 138 | "SELECT client, scope, revoked_at FROM oauth_reuse WHERE user_id = ?1 ORDER BY revoked_at DESC LIMIT 20", | |
| 139 | ) | |
| 140 | .all(userId) | |
| 141 | .map((r) => ({ client: r.client, scope: r.scope, revokedAt: r.revoked_at })); | |
| 142 | } |
src/tui/screens/oauthgrants.ts +10 −2
| @@ -5,7 +5,7 @@ | ||
| 5 | 5 | * `revokeOAuthGrant` (the page's action and gate: your own grants only) and |
| 6 | 6 | * says the page's receipt. An agent and a guest see nothing to revoke. |
| 7 | 7 | */ |
| 8 | import { myOAuthGrants, revokeOAuthGrant, revokedWords } from "../../actions/oauth_grants.ts"; | |
| 8 | import { myOAuthGrants, myReusedGrants, revokeOAuthGrant, revokedWords } from "../../actions/oauth_grants.ts"; | |
| 9 | 9 | import type { OAuthGrant } from "../../core/oauth_grants.ts"; |
| 10 | 10 | import type { Ctx, Screen } from "../app/app.ts"; |
| 11 | 11 | import { binding } from "../app/keys.ts"; |
| @@ -15,6 +15,9 @@ import type { Session } from "../session.ts"; | ||
| 15 | 15 | import { fill, len, split } from "../ui/layout.ts"; |
| 16 | 16 | import { ListState, ago, confirmScreen, drawList, type ListRow } from "./common.ts"; |
| 17 | 17 | |
| 18 | /** A client's registered name is untrusted: control characters become a space. */ | |
| 19 | const plain = (s: string): string => s.replace(/[\x00-\x1f\x7f-\x9f]+/g, " ").trim(); | |
| 20 | ||
| 18 | 21 | /** One row per grant, in the page's words. */ |
| 19 | 22 | export function grantRows(grants: readonly OAuthGrant[]): ListRow[] { |
| 20 | 23 | return grants.map((g) => ({ |
| @@ -50,7 +53,8 @@ export function oauthGrantsScreen(f: Session, ctx: Ctx): Screen { | ||
| 50 | 53 | render(area, s) { |
| 51 | 54 | const c = ctx.theme.c; |
| 52 | 55 | const all = myOAuthGrants(f.app, f.user); |
| 53 | const [head, body] = split(area, "v", [len(1), fill(1)]); | |
| 56 | const reused = myReusedGrants(f.app, f.user); | |
| 57 | const [head, reuse, body] = split(area, "v", [len(1), len(reused.length === 0 ? 0 : 1), fill(1)]); | |
| 54 | 58 | const text = |
| 55 | 59 | note !== "" |
| 56 | 60 | ? note |
| @@ -60,6 +64,10 @@ export function oauthGrantsScreen(f: Session, ctx: Ctx): Screen { | ||
| 60 | 64 | ? "No agent is connected through OAuth." |
| 61 | 65 | : "Agents you let in through the MCP's sign-in. x revokes one."; |
| 62 | 66 | s.text(head!.x, head!.y, truncate(text, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w); |
| 67 | if (reused.length > 0) { | |
| 68 | const names = reused.map((g) => plain(g.client)).join(", "); | |
| 69 | s.text(reuse!.x, reuse!.y, truncate(`Revoked after a token was reused: ${names}`, reuse!.w), style(c.mutedFg, c.bg), reuse!.x + reuse!.w); | |
| 70 | } | |
| 63 | 71 | drawList(s, body!, c, state, grantRows(all)); |
| 64 | 72 | }, |
| 65 | 73 | key(e) { |
src/web/pages/grants.ts +18 −5
| @@ -7,16 +7,16 @@ | ||
| 7 | 7 | * rows and the gate are `actions/oauth_grants.ts`, which the terminal's |
| 8 | 8 | * `screens/oauthgrants.ts` shares. |
| 9 | 9 | */ |
| 10 | import { myOAuthGrants, revokeOAuthGrant, revokedWords } from "../../actions/oauth_grants.ts"; | |
| 10 | import { myOAuthGrants, myReusedGrants, revokeOAuthGrant, revokedWords } from "../../actions/oauth_grants.ts"; | |
| 11 | 11 | import { emptyNote } from "../empty_words.ts"; |
| 12 | import type { OAuthGrant } from "../../core/oauth_grants.ts"; | |
| 12 | import type { OAuthGrant, ReusedGrant } from "../../core/oauth_grants.ts"; | |
| 13 | 13 | import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts"; |
| 14 | 14 | import type { Ctx } from "../../http/context.ts"; |
| 15 | 15 | import { signInFirst } from "../chrome.ts"; |
| 16 | 16 | import { readForm } from "../form.ts"; |
| 17 | 17 | import { html, when, type Html } from "../html.ts"; |
| 18 | 18 | import { flashTo } from "../layout.ts"; |
| 19 | import { badge, confirmAction, row, time } from "../ui.ts"; | |
| 19 | import { badge, confirmAction, listCard, row, time } from "../ui.ts"; | |
| 20 | 20 | import { accountShell } from "./account.ts"; |
| 21 | 21 | |
| 22 | 22 | export const GRANTS_PATH = "/settings/grants"; |
| @@ -45,7 +45,14 @@ function grantRow(g: OAuthGrant): Html { | ||
| 45 | 45 | }); |
| 46 | 46 | } |
| 47 | 47 | |
| 48 | function grantsView(grants: readonly OAuthGrant[]): Html { | |
| 48 | function reusedRow(g: ReusedGrant): Html { | |
| 49 | return row({ | |
| 50 | title: html`<strong>${g.client}</strong> ${badge(g.scope)}`, | |
| 51 | meta: html`${time(g.revokedAt)}`, | |
outdated
Principle 1 (nothing explains itself twice): the h3 already says 'Revoked after a token was reused'; every row then repeats the reason in a long sentence. Keep one short line, e.g. 'reused token'. Principle 7: check that listCard is rows and not a box. |
||
| 52 | }); | |
| 53 | } | |
| 54 | ||
| 55 | function grantsView(grants: readonly OAuthGrant[], reused: readonly ReusedGrant[]): Html { | |
| 49 | 56 | const list = |
| 50 | 57 | grants.length === 0 |
| 51 | 58 | ? emptyNote("noAgentIsConnected") |
| @@ -58,6 +65,11 @@ function grantsView(grants: readonly OAuthGrant[]): Html { | ||
| 58 | 65 | The agents you let in through sign-in; tokens you made are under <a href="/settings/tokens">Access codes</a>. |
| 59 | 66 | </p> |
| 60 | 67 | ${list} |
| 68 | ${when( | |
| 69 | reused.length === 0 ? null : reused, | |
| 70 | (r) => html`<h3>Revoked after a token was reused</h3> | |
| 71 | ${listCard(r.map(reusedRow))}`, | |
| 72 | )} | |
| 61 | 73 | </section>`; |
| 62 | 74 | } |
| 63 | 75 | |
| @@ -66,8 +78,9 @@ export function grantsPage(ctx: Ctx): Response { | ||
| 66 | 78 | if (!ctx.auth.user) return signInFirst(ctx); |
| 67 | 79 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); |
| 68 | 80 | const grants = timePhase(ctx.request, "grants", () => myOAuthGrants(ctx.app, ctx.auth.user)); |
| 81 | const reused = myReusedGrants(ctx.app, ctx.auth.user); | |
| 69 | 82 | return timePhase(ctx.request, "render", () => |
| 70 | accountShell(ctx, "grants", "Connected agents", grantsView(grants)), | |
| 83 | accountShell(ctx, "grants", "Connected agents", grantsView(grants, reused)), | |
| 71 | 84 | ); |
| 72 | 85 | } |
| 73 | 86 |
test/oauth-grants.test.ts +30
| @@ -316,3 +316,33 @@ test("in the terminal a guest and an agent see no rows and x revokes nothing", a | ||
| 316 | 316 | expect(listOAuthGrants(app.db, alice.id).map((g) => g.client)).toContain("Still mine"); |
| 317 | 317 | expect((await mcp(token)).status).not.toBe(401); |
| 318 | 318 | }); |
| 319 | ||
| 320 | test("a rotated refresh token replayed at once revokes the grant, the new token dies too, and Settings says so (RFC 9700)", async () => { | |
| 321 | const g = await grant(alice, "Replayed <b>Agent</b>", 86_400); | |
| 322 | const input = { clientId: g.clientId, scope: "" }; | |
| 323 | const rotated = refreshGrant(app.db, { ...input, refreshToken: g.refresh! }); | |
| 324 | if (!rotated.ok) throw new Error("no rotation"); | |
| 325 | const fresh = rotated.value.refreshToken!; | |
| 326 | expect((await mcp(rotated.value.token!)).status).not.toBe(401); | |
| 327 | const replay = refreshGrant(app.db, { ...input, refreshToken: g.refresh! }); | |
| 328 | expect(replay).toMatchObject({ ok: false, error: "invalid_grant" }); | |
| 329 | expect("reuse" in replay).toBe(true); | |
| 330 | expect((await mcp(rotated.value.token!)).status).toBe(401); | |
| 331 | expect(refreshGrant(app.db, { ...input, refreshToken: fresh }).ok).toBe(false); | |
| 332 | const html = await page(); | |
| 333 | expect(html).toContain("Revoked after a token was reused"); | |
| 334 | expect(html).toContain("Replayed <b>Agent</b>"); | |
| 335 | expect(html).not.toContain("<b>Agent</b>"); | |
| 336 | expect(html).not.toContain("already used was presented"); | |
| 337 | }); | |
| 338 | ||
| 339 | test("the terminal's grants screen names a grant ended by token reuse, on its own row, control characters stripped", async () => { | |
| 340 | const g = await grant(alice, "Reused\x1b[31m in terminal", 86_400); | |
| 341 | const input = { clientId: g.clientId, scope: "" }; | |
| 342 | refreshGrant(app.db, { ...input, refreshToken: g.refresh! }); | |
outdated
This test only calls the action, so the screen change would pass without it. Drive oauthGrantsScreen and assert the rendered text. |
||
| 343 | refreshGrant(app.db, { ...input, refreshToken: g.refresh! }); | |
| 344 | const drawn = terminal(alice).draw(); | |
| 345 | expect(drawn).toContain("Revoked after a token was reused: Reused [31m in terminal"); | |
| 346 | expect(drawn).not.toContain("\x1b"); | |
| 347 | expect(terminal(undefined).draw()).not.toContain("token was reused"); | |
| 348 | }); |
new above
offline
HIGH: this returns invalid_grant without revoking when a rotated token is replayed within 10s. A thief replaying a leaked token right away keeps the grant alive, and box 1 says every presentation of a rotated token revokes. Remove the window, REPLAY_WINDOW_MS, spent_at, and the test workaround in oauth-refresh.test.ts.