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

A session's list on the account page shows each signed-in browser with when it last acted, and signs one out in one tap #14166

Merged opened this

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

Merged

torque/forge:torque/14154-a-session-s-list-on-the-account-page-sho → main 2 commits fork 1 thread · 1 unresolved

  • Merged. torque/14154-a-session-s-list-on-the-account-page-sho was merged into main as cbf5fa8.

Review

Sign in to review this change.
11 files changed +180 −13
docs/features/README.md +1
@@ -450,6 +450,7 @@ Read with the guide page [Agents: MCP, git, or the terminal](../guide-agents.md)
450450 - [The receipt an outsider is handed for a report](report-receipt.md)
451451 - [A team's effective share of builder slots](team-effective-share.md)
452452 - [Which harness holds a token](tokens-harness.md)
453 - [Signed-in browsers: each named, and signed out one at a time](signed-in-browsers.md)
453454
454455 ### Backups and moving
455456
docs/features/signed-in-browsers.md added +27
@@ -0,0 +1,27 @@
1 # Signed-in browsers
2
3 **Settings › Tokens** lists every browser your account is signed in on (#14154).
4 Each row names the browser in plain words, such as "Firefox on Linux" or "Safari
5 on iPhone", and says when it signed in and when it was last used (and from which
6 address, when that was recorded).
7
8 - **The name** comes from the browser's User-Agent the first time the session is
9 used (`src/auth/browser_name.ts`), and stays the same after that. Only the
10 short name is kept, never the raw header. A session that has not been used
11 since this change reads "A browser".
12 - **Sign out** on a row first asks you to confirm, then sends a same-origin
13 POST to `/settings/sessions/<row id>/delete`. That browser is signed out on
14 its next request, its open live streams end, and the row is gone from the
15 page. The row id is opaque: it is not the cookie's secret, and the secret
16 never appears on a page.
17 - **This browser** is marked, and its own row has no Sign out, so you cannot end
18 the session you are reading by mistake. Use the menu's Sign out for that.
19 - You can only end your own browsers. The forge's owner can end a person's
20 browsers from their account page ([account-access.md](account-access.md)).
21 Anyone else gets "not found", whether they use the page, the API or the MCP.
22
23 The same list and the same act are available as
24 `GET /api/v1/users/<name>/signins` and `DELETE /api/v1/users/<name>/sessions/<id>`,
25 as the MCP `sessions` tool (`action: "end"` with an `id`), and on the terminal's
26 sign-ins screen, where each browser row carries the same name. Tested in
27 `test/signins.test.ts` and `test/browser-name.test.ts`.
src/auth/browser_name.ts added +50
@@ -0,0 +1,50 @@
1 /**
2 * A signed-in browser's name in plain words (#14154): "Firefox on Linux",
3 * "Safari on iPhone". Taken from the User-Agent the first time a session is
4 * used and kept on its row, so a person can tell their browsers apart on
5 * the account page. Only this short name is kept, never the raw header.
6 *
7 * The header is the client's word, not a proof: the name is a label, and no
8 * decision is ever made on it. The order matters where browsers borrow each
9 * other's tokens (Edge and Opera say Chrome, Chrome says Safari).
10 */
11
12 /** The longest header looked at; a longer one is a client being odd, not a richer name. */
13 const UA_MAX = 400;
14
15 const BROWSERS: readonly (readonly [RegExp, string])[] = [
16 [/\bEdg(?:e|A|iOS)?\//, "Edge"],
17 [/\b(?:OPR|Opera)\//, "Opera"],
18 [/\b(?:Firefox|FxiOS)\//, "Firefox"],
19 [/\bSamsungBrowser\//, "Samsung Internet"],
20 [/\b(?:Chrome|Chromium|CriOS)\//, "Chrome"],
21 [/\bSafari\//, "Safari"],
22 [/\bcurl\//i, "curl"],
23 ];
24
25 const SYSTEMS: readonly (readonly [RegExp, string])[] = [
26 [/\biPhone\b/, "iPhone"],
27 [/\biPad\b/, "iPad"],
28 [/\bAndroid\b/, "Android"],
29 [/\bCrOS\b/, "ChromeOS"],
30 [/\bWindows\b/, "Windows"],
31 [/\bMac OS X\b|\bMacintosh\b/, "macOS"],
32 [/\bLinux\b/, "Linux"],
33 ];
34
35 /**
36 * The plain name of the browser a User-Agent describes; "A browser" when
37 * neither the browser nor the system is one this knows, and null when there
38 * is no header at all.
39 */
40 export function browserName(userAgent: string | null | undefined): string | null {
41 if (userAgent === null || userAgent === undefined) return null;
42 const ua = userAgent.slice(0, UA_MAX);
43 if (ua.trim() === "") return null;
44 const browser = BROWSERS.find(([re]) => re.test(ua))?.[1];
45 const system = SYSTEMS.find(([re]) => re.test(ua))?.[1];
46 if (browser !== undefined && system !== undefined) return `${browser} on ${system}`;
47 if (browser !== undefined) return browser;
48 if (system !== undefined) return `A browser on ${system}`;
49 return "A browser";
50 }
src/core/migration-pins/20261116120000-session-browser.pin added +1
@@ -0,0 +1,1 @@
1 9c69a8a99330d76c692ef987ac358ca0bcbfbad0907d2b0e3adecfdb995c911d
src/core/migrations/20261116120000-session-browser.ts added +6
@@ -0,0 +1,6 @@
1 // A signed-in browser's name in plain words (#14154), from its User-Agent the first time the
2 // session is used (`auth/browser_name.ts`): "Firefox on Linux". Only the short name, never the
3 // raw header. One nullable column. Additive.
4 export default `
5 ALTER TABLE session ADD COLUMN browser TEXT;
6 `;
src/core/sessions.ts +16 −3
@@ -22,6 +22,11 @@ export interface SessionInfo {
2222 readonly expiresAt: string;
2323 /** Where it was first seen from, when that was recorded. */
2424 readonly address: string | null;
25 /**
26 * Its browser in plain words ("Firefox on Linux"), once it has been used
27 * (`auth/browser_name.ts`).
28 */
29 readonly browser: string | null;
2530 /** The browser asking: signing it out signs the asker out. */
2631 readonly current: boolean;
2732 }
@@ -51,6 +56,7 @@ export function sessionOf(
5156 db: Database,
5257 token: string,
5358 address?: string,
59 browser?: string | null,
5460 ): Result<{ user: User; id: string; notice: boolean }, "invalid_session"> {
5561 const hash = sha256(token);
5662 const row = db
@@ -80,9 +86,14 @@ export function sessionOf(
8086 quietly(db, () =>
8187 db
8288 .query(
83 "UPDATE session SET last_seen_at = ?1, address = COALESCE(address, ?3) WHERE token_hash = ?2",
89 "UPDATE session SET last_seen_at = ?1, address = COALESCE(address, ?3), browser = COALESCE(browser, ?4) WHERE token_hash = ?2",
8490 )
85 .run(now.toISOString(), hash, address === undefined || address === "unknown" ? null : address),
91 .run(
92 now.toISOString(),
93 hash,
94 address === undefined || address === "unknown" ? null : address,
95 browser === undefined || browser === null ? null : browser.slice(0, 64),
96 ),
8697 );
8798 return ok({ user, id: row.id, notice: row.notice === 1 });
8899 }
@@ -110,10 +121,11 @@ export function listSessions(
110121 last_seen_at: string | null;
111122 expires_at: string;
112123 address: string | null;
124 browser: string | null;
113125 },
114126 [string, string]
115127 >(
116 `SELECT id, token_hash, created_at, last_seen_at, expires_at, address FROM session
128 `SELECT id, token_hash, created_at, last_seen_at, expires_at, address, browser FROM session
117129 WHERE user_id = ?1 AND expires_at > ?2 ORDER BY created_at DESC, id`,
118130 )
119131 .all(userId, new Date().toISOString())
@@ -123,6 +135,7 @@ export function listSessions(
123135 lastSeenAt: r.last_seen_at,
124136 expiresAt: r.expires_at,
125137 address: r.address,
138 browser: r.browser,
126139 current: r.token_hash === mine,
127140 }));
128141 }
src/http/server.ts +2 −1
@@ -95,6 +95,7 @@ import { pullForBranch, trackPullHead } from "../core/pulls.ts";
9595 import { recombine } from "../core/recombine.ts";
9696 import { createRepo, repositoryLimitMessage, resolveOwner } from "../actions/repos.ts";
9797 import { sessionOf } from "../core/sessions.ts";
98 import { browserName } from "../auth/browser_name.ts";
9899 import { scopeAllows, verifyToken } from "../core/tokens.ts";
99100 import {
100101 ensureEdgeUser,
@@ -731,7 +732,7 @@ async function resolveAuth(app: App, request: Request): Promise<Auth> {
731732
732733 const session = cookieValue(request, "forge_session");
733734 if (session !== undefined) {
734 const found = sessionOf(app.db, session, clientAddress(request));
735 const found = sessionOf(app.db, session, clientAddress(request), browserName(request.headers.get("user-agent")));
735736 if (found.ok)
736737 return {
737738 user: found.value.user,
src/tui/screens/signins.ts +1 −1
@@ -79,7 +79,7 @@ export function signInsOf(f: Session): SignIn[] {
7979 ...seen.value.sessions.map((s) => ({
8080 kind: "browser" as const,
8181 id: s.id,
82 where: `web browser ${shortId(s.id)}`,
82 where: `${s.browser ?? "web browser"} ${shortId(s.id)}`,
8383 seen: s.lastSeenAt,
8484 since: s.createdAt,
8585 here: s.current,
src/web/pages/account.ts +13 −7
@@ -778,13 +778,19 @@ export function sessionsCard(
778778 : html`<ul class="list setting-list">
779779 ${sessions.map((x) =>
780780 row({
781 title: html`${time(x.createdAt)} ${x.current ? badge("This browser") : null}`,
782 meta: html`last seen ${x.lastSeenAt ? time(x.lastSeenAt) : "not since"}${x.address === null ? null : html` · from ${x.address}`}`,
783 trail: html`${confirmAction({
784 action: `${base}/sessions/${x.id}/delete`,
785 verb: "Sign out",
786 size: "sm",
787 })}`,
781 title: html`${x.browser ?? "A browser"} ${x.current ? badge("This browser") : null}`,
782 meta: html`signed in ${time(x.createdAt)} · last used ${x.lastSeenAt ? time(x.lastSeenAt) : "not since"}${x.address === null ? null : html` · from ${x.address}`}`,
783 // The browser asking has no Sign out on its own row (#14154): ending it here would
784 // sign this page out by a slip. The menu's Sign out is the deliberate way. The
785 // title's badge already marks it, so the trail stays empty.
786 trail: x.current
outdated

Principle 1: nothing explains itself twice. The title already carries badge("This browser"); this span repeats it. Keep one marker and leave the trail empty on the current row.

787 ? html``
788 : html`${confirmAction({
789 action: `${base}/sessions/${x.id}/delete`,
790 verb: "Sign out",
791 size: "sm",
792 label: `Sign out ${x.browser ?? "the browser"} signed in ${x.createdAt.slice(0, 10)}`,
793 })}`,
788794 }),
789795 )}
790796 </ul>`,
test/browser-name.test.ts added +31
@@ -0,0 +1,31 @@
1 import { describe, expect, test } from "bun:test";
2 import { browserName } from "../src/auth/browser_name.ts";
3
4 // Real User-Agent strings, each named the way a person would say it (#14154).
5 describe("a browser's name in plain words", () => {
6 const cases: [string, string][] = [
7 ["Mozilla/5.0 (X11; Linux x86_64; rv:132.0) Gecko/20100101 Firefox/132.0", "Firefox on Linux"],
8 ["Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.1 Safari/605.1.15", "Safari on macOS"],
9 ["Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36", "Chrome on Windows"],
10 ["Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0", "Edge on Windows"],
11 ["Mozilla/5.0 (iPhone; CPU iPhone OS 18_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.1 Mobile/15E148 Safari/604.1", "Safari on iPhone"],
12 ["Mozilla/5.0 (iPhone; CPU iPhone OS 18_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/131.0.6778.73 Mobile/15E148 Safari/604.1", "Chrome on iPhone"],
13 ["Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Mobile Safari/537.36", "Chrome on Android"],
14 ["Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 OPR/114.0.0.0", "Opera on Linux"],
15 ["Mozilla/5.0 (X11; CrOS x86_64 14541.0.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36", "Chrome on ChromeOS"],
16 ["curl/8.5.0", "curl"],
17 ["Mozilla/5.0 (Windows NT 10.0) Something/1.0", "A browser on Windows"],
18 ["weird-client", "A browser"],
19 ];
20 for (const [ua, name] of cases) test(name, () => expect(browserName(ua)).toBe(name));
21
22 test("no header is no name", () => {
23 expect(browserName(null)).toBeNull();
24 expect(browserName(undefined)).toBeNull();
25 expect(browserName(" ")).toBeNull();
26 });
27
28 test("the name is one of a short fixed set, whatever the header carries", () => {
29 expect(browserName(`<script>alert(1)</script> ${"x".repeat(10_000)}`)).toBe("A browser");
30 });
31 });
test/signins.test.ts +32 −1
@@ -85,7 +85,9 @@ describe("sign-ins: tokens and browsers, seen and ended", () => {
8585 ).text();
8686 expect(page).toContain("Signed-in browsers");
8787 expect(page).toContain("This browser");
88 expect(page.match(/%2Fsettings%2Fsessions%2F[^%"]+%2Fdelete/g)?.length).toBe(2);
88 // Only the other browser's row offers Sign out: this one's cannot end itself by a slip
89 // (#14154).
90 expect(page.match(/%2Fsettings%2Fsessions%2F[^%"]+%2Fdelete/g)?.length).toBe(1);
8991 expect(await signedIn({ cookie: there })).toBe(true);
9092
9193 const mine = listSessions(app.db, ada.id, here.split("=")[1]);
@@ -97,6 +99,35 @@ describe("sign-ins: tokens and browsers, seen and ended", () => {
9799 expect(await signedIn({ cookie: here })).toBe(true);
98100 });
99101
102 test("each browser is named in plain words, with when it signed in and was last used, and no secret on the page", async () => {
103 const carl = await person("carl");
104 const here = cookieFor(carl);
105 const there = cookieFor(carl);
106 const firefox = "Mozilla/5.0 (X11; Linux x86_64; rv:132.0) Gecko/20100101 Firefox/132.0";
107 const iphone =
108 "Mozilla/5.0 (iPhone; CPU iPhone OS 18_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.1 Mobile/15E148 Safari/604.1";
109 await fetch(`${base}/api/v1/user`, { headers: { cookie: there, "user-agent": iphone } });
110 const page = await (
111 await fetch(`${base}/settings/tokens`, { headers: { cookie: here, "user-agent": firefox } })
112 ).text();
113 expect(page).toContain("Firefox on Linux");
114 expect(page).toContain("Safari on iPhone");
115 expect(page).toContain("last used");
116 // The current row is marked once, by its badge (DESIGN.md principle 1).
117 expect(page).toContain("This browser");
118 expect(page).not.toContain(`<span class="muted small">this browser</span>`);
119 // The cookie's secret never reaches HTML; the row's id is not the secret.
120 for (const c of [here, there]) expect(page).not.toContain(c.split("=")[1]!);
121 const named = listSessions(app.db, carl.id).map((s) => s.browser).sort();
122 expect(named).toEqual(["Firefox on Linux", "Safari on iPhone"]);
123 // Signing the other one out takes its row off the page.
124 const away = listSessions(app.db, carl.id, here.split("=")[1]).find((s) => !s.current)!;
125 expect((await post(`/settings/sessions/${away.id}/delete`, here)).status).toBe(303);
126 const after = await (await fetch(`${base}/settings/tokens`, { headers: { cookie: here } })).text();
127 expect(after).not.toContain("Safari on iPhone");
128 expect(after).toContain("Firefox on Linux");
129 });
130
100131 test("signing a browser out ends the live streams it opened, and only those", async () => {
101132 const here = cookieFor(ada);
102133 const there = cookieFor(ada);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs