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

Making a forge from an unknown template answers 404 and names the known templates, on the page and the API #13414

Merged opened this

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

Merged

scout/forge:scout/13389-making-a-forge-from-an-unknown-template → main 8 commits fork 3 threads · 3 unresolved

  • Merged. scout/13389-making-a-forge-from-an-unknown-template was merged into main as c61baf5.

Review

Sign in to review this change.
8 files changed +147 −22
docs/features/new-forge-template.md +1 −1
@@ -1,6 +1,6 @@
11 # New forge from a template
22
3 A new forge can start from a template repository: one an admin marked at Settings → Templates and the maker can read. The New forge page has one Template select (default "The forge's own code", then Blank, Starter app and each readable template repository); the terminal's New forge screen cycles the same list with left and right, or takes `owner/name` typed. `POST /api/v1/forges` and the MCP spawn tool take `template: "owner/name"`. An unmarked or unreadable repository answers 422 saying which.
3 A new forge can start from a template repository: one an admin marked at Settings → Templates and the maker can read. The New forge page has one Template select (default "The forge's own code", then Blank, Starter app and each readable template repository); the terminal's New forge screen cycles the same list with left and right, or takes `owner/name` typed. `POST /api/v1/forges` and the MCP spawn tool take `template: "owner/name"`. An unmarked or unreadable `owner/name` answers 422 saying which. A string that is no template at all (not `blank`, `starter` or `owner/name`) answers 404 `unknown_template` with one sentence, "There is no such template.", and the known built-in ids in `templates`; the id sent is never echoed, and any other wrong type stays the 422. The page door answers the same 404: the form again with the name kept and the sentence, and below it the `/templates` rows as buttons that open the form with that template chosen. The terminal has no free-text id to get wrong: its New forge screen cycles the list, and a typed `owner/name` that is not a template gets the sentence only; its Templates screen is where the list is.
44
55 The template's code becomes the child's own `forge` repository. It keeps the template's visibility: a private template never becomes a public repository in the child.
66
src/spawn/door.ts +19
@@ -53,6 +53,7 @@ import { readdir, stat } from "node:fs/promises";
5353 import { join } from "node:path";
5454 import { FREE, getPlan, getPlans, PAID_PLAN_ADMIN_ONLY } from "../settings/plans.ts";
5555 import { giftOf, REDEEM_WORDS, settleGift, unclaimGift } from "../actions/codes.ts";
56 import { parseTemplate, TEMPLATES } from "./templates.ts";
5657 import { claimCode, CODE_WORDS, type Code } from "../billing/codes.ts";
5758
5859 export interface Door {
@@ -182,6 +183,22 @@ export function spawnWords(e: SpawnError): Door {
182183 const invalid = (field: string, reason: string): Door =>
183184 spawnWords({ kind: "invalid", field, reason });
184185
186 /**
187 * A template id that is a string and not a known one: 404, one sentence and the known ids. The
188 * id asked for is not echoed. Other wrong types stay the plan's 422.
189 */
190 export function unknownTemplate(v: unknown): Door | undefined {

Principle 1/8: the message names the ids and the page then lists them again as links. Keep the sentence short ('There is no such template.') and let templates carry the ids, or the reverse. Also add the MCP test for this path.

191 if (typeof v !== "string" || v === "" || parseTemplate(v).ok) return undefined;
192 return {
193 status: 404,
194 body: {
195 error: "unknown_template",
196 message: "There is no such template.",
197 templates: TEMPLATES.map((t) => ({ id: t.id, title: t.title })),
198 },
199 };
200 }
201
185202 const names = (v: unknown, field: string, max: number): string[] | Door => {
186203 if (v === undefined) return [];
187204 if (!Array.isArray(v) || v.length > max || v.some((x) => typeof x !== "string"))
@@ -368,6 +385,8 @@ export async function spawnDoor(
368385 if (dry && said === undefined && (await forgeNameVerdict(ctx.app, raw["name"])).verdict === "taken")
369386 return invalid("name", await takenReason(ctx.app, raw["name"]));
370387 }
388 const unknown = unknownTemplate(raw["template"]);
389 if (unknown !== undefined) return unknown;
371390 const input = {
372391 name: raw["name"],
373392 org: raw["name"],
src/web/pages/new-forge.ts +7
@@ -36,6 +36,8 @@ import { FOLLOW_LABELS, FOLLOW_WORDS } from "../../spawn/follow_words.ts";
3636 import { dropGift, keepGift, keptGift } from "../gift_cookie.ts";
3737 import { notFoundPage, pageHead } from "../chrome.ts";
3838 import { field, readForm, type Form } from "../form.ts";
39 import { templateList } from "../../spawn/template_list.ts";
40 import { templateRows } from "./templates.ts";
3941 import { html, type Html } from "../html.ts";
4042 import { noteForgeMade } from "../funnel_door.ts";
4143 import { page } from "../layout.ts";
@@ -706,6 +708,11 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> {
706708 ...(values.code === "" ? {} : { code: values.code }),
707709 dryRun: planOnly,
708710 }, { page: true });
711 if (door.status === 404 && door.body["error"] === "unknown_template")
712 return page(
713 { ctx, title: "New forge", body: formView(ctx, user, { ...values, template: DEFAULT_TEMPLATE }, { form: String(door.body["message"]) }, templateRows(templateList(ctx.app.db, user?.kind === "user" ? user : undefined)), readsFor(ctx, user)) },
714 404,
715 );
709716 if (door.status >= 400)
710717 return page(
711718 {
src/web/pages/templates.ts +18 −13
@@ -7,14 +7,29 @@
77
88 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
99 import type { Ctx } from "../../http/context.ts";
10 import { templateList } from "../../spawn/template_list.ts";
10 import { templateList, type TemplateRow } from "../../spawn/template_list.ts";
1111 import { pageHead } from "../chrome.ts";
12 import { html } from "../html.ts";
12 import { html, type Html } from "../html.ts";
1313 import { page } from "../layout.ts";
1414 import { btn } from "../ui.ts";
1515
1616 export const TEMPLATES_WORDS = "Pick where your forge starts. You can change everything after.";
1717
18 /** The rows: one sentence and one button each. The unknown-template 404 shows the same list. */
19 export function templateRows(rows: readonly TemplateRow[]): Html {
20 return html`<ul class="plain" id="templates">
21 ${rows.map(
22 (r) => html`<li data-template="${r.id}">

Non-blocking, principle 7/design rule: navigation should be an <a>. A GET form plus button works with JS off and matches /templates, so fine for now; consider links.

23 <form method="get" action="/forges/new" class="row">
24 <input type="hidden" name="template" value="${r.id}">
25 <span><b>${r.title}</b> ${r.says}</span>
26 ${btn(`Start a forge from ${r.title}`, { variant: "secondary" })}
27 </form>
28 </li>`,
29 )}
30 </ul>`;
31 }
32
1833 export function templatesPage(ctx: Ctx): Response {
1934 const user = ctx.auth.user;
2035 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
@@ -26,17 +41,7 @@ export function templatesPage(ctx: Ctx): Response {
2641 description: TEMPLATES_WORDS,
2742 body: html`<div class="narrow-wide">
2843 ${pageHead("Templates", { sub: TEMPLATES_WORDS })}
29 <ul class="plain" id="templates">
30 ${rows.map(
31 (r) => html`<li data-template="${r.id}">
32 <form method="get" action="/forges/new" class="row">
33 <input type="hidden" name="template" value="${r.id}">
34 <span><b>${r.title}</b> ${r.says}</span>
35 ${btn(`Start a forge from ${r.title}`, { variant: "secondary" })}
36 </form>
37 </li>`,
38 )}
39 </ul>
44 ${templateRows(rows)}
4045 </div>`,
4146 }),
4247 );
test/new-forge.test.ts +4 −3
@@ -152,10 +152,11 @@ describe("+ New forge", () => {
152152 expect(await blank.text()).not.toContain("template.</li>");
153153
154154 const bad = await post(admin, [["name", "tpl"], ["do", "plan"], ["template", "nope"]]);
155 expect(bad.status).toBe(422);
155 expect(bad.status).toBe(404);
156156 const body = await bad.text();
157 expect(body).toContain("template must be blank, starter or the owner/name of a template repository");
158 expect(body).toContain('value="tpl"');
157 expect(body).toContain("There is no such template.");
158 expect(body).toContain(`data-template="starter"`);
159 expect(body).toContain(`value="tpl"`);
159160 expect(await children()).toBe(0);
160161 });
161162
test/spawn-template-api.test.ts +2 −4
@@ -90,16 +90,14 @@ describe("choosing a template for a new forge", () => {
9090 });
9191
9292 test("an unknown template is a 422 on template", async () => {
93 for (const template of ["nope", 7, ["starter"]]) {
93 for (const template of [7, ["starter"]]) {
9494 const res = await post({ name: "kid", apps: ["alice/notes"], template });
9595 expect(res.status).toBe(422);
9696 const body = (await res.json()) as any;
9797 expect(body.error).toBe("invalid");
9898 expect(body.message).toBe("template: template must be blank, starter or the owner/name of a template repository");
9999 }
100 const viaMcp = await mcp("spawn", { name: "kid", template: "nope" });
101 expect(viaMcp.error).toBe(true);
102 expect(viaMcp.text).toContain("template: template must be blank, starter or the owner/name of a template repository");
100 // A string that is no template is the 404 test/template-unknown.test.ts holds.
103101 });
104102
105103 test("the templates list is public and ETagged", async () => {
test/template-unknown.test.ts added +95
@@ -0,0 +1,95 @@
1 /** An unknown template id is a 404 that names the known ones, on the page and the API. */
2 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App } from "../src/app.ts";
7 import { usePlacement, useProbe } from "../src/spawn/door.ts";
8 import { createToken } from "../src/core/tokens.ts";
9 import { createUser } from "../src/core/users.ts";
10 import { serve, type Servers } from "../src/http/server.ts";
11 import { ok } from "../src/kernel/result.ts";
12 import { quietLogs } from "./helpers/globals.ts";
13
14 quietLogs();
15
16 describe("unknown template", () => {
17 let dataDir: string;
18 let app: App;
19 let servers: Servers;
20 let base: string;
21 let rw: string;
22 const evil = `<script>alert(1)</script>`;
23
24 beforeAll(async () => {
25 dataDir = await mkdtemp(join(tmpdir(), "forge-template-unknown-"));
26 app = createApp({ dataDir, port: 0 });
27 servers = await serve(app);
28 base = servers.url;
29 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
30 if (!a.ok) throw new Error("user");
31 rw = createToken(app.db, a.value.id, "rw", "rw").token;
32 useProbe(app, () => async () => true);
33 usePlacement(app, { place: async (p) => ok({ url: `https://${p.name}.fake.test`, bodyId: "x" }), retire: async () => ok() });
34 }, 30_000);
35
36 afterAll(async () => {
37 servers.stop();
38 app.close();
39 await rm(dataDir, { recursive: true, force: true });
40 });
41
42 test("the API answers 404 with the sentence and the known ids, not the id sent", async () => {
43 for (const dryRun of [true, false]) {
44 const res = await fetch(`${base}/api/v1/forges`, {
45 method: "POST",
46 headers: { "content-type": "application/json", authorization: `Bearer ${rw}` },
47 body: JSON.stringify({ name: "kid", template: evil, dryRun }),
48 });
49 expect(res.status).toBe(404);
50 const text = await res.text();
51 const body = JSON.parse(text);
52 expect(body.error).toBe("unknown_template");
53 expect(body.message).toBe("There is no such template.");
54 expect(body.templates.map((t: any) => t.id)).toEqual(["blank", "starter"]);
55 expect(text).not.toContain("alert");
56 }
57 });
58
59 test("the page answers 404 for a signed-in maker with the rows as links and the form kept", async () => {
60 const login = await fetch(`${base}/signin`, {
outdated

This fetch of /forges/templates proves nothing about the page. Remove it, and post the form signed in as alice so the 404 re-render with the user's form is what is tested.

61 method: "POST",
62 redirect: "manual",
63 headers: { origin: base },
64 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
65 });
66 const cookie = (login.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
67 expect(cookie).not.toBe("");
68 const form = new URLSearchParams({ name: "kid", template: evil, do: "plan" });
69 const res = await fetch(`${base}/forges/new`, { method: "POST", headers: { origin: base, cookie }, body: form });
70 expect(res.status).toBe(404);
71 const html = await res.text();
72 expect(html).toContain("There is no such template.");
73 expect(html).toContain(`data-template="starter"`);
74 expect(html).toContain(`name="template" value="blank"`);
75 expect(html).toMatch(/name="name"[^>]*value="kid"|value="kid"[^>]*name="name"/);
76 expect(html).not.toContain(evil);
77 });
78
79 test("the MCP spawn tool answers the same for an unknown string template", async () => {
80 const res = await fetch(`${base}/mcp`, {
81 method: "POST",
82 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${rw}` },
83 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "spawn", arguments: { name: "kid", template: "nope" } } }),
84 });
85 const text = await res.text();
86 expect(text).toContain("There is no such template.");
87 expect(text).toContain("unknown_template");
88 expect(text).not.toContain("alert");
89 });
90
91 test("a known id in the link preselects it", async () => {
92 const html = await (await fetch(`${base}/forges/new?template=starter`)).text();
93 expect(html).toMatch(/value="starter"\s+selected/);
94 });
95 });
test/tui-newforge.test.ts +1 −1
@@ -271,7 +271,7 @@ describe("the new forge screen", () => {
271271 withScreen(admin, async ({ tui, terminal }) => {
272272 terminal.feed("tuitpl" + "\t".repeat(10) + "nope\x10");
273273 await settleApp(tui);
274 expect(tui.screen.toText()).toContain("template must be blank, starter or the owner/name of a template repository");
274 expect(tui.screen.toText()).toContain("There is no such template.");
275275 }));
276276
277277 test("an unknown size is refused beside the field", () =>

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs