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

Make my forge takes a stranger with JavaScript to the claim form already filled in; without JavaScript the answer still shows the link once #11304

Closed opened this
Closed without merging

mason/forge:mason/11202-make-my-forge-takes-a-stranger-with-java → main 5 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
6 files changed +149 −78
docs/features/claim-redirect.md added +18
@@ -0,0 +1,18 @@
1 # Claim redirect
2
3 What a stranger sees after pressing Start my forge (or Spawn on `/forges/new`).
4
5 - **With JavaScript.** The page's script adds `js=1` to the form. The answer is
6 a 303 to `/forges/<name>/waiting#<code>`. The waiting page is static and
7 never holds the code: a few lines of script read the fragment, clear it from
8 the address bar, poll `/forges/<name>/ready` (at most 120 tries), then go to
9 the child's `/claim#<code>`. No code to copy.
10 - **Without JavaScript.** No `js` field, so the answer is the 200 page that
11 shows the claim link once (`no-store`), to send or open. The waiting page
12 needs the script and says so in plain text.
13 - **From the terminal.** Unchanged: the door returns the claim link once and
14 the terminal prints it.
15
16 A signed-in person always gets the link page: only a stranger is redirected.
17 A claim code that is not well formed is never put in an address; the link page
18 shows it instead.
src/http/server.ts +2
@@ -279,6 +279,7 @@ import { forgeLinkRevoke, forgeLinkSubmit, forgeLinkUndo, forgeRemoveConfirm, fo
279279 forgeOwnCodeSubmit, forgesPage } from "../web/pages/forges.ts";
280280 import { forgeItSubmit } from "../web/pages/forge-it.ts";
281281 import { funnelSubmit } from "./funnel.ts";
282 import { forgeWaitingPage } from "../web/pages/forge-waiting.ts";
282283 import { startForgeSubmit } from "../web/pages/start-forge.ts";
283284 import { newForgePage, newForgeSubmit } from "../web/pages/new-forge.ts";
284285 import { askedPage } from "../web/studio/asked_page.ts";
@@ -855,6 +856,7 @@ export function buildRouter(): Router<Handler> {
855856 router.add("GET", "/forges/:name/remove", forgeRemoveConfirm);
856857 router.add("POST", "/forges/:name/remove", forgeRemoveSubmit);
857858 router.add("GET", "/forges/:name/ready", forgeReady);
859 router.add("GET", "/forges/:name/waiting", forgeWaitingPage);
858860 router.add("GET", "/forges/new", newForgePage);
859861 router.add("POST", "/forges/new", newForgeSubmit);
860862 router.add("POST", "/forges/start", startForgeSubmit);
src/web/pages/forge-waiting.ts added +59
@@ -0,0 +1,59 @@
1 /**
2 * `GET /forges/<name>/waiting`: where a stranger with JavaScript waits for the
3 * forge they just made (#11202). The page is static and holds no claim code:
4 * the code rides the fragment of this address (`#<code>`), which a server never
5 * sees. A few lines of script read it, clear it from the address bar, poll
6 * `/forges/<name>/ready` (capped), then go to the child's `/claim#<code>`.
7 */
8 import { isChildName } from "../../core/proposal_token.ts";
9 import type { Ctx } from "../../http/context.ts";
10 import { childUrlOf } from "../../spawn/door.ts";
11 import { notFoundPage, pageHead } from "../chrome.ts";
12 import { html } from "../html.ts";
13 import { page } from "../layout.ts";
14
15 /** What the claim code looks like: 32 random bytes, base64url. */
16 export const CLAIM_CODE = /^[A-Za-z0-9_-]{43}$/;
17
18 export const WAITING_JS = /* js */ `
19 (function () {
20 var el = document.getElementById("waiting");
21 if (!el) return;
22 var code = location.hash.slice(1), tries = 0;
23 if (!/^[A-Za-z0-9_-]{43}$/.test(code)) { el.textContent = "This link has no claim code. Start again from the new forge page."; return; }
24 history.replaceState(null, "", location.pathname);
25 var name = el.getAttribute("data-name"), base = el.getAttribute("data-claim");
26 function again(ms) {
27 if (tries < 120) setTimeout(poll, ms);
28 else el.textContent = "This is taking longer than usual. Reload this page in a minute.";
29 }
30 function poll() {
31 tries++;
32 fetch("/forges/" + encodeURIComponent(name) + "/ready", { credentials: "same-origin" })
33 .then(function (r) { return r.json(); })
34 .then(function (j) { if (j && j.ready) location.replace(base + "#" + code); else again(1000); })
35 .catch(function () { again(2000); });
36 }
37 poll();
38 })();
39 `;
40
41 export function forgeWaitingPage(ctx: Ctx): Response {
42 const name = ctx.params.name ?? "";
43 if (!isChildName(name)) return notFoundPage(ctx);
44 const claim = `${childUrlOf(ctx.app, name).replace(/\/+$/, "")}/claim`;
45 const response = page({
46 ctx,
47 title: "Making your forge",
48 scriptJs: WAITING_JS,
49 body: html`<div class="narrow stack">
50 ${pageHead("Making your forge")}
51 <p id="waiting" role="status" data-name="${name}" data-claim="${claim}">
52 <noscript>This page needs JavaScript. Go back and make the forge again to get its link.</noscript>
53 It will be ready in a moment; you will go on by yourself, to choose a username and a password.
54 </p>
55 </div>`,
56 });
57 response.headers.set("cache-control", "no-store");
58 return response;
59 }
src/web/pages/new-forge.ts +25 −51
@@ -18,7 +18,6 @@ import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.t
1818 import { giftOf, REDEEM_WORDS } from "../../actions/codes.ts";
1919 import { quotaFull } from "../../spawn/quota.ts";
2020 import { isChildName } from "../../core/proposal_token.ts";
21 import { childReady } from "../../spawn/ready.ts";
2221 import { childHost, childUrlOf, noRoom, spawnDoor, type Door } from "../../spawn/door.ts";
2322 import {
2423 LEFT_BEHIND,
@@ -37,6 +36,7 @@ import { field, readForm, type Form } from "../form.ts";
3736 import { html, type Html } from "../html.ts";
3837 import { noteForgeMade } from "../funnel_door.ts";
3938 import { page, redirect } from "../layout.ts";
39 import { CLAIM_CODE } from "./forge-waiting.ts";
4040 import { startRefusalHref, startRefusalOf } from "../start_refusal.ts";
4141 import { pickList } from "../pick.ts";
4242 import { btn, field as formField, row, selectField } from "../ui.ts";
@@ -203,7 +203,7 @@ function formView(
203203 ${plan}
204204 <section class="settings-block">
205205 <h2>Its name and apps</h2>
206 <form method="post" action="/forges/new" class="stack" id="new-forge">
206 <form method="post" action="/forges/new" class="stack" id="new-forge" data-js>
207207 ${formField({
208208 label: "Name",
209209 name: "name",
@@ -459,55 +459,29 @@ function madeView(body: Record<string, unknown>): Html {
459459 </div>`;
460460 }
461461
462 /** The script that waits for the new forge to answer, then goes on to its claim form. */
463 export const WAIT_JS = /* js */ `
462 /**
463 * Sets `js=1` on the forms that ask for it, so the answer can tell a browser
464 * that ran this script (it is sent to the waiting page, the code in the
465 * fragment) from one that did not (it is shown the link once).
466 */
467 export const JS_FLAG_JS = /* js */ `
464468 (function () {
465 var el = document.getElementById("making");
466 if (!el) return;
467 var name = el.getAttribute("data-name"), go = document.getElementById("making-go"), tries = 0;
468 function late() {
469 el.textContent = "This is taking longer than usual. Press Continue to try the new forge now; if it is not up yet, come back to this page in a minute.";
469 var forms = document.querySelectorAll("form[data-js]");
470 for (var i = 0; i < forms.length; i++) {
471 var f = document.createElement("input");
472 f.type = "hidden"; f.name = "js"; f.value = "1";
473 forms[i].appendChild(f);
470474 }
471 function again(ms) { if (tries < 120) setTimeout(poll, ms); else late(); }
472 function poll() {
473 tries++;
474 fetch("/forges/" + encodeURIComponent(name) + "/ready", { credentials: "same-origin" })
475 .then(function (r) { return r.json(); })
476 .then(function (j) { if (j && j.ready) location.replace(go.href); else again(1000); })
477 .catch(function () { again(2000); });
478 }
479 poll();
480475 })();
481476 `;
482477
483 /**
484 * Screen two of "Start my forge": the new forge's claim form, where the
485 * person picks a username and password and lands signed in as its admin
486 * (`/claim`). Answering already, the browser is sent straight there; still
487 * booting, a waiting page polls `/forges/<name>/ready` and goes on by itself.
488 * The code travels in the fragment of that one address and is never copied.
489 */
490 async function walkOn(ctx: Ctx, body: Record<string, unknown>): Promise<Response | undefined> {
478 /** The waiting page for a new forge, the claim code in the fragment only (never sent to a server). */
479 function waitingAddress(body: Record<string, unknown>): string | undefined {
491480 const link = body["claimUrl"];
492481 const name = String(body["name"] ?? "");
493 if (typeof link !== "string" || !/^https?:\/\//.test(link) || !isChildName(name)) return undefined;
494 if ((await childReady(ctx.app, name)) === true) {
495 const res = redirect(link);
496 res.headers.set("cache-control", "no-store");
497 return res;
498 }
499 const response = page({
500 ctx,
501 title: "Making your forge",
502 scriptJs: WAIT_JS,
503 body: html`<div class="narrow stack">
504 ${pageHead("Making your forge")}
505 <p id="making" role="status" data-name="${name}">It will be ready in a moment; you will go on by yourself, to choose a username and a password.</p>
506 <p>${btn("Continue", { href: link, variant: "primary", id: "making-go" })}</p>
507 </div>`,
508 });
509 response.headers.set("cache-control", "no-store");
510 return response;
482 if (typeof link !== "string" || !isChildName(name)) return undefined;
483 const code = link.split("#")[1] ?? "";
484 return CLAIM_CODE.test(code) ? `/forges/${name}/waiting#${code}` : undefined;
511485 }
512486
513487 const asBool = (form: Form, name: string): boolean =>
@@ -544,6 +518,7 @@ export function newForgePage(ctx: Ctx): Response {
544518 const response = page({
545519 ctx,
546520 title: "New forge",
521 ...(user === undefined ? { scriptJs: JS_FLAG_JS } : {}),
547522 body: formView(ctx, user, { ...EMPTY, code, name: (ctx.url.searchParams.get("name") ?? "").slice(0, 38), ...fromPack(ctx, user) }, errors, gift, reads),
548523 });
549524 notePhase(ctx.request, "render", performance.now() - rendering);
@@ -614,13 +589,12 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> {
614589 body: formView(ctx, user, values, {}, planView(ctx, user, values, door.body), readsFor(ctx, user)),
615590 });
616591 noteForgeMade(ctx);
617 // A stranger from the home page is not handed a link: the browser goes on to the claim form itself (#11242).
618 const going = user === undefined && field(form, "from") === "home" ? await walkOn(ctx, door.body) : undefined;
619 if (going !== undefined) return going;
620 const response = page(
621 { ctx, title: "New forge", body: madeView(door.body) },
622 door.status,
623 );
592 // A stranger whose script ran is not handed a link: the waiting page carries the code in its fragment (#11202).
593 const going = user === undefined && field(form, "js") === "1" ? waitingAddress(door.body) : undefined;
594 const response =
595 going !== undefined
596 ? redirect(going)
597 : page({ ctx, title: "New forge", body: madeView(door.body) }, door.status);
624598 // The link is in this body only: never kept by a cache.
625599 response.headers.set("cache-control", "no-store");
626600 if (values.code !== "") response.headers.append("set-cookie", dropGift(ctx.url, ctx.app.config.url));
src/web/studio/home.ts +4 −2
@@ -6,6 +6,7 @@
66 * best of what is public (`actions/front.ts`).
77 */
88
9 import { JS_FLAG_JS } from "../pages/new-forge.ts";
910 import { UPSTREAM_REPO } from "../../core/upstream.ts";
1011 import { foundryHref } from "../../actions/foundry_door.ts";
1112 import { forgeCeiling } from "../../flow/ceiling.ts";
@@ -797,7 +798,8 @@ export function studioDoor(ctx: Ctx): Response {
797798 <div class="door-under">
798799 <div class="door-lead">
799800 <p class="door-support">Say what you need and an AI crew builds it in your own forge, free to try.</p>
800 <form method="post" action="/forges/start" class="door-start" id="start-forge">
801 <form method="post" action="/forges/new" class="door-start" id="start-forge" data-js>
802 <input type="hidden" name="from" value="home" />
801803 ${refusal === undefined ? null : html`<p class="error" id="start-refused">${START_REFUSALS[refusal]}</p>`}
802804 <div class="field">
803805 <label for="start-name">Forge name</label>
@@ -928,7 +930,7 @@ bun run src/main.ts</code></pre>
928930 title: "forge: software for what you're building, yours to keep",
929931 description: "Your own forge, with a private AI crew that builds your apps, games and business tools. Open source, and yours to keep.",
930932 body,
931 scriptJs: `${liveClientJs}\n${liveRegionsJs}\n${funnelJs}\n${startNameJs}`,
933 scriptJs: `${liveClientJs}\n${liveRegionsJs}\n${funnelJs}\n${startNameJs}\n${JS_FLAG_JS}`,
932934 jsonLd: siteStructuredData(origin, running().version),
933935 ...(visitor
934936 ? {
test/stranger-three-screens.test.ts +41 −25
@@ -12,7 +12,7 @@ import { join } from "node:path";
1212 import { childDirOf, childNamed } from "../src/actions/spawn.ts";
1313 import { createApp, type App } from "../src/app.ts";
1414 import { serve, type Servers } from "../src/http/server.ts";
15 import { WAIT_JS } from "../src/web/pages/new-forge.ts";
15 import { WAITING_JS } from "../src/web/pages/forge-waiting.ts";
1616 import { useProbe } from "../src/spawn/door.ts";
1717 import { firstBoot } from "../src/spawn/first-boot.ts";
1818 import { getUserByName } from "../src/core/users.ts";
@@ -41,48 +41,59 @@ afterAll(async () => {
4141 await rm(dir, { recursive: true, force: true });
4242 });
4343
44 const start = (name: string) =>
44 const start = (name: string, js = true) =>
4545 fetch(`${parentServers.url}/forges/new`, {
4646 method: "POST",
4747 headers: { "content-type": "application/x-www-form-urlencoded" },
48 body: new URLSearchParams({ name, from: "home" }),
48 body: new URLSearchParams({ name, from: "home", ...(js ? { js: "1" } : {}) }),
4949 redirect: "manual",
5050 });
5151
52 test("screen 1 to 2: a forge still booting shows a waiting page that goes on by itself, with no link to copy", async () => {
52 test("screen 1 to 2: with JavaScript the answer is a 303 to the waiting page, the code only in the fragment", async () => {
5353 up = false;
5454 const home = await (await fetch(`${parentServers.url}/`)).text();
5555 expect(home).toContain('id="start-forge"');
56 expect(home).toContain("data-js");
5657 const res = await start("walker");
57 expect(res.status).toBe(200);
58 expect(res.status).toBe(303);
59 expect(res.headers.get("cache-control")).toBe("no-store");
60 expect(res.headers.get("location") ?? "").toMatch(/^\/forges\/walker\/waiting#[A-Za-z0-9_-]{43}$/);
61 });
62
63 test("without JavaScript the answer is the page (201) that shows the claim link once", async () => {
64 const res = await start("plainwalker", false);
65 expect(res.status).toBe(201);
5866 expect(res.headers.get("cache-control")).toBe("no-store");
5967 const body = await res.text();
60 expect(body).toContain('id="making"');
61 expect(body).toContain('data-name="walker"');
62 expect(body).not.toContain("The link to send");
63 expect(body).not.toContain("data-copy");
64 // The only way on is one Continue link, always rendered (not only without JavaScript), to the claim form.
65 const claims = body.match(/href="https:\/\/walker--forge\.test\/claim#[A-Za-z0-9_-]{43}"/g) ?? [];
66 expect(claims).toHaveLength(1);
67 expect(body).toMatch(/<a[^>]*id="making-go"[^>]*>\s*Continue/);
68 expect(body).not.toContain("<noscript>");
68 expect(body).toContain("The link to send");
69 expect(body).toMatch(/plainwalker--forge\.test\/claim#[A-Za-z0-9_-]{43}/);
70 });
71
72 test("the waiting page is static and never contains the code", async () => {
73 const page = await fetch(`${parentServers.url}/forges/walker/waiting`);
74 expect(page.status).toBe(200);
75 const body = await page.text();
76 expect(body).not.toContain("/claim#");
77 expect(body).toContain('data-claim="https://walker--forge.test/claim"');
78 expect((await fetch(`${parentServers.url}/forges/Bad_Name/waiting`)).status).toBe(404);
6979 });
7080
7181 /** Run the waiting script against stubs; `answers` is what each poll gets. */
72 function runWait(answers: Array<"pending" | "down">) {
73 const status = { textContent: "", getAttribute: () => "walker" };
74 const go = { href: "https://walker--forge.test/claim#x" };
82 function runWait(answers: Array<"pending" | "down" | "ready">) {
83 const code = "a".repeat(43);
84 const status = { textContent: "", getAttribute: (k: string) => (k === "data-name" ? "walker" : "https://walker--forge.test/claim") };
7585 const replaced: string[] = [];
86 const cleared: string[] = [];
7687 let timers = 0;
7788 let n = 0;
7889 const fetchStub = () => {
7990 const a = answers[Math.min(n++, answers.length - 1)];
80 return a === "down" ? Promise.reject(new Error("net")) : Promise.resolve({ json: async () => ({ ready: false }) });
91 return a === "down" ? Promise.reject(new Error("net")) : Promise.resolve({ json: async () => ({ ready: a === "ready" }) });
8192 };
82 const doc = { getElementById: (id: string) => (id === "making" ? status : go) };
93 const doc = { getElementById: () => status };
8394 const timeout = (f: () => void) => { timers++; queueMicrotask(f); return 0; };
84 new Function("document", "fetch", "setTimeout", "location", WAIT_JS)(doc, fetchStub, timeout, { replace: (u: string) => replaced.push(u) });
85 return { status, replaced, polls: () => n, timers: () => timers };
95 new Function("document", "fetch", "setTimeout", "location", "history", WAITING_JS)(doc, fetchStub, timeout, { hash: `#${code}`, pathname: "/forges/walker/waiting", replace: (u: string) => replaced.push(u) }, { replaceState: (_a: unknown, _b: string, u: string) => cleared.push(u) });
96 return { status, replaced, cleared, polls: () => n, timers: () => timers };
8697 }
8798 const settle = () => new Promise((r) => setTimeout(r, 50));
8899
@@ -91,7 +102,7 @@ test("the waiting script gives up after 120 tries and says so in plain words, ne
91102 await settle();
92103 expect(w.polls()).toBe(120);
93104 expect(w.status.textContent).toContain("taking longer than usual");
94 expect(w.status.textContent).toContain("Continue");
105 expect(w.cleared).toEqual(["/forges/walker/waiting"]);
95106 expect(w.replaced).toEqual([]);
96107 });
97108
@@ -102,19 +113,24 @@ test("a network error keeps trying and says the same when it gives up", async ()
102113 expect(w.status.textContent).toContain("taking longer than usual");
103114 });
104115
116 test("the waiting script goes to the child's claim form with the code once the forge answers", async () => {
117 const w = runWait(["ready"]);
118 await settle();
119 expect(w.replaced).toEqual([`https://walker--forge.test/claim#${"a".repeat(43)}`]);
120 });
121
105122 test("a name the door refuses still comes back to `/`, not to the waiting page", async () => {
106123 const res = await start("Bad_Name");
107124 expect(res.status).toBe(303);
108125 expect(res.headers.get("location") ?? "").toStartWith("/?start=");
109126 });
110127
111 test("screen 2 to 3: a forge that answers sends the browser to its claim form; a username and password land signed in as its admin", async () => {
128 test("screen 2 to 3: the waiting page hands on to the claim form; a username and password land signed in as its admin", async () => {
112129 up = true;
113130 const res = await start("runner");
114131 expect(res.status).toBe(303);
115132 const to = res.headers.get("location") ?? "";
116 expect(to).toMatch(/^https:\/\/runner--forge\.test\/claim#[A-Za-z0-9_-]{43}$/);
117 expect(res.headers.get("cache-control")).toBe("no-store");
133 expect(to).toMatch(/^\/forges\/runner\/waiting#[A-Za-z0-9_-]{43}$/);
118134 const token = to.split("#")[1] ?? "";
119135
120136 const made = await childNamed(parent, "runner");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs