Public: anyone can read this; the crew can change it.
A token's last-used time shows on its row in settings, so an unused token is easy to spot and revoke #14165
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/14120-a-token-s-last-used-time-shows-on-its-ro → main 5 commits fork
10 files
changed +165
−13
docs/features/README.md +1
| @@ -450,6 +450,7 @@ Read with the guide page [Agents: MCP, git, or the terminal](../guide-agents.md) | ||
| 450 | 450 | - [](report-receipt.md) |
| 451 | 451 | - [](team-effective-share.md) |
| 452 | 452 | - [](tokens-harness.md) |
| 453 | - [](token-last-used.md) | |
| 453 | 454 | |
| 454 | 455 | ### Backups and moving |
| 455 | 456 |
docs/features/token-last-used.md added +5
| @@ -0,0 +1,5 @@ | ||
| 1 | # A token's last use (#14120) | |
| 2 | ||
| 3 | Settings › Tokens shows each access code's last use on its row: "last used 3d ago", or "never used" until it first answers a request. The terminal's *Signed in* screen (palette: *Signed in*) reads a token's row the same way. | |
| 4 | ||
| 5 | The time is written when the token is verified, at most once an hour per token (`TOUCH_EVERY_MS` in `src/core/tokens.ts`), so it answers "is this still in use, or can I revoke it?" without a write on every request. A refused token (unknown, expired, its person suspended) is never recorded as used. Tests: `test/token-last-used.test.ts`, `test/tui-signins-token.test.ts`. |
src/core/oauth_grants.ts +3 −3
| @@ -3,9 +3,9 @@ | ||
| 3 | 3 | * endpoint minted, with the client that holds it, what it may do, when it |
| 4 | 4 | * was granted and when it was last used. A refresh rotates the token but not |
| 5 | 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. | |
| 6 | * `refreshGrant`). `last_used_at` is the token's own, written at most once an | |
| 7 | * hour per token by `verifyToken` (`TOUCH_EVERY_MS`), so a busy harness | |
| 8 | * costs one write an hour, not one per call. | |
| 9 | 9 | */ |
| 10 | 10 | import type { Database } from "bun:sqlite"; |
| 11 | 11 | import type { TokenScope } from "./tokens.ts"; |
src/core/tokens.ts +7 −4
| @@ -68,11 +68,14 @@ export function createToken( | ||
| 68 | 68 | * whose only reader is a human glancing at a settings page. At two hundred |
| 69 | 69 | * agents that is the busiest write in the forge, and it is bookkeeping. |
| 70 | 70 | * |
| 71 | * A minute of resolution answers the only question anyone asks of this field | |
| 72 | * — "is this token still in use?" — and turns those writes into one per | |
| 73 | * token per minute. | |
| 71 | * An hour of resolution answers the only question anyone asks of this field | |
| 72 | * — "is this token still in use, or can I revoke it?" — and turns those | |
| 73 | * writes into one per token per hour (#14120). The row is already read to | |
| 74 | * verify the token, so the throttle costs no extra query. A refused token | |
| 75 | * (unknown, expired, its person suspended) returns before this and is never | |
| 76 | * recorded as used. | |
| 74 | 77 | */ |
| 75 | const TOUCH_EVERY_MS = 60_000; | |
| 78 | export const TOUCH_EVERY_MS = 3_600_000; | |
| 76 | 79 | |
| 77 | 80 | export function verifyToken( |
| 78 | 81 | db: Database, |
src/tui/screens/signins.ts +5 −1
| @@ -162,7 +162,11 @@ export function signInsScreen(f: Session, ctx: Ctx): Screen { | ||
| 162 | 162 | all.map((s) => ({ |
| 163 | 163 | title: s.here ? `${s.where} · this one` : s.where, |
| 164 | 164 | secondary: s.kind, |
| 165 | meta: `last seen ${s.seen === null ? "never" : ago(s.seen)} · since ${s.since.slice(0, 10)}`, | |
| 165 | // A token's row reads as Settings › Tokens does: "never used" or "last used 3d ago" (#14120). | |
| 166 | meta: | |
| 167 | s.kind === "token" | |
| 168 | ? `${s.seen === null ? "never used" : `last used ${ago(s.seen)}`} · since ${s.since.slice(0, 10)}` | |
| 169 | : `last seen ${s.seen === null ? "never" : ago(s.seen)} · since ${s.since.slice(0, 10)}`, | |
| 166 | 170 | })); |
| 167 | 171 | |
| 168 | 172 | const end = (picked: SignIn): void => { |
src/web/pages/account.ts +1 −1
| @@ -840,7 +840,7 @@ function tokensView(ctx: Ctx): Html { | ||
| 840 | 840 | ${tokens.map((t) => |
| 841 | 841 | row({ |
| 842 | 842 | title: html`<strong>${t.name}</strong> ${badge(t.scope)} ${actsAsAdmin}`, |
| 843 | meta: html`created ${time(t.createdAt)} · last used ${t.lastUsedAt ? time(t.lastUsedAt) : "never"}${when( | |
| 843 | meta: html`created ${time(t.createdAt)} · ${t.lastUsedAt ? html`last used ${time(t.lastUsedAt)}` : "never used"}${when( | |
| 844 | 844 | t.oauthClient, |
| 845 | 845 | (client) => html`<span data-oauth-client> · ${client} · Signed in through OAuth; renews itself until you delete it</span>`, |
| 846 | 846 | )}`, |
test/scale.test.ts +3 −3
| @@ -568,7 +568,7 @@ describe("the cat-file reader pool", () => { | ||
| 568 | 568 | }); |
| 569 | 569 | |
| 570 | 570 | describe("a token in constant use is not a write per request", () => { |
| 571 | test("last_used_at is recorded once, then left alone for a minute", async () => { | |
| 571 | test("last_used_at is recorded once, then left alone for an hour", async () => { | |
| 572 | 572 | const dataDir = await mkdtemp(join(tmpdir(), "forge-touch-")); |
| 573 | 573 | const app = createApp({ dataDir, port: 0 }); |
| 574 | 574 | try { |
| @@ -589,7 +589,7 @@ describe("a token in constant use is not a write per request", () => { | ||
| 589 | 589 | .get(minted.id)!.last_used_at; |
| 590 | 590 | expect(first).not.toBeNull(); |
| 591 | 591 | |
| 592 | // A hundred more requests in the same minute must not write a hundred | |
| 592 | // A hundred more requests in the same hour must not write a hundred | |
| 593 | 593 | // times — this used to be the busiest write in the forge, for a |
| 594 | 594 | // timestamp whose only reader is a settings page. |
| 595 | 595 | for (let i = 0; i < 100; i++) verifyToken(app.db, minted.token); |
| @@ -609,7 +609,7 @@ describe("a token in constant use is not a write per request", () => { | ||
| 609 | 609 | // strings, so `refreshed !== first` is a coin flip that comes up |
| 610 | 610 | // heads on an idle laptop and tails on a loaded one. This asserts the |
| 611 | 611 | // write happened, which is the actual claim. |
| 612 | const backdated = new Date(Date.now() - 10 * 60_000).toISOString(); | |
| 612 | const backdated = new Date(Date.now() - 2 * 3_600_000).toISOString(); | |
| 613 | 613 | app.db |
| 614 | 614 | .query("UPDATE token SET last_used_at = ?1 WHERE id = ?2") |
| 615 | 615 | .run(backdated, minted.id); |
test/token-last-used.test.ts added +125
| @@ -0,0 +1,125 @@ | ||
| 1 | /** | |
| 2 | * A token's last use (#14120): one stored timestamp, written by `verifyToken` | |
| 3 | * at most once an hour per token and never for a refused token; Settings › | |
| 4 | * Access codes reads it as "last used 3d ago" or "never used", and the MCP | |
| 5 | * `tokens` answer carries the same `lastUsedAt`. | |
| 6 | */ | |
| 7 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 8 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { createApp, type App } from "../src/app.ts"; | |
| 12 | import { createToken, TOUCH_EVERY_MS, verifyToken } from "../src/core/tokens.ts"; | |
| 13 | import { getUserByName } from "../src/core/users.ts"; | |
| 14 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 15 | import { quietLogs } from "./helpers/globals.ts"; | |
| 16 | import { mcpTool } from "./helpers/mcp.ts"; | |
| 17 | ||
| 18 | quietLogs(); | |
| 19 | ||
| 20 | let dir = ""; | |
| 21 | let app: App, servers: Servers, base = "", cookie = "", userId = ""; | |
| 22 | ||
| 23 | beforeAll(async () => { | |
| 24 | dir = await mkdtemp(join(tmpdir(), "forge-lastused-")); | |
| 25 | app = createApp({ dataDir: dir, port: 0 }); | |
| 26 | servers = await serve(app); | |
| 27 | base = servers.url; | |
| 28 | const signup = await fetch(`${base}/signup`, { | |
| 29 | method: "POST", | |
| 30 | body: new URLSearchParams({ username: "ada", email: "[email protected]", password: "account-password" }), | |
| 31 | redirect: "manual", | |
| 32 | }); | |
| 33 | cookie = (signup.headers.get("set-cookie") ?? "").split(";")[0]!; | |
| 34 | userId = getUserByName(app.db, "ada")!.id; | |
| 35 | }); | |
| 36 | ||
| 37 | afterAll(async () => { | |
| 38 | servers.stop(); | |
| 39 | app.close(); | |
| 40 | await rm(dir, { recursive: true, force: true }); | |
| 41 | }); | |
| 42 | ||
| 43 | const lastUsed = (id: string): string | null => | |
| 44 | app.db.query<{ last_used_at: string | null }, [string]>("SELECT last_used_at FROM token WHERE id = ?1").get(id)! | |
| 45 | .last_used_at; | |
| 46 | const setLastUsed = (id: string, at: string | null): void => { | |
| 47 | app.db.query("UPDATE token SET last_used_at = ?1 WHERE id = ?2").run(at, id); | |
| 48 | }; | |
| 49 | ||
| 50 | test("the throttle is an hour", () => { | |
| 51 | expect(TOUCH_EVERY_MS).toBe(3_600_000); | |
| 52 | }); | |
| 53 | ||
| 54 | test("a use is written once, then not again within the hour, then again after it", () => { | |
| 55 | const t = createToken(app.db, userId, "hourly", "ro"); | |
| 56 | expect(lastUsed(t.id)).toBeNull(); | |
| 57 | expect(verifyToken(app.db, t.token).ok).toBe(true); | |
| 58 | expect(lastUsed(t.id)).not.toBeNull(); | |
| 59 | ||
| 60 | // Fifty-nine minutes ago: inside the hour, so no write. | |
| 61 | const recent = new Date(Date.now() - 59 * 60_000).toISOString(); | |
| 62 | setLastUsed(t.id, recent); | |
| 63 | for (let i = 0; i < 20; i++) verifyToken(app.db, t.token); | |
| 64 | expect(lastUsed(t.id)).toBe(recent); | |
| 65 | ||
| 66 | // An hour and a minute ago: past it, so exactly one fresh write. | |
| 67 | const stale = new Date(Date.now() - 61 * 60_000).toISOString(); | |
| 68 | setLastUsed(t.id, stale); | |
| 69 | verifyToken(app.db, t.token); | |
| 70 | const fresh = lastUsed(t.id)!; | |
| 71 | expect(Date.parse(fresh)).toBeGreaterThan(Date.parse(stale) + 60 * 60_000); | |
| 72 | }); | |
| 73 | ||
| 74 | test("a refused token is never recorded as used", () => { | |
| 75 | const expired = createToken(app.db, userId, "lapsed", "ro", { | |
| 76 | expiresAt: new Date(Date.now() - 1000).toISOString(), | |
| 77 | }); | |
| 78 | expect(verifyToken(app.db, expired.token).ok).toBe(false); | |
| 79 | expect(lastUsed(expired.id)).toBeNull(); | |
| 80 | ||
| 81 | // A suspended person's token is refused, and stays unused. | |
| 82 | const held = createToken(app.db, userId, "held", "ro"); | |
| 83 | app.db.query("UPDATE user SET suspended_at = ?1 WHERE id = ?2").run(new Date().toISOString(), userId); | |
| 84 | try { | |
| 85 | expect(verifyToken(app.db, held.token).ok).toBe(false); | |
| 86 | expect(lastUsed(held.id)).toBeNull(); | |
| 87 | } finally { | |
| 88 | app.db.query("UPDATE user SET suspended_at = NULL WHERE id = ?1").run(userId); | |
| 89 | } | |
| 90 | }); | |
| 91 | ||
| 92 | test("a refused request over HTTP writes nothing", async () => { | |
| 93 | const t = createToken(app.db, userId, "gone", "ro", { expiresAt: new Date(Date.now() - 1000).toISOString() }); | |
| 94 | const res = await fetch(`${base}/api/v1/user`, { headers: { authorization: `Bearer ${t.token}` } }); | |
| 95 | expect(res.status).toBe(401); | |
| 96 | expect(lastUsed(t.id)).toBeNull(); | |
| 97 | }); | |
| 98 | ||
| 99 | test("the settings row reads 'last used 3d ago' or 'never used'", async () => { | |
| 100 | const used = createToken(app.db, userId, "used-one", "ro"); | |
| 101 | createToken(app.db, userId, "idle-one", "ro"); | |
| 102 | setLastUsed(used.id, new Date(Date.now() - 3 * 86_400_000 - 60_000).toISOString()); | |
| 103 | const res = await fetch(`${base}/settings/tokens`, { headers: { cookie } }); | |
| 104 | expect(res.status).toBe(200); | |
| 105 | const body = await res.text(); | |
| 106 | const rowOf = (name: string): string => { | |
| 107 | const at = body.indexOf(`<strong>${name}</strong>`); | |
| 108 | expect(at).toBeGreaterThan(-1); | |
| 109 | return body.slice(at, body.indexOf("</li>", at)); | |
| 110 | }; | |
| 111 | expect(rowOf("used-one")).toMatch(/last used <time[^>]*>3d ago<\/time/); | |
| 112 | expect(rowOf("idle-one")).toContain("never used"); | |
| 113 | expect(rowOf("idle-one")).not.toContain("last used"); | |
| 114 | }); | |
| 115 | ||
| 116 | test("the MCP tokens answer carries lastUsedAt", async () => { | |
| 117 | const caller = createToken(app.db, userId, "mcp-caller", "ro"); | |
| 118 | const quiet = createToken(app.db, userId, "mcp-quiet", "ro"); | |
| 119 | const answer = await mcpTool(base, caller.token, "tokens"); | |
| 120 | expect(answer.error).toBeUndefined(); | |
| 121 | const items = answer.value.items as { id: string; lastUsedAt: string | null }[]; | |
| 122 | expect(items.find((i) => i.id === caller.id)!.lastUsedAt).toBe(lastUsed(caller.id)); | |
| 123 | expect(items.find((i) => i.id === caller.id)!.lastUsedAt).not.toBeNull(); | |
| 124 | expect(items.find((i) => i.id === quiet.id)!.lastUsedAt).toBeNull(); | |
| 125 | }); |
test/tui-signins-token.test.ts +14
| @@ -92,6 +92,20 @@ describe("revoking a token from the sign-ins screen", () => { | ||
| 92 | 92 | }; |
| 93 | 93 | } |
| 94 | 94 | |
| 95 | test("a token's row reads 'never used' until it is used, then 'last used', as Settings › Tokens (#14120)", async () => { | |
| 96 | const h = boot(); | |
| 97 | await h.open(); | |
| 98 | const before = h.text().split("\n").join(" "); | |
| 99 | expect(before).toContain("never used"); | |
| 100 | expect(before).not.toContain("last used"); | |
| 101 | h.stop(); | |
| 102 | expect(verifyToken(forge.db, deploy.token).ok).toBe(true); | |
| 103 | const again = boot(); | |
| 104 | await again.open(); | |
| 105 | expect(again.text()).toContain("last used just now"); | |
| 106 | again.stop(); | |
| 107 | }); | |
| 108 | ||
| 95 | 109 | test("a cancelled confirm changes nothing; yes revokes only that token", async () => { |
| 96 | 110 | const seen: { kind: string; payload: unknown }[] = []; |
| 97 | 111 | const stop = forge.bus.subscribe((e) => seen.push({ kind: e.kind, payload: e.payload })); |
test/tui-token-make.test.ts +1 −1
| @@ -102,7 +102,7 @@ describe("making a token in the terminal", () => { | ||
| 102 | 102 | const after = h.text(); |
| 103 | 103 | expect(after).not.toContain(secret!); |
| 104 | 104 | expect(after).toContain("ci · rw"); |
| 105 | expect(after).toMatch(/ci · rw[\s\S]*last seen never/); | |
| 105 | expect(after).toMatch(/ci · rw[\s\S]*never used/); | |
| 106 | 106 | h.stop(); |
| 107 | 107 | }); |
| 108 | 108 |
new above
offline