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

An admin-only page refuses the everyday session and names the admin account to use #13620

Merged opened this

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

Merged

scout/forge:scout/13597-an-admin-only-page-refuses-the-everyday → main 6 commits fork 1 thread · 1 unresolved

  • Merged. scout/13597-an-admin-only-page-refuses-the-everyday was merged into main as 7029601.

Review

Sign in to review this change.
21 files changed +415 −39
docs/features/welcome.md +2
@@ -22,6 +22,8 @@ On a new forge's first screen the box under "What do you want built?" sends on E
2222
2323 An admin with no everyday account and no recorded choice is asked in one line of the home's needs-you row: "You are signed in as the admin. Make an everyday account" (`EVERYDAY_NEED`, `src/web/pages/home_flow.ts`). It is never a form on the home. The line opens `/settings/everyday` (`everydayPage`, `src/web/pages/everyday.ts`): why, a username, **Make it with a passkey**, and **Keep using admin**, which is remembered (`keepAdmin`) and ends the asking. No email on a forge that sends no mail; never a password. On a spawned forge the first-login card's step is the same link and the same way to decline.
2424
25 An everyday account that opens an admin-only route is refused in two sentences that name the admin account (`adminRefusal`, `src/core/everyday.ts`): "This is admin-only, and you are signed in as carol, your everyday account. Sign in as alice to open it, or stay carol for everything else." The page (`everydayRefusedPage`) answers 403 with **Sign in as alice**, which signs this session out and opens sign-in (`POST /settings/everyday/to-admin`), and **Go home**, which keeps the everyday account. The API's `not_admin` message and MCP's refusal of an admin tool say the same words. A stranger never sees this: they get the route's usual answer, so the admin's name stays private. Test: `test/admin-everyday-refusal.test.ts`.
26
2527 ## The terminal
2628
2729 The terminal does not reach `/welcome`: it is the screen where the first account is made, and the terminal needs an account to sign in. Once there is one, the first ask is the terminal's own first screen (`crewFirstText`).
src/checks/looks.ts +2 −2
@@ -30,8 +30,8 @@ export const commitLooksPath = (
3030 const SAFE = /^[0-9A-Za-z]{1,64}$/;
3131
3232 const MAX_BYTES = 1024 * 1024;
33 // The forge's own preview takes ~55 looks (`PREVIEW_OWNER_LOOKS`); every one must fit.
34 const MAX_LOOKS = 80;
33 // The forge's own preview takes ~80 looks (`PREVIEW_OWNER_LOOKS`); every one must fit.
34 const MAX_LOOKS = 120;
3535 const MAX_WORDS = 80;
3636
3737 const words = (v: unknown): string | null =>
src/core/everyday.ts +25
@@ -13,6 +13,7 @@
1313
1414 import type { Database } from "bun:sqlite";
1515 import { addTeamMember, createTeam, listTeams } from "./orgs.ts";
16 import { SIGN_IN_AS_ADMIN } from "./roles.ts";
1617 import { getUserSetting, setUserSetting } from "./settings.ts";
1718 import { getUserById, type User } from "./users.ts";
1819
@@ -77,3 +78,27 @@ export const keptAdmin = (db: Database, admin: User): boolean =>
7778 /** The two sentences of why, said the same way everywhere. */
7879 export const EVERYDAY_WHY =
7980 "Admin can change everything here, including who can see what. Use it when you mean to; day to day, use an account that cannot break the forge.";
81
82 /**
83 * What an admin-only route or tool says to a person who may not administer
84 * (#13597). To an everyday account it is two sentences: what this is, and
85 * which account opens it, by name; staying as the everyday account is the
86 * other choice, named too. Anyone else hears the forge's one sentence.
87 */
88 export function adminRefusal(db: Database, user: User): string {
89 const admin = adminOf(db, user);
90 if (admin === undefined || !admin.isAdmin) return SIGN_IN_AS_ADMIN;
91 return everydayRefusal(user, admin).join(" ");
92 }
93
94 /**
95 * The two sentences an everyday account hears at an admin-only door: who it
96 * is, then which account opens the door. The page draws the first as its
97 * head and the second as its body, so it says each once (#13597).
98 */
99 export function everydayRefusal(everyday: User, admin: User): readonly [string, string] {
100 return [
101 `This is admin-only, and you are signed in as ${everyday.username}, your everyday account.`,
102 `Sign in as ${admin.username} to open it, or stay ${everyday.username} for everything else.`,
103 ];
104 }
src/http/admin_gate.ts +15 −9
@@ -2,18 +2,22 @@
22 * The one gate in front of every admin-only route: those `route_marks.ts`
33 * marks `admin` — `/admin/*`, `/api/v1/admin/*`, `/releases` with its
44 * rollback, and the admin's pages elsewhere (`/settings/billing`, `/boards`,
5 * …), and every operation the OpenAPI contract publishes as `x-role: admin`. A signed-in person whose role lacks `administer` (`core/roles.ts`) is
6 * refused with a 403 and one plain sentence saying to sign in as admin, as
7 * JSON for the API and as a page for a browser, before any handler runs. Anyone else meets the handler's own
8 * rules, so an admin is unchanged. For releases the rule itself is
9 * `release/gate.ts`'s, which the terminal shares; this gate only supplies the
10 * 403 and its wording on the page. `/releases.json` stays public.
5 * …), and every operation the OpenAPI contract publishes as `x-role: admin`. A signed-in person
6 * whose role lacks `administer` (`core/roles.ts`) is refused with a 403 and one plain sentence
7 * saying to sign in as admin, as JSON for the API and as a page for a browser, before any handler
8 * runs. An everyday account hears which admin account opens it, by name, with a button that signs
9 * it out to sign in as that one (#13597); a stranger never reaches this and meets the handler's
10 * usual answer, so no name leaks. Anyone else meets the handler's own rules, so an admin is
11 * unchanged. For releases the rule itself is `release/gate.ts`'s, which the terminal shares; this
12 * gate only supplies the 403 and its wording on the page. `/releases.json` stays public.
1113 */
1214
1315 import type { App } from "../app.ts";
1416 import { ROUTES } from "../contract/openapi.ts";
15 import { lacks, SIGN_IN_AS_ADMIN } from "../core/roles.ts";
17 import { adminOf, adminRefusal } from "../core/everyday.ts";
18 import { lacks } from "../core/roles.ts";
1619 import { forbiddenPage } from "../web/chrome.ts";
20 import { everydayRefusedPage } from "../web/pages/everyday.ts";
1721 import type { Auth, Ctx } from "./context.ts";
1822 import { json } from "./respond.ts";
1923 import { isAdminRoute, markOf } from "./route_marks.ts";
@@ -55,7 +59,9 @@ export function adminGate(app: App, request: Request, url: URL, auth: Auth, patt
5559 const contract = pattern !== undefined && isContractAdmin(request.method, pattern);
5660 if (!contract && !(mark === undefined ? isAdminPath(url.pathname) : mark === "admin")) return undefined;
5761 if (!lacks(app.db, auth.user, "administer")) return undefined;
58 if (contract || url.pathname.startsWith("/api/")) return json({ error: "not_admin", message: SIGN_IN_AS_ADMIN }, 403);
62 const why = adminRefusal(app.db, auth.user);
63 if (contract || url.pathname.startsWith("/api/")) return json({ error: "not_admin", message: why }, 403);
5964 const ctx: Ctx = { app, request, url, params: {}, auth, theme: undefined };
60 return forbiddenPage(ctx, SIGN_IN_AS_ADMIN);
65 const admin = adminOf(app.db, auth.user);
66 return admin?.isAdmin === true ? everydayRefusedPage(ctx, admin) : forbiddenPage(ctx, why);
6167 }
src/http/mcp.ts +2 −2
@@ -41,7 +41,7 @@ import { fileReport } from "../actions/reports.ts";
4141 import { START_HINT, START_WORDS, startBuilding } from "../actions/start.ts";
4242 import { CONTRIBUTE_TOKEN_HINT, CONTRIBUTE_TOKEN_WORDS, mintContributeToken } from "../actions/contribute_token.ts";
4343 import { BODY_MAX, REQUEST_MAX, TITLE_MAX } from "../core/reports.ts";
44 import { everydayOf } from "../core/everyday.ts";
44 import { adminRefusal, everydayOf } from "../core/everyday.ts";
4545 import { claimDone, completeWrite, dropWrite, recordWrite } from "../core/conversation_writes.ts";
4646 import { type Args, alreadyDone, notAdminTool, visible, plansOnly, str, REPO_ARG, lean, fenceAnswer, heldWrite, askedFirst, readThrough } from "./mcp/shared.ts";
4747 import { CONVERSATION_BRIEF } from "../crew/conversation_brief.ts";
@@ -243,7 +243,7 @@ function rpcOne(
243243 : {};
244244 // An admin's tool stays out of an everyday account's list, and a call to
245245 // it by name is told how to reach it before anything is held or asked (#11818).
246 if (tool?.adminOnly === true && !user.isAdmin) return refuse(-32602, notAdminTool(tool.name), NO_TOOL_HINT);
246 if (tool?.adminOnly === true && !user.isAdmin) return refuse(-32602, notAdminTool(tool.name, adminRefusal(ctx.app.db, user)), NO_TOOL_HINT);
247247 // Before the scope floor, so an admin tool the forge's agent was
248248 // steered to is held as a confirm too, not merely refused (#7649), and
249249 // one the person asked for waits for their yes (#7650).
src/http/mcp/shared.ts +1 −1
@@ -96,7 +96,7 @@ export interface Tool {
9696 * What an everyday account calling an admin's tool by name is told: not here, and the one sentence
9797 * on what to do next.
9898 */
99 export const notAdminTool = (name: string): string => `no tool named ${name} for this account. ${SIGN_IN_AS_ADMIN}`;
99 export const notAdminTool = (name: string, why: string = SIGN_IN_AS_ADMIN): string => `no tool named ${name} for this account. ${why}`;
100100
101101 /**
102102 * Whether this caller is shown the tool and may call it: one rule for the manifest and dispatch.
src/http/route_marks.ts +1
@@ -278,6 +278,7 @@ export const ROUTES: Readonly<Record<string, Mark>> = {
278278 "/settings/everyday": "open",
279279 "/settings/everyday/options": "admin",
280280 "/settings/everyday/switch": "open",
281 "/settings/everyday/to-admin": "open",
281282 "/settings/everyday/keep": "open",
282283 "/settings/payments": "open",
283284 "/settings/shells": "open",
src/http/settings_routes.ts +2
@@ -89,6 +89,7 @@ import {
8989 everydayKeep,
9090 everydayOptions,
9191 everydaySwitch,
92 everydayToAdmin,
9293 } from "../web/pages/everyday.ts";
9394 import {
9495 agentCreate,
@@ -172,6 +173,7 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea
172173 router.add("POST", "/settings/everyday", everydayCreate);
173174 router.add("POST", "/settings/everyday/options", everydayOptions);
174175 router.add("POST", "/settings/everyday/switch", everydaySwitch);
176 router.add("POST", "/settings/everyday/to-admin", everydayToAdmin);
175177 router.add("POST", "/settings/everyday/keep", everydayKeep);
176178 router.add("GET", "/settings/appearance", appearancePage);
177179 router.add("GET", "/settings/payments", paymentsPage);
src/looks/service.ts +7 −2
@@ -71,7 +71,7 @@ import { listActive } from "../core/runs.ts";
7171 import { frontPicks } from "../core/front.ts";
7272 import { getRepoById } from "../core/repos.ts";
7373 import { getUserById } from "../core/users.ts";
74 import { ownerLooksFor, PREVIEW_NEWCOMER } from "../spawn/preview-looks.ts";
74 import { ownerLooksFor, PREVIEW_EVERYDAY, PREVIEW_NEWCOMER } from "../spawn/preview-looks.ts";
7575 import { pngHeader } from "../design/image/png.ts";
7676 import { createLog } from "../kernel/log.ts";
7777 import { addCommitLook } from "../checks/looks.ts";
@@ -613,6 +613,11 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
613613 const newcomer: GrantWho = { id: PREVIEW_NEWCOMER, name: PREVIEW_NEWCOMER, role: "admin" };
614614 const isNewcomerLook = (page: string): boolean =>
615615 ownerLooks.some((l) => l.page === page && l.as === "newcomer");
616 // The everyday account's door (#13597): the parent vouches for it by name
617 // as it does for the newcomer; the preview hears it as that account.
618 const everyday: GrantWho = { id: PREVIEW_EVERYDAY, name: PREVIEW_EVERYDAY, role: "admin" };
619 const isEverydayLook = (page: string): boolean =>
620 ownerLooks.some((l) => l.page === page && l.as === "everyday");
616621 let allOk = true;
617622 let failedHere = false;
618623 let verdict: string | undefined;
@@ -637,7 +642,7 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
637642 { app: record, env: item.env },
638643 GRANT_TTL_MS,
639644 Date.now(),
640 asNobody(kind, page) ? undefined : isNewcomerLook(page) ? newcomer : asOwner,
645 asNobody(kind, page) ? undefined : isNewcomerLook(page) ? newcomer : isEverydayLook(page) ? everyday : asOwner,
641646 );
642647 const url = lookUrl(dataDir, host, port, token, page);
643648 const path = lookPath(item.appId, item.env, item.commitOid, page, kind, theme);
src/spawn/live.ts +4 −1
@@ -16,7 +16,10 @@ export const SLOW_POLL_MS = 5000;
1616 /** At most this many watchers at once per forge; a spawn past it is made but not timed. */
1717 export const MAX_WATCHERS = 20;
1818 const open = new WeakMap<App, number>();
19 /** Give up after this long: well past the 3-minute budget, so a slow forge still counts as live, late. */
19 /**
20 * Give up after this long: well past the 3-minute budget, so a slow forge still counts as live,
21 * late.
22 */
2023 export const GIVE_UP_MS = 10 * 60_000;
2124
2225 export type Probe = () => Promise<boolean>;
src/spawn/preview-looks.ts +21 −5
@@ -194,6 +194,16 @@ export const PREVIEW_NEWCOMER = "preview-newcomer";
194194 export const PREVIEW_NEWCOMER_ORG = "preview-newcomer-forge";
195195 export const PREVIEW_NEWCOMER_PAGE = "/?as=newcomer";
196196
197 /**
198 * An everyday account at an admin-only door (#13597): a preview-only person
199 * who is the everyday account of a preview-only admin of its own (so the
200 * preview admin's pages stay as they were), taken at `/admin/limits` with a
201 * query the page ignores. Its picture is the refusal that names that admin.
202 */
203 export const PREVIEW_EVERYDAY = "preview-everyday";
204 export const PREVIEW_EVERYDAY_ADMIN = "preview-everyday-admin";
205 export const PREVIEW_EVERYDAY_PAGE = "/admin/limits?as=everyday";
206
197207 /**
198208 * `/` as a stranger sees it (#11313). The home is a signed-in page for the owner, so
199209 * `/` itself is taken as the owner; this page is the same route with a query it ignores,
@@ -207,8 +217,11 @@ export const PREVIEW_INVENTORY_PAGE = "/migrate/inventory";
207217 export interface OwnerLook {
208218 readonly page: string;
209219 readonly kind: LookKind;
210 /** Taken as the newcomer, not the preview admin, or as nobody: no session at all. */
211 readonly as?: "newcomer" | "nobody";
220 /**
221 * Taken as the newcomer or the everyday account, not the preview admin, or as nobody: no session
222 * at all.
223 */
224 readonly as?: "newcomer" | "everyday" | "nobody";
212225 }
213226
214227 /** The named list: each page at desk and phone, taken as the owner. */
@@ -241,6 +254,7 @@ export const PREVIEW_OWNER_LOOKS: readonly OwnerLook[] = [
241254 PREVIEW_RESILIENCE_PAGE,
242255 PREVIEW_SEARCH_PAGE,
243256 PREVIEW_NEWCOMER_PAGE,
257 PREVIEW_EVERYDAY_PAGE,
244258 PREVIEW_SIGNED_OUT_PAGE,
245259 PREVIEW_MACHINES_PAGE,
246260 PREVIEW_DISK_OPEN_LOOK,
@@ -252,9 +266,11 @@ export const PREVIEW_OWNER_LOOKS: readonly OwnerLook[] = [
252266 (["desktop", "phone"] as const).map((kind): OwnerLook =>
253267 page === PREVIEW_NEWCOMER_PAGE
254268 ? { page, kind, as: "newcomer" }
255 : page === PREVIEW_SIGNED_OUT_PAGE
256 ? { page, kind, as: "nobody" }
257 : { page, kind },
269 : page === PREVIEW_EVERYDAY_PAGE
270 ? { page, kind, as: "everyday" }
271 : page === PREVIEW_SIGNED_OUT_PAGE
272 ? { page, kind, as: "nobody" }
273 : { page, kind },
258274 ),
259275 );
260276
src/spawn/preview-owner.ts +7 −4
@@ -15,8 +15,8 @@
1515 import { createHmac, timingSafeEqual } from "node:crypto";
1616 import type { App } from "../app.ts";
1717 import type { User } from "../core/users.ts";
18 import { PREVIEW_NEWCOMER } from "./preview-looks.ts";
19 import { isPreviewEnv, previewAdmin, previewNewcomer } from "./preview-seed.ts";
18 import { PREVIEW_EVERYDAY, PREVIEW_NEWCOMER } from "./preview-looks.ts";
19 import { isPreviewEnv, previewAdmin, previewEveryday, previewNewcomer } from "./preview-seed.ts";
2020
2121 type Env = Record<string, string | undefined>;
2222
@@ -49,6 +49,9 @@ export function previewOwner(
4949 const [, name, role, expires] = parts as [string, string, string, string];
5050 if (role !== "admin" || !/^\d+$/.test(expires) || Number(expires) <= now)
5151 return undefined;
52 // The parent's looks of the first screen are taken as the newcomer (#11285).
53 return name === PREVIEW_NEWCOMER ? previewNewcomer(app) : previewAdmin(app);
52 // The parent's looks of the first screen are taken as the newcomer (#11285),
53 // and of an admin-only door as the everyday account (#13597).
54 if (name === PREVIEW_NEWCOMER) return previewNewcomer(app);
55 if (name === PREVIEW_EVERYDAY) return previewEveryday(app);
56 return previewAdmin(app);
5457 }
src/spawn/preview-seed.ts +43
@@ -57,6 +57,7 @@ import { createSession, destroySession } from "../core/sessions.ts";
5757 import { createToken, listTokens } from "../core/tokens.ts";
5858 import { recordUsage } from "../core/usage.ts";
5959 import { PREVIEW_SEEDED, getUserSetting, setUserSetting } from "../core/settings.ts";
60 import { adminOf, linkEveryday } from "../core/everyday.ts";
6061 import { createUser, getUserByName, type User } from "../core/users.ts";
6162 import { diskSummary, recordReading } from "../machines/disk_readings.ts";
6263 import { err, ok, type Result } from "../kernel/result.ts";
@@ -83,6 +84,8 @@ import {
8384 PREVIEW_MOVED_OWNER,
8485 PREVIEW_MOVED_PAGE,
8586 PREVIEW_MOVE_PAGE,
87 PREVIEW_EVERYDAY,
88 PREVIEW_EVERYDAY_ADMIN,
8689 PREVIEW_NEWCOMER,
8790 PREVIEW_NEWCOMER_ORG,
8891 PREVIEW_REPO,
@@ -289,6 +292,42 @@ export function previewNewcomer(app: App): User | undefined {
289292 return user?.isAdmin === true && user.kind === "user" ? user : undefined;
290293 }
291294
295 /** The everyday account the preview pictures at an admin-only door, when this forge has one. */
296 export function previewEveryday(app: App): User | undefined {
297 const user = getUserByName(app.db, PREVIEW_EVERYDAY);
298 if (user === undefined || user.isAdmin || user.kind !== "user") return undefined;
299 return adminOf(app.db, user)?.username === PREVIEW_EVERYDAY_ADMIN ? user : undefined;
300 }
301
302 /**
303 * An admin of its own and that admin's everyday account (#13597), so the
304 * looks picture the refusal an everyday account meets at an admin-only page.
305 * Idempotent; only a preview reaches it. The preview admin is left without
306 * an everyday account, so its own pages are pictured as they were.
307 */
308 async function seedEveryday(app: App): Promise<Result<void, string>> {
309 const made = async (username: string, isAdmin: boolean): Promise<Result<User, string>> => {
310 const there = getUserByName(app.db, username);
311 if (there !== undefined)
312 return there.kind === "user" && there.isAdmin === isAdmin ? ok(there) : err(`the name ${username} is someone else's`);
313 const r = await createUser(app.db, {
314 origin: "seed",
315 trusted: true,
316 isAdmin,
317 allowReserved: true,
318 username,
319 email: `${username}@preview.invalid`,
320 });
321 return r.ok ? ok(r.value) : err(`${username}: ${r.error}`);
322 };
323 const admin = await made(PREVIEW_EVERYDAY_ADMIN, true);
324 if (!admin.ok) return admin;
325 const daily = await made(PREVIEW_EVERYDAY, false);
326 if (!daily.ok) return daily;
327 linkEveryday(app.db, admin.value, daily.value);
328 return ok(undefined);
329 }
330
292331 /**
293332 * The person of a spawned forge who has claimed it and told the crew nothing
294333 * (#11285): the preview is given a `parent.json` naming a seeded organisation,
@@ -385,6 +424,8 @@ export async function seedPreview(
385424 if (!office.ok) return office;
386425 const newcomer = await seedNewcomer(app);
387426 if (!newcomer.ok) return newcomer;
427 const everyday = await seedEveryday(app);
428 if (!everyday.ok) return everyday;
388429 seedGrace(app);
389430 const inventory = seedInventory(app, admin);
390431 if (!inventory.ok) return inventory;
@@ -405,6 +446,8 @@ export async function seedPreview(
405446 if (!office.ok) return office;
406447 const newcomer = await seedNewcomer(app);
407448 if (!newcomer.ok) return newcomer;
449 const everyday = await seedEveryday(app);
450 if (!everyday.ok) return everyday;
408451 seedGrace(app);
409452 const inventory = seedInventory(app, admin);
410453 if (!inventory.ok) return inventory;
src/web/pages/everyday.ts +56 −3
@@ -10,6 +10,7 @@
1010 import {
1111 adminOf,
1212 everydayOf,
13 everydayRefusal,
1314 EVERYDAY_WHY,
1415 keepAdmin,
1516 keptAdmin,
@@ -36,6 +37,7 @@ import { passkeyNote } from "../passkey-state.ts";
3637 import { btn, card, field as formField } from "../ui.ts";
3738 import { signOutHere } from "../../actions/signins.ts";
3839 import { sessionCookie } from "./site.ts";
40 import { safeNext, withReturn } from "../return_to.ts";
3941 import { EMAIL_TAKEN_MESSAGE, EMAIL_WANTED, USERNAME_TAKEN } from "../../actions/signup_words.ts";
4042
4143 const USERNAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,38}$/;
@@ -46,7 +48,8 @@ function suggestedName(ctx: Ctx, admin: User): string {
4648 return getUserByName(ctx.app.db, name) === undefined ? name : "";
4749 }
4850
49 // GET /settings/everyday — the step on its own page: why, a username, one passkey button, and "Keep using admin".
51 // GET /settings/everyday — the step on its own page: why, a username, one passkey button, and "Keep
52 // using admin".
5053 export function everydayPage(ctx: Ctx): Response {
5154 const user = ctx.auth.user;
5255 if (!user) return signInFirst(ctx);
@@ -197,8 +200,8 @@ export async function everydayCreate(ctx: Ctx): Promise<Response> {
197200 if (!key.ok) return say(PASSKEY_WORDS[key.error]);
198201 // The same names a sign-up may not take (a crew member's, a page's,
199202 // another admin's), held where accounts are made; the admin's own handle
200 // may appear in their everyday name ("ada-me"). A proven admin vouches for their own second account, as a claim
201 // vouches for the first: held back, it could not tell the crew.
203 // may appear in their everyday name ("ada-me"). A proven admin vouches for their own second
204 // account, as a claim vouches for the first: held back, it could not tell the crew.
202205 const made = await createUser(ctx.app.db, {
203206 username,
204207 email,
@@ -273,3 +276,53 @@ export async function everydaySwitch(ctx: Ctx): Promise<Response> {
273276 flash: { message: `Sign in as ${daily.username}, your everyday account.` },
274277 });
275278 }
279
280 /**
281 * An admin-only page, opened by an everyday account (#13597): a 403 whose
282 * head is the first sentence of the refusal (who you are) and whose body is
283 * the second (which account opens it), and one button that signs this
284 * session out to sign in as that admin, coming back to this page. "Go home"
285 * is the other choice, staying as the everyday account.
286 */
287 export function everydayRefusedPage(ctx: Ctx, admin: User): Response {
288 const daily = ctx.auth.user;
outdated

Principle 1 (and 8): the head "This is for the admin account" and the body "This is admin-only, and you are signed in as …" say the same thing twice. Make the head the one confident sentence for the page, for example "Admin only", and let the body carry only what is new: who you are and which account opens it. Or drop the head sentence and keep the two-sentence body.

289 if (daily === undefined) return signInFirst(ctx);
290 const [who, way] = everydayRefusal(daily, admin);
291 const back = ctx.request.method === "GET" ? safeNext(ctx.url.pathname + ctx.url.search) : undefined;
292 return page(
293 {
294 ctx,
295 title: "Admin only",
296 body: html`<div class="narrow">
297 ${pageHead(who)}
298 <section class="settings-block" id="everyday-refused">
299 <p class="mb">${way}</p>
300 <form method="post" action="/settings/everyday/to-admin" class="mt">
301 ${back === undefined ? null : html`<input type="hidden" name="next" value="${back}">`}
302 ${btn(`Sign in as ${admin.username}`, { variant: "primary" })}
303 ${btn("Go home", { href: "/" })}
304 </form>
305 </section>
306 </div>`,
307 },
308 403,
309 );
310 }
311
312 // POST /settings/everyday/to-admin — leave the everyday account for its
313 // admin: this session ends, and sign-in says as whom to come back.
314 export async function everydayToAdmin(ctx: Ctx): Promise<Response> {
315 const daily = ctx.auth.user;
316 if (!daily) return signInFirst(ctx);
317 const form = await readForm(ctx);
318 if (form instanceof Response) return form;
319 const admin = adminOf(ctx.app.db, daily);
320 if (!admin?.isAdmin) return new Response("not found", { status: 404 });
321 signOutHere(ctx.app, cookieValue(ctx.request, "forge_session"));
322 return redirect(withReturn("/signin", safeNext(field(form, "next"))), {
323 cookie: sessionCookie("", new Date(0), ctx.url, ctx.app.config.url),
324 url: ctx.url,
325 forgeUrl: ctx.app.config.url,
326 flash: { message: `Sign in as ${admin.username}, the forge's admin account.` },
327 });
328 }
test/admin-everyday-refusal.test.ts added +153
@@ -0,0 +1,153 @@
1 /**
2 * An everyday account at an admin-only door (#13597): the page, the API and
3 * MCP refuse in the same two sentences, naming the admin account that opens
4 * it; the page's button signs the everyday session out to sign in as that
5 * one; the terminal's dashboard names it too; a stranger never hears it.
6 */
7
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createApp, type App } from "../src/app.ts";
13 import { adminRefusal, linkEveryday } from "../src/core/everyday.ts";
14 import { SIGN_IN_AS_ADMIN } from "../src/core/roles.ts";
15 import { createSession, listSessions } from "../src/core/sessions.ts";
16 import { createToken } from "../src/core/tokens.ts";
17 import { createUser, type User } from "../src/core/users.ts";
18 import { TOOLS } from "../src/http/mcp/tools.ts";
19 import { serve, type Servers } from "../src/http/server.ts";
20 import { quietLogs } from "./helpers/globals.ts";
21
22 quietLogs();
23
24 describe("an admin-only door, asked by an everyday account", () => {
25 let dataDir = "";
26 let app: App;
27 let servers: Servers;
28 let ada: User; // the admin
29 let daily: User; // ada's everyday account
30 let bob: User; // an ordinary account, nobody's everyday one
31
32 const mk = async (username: string, admin = false) => {
33 const r = await createUser(app.db, {
34 origin: "seed",
35 trusted: true,
36 username,
37 email: `${username}@forge.local`,
38 password: "a-good-passphrase",
39 ...(admin ? { adminIfFirst: true } : {}),
40 });
41 if (!r.ok) throw new Error(r.error);
42 return r.value;
43 };
44 const words = () =>
45 "This is admin-only, and you are signed in as piper, your everyday account. Sign in as ada to open it, or stay piper for everything else.";
46 const escaped = (s: string) => s.replaceAll("'", "&#39;");
47 const cookieOf = (u: User) => `forge_session=${createSession(app.db, u.id).token}`;
48
49 beforeAll(async () => {
50 dataDir = await mkdtemp(join(tmpdir(), "forge-everyday-refusal-"));
51 app = createApp({ dataDir, port: 0 });
52 servers = await serve(app);
53 ada = await mk("ada", true);
54 daily = await mk("piper");
55 bob = await mk("bob");
56 linkEveryday(app.db, ada, daily);
57 }, 60_000);
58
59 afterAll(async () => {
60 servers.stop();
61 app.close();
62 await rm(dataDir, { recursive: true, force: true });
63 });
64
65 test("the refusal is two sentences naming the admin account; others keep the one sentence", () => {
66 expect(adminRefusal(app.db, daily)).toBe(words());
67 expect(adminRefusal(app.db, bob)).toBe(SIGN_IN_AS_ADMIN);
68 });
69
70 test("the page answers 403, says each sentence once, and offers the admin by name or home", async () => {
71 for (const path of ["/admin/limits", "/releases"]) {
72 const res = await fetch(`${servers.url}${path}`, { headers: { cookie: cookieOf(daily), accept: "text/html" }, redirect: "manual" });
73 expect(res.status, path).toBe(403);
74 const body = await res.text();
75 const [who, way] = [
76 "This is admin-only, and you are signed in as piper, your everyday account.",
77 "Sign in as ada to open it, or stay piper for everything else.",
78 ];
79 expect(body).toContain(`<h1>${escaped(who)}</h1>`);
80 expect(body.split(escaped(who)).length - 1, "the first sentence once").toBe(1);
81 expect(body.split(escaped(way)).length - 1, "the second sentence once").toBe(1);
82 const section = body.slice(body.indexOf('id="everyday-refused"'), body.indexOf("</section>", body.indexOf('id="everyday-refused"')));
83 expect(section).toContain(escaped(way));
84 expect(section).toContain('action="/settings/everyday/to-admin"');
85 expect(section).toContain(`name="next" value="${path}"`);
86 expect(section).toContain("Sign in as ada");
87 expect(section).toContain('href="/"');
88 expect(section).toContain("Go home");
89 }
90 });
91
92 test("the button signs the everyday session out and asks for the admin by name, back to the page", async () => {
93 const session = createSession(app.db, daily.id);
94 const before = listSessions(app.db, daily.id).length;
95 const res = await fetch(`${servers.url}/settings/everyday/to-admin`, {
96 method: "POST",
97 headers: { cookie: `forge_session=${session.token}`, origin: servers.url, "content-type": "application/x-www-form-urlencoded" },
98 body: "next=%2Fadmin%2Flimits",
99 redirect: "manual",
100 });
101 expect(res.status).toBe(303);
102 expect(res.headers.get("location")).toEndWith("/signin?next=%2Fadmin%2Flimits");
103 expect(listSessions(app.db, daily.id).length).toBe(before - 1);
104 const offsite = await fetch(`${servers.url}/settings/everyday/to-admin`, {
105 method: "POST",
106 headers: { cookie: cookieOf(daily), origin: servers.url, "content-type": "application/x-www-form-urlencoded" },
107 body: "next=%2F%2Fevil.example",
108 redirect: "manual",
109 });
110 expect(offsite.status).toBe(303);
111 expect(offsite.headers.get("location")).toEndWith("/signin");
112 const refused = await fetch(`${servers.url}/settings/everyday/to-admin`, {
113 method: "POST",
114 headers: { cookie: cookieOf(bob), origin: servers.url, "content-type": "application/x-www-form-urlencoded" },
115 body: "",
116 redirect: "manual",
117 });
118 expect(refused.status).toBe(404);
119 });
120
121 test("the API says the same words", async () => {
122 const res = await fetch(`${servers.url}/api/v1/admin/settings`, {
123 headers: { authorization: `Bearer ${createToken(app.db, daily.id, "t", "admin").token}` },
124 });
125 expect(res.status).toBe(403);
126 expect(await res.json()).toMatchObject({ error: "not_admin", message: words() });
127 });
128
129 test("MCP says the same words for an admin tool", async () => {
130 const tool = TOOLS.find((t) => t.adminOnly === true);
131 if (tool === undefined) throw new Error("no admin tool");
132 const res = await fetch(`${servers.url}/mcp`, {
133 method: "POST",
134 headers: {
135 "content-type": "application/json",
136 accept: "application/json, text/event-stream",
137 authorization: `Bearer ${createToken(app.db, daily.id, "t", "admin").token}`,
138 },
139 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: tool.name, arguments: {} } }),
140 });
141 const out = (await res.json()) as { error?: { message: string } };
142 expect(out.error?.message.endsWith(words())).toBe(true);
143 });
144
145 test("a stranger is never told an admin's name", async () => {
146 const res = await fetch(`${servers.url}/admin/limits`, { headers: { accept: "text/html" }, redirect: "manual" });
147 // Signed out, an admin page is not there at all: the same 404 as a page that never was.
148 expect(res.status).toBe(404);
149 const body = await res.text();
150 expect(body).not.toContain("Sign in as ada");
151 expect(body).not.toContain("everyday account");
152 });
153 });
test/admin-journey.test.ts +5 −4
@@ -18,8 +18,7 @@ import { tmpdir } from "node:os";
1818 import { join } from "node:path";
1919 import { createApp, type App } from "../src/app.ts";
2020 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";
21 import { adminOf, everydayOf, everydayRefusal, EVERYDAY_WHY, keptAdmin } from "../src/core/everyday.ts";
2322 import { getUserByName } from "../src/core/users.ts";
2423 import { serve, type Servers } from "../src/http/server.ts";
2524 import { escapeHtml } from "../src/web/html.ts";
@@ -111,11 +110,13 @@ describe("the new owner who makes an everyday account", () => {
111110 expect((await f.page(daily, "/")).text).not.toContain(HOME_LINE);
112111
113112 // An admin page, asked by the everyday session: refused, in the words
114 // that say to sign in as admin.
113 // that name the admin account to sign in as (#13597).
115114 for (const path of ["/admin/limits", "/settings/people"]) {
116115 const refused = await f.page(daily, path);
117116 expect(refused.status).toBe(403);
118 expect(refused.text).toContain(escapeHtml(SIGN_IN_AS_ADMIN));
117 // The page's head is the first sentence and its body the second.
118 for (const sentence of everydayRefusal(adaMe, adminOf(f.app.db, adaMe)!))
119 expect(refused.text).toContain(escapeHtml(sentence));
119120 }
120121
121122 // The everyday account's token is its own: not labelled admin.
test/admin-refusal-table.test.ts +6 −4
@@ -4,7 +4,8 @@
44 * OpenAPI row whose role is `admin` (`src/contract/openapi.ts`) and every MCP
55 * tool marked `adminOnly` (`src/http/mcp/tools.ts`). Each is called by the
66 * everyday account linked to the admin (`core/everyday.ts`), the same person
7 * signed in day to day, and must answer 403 with `ADMIN_WORDS.signIn`. A new
7 * signed in day to day, and must answer 403 with `adminRefusal`, the words
8 * that name the admin account to sign in as (#13597). A new
89 * admin operation joins the table without an edit here.
910 */
1011
@@ -15,7 +16,7 @@ import { join } from "node:path";
1516 import { ADMIN_WORDS } from "../src/actions/admin_words.ts";
1617 import { createApp, type App } from "../src/app.ts";
1718 import { ROUTES } from "../src/contract/openapi.ts";
18 import { adminOf, linkEveryday } from "../src/core/everyday.ts";
19 import { adminOf, adminRefusal, linkEveryday } from "../src/core/everyday.ts";
1920 import { lacks } from "../src/core/roles.ts";
2021 import { createSession } from "../src/core/sessions.ts";
2122 import { createToken } from "../src/core/tokens.ts";
@@ -68,6 +69,7 @@ describe("an everyday session meets the admin sign-in at every admin door", () =
6869 expect(adminOf(app.db, everyday)?.id).toBe(admin.id);
6970 expect(lacks(app.db, everyday, "administer")).toBe(true);
7071 expect(ADMIN_WORDS.signIn).toContain("sign in as admin");
72 expect(adminRefusal(app.db, everyday)).toContain("Sign in as alice");
7173 });
7274
7375 const call = async (method: string, path: string, auth: Record<string, string>) => {
@@ -91,7 +93,7 @@ describe("an everyday session meets the admin sign-in at every admin door", () =
9193 for (const r of rows) {
9294 const got = await call(r.method, r.path, auth());
9395 const words = (got.body as { message?: unknown } | undefined)?.message;
94 if (got.status !== 403 || words !== ADMIN_WORDS.signIn)
96 if (got.status !== 403 || words !== adminRefusal(app.db, everyday))
9597 wrong.push(`${r.method.toUpperCase()} ${r.path}: ${got.status} ${JSON.stringify(got.body).slice(0, 120)}`);
9698 }
9799 expect(wrong).toEqual([]);
@@ -111,7 +113,7 @@ describe("an everyday session meets the admin sign-in at every admin door", () =
111113 }),
112114 );
113115 const got = (await res.json()) as { error?: { message?: string } };
114 if (!got.error?.message?.endsWith(ADMIN_WORDS.signIn)) wrong.push(`${t.name}: ${JSON.stringify(got).slice(0, 160)}`);
116 if (!got.error?.message?.endsWith(adminRefusal(app.db, everyday))) wrong.push(`${t.name}: ${JSON.stringify(got).slice(0, 160)}`);
115117 }
116118 expect(wrong).toEqual([]);
117119 });
test/preview-everyday.test.ts added +60
@@ -0,0 +1,60 @@
1 /**
2 * The preview's everyday account (#13597): the everyday account of a
3 * preview-only admin, so the forge's looks picture the refusal an everyday
4 * account meets at an admin-only page, as the parent vouches for it by name.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { createHmac } from "node:crypto";
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 { everydayOf } from "../src/core/everyday.ts";
13 import { serve, type Servers } from "../src/http/server.ts";
14 import { PREVIEW_EVERYDAY, PREVIEW_EVERYDAY_ADMIN, PREVIEW_EVERYDAY_PAGE, PREVIEW_OWNER_LOOKS } from "../src/spawn/preview-looks.ts";
15 import { previewAdmin, previewEveryday, seedPreview } from "../src/spawn/preview-seed.ts";
16
17 const KEY = "preview-everyday-test-key";
18 let dir: string;
19 let app: App;
20 let servers: Servers;
21 beforeAll(async () => {
22 dir = await mkdtemp(join(tmpdir(), "forge-preview-everyday-"));
23 app = createApp({ dataDir: dir, port: 0, previewIdentityKey: KEY });
24 const seeded = await seedPreview(app, { FORGE_APP_ENV: "preview" });
25 if (!seeded.ok) throw new Error(seeded.error);
26 // A second run finds everything in place and still succeeds.
27 const again = await seedPreview(app, { FORGE_APP_ENV: "preview" });
28 if (!again.ok) throw new Error(again.error);
29 servers = await serve(app);
30 }, 30_000);
31 afterAll(async () => {
32 servers.stop();
33 app.close();
34 await rm(dir, { recursive: true, force: true });
35 });
36
37 const vouched = (name: string) => {
38 const said = `look|${name}|admin|${String(Date.now() + 60_000)}`;
39 return { "x-forge-identity": said, "x-forge-signature": createHmac("sha256", KEY).update(said).digest("base64url") };
40 };
41
42 test("the everyday account belongs to its own admin, and the preview admin keeps none", () => {
43 const daily = previewEveryday(app);
44 expect(daily?.username).toBe(PREVIEW_EVERYDAY);
45 expect(daily?.isAdmin).toBe(false);
46 expect(everydayOf(app.db, previewAdmin(app)!)).toBeUndefined();
47 });
48
49 test("vouched for by name, the look's page is the refusal naming its admin", async () => {
50 const res = await fetch(`${servers.url}${PREVIEW_EVERYDAY_PAGE}`, { headers: { ...vouched(PREVIEW_EVERYDAY), accept: "text/html" } });
51 expect(res.status).toBe(403);
52 const body = await res.text();
53 expect(body).toContain('id="everyday-refused"');
54 expect(body).toContain(`Sign in as ${PREVIEW_EVERYDAY_ADMIN}`);
55 });
56
57 test("it is a look taken as the everyday account, at desktop and phone", () => {
58 for (const kind of ["desktop", "phone"] as const)
59 expect(PREVIEW_OWNER_LOOKS).toContainEqual({ page: PREVIEW_EVERYDAY_PAGE, kind, as: "everyday" });
60 });
test/settings-routes.test.ts +1
@@ -31,6 +31,7 @@ POST /settings/password
3131 POST /settings/everyday
3232 POST /settings/everyday/options
3333 POST /settings/everyday/switch
34 POST /settings/everyday/to-admin
3435 POST /settings/everyday/keep
3536 GET /settings/tokens
3637 POST /settings/tokens
test/signup-gate-parent.test.ts +1 −1
@@ -120,7 +120,7 @@ test("every caller of createUser says where its account comes from", async () =>
120120 "src/chaos/world.ts": ["seed"],
121121 "src/packs/mirror.ts": ["seed"],
122122 "src/packs/up.ts": ["seed"],
123 "src/spawn/preview-seed.ts": ["seed", "seed", "seed"],
123 "src/spawn/preview-seed.ts": ["seed", "seed", "seed", "seed"],
124124 "src/spawn/starter_crew.ts": ["spawn"],
125125 "src/web/pages/claim.ts": ["claim"],
126126 "src/web/pages/everyday.ts": ["everyday"],

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs