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

Revert "An admin-only page refuses the everyday session and names the admin account to use" #13767

Closed opened this
Closed without merging

revert-13620 → main 1 commit

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
20 files changed +35 −407
docs/features/welcome.md −2
@@ -22,8 +22,6 @@ 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
2725 ## The terminal
2826
2927 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 ~80 looks (`PREVIEW_OWNER_LOOKS`); every one must fit.
34 const MAX_LOOKS = 120;
33 // The forge's own preview takes ~55 looks (`PREVIEW_OWNER_LOOKS`); every one must fit.
34 const MAX_LOOKS = 80;
3535 const MAX_WORDS = 80;
3636
3737 const words = (v: unknown): string | null =>
src/core/everyday.ts −25
@@ -13,7 +13,6 @@
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";
1716 import { getUserSetting, setUserSetting } from "./settings.ts";
1817 import { getUserById, type User } from "./users.ts";
1918
@@ -78,27 +77,3 @@ export const keptAdmin = (db: Database, admin: User): boolean =>
7877 /** The two sentences of why, said the same way everywhere. */
7978 export const EVERYDAY_WHY =
8079 "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 +9 −15
@@ -2,22 +2,18 @@
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
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.
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.
1311 */
1412
1513 import type { App } from "../app.ts";
1614 import { ROUTES } from "../contract/openapi.ts";
17 import { adminOf, adminRefusal } from "../core/everyday.ts";
18 import { lacks } from "../core/roles.ts";
15 import { lacks, SIGN_IN_AS_ADMIN } from "../core/roles.ts";
1916 import { forbiddenPage } from "../web/chrome.ts";
20 import { everydayRefusedPage } from "../web/pages/everyday.ts";
2117 import type { Auth, Ctx } from "./context.ts";
2218 import { json } from "./respond.ts";
2319 import { isAdminRoute, markOf } from "./route_marks.ts";
@@ -59,9 +55,7 @@ export function adminGate(app: App, request: Request, url: URL, auth: Auth, patt
5955 const contract = pattern !== undefined && isContractAdmin(request.method, pattern);
6056 if (!contract && !(mark === undefined ? isAdminPath(url.pathname) : mark === "admin")) return undefined;
6157 if (!lacks(app.db, auth.user, "administer")) return undefined;
62 const why = adminRefusal(app.db, auth.user);
63 if (contract || url.pathname.startsWith("/api/")) return json({ error: "not_admin", message: why }, 403);
58 if (contract || url.pathname.startsWith("/api/")) return json({ error: "not_admin", message: SIGN_IN_AS_ADMIN }, 403);
6459 const ctx: Ctx = { app, request, url, params: {}, auth, theme: undefined };
65 const admin = adminOf(app.db, auth.user);
66 return admin?.isAdmin === true ? everydayRefusedPage(ctx, admin) : forbiddenPage(ctx, why);
60 return forbiddenPage(ctx, SIGN_IN_AS_ADMIN);
6761 }
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 { adminRefusal, everydayOf } from "../core/everyday.ts";
44 import { 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, adminRefusal(ctx.app.db, user)), NO_TOOL_HINT);
246 if (tool?.adminOnly === true && !user.isAdmin) return refuse(-32602, notAdminTool(tool.name), 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, why: string = SIGN_IN_AS_ADMIN): string => `no tool named ${name} for this account. ${why}`;
99 export const notAdminTool = (name: string): string => `no tool named ${name} for this account. ${SIGN_IN_AS_ADMIN}`;
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,7 +278,6 @@ 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",
282281 "/settings/everyday/keep": "open",
283282 "/settings/payments": "open",
284283 "/settings/shells": "open",
src/http/settings_routes.ts −2
@@ -89,7 +89,6 @@ import {
8989 everydayKeep,
9090 everydayOptions,
9191 everydaySwitch,
92 everydayToAdmin,
9392 } from "../web/pages/everyday.ts";
9493 import {
9594 agentCreate,
@@ -173,7 +172,6 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea
173172 router.add("POST", "/settings/everyday", everydayCreate);
174173 router.add("POST", "/settings/everyday/options", everydayOptions);
175174 router.add("POST", "/settings/everyday/switch", everydaySwitch);
176 router.add("POST", "/settings/everyday/to-admin", everydayToAdmin);
177175 router.add("POST", "/settings/everyday/keep", everydayKeep);
178176 router.add("GET", "/settings/appearance", appearancePage);
179177 router.add("GET", "/settings/payments", paymentsPage);
src/looks/service.ts +2 −7
@@ -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_EVERYDAY, PREVIEW_NEWCOMER } from "../spawn/preview-looks.ts";
74 import { ownerLooksFor, 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,11 +613,6 @@ 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");
621616 let allOk = true;
622617 let failedHere = false;
623618 let verdict: string | undefined;
@@ -642,7 +637,7 @@ export function startLooks(app: App, options: LooksOptions): LooksHandle {
642637 { app: record, env: item.env },
643638 GRANT_TTL_MS,
644639 Date.now(),
645 asNobody(kind, page) ? undefined : isNewcomerLook(page) ? newcomer : isEverydayLook(page) ? everyday : asOwner,
640 asNobody(kind, page) ? undefined : isNewcomerLook(page) ? newcomer : asOwner,
646641 );
647642 const url = lookUrl(dataDir, host, port, token, page);
648643 const path = lookPath(item.appId, item.env, item.commitOid, page, kind, theme);
src/spawn/preview-looks.ts +5 −21
@@ -194,16 +194,6 @@ 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
207197 /**
208198 * `/` as a stranger sees it (#11313). The home is a signed-in page for the owner, so
209199 * `/` itself is taken as the owner; this page is the same route with a query it ignores,
@@ -217,11 +207,8 @@ export const PREVIEW_INVENTORY_PAGE = "/migrate/inventory";
217207 export interface OwnerLook {
218208 readonly page: string;
219209 readonly kind: LookKind;
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";
210 /** Taken as the newcomer, not the preview admin, or as nobody: no session at all. */
211 readonly as?: "newcomer" | "nobody";
225212 }
226213
227214 /** The named list: each page at desk and phone, taken as the owner. */
@@ -254,7 +241,6 @@ export const PREVIEW_OWNER_LOOKS: readonly OwnerLook[] = [
254241 PREVIEW_RESILIENCE_PAGE,
255242 PREVIEW_SEARCH_PAGE,
256243 PREVIEW_NEWCOMER_PAGE,
257 PREVIEW_EVERYDAY_PAGE,
258244 PREVIEW_SIGNED_OUT_PAGE,
259245 PREVIEW_MACHINES_PAGE,
260246 PREVIEW_DISK_OPEN_LOOK,
@@ -266,11 +252,9 @@ export const PREVIEW_OWNER_LOOKS: readonly OwnerLook[] = [
266252 (["desktop", "phone"] as const).map((kind): OwnerLook =>
267253 page === PREVIEW_NEWCOMER_PAGE
268254 ? { page, kind, as: "newcomer" }
269 : page === PREVIEW_EVERYDAY_PAGE
270 ? { page, kind, as: "everyday" }
271 : page === PREVIEW_SIGNED_OUT_PAGE
272 ? { page, kind, as: "nobody" }
273 : { page, kind },
255 : page === PREVIEW_SIGNED_OUT_PAGE
256 ? { page, kind, as: "nobody" }
257 : { page, kind },
274258 ),
275259 );
276260
src/spawn/preview-owner.ts +4 −7
@@ -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_EVERYDAY, PREVIEW_NEWCOMER } from "./preview-looks.ts";
19 import { isPreviewEnv, previewAdmin, previewEveryday, previewNewcomer } from "./preview-seed.ts";
18 import { PREVIEW_NEWCOMER } from "./preview-looks.ts";
19 import { isPreviewEnv, previewAdmin, previewNewcomer } from "./preview-seed.ts";
2020
2121 type Env = Record<string, string | undefined>;
2222
@@ -49,9 +49,6 @@ 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 // 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);
52 // The parent's looks of the first screen are taken as the newcomer (#11285).
53 return name === PREVIEW_NEWCOMER ? previewNewcomer(app) : previewAdmin(app);
5754 }
src/spawn/preview-seed.ts −43
@@ -57,7 +57,6 @@ 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";
6160 import { createUser, getUserByName, type User } from "../core/users.ts";
6261 import { diskSummary, recordReading } from "../machines/disk_readings.ts";
6362 import { err, ok, type Result } from "../kernel/result.ts";
@@ -84,8 +83,6 @@ import {
8483 PREVIEW_MOVED_OWNER,
8584 PREVIEW_MOVED_PAGE,
8685 PREVIEW_MOVE_PAGE,
87 PREVIEW_EVERYDAY,
88 PREVIEW_EVERYDAY_ADMIN,
8986 PREVIEW_NEWCOMER,
9087 PREVIEW_NEWCOMER_ORG,
9188 PREVIEW_REPO,
@@ -292,42 +289,6 @@ export function previewNewcomer(app: App): User | undefined {
292289 return user?.isAdmin === true && user.kind === "user" ? user : undefined;
293290 }
294291
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
331292 /**
332293 * The person of a spawned forge who has claimed it and told the crew nothing
333294 * (#11285): the preview is given a `parent.json` naming a seeded organisation,
@@ -424,8 +385,6 @@ export async function seedPreview(
424385 if (!office.ok) return office;
425386 const newcomer = await seedNewcomer(app);
426387 if (!newcomer.ok) return newcomer;
427 const everyday = await seedEveryday(app);
428 if (!everyday.ok) return everyday;
429388 seedGrace(app);
430389 const inventory = seedInventory(app, admin);
431390 if (!inventory.ok) return inventory;
@@ -446,8 +405,6 @@ export async function seedPreview(
446405 if (!office.ok) return office;
447406 const newcomer = await seedNewcomer(app);
448407 if (!newcomer.ok) return newcomer;
449 const everyday = await seedEveryday(app);
450 if (!everyday.ok) return everyday;
451408 seedGrace(app);
452409 const inventory = seedInventory(app, admin);
453410 if (!inventory.ok) return inventory;
src/web/pages/everyday.ts −52
@@ -10,7 +10,6 @@
1010 import {
1111 adminOf,
1212 everydayOf,
13 everydayRefusal,
1413 EVERYDAY_WHY,
1514 keepAdmin,
1615 keptAdmin,
@@ -37,7 +36,6 @@ import { passkeyNote } from "../passkey-state.ts";
3736 import { btn, card, field as formField } from "../ui.ts";
3837 import { signOutHere } from "../../actions/signins.ts";
3938 import { sessionCookie } from "./site.ts";
40 import { safeNext, withReturn } from "../return_to.ts";
4139 import { EMAIL_TAKEN_MESSAGE, EMAIL_WANTED, USERNAME_TAKEN } from "../../actions/signup_words.ts";
4240
4341 const USERNAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,38}$/;
@@ -276,53 +274,3 @@ export async function everydaySwitch(ctx: Ctx): Promise<Response> {
276274 flash: { message: `Sign in as ${daily.username}, your everyday account.` },
277275 });
278276 }
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;
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 deleted −153
@@ -1,153 +0,0 @@
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 +4 −5
@@ -18,7 +18,8 @@ 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, everydayRefusal, EVERYDAY_WHY, keptAdmin } from "../src/core/everyday.ts";
21 import { adminOf, everydayOf, EVERYDAY_WHY, keptAdmin } from "../src/core/everyday.ts";
22 import { SIGN_IN_AS_ADMIN } from "../src/core/roles.ts";
2223 import { getUserByName } from "../src/core/users.ts";
2324 import { serve, type Servers } from "../src/http/server.ts";
2425 import { escapeHtml } from "../src/web/html.ts";
@@ -110,13 +111,11 @@ describe("the new owner who makes an everyday account", () => {
110111 expect((await f.page(daily, "/")).text).not.toContain(HOME_LINE);
111112
112113 // An admin page, asked by the everyday session: refused, in the words
113 // that name the admin account to sign in as (#13597).
114 // that say to sign in as admin.
114115 for (const path of ["/admin/limits", "/settings/people"]) {
115116 const refused = await f.page(daily, path);
116117 expect(refused.status).toBe(403);
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));
118 expect(refused.text).toContain(escapeHtml(SIGN_IN_AS_ADMIN));
120119 }
121120
122121 // The everyday account's token is its own: not labelled admin.
test/admin-refusal-table.test.ts +4 −6
@@ -4,8 +4,7 @@
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 `adminRefusal`, the words
8 * that name the admin account to sign in as (#13597). A new
7 * signed in day to day, and must answer 403 with `ADMIN_WORDS.signIn`. A new
98 * admin operation joins the table without an edit here.
109 */
1110
@@ -16,7 +15,7 @@ import { join } from "node:path";
1615 import { ADMIN_WORDS } from "../src/actions/admin_words.ts";
1716 import { createApp, type App } from "../src/app.ts";
1817 import { ROUTES } from "../src/contract/openapi.ts";
19 import { adminOf, adminRefusal, linkEveryday } from "../src/core/everyday.ts";
18 import { adminOf, linkEveryday } from "../src/core/everyday.ts";
2019 import { lacks } from "../src/core/roles.ts";
2120 import { createSession } from "../src/core/sessions.ts";
2221 import { createToken } from "../src/core/tokens.ts";
@@ -69,7 +68,6 @@ describe("an everyday session meets the admin sign-in at every admin door", () =
6968 expect(adminOf(app.db, everyday)?.id).toBe(admin.id);
7069 expect(lacks(app.db, everyday, "administer")).toBe(true);
7170 expect(ADMIN_WORDS.signIn).toContain("sign in as admin");
72 expect(adminRefusal(app.db, everyday)).toContain("Sign in as alice");
7371 });
7472
7573 const call = async (method: string, path: string, auth: Record<string, string>) => {
@@ -93,7 +91,7 @@ describe("an everyday session meets the admin sign-in at every admin door", () =
9391 for (const r of rows) {
9492 const got = await call(r.method, r.path, auth());
9593 const words = (got.body as { message?: unknown } | undefined)?.message;
96 if (got.status !== 403 || words !== adminRefusal(app.db, everyday))
94 if (got.status !== 403 || words !== ADMIN_WORDS.signIn)
9795 wrong.push(`${r.method.toUpperCase()} ${r.path}: ${got.status} ${JSON.stringify(got.body).slice(0, 120)}`);
9896 }
9997 expect(wrong).toEqual([]);
@@ -113,7 +111,7 @@ describe("an everyday session meets the admin sign-in at every admin door", () =
113111 }),
114112 );
115113 const got = (await res.json()) as { error?: { message?: string } };
116 if (!got.error?.message?.endsWith(adminRefusal(app.db, everyday))) wrong.push(`${t.name}: ${JSON.stringify(got).slice(0, 160)}`);
114 if (!got.error?.message?.endsWith(ADMIN_WORDS.signIn)) wrong.push(`${t.name}: ${JSON.stringify(got).slice(0, 160)}`);
117115 }
118116 expect(wrong).toEqual([]);
119117 });
test/preview-everyday.test.ts deleted −60
@@ -1,60 +0,0 @@
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,7 +31,6 @@ POST /settings/password
3131 POST /settings/everyday
3232 POST /settings/everyday/options
3333 POST /settings/everyday/switch
34 POST /settings/everyday/to-admin
3534 POST /settings/everyday/keep
3635 GET /settings/tokens
3736 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", "seed"],
123 "src/spawn/preview-seed.ts": ["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