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

The Admin test: a new owner is guided to a separate everyday account, told why in two sentences, and can still choose otherwise on purpose, in one journey test #12478

Merged opened this

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

Merged

mason/forge:mason/12466-the-admin-test-a-new-owner-is-guided-to → main 4 commits fork 1 thread · 1 unresolved

  • Merged. mason/12466-the-admin-test-a-new-owner-is-guided-to was merged into main as 62e6256.

Review

Sign in to review this change.
7 files changed +190 −8
docs/features/tokens-harness.md +10
@@ -16,6 +16,16 @@ client is registered. A token from before OAuth tokens were marked is listed as
1616 hand-made. "Renews itself" means the harness swaps it with its refresh token
1717 before it lapses; deleting it ends that, see [OAuth refresh](oauth-refresh.md).
1818
19 ## A site admin's tokens are labelled
20
21 A site admin's token acts as admin whatever scope it was made with (#596), so
22 every token of a site admin carries the label "acts as admin" beside its scope
23 (#12466): a badge in **Settings › Tokens**, and `<name> · <scope> · acts as
24 admin` on the **terminal's sign-ins screen**. The words are one constant,
25 `ACTS_AS_ADMIN_WORDS` in `src/core/tokens.ts`, used by both doors. Tested in
26 `test/admin-journey.test.ts` (the page) and `test/tui-signins.test.ts` (the
27 terminal).
28
1929 ## Connect Claude Code from anywhere
2030
2131 Settings › Tokens, "Connect your harness", offers one command that works
src/core/tokens.ts +6
@@ -18,6 +18,12 @@ export type TokenScope = "ro" | "rw" | "admin";
1818 /** What a non-admin is told when they ask for a token that acts as admin. */
1919 export const ADMIN_TOKEN_WORDS = "Only an admin can make a token with admin scope; ro and rw are open to you.";
2020
21 /**
22 * The label beside every token of a site admin, on the page and in the
23 * terminal alike: such a token acts as admin whatever its scope (#596, #12466).
24 */
25 export const ACTS_AS_ADMIN_WORDS = "acts as admin";
26
2127 const rank: Record<TokenScope, number> = { ro: 0, rw: 1, admin: 2 };
2228
2329 export function scopeAllows(held: TokenScope, needed: TokenScope): boolean {
src/tui/screens/signins.ts +5 −3
@@ -35,7 +35,7 @@ import { offeredPluginRepo } from "../../core/mcp_card.ts";
3535 import { publicOrigin } from "../../core/public_origin.ts";
3636 import { withinPasswordCap } from "../../core/hash-gate.ts";
3737 import { listKeys } from "../../core/keys.ts";
38 import { ADMIN_TOKEN_WORDS, type TokenScope } from "../../core/tokens.ts";
38 import { ACTS_AS_ADMIN_WORDS, ADMIN_TOKEN_WORDS, type TokenScope } from "../../core/tokens.ts";
3939 import { MIN_PASSWORD } from "../../core/users.ts";
4040 import type { Ctx, Screen } from "../app/app.ts";
4141 import { binding } from "../app/keys.ts";
@@ -68,6 +68,9 @@ export function signInsOf(f: Session): SignIn[] {
6868 // row is ever "this one" here; this terminal's key is.
6969 const seen = accountSignIns(f.app, user, user.username);
7070 if (!seen.ok) return [];
71 // A site admin's token acts as admin whatever its scope (#596): the row says
72 // so, as Settings › Tokens does (#12466).
73 const admin = user.isAdmin ? ` · ${ACTS_AS_ADMIN_WORDS}` : "";
7174 const key = f.keyId === undefined ? undefined : listKeys(f.db, user.id).find((k) => k.id === f.keyId);
7275 return [
7376 ...(key === undefined
@@ -85,8 +88,7 @@ export function signInsOf(f: Session): SignIn[] {
8588 kind: "token" as const,
8689 id: t.id,
8790 where:
88 `${t.name} · ${t.scope}${user.isAdmin ? " · acts as admin" : ""}` +
89 (t.oauthClient === null ? "" : ` · ${t.oauthClient}, renews itself`),
91 `${t.name} · ${t.scope}${admin}` + (t.oauthClient === null ? "" : ` · ${t.oauthClient}, renews itself`),
9092 seen: t.lastUsedAt,
9193 since: t.createdAt,
9294 here: false,
src/web/pages/account.ts +5 −2
@@ -43,7 +43,7 @@ import {
4343 } from "../../actions/profile_words.ts";
4444 import { endAccountSession } from "../../actions/signins.ts";
4545 import { listSessions, type SessionInfo } from "../../core/sessions.ts";
46 import { ADMIN_TOKEN_WORDS, type TokenScope } from "../../core/tokens.ts";
46 import { ACTS_AS_ADMIN_WORDS, ADMIN_TOKEN_WORDS, type TokenScope } from "../../core/tokens.ts";
4747 import { claudeInstall, opencodeInstall } from "../../core/plugin_install.ts";
4848 import type { CommitEmail, User } from "../../core/users.ts";
4949 import { isStandInEmail } from "../../core/users.ts";
@@ -818,12 +818,15 @@ function tokensView(ctx: Ctx): Html {
818818 const sessions = timePhase(ctx.request, "sessions", () =>
819819 listSessions(ctx.app.db, ctx.auth.user!.id, cookieValue(ctx.request, "forge_session")),
820820 );
821 // A site admin's token acts as admin whatever its scope (#596),
822 // so the list says so beside it (#12466).
outdated

Both doors: this label is web-only. Put the text in one shared place and use it in src/tui/screens/signins.ts too, with a test there. Principle 8: the badge copy is plain, keep it.

823 const actsAsAdmin = ctx.auth.user!.isAdmin ? badge(ACTS_AS_ADMIN_WORDS) : null;
821824 const list = tokens.length === 0
822825 ? html`<p class="muted">No access codes yet. Mint one when a script, a CI job, or another machine needs to act as you.</p>`
823826 : html`<ul class="list setting-list">
824827 ${tokens.map((t) =>
825828 row({
826 title: html`<strong>${t.name}</strong> ${badge(t.scope)}`,
829 title: html`<strong>${t.name}</strong> ${badge(t.scope)} ${actsAsAdmin}`,
827830 meta: html`created ${time(t.createdAt)} · last used ${t.lastUsedAt ? time(t.lastUsedAt) : "never"}${when(
828831 t.oauthClient,
829832 (client) => html`<span data-oauth-client> · ${client} · Signed in through OAuth; renews itself until you delete it</span>`,
test/admin-journey.test.ts added +159
@@ -0,0 +1,159 @@
1 /**
2 * The Admin test (#12466): a new owner's first minutes, walked through the
3 * doors a person uses. A forge's first sign-in is its admin (the operator's
4 * first-admin code, redeemed with a passkey); the home points to the
5 * everyday account in one quiet line; its page says why in the two sentences
6 * of `EVERYDAY_WHY` with one primary action. Making it signs the person in as
7 * the everyday account, and an admin page there is refused with the words
8 * that say to sign in as admin. Choosing to stay on admin instead is one
9 * explicit post, receipted in a flash and recorded, and the home stops
10 * asking. A token minted from the admin account says in the list that it
11 * acts as admin; the everyday account's does not.
12 */
13
14 import { ACTS_AS_ADMIN_WORDS } from "../src/core/tokens.ts";
15 import { afterAll, describe, expect, test } from "bun:test";
16 import { mkdtemp, rm } from "node:fs/promises";
17 import { tmpdir } from "node:os";
18 import { join } from "node:path";
19 import { createApp, type App } from "../src/app.ts";
20 import { mintFirstAdmin } from "../src/core/first_admin.ts";
21 import { adminOf, everydayOf, EVERYDAY_WHY, keptAdmin } from "../src/core/everyday.ts";
22 import { SIGN_IN_AS_ADMIN } from "../src/core/roles.ts";
23 import { getUserByName } from "../src/core/users.ts";
24 import { serve, type Servers } from "../src/http/server.ts";
25 import { escapeHtml } from "../src/web/html.ts";
26 import { quietLogs } from "./helpers/globals.ts";
27 import { passkeyFields } from "./helpers/passkey.ts";
28
29 quietLogs();
30
31 const HOME_LINE = "You are signed in as the admin. Make an everyday account";
32 const ACTS_AS_ADMIN = `<span class="badge">${ACTS_AS_ADMIN_WORDS}</span>`;
33
34 const dirs: string[] = [];
35 const opened: { app: App; servers: Servers }[] = [];
36 afterAll(async () => {
37 for (const { app, servers } of opened) {
38 servers.stop();
39 app.close();
40 }
41 for (const d of dirs) await rm(d, { recursive: true, force: true });
42 });
43
44 /** A fresh forge with no one on it yet. */
45 async function freshForge() {
46 const dir = await mkdtemp(join(tmpdir(), "forge-admin-journey-"));
47 dirs.push(dir);
48 const app = createApp({ dataDir: dir, port: 0, passkeyOnlySignup: true });
49 const servers = await serve(app);
50 opened.push({ app, servers });
51 const url = (path: string) => `${servers.url}${path}`;
52 const cookieOf = (res: Response) => (res.headers.get("set-cookie") ?? "").split(";")[0]!;
53 const page = async (cookie: string, path: string) => {
54 const res = await fetch(url(path), { headers: { cookie }, redirect: "manual" });
55 return { status: res.status, text: (await res.text()).replace(/\s+/g, " ").replace(/ >/g, ">") };
56 };
57 const post = (cookie: string, path: string, form: Record<string, string>) =>
58 fetch(url(path), { method: "POST", headers: { cookie, origin: servers.url }, body: new URLSearchParams(form), redirect: "manual" });
59 /** The forge's first sign-in: the operator's code, redeemed with a passkey. */
60 const firstSignIn = async (username: string): Promise<string> => {
61 const who = { token: mintFirstAdmin(app.db)!.code, username, email: `${username}@x.test` };
62 const res = await fetch(url("/first-admin"), {
63 method: "POST",
64 headers: { origin: servers.url },
65 body: new URLSearchParams({ ...who, ...(await passkeyFields(servers.url, "/first-admin/options", who)) }),
66 redirect: "manual",
67 });
68 expect(res.status).toBe(303);
69 return cookieOf(res);
70 };
71 return { app, url, cookieOf, page, post, firstSignIn, base: servers.url };
72 }
73
74 describe("the new owner who makes an everyday account", () => {
75 test("first sign-in is the admin; the page says why in two sentences and one action; Make it signs them in as the everyday account, where admin is refused", async () => {
76 const f = await freshForge();
77 const admin = await f.firstSignIn("ada");
78 expect(admin).toContain("forge_session=");
79 expect(getUserByName(f.app.db, "ada")!.isAdmin).toBe(true);
80
81 // The home asks in one quiet line that leads to the step's own page.
82 const home = (await f.page(admin, "/")).text;
83 expect(home).toContain(`<a href="/settings/everyday">${HOME_LINE}</a>`);
84 expect(home).not.toContain('role="alert"');
85
86 // Two sentences of why, said once; one primary action; staying on admin is offered, on purpose.
87 expect(EVERYDAY_WHY.split(/(?<=\.)\s+/)).toHaveLength(2);
88 const step = (await f.page(admin, "/settings/everyday")).text;
89 expect(step.split(EVERYDAY_WHY)).toHaveLength(2);
90 expect(step.match(/data-variant="primary"/g)).toHaveLength(1);
91 expect(step).toContain("Make it with a passkey");
92 expect(step).toContain("Keep using admin");
93
94 // Make it: an ordinary account, linked, and the browser is signed in as it.
95 const form = { username: "ada-me" };
96 const made = await f.post(admin, "/settings/everyday", {
97 ...form,
98 ...(await passkeyFields(f.base, "/settings/everyday/options", form, { headers: { cookie: admin } })),
99 });
100 expect(made.status).toBe(303);
101 expect(made.headers.get("location")).toBe("/");
102 const daily = f.cookieOf(made);
103 expect(daily).toContain("forge_session=");
104 expect(daily).not.toBe(admin);
105 const ada = getUserByName(f.app.db, "ada")!;
106 const adaMe = getUserByName(f.app.db, "ada-me")!;
107 expect(adaMe.isAdmin).toBe(false);
108 expect(everydayOf(f.app.db, ada)?.id).toBe(adaMe.id);
109 expect(adminOf(f.app.db, adaMe)?.id).toBe(ada.id);
110 expect((await f.page(daily, "/settings")).text).toContain("This is the everyday account of");
111 expect((await f.page(daily, "/")).text).not.toContain(HOME_LINE);
112
113 // An admin page, asked by the everyday session: refused, in the words
114 // that say to sign in as admin.
115 for (const path of ["/admin/limits", "/settings/people"]) {
116 const refused = await f.page(daily, path);
117 expect(refused.status).toBe(403);
118 expect(refused.text).toContain(escapeHtml(SIGN_IN_AS_ADMIN));
119 }
120
121 // The everyday account's token is its own: not labelled admin.
122 await f.post(daily, "/settings/tokens", { name: "laptop", scope: "rw" });
123 const tokens = (await f.page(daily, "/settings/tokens")).text;
124 expect(tokens).toContain("<strong>laptop</strong>");
125 expect(tokens).not.toContain(ACTS_AS_ADMIN);
126 }, 30_000);
127 });
128
129 describe("the new owner who stays on admin, on purpose", () => {
130 test("Keep using admin is one post, receipted and recorded, and the home stops asking; its agent token is labelled admin", async () => {
131 const f = await freshForge();
132 const admin = await f.firstSignIn("bea");
133 expect((await f.page(admin, "/")).text).toContain(HOME_LINE);
134
135 const kept = await f.post(admin, "/settings/everyday/keep", {});
136 expect(kept.status).toBe(303);
137 expect(kept.headers.get("location")).toBe("/");
138 expect(keptAdmin(f.app.db, getUserByName(f.app.db, "bea")!)).toBe(true);
139 // The receipt: the flash the home shows once, in the calm toast, never an alert.
140 const receipt = (await f.page(`${admin}; ${f.cookieOf(kept)}`, "/")).text;
141 expect(receipt).toContain("You keep working as admin.");
142 expect(receipt).not.toContain('role="alert"');
143 // Nothing nags afterwards: the home says nothing of it, and the account
144 // page keeps the way without asking again.
145 const home = (await f.page(admin, "/")).text;
146 expect(home).not.toContain(HOME_LINE);
147 expect(home).not.toContain("everyday");
148 expect(home).not.toContain('role="alert"');
149 const settings = (await f.page(admin, "/settings")).text;
150 expect(settings).toContain("Make your everyday account");
151 expect(settings).not.toContain("Keep using admin");
152
153 // An agent's token minted from the admin account: the list says it acts as admin.
154 const minted = await f.post(admin, "/settings/tokens", { name: "agent", scope: "rw", aiAdmin: "on" });
155 expect(minted.status).toBe(303);
156 const list = (await f.page(admin, "/settings/tokens")).text;
157 expect(list).toMatch(new RegExp(`<strong>agent</strong> <span class="badge">rw</span> ${ACTS_AS_ADMIN}`));
158 }, 30_000);
159 });
test/tokens-oauth-client.test.ts +1
@@ -152,6 +152,7 @@ test("MCP `tokens` carries oauthClient on each token, null for a hand-made one",
152152 test("the terminal's sign-ins screen names the harness on an OAuth token's row", () => {
153153 const rows = signInsOf(new Session(app, { sshUsername: "t", remoteAddress: "127.0.0.1", user: alice }));
154154 const where = (name: string) => rows.find((r) => r.kind === "token" && r.where.startsWith(`${name} · `))?.where;
155 // alice is the first user, so a site admin: the row says so (#12466).
155156 expect(where("harness-token")).toBe("harness-token · rw · acts as admin · Claude Code, renews itself");
156157 expect(where("laptop")).toBe("laptop · rw · acts as admin");
157158 });
test/tui-signins.test.ts +4 −3
@@ -12,7 +12,7 @@ import { join } from "node:path";
1212 import { createApp, type App as Forge } from "../src/app.ts";
1313 import { addKey, parseAuthorizedKey } from "../src/core/keys.ts";
1414 import { createSession, sessionOf } from "../src/core/sessions.ts";
15 import { createToken } from "../src/core/tokens.ts";
15 import { ACTS_AS_ADMIN_WORDS, createToken } from "../src/core/tokens.ts";
1616 import { createUser, getUserByName } from "../src/core/users.ts";
1717 import { createForgeApp } from "../src/tui/forge.ts";
1818 import { signInsOf, signInsScreen } from "../src/tui/screens/signins.ts";
@@ -154,9 +154,10 @@ describe("where you are signed in, in the terminal", () => {
154154 forge.db.run("UPDATE user SET is_admin = 1 WHERE username = 'carol'");
155155 const carolId = getUserByName(forge.db, "carol")!.id;
156156 createToken(forge.db, carolId, "carol-ci", "ro");
157 expect(ACTS_AS_ADMIN_WORDS).toBe("acts as admin");
157158 const h = boot("carol");
158159 await h.open();
159 expect(h.text()).toContain("carol-ci · ro · acts as admin");
160 expect(h.text()).toContain(`carol-ci · ro · ${ACTS_AS_ADMIN_WORDS}`);
160161 await h.press("m", "enter");
161162 await h.press("enter");
162163 expect(h.text()).toContain("Make an admin access code");
@@ -167,7 +168,7 @@ describe("where you are signed in, in the terminal", () => {
167168 const g = boot("alice");
168169 await g.open();
169170 expect(g.text()).toContain("alice-ci · ro");
170 expect(g.text()).not.toContain("acts as admin");
171 expect(g.text()).not.toContain(ACTS_AS_ADMIN_WORDS);
171172 await g.press("m", "enter");
172173 await g.press("enter");
173174 expect(g.text()).toContain("New access code");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs