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 #11284

Parked opened this
Closed without merging

scout/forge:scout/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.
7 files changed +191 −2
docs/features/claim-redirect.md added +21
@@ -0,0 +1,21 @@
1 # A stranger makes a forge and lands on its claim form
2
3 What the person sees after "Start my forge" (`POST /forges/new`, as a stranger):
4
5 - **With JavaScript.** The page's script adds `js=1` to the form. The answer is a
6 `303` to `/forges/<name>/waiting#<code>`. That page is static and holds no
7 code: a few lines of script read the fragment, clear it from the address bar,
8 poll `/forges/<name>/ready` every two seconds (30 times at most), then go to
9 the child's `/claim#<code>`. Nothing to copy. If the wait runs out, the page
10 says so and offers "Open it anyway".
11 - **Without JavaScript.** No `js=1`, so the answer is the page (`201`, as before) that shows
12 the claim link once (`no-store`), to copy and send or open. Nothing is lost.
13 The waiting page's `<noscript>` line says the same in plain text.
14 - **In the terminal** (and the API): unchanged. The claim link is printed once.
15
16 The code is only ever in a fragment or in that one response body, never in a
17 request URL or a log. A malformed code (not 43 base64url characters) falls back
18 to that page. Signed-in people always get that page.
19
20 Tests: `test/claim-redirect.test.ts`. Code: `src/web/pages/forge-waiting.ts`,
21 `newForgeSubmit` in `src/web/pages/new-forge.ts`.
src/http/server.ts +2
@@ -271,6 +271,7 @@ import {
271271 tellSubmit,
272272 } from "../web/studio/actions.ts";
273273 import { forgeReady } from "../web/pages/forge-ready.ts";
274 import { forgeWaiting } from "../web/pages/forge-waiting.ts";
274275 import { claimFragmentPage, claimOptions, claimSubmit } from "../web/pages/claim.ts";
275276 import { firstAdminOptions, firstAdminPage, firstAdminSubmit } from "../web/pages/first-admin.ts";
276277 import { familyPage } from "../web/pages/family.ts";
@@ -853,6 +854,7 @@ export function buildRouter(): Router<Handler> {
853854 router.add("GET", "/forges/:name/remove", forgeRemoveConfirm);
854855 router.add("POST", "/forges/:name/remove", forgeRemoveSubmit);
855856 router.add("GET", "/forges/:name/ready", forgeReady);
857 router.add("GET", "/forges/:name/waiting", forgeWaiting);
856858 router.add("GET", "/forges/new", newForgePage);
857859 router.add("POST", "/forges/new", newForgeSubmit);
858860 // The front page as a stranger sees it, for anyone; a site admin there
src/web/pages/forge-waiting.ts added +73
@@ -0,0 +1,73 @@
1 /**
2 * `GET /forges/<name>/waiting`: where a stranger with JavaScript waits for the
3 * forge they just made, then goes on to its claim form already filled in.
4 * The page is static and holds no code: the claim code rides the address's
5 * fragment (`#<code>`), which no server, log or cache ever sees. A few lines of
6 * script read it, clear it from the address bar, poll `/forges/<name>/ready`
7 * (capped), then go to the child's `/claim#<code>`.
8 */
9 import { isChildName } from "../../core/proposal_token.ts";
10 import type { Ctx } from "../../http/context.ts";
11 import { childUrlOf } from "../../spawn/door.ts";
12 import { notFoundPage, pageHead } from "../chrome.ts";
13 import { html } from "../html.ts";
14 import { page } from "../layout.ts";
15
16 /** Polls of `/ready`, two seconds apart: a minute, then the page says so. */
17 export const WAIT_POLLS = 30;
18
19 /** Trusted, static: the name and the child's address arrive as data attributes. */
20 export const waitingJs = `
21 var el=document.getElementById("waiting");
22 if(el){
23 var code=location.hash.slice(1);
24 var st=document.getElementById("waiting-status");
25 var say=function(t){st.textContent=t;};
26 if(!/^[A-Za-z0-9_-]{43}$/.test(code)){say("This page needs the link you were given. Open the forge's address instead.");}
27 else{
28 history.replaceState(null,"",location.pathname);
29 var n=0,max=${WAIT_POLLS};
30 var go=function(){location.replace(el.dataset.child+"/claim#"+code);};
31 var again=function(){setTimeout(poll,2000);};
32 var poll=function(){
33 n++;
34 fetch("/forges/"+encodeURIComponent(el.dataset.name)+"/ready",{cache:"no-store"})
35 .then(function(r){return r.ok?r.json():{ready:false};})
36 .catch(function(){return {ready:false};})
37 .then(function(j){
38 if(j.ready===true){say("Ready. Opening it…");go();}
39 else if(n>=max){say("It is taking longer than usual.");el.insertAdjacentHTML("beforeend",'<p><a id="waiting-go" href="'+el.dataset.child+'/claim#'+code+'">Open it anyway</a></p>');}
40 else again();
41 });
42 };
43 poll();
44 }
45 }`;
46
47 /** The code in a claim link's fragment, when it is well formed (43 base64url characters). */
48 export function claimCodeOf(link: unknown): string | undefined {
49 if (typeof link !== "string") return undefined;
50 const m = /\/claim#([A-Za-z0-9_-]{43})$/.exec(link);
51 return m?.[1];
52 }
53
54 /** Tells the server the script ran: the posted form then gets the answer that needs no copying. */
55 export const jsFlagJs = `document.querySelectorAll('form[action="/forges/new"]').forEach(function(f){var i=document.createElement("input");i.type="hidden";i.name="js";i.value="1";f.appendChild(i);});`;
56
57 // GET /forges/:name/waiting
58 export function forgeWaiting(ctx: Ctx): Response {
59 const name = ctx.params.name ?? "";
60 if (!isChildName(name)) return notFoundPage(ctx);
61 const response = page({
62 ctx,
63 title: "Making your forge",
64 scriptJs: waitingJs,
65 body: html`<div class="narrow-wide" id="waiting" data-name="${name}" data-child="${childUrlOf(ctx.app, name)}">
66 ${pageHead("Making your forge")}
67 <p role="status" id="waiting-status" class="muted">Waiting for ${name} to answer…</p>
68 <noscript><p>This page needs JavaScript to open your forge. Go back and make it again: without JavaScript the link is shown once.</p></noscript>
69 </div>`,
70 });
71 response.headers.set("cache-control", "no-store");
72 return response;
73 }
src/web/pages/new-forge.ts +10
@@ -37,6 +37,7 @@ import { field, readForm, type Form } from "../form.ts";
3737 import { html, type Html } from "../html.ts";
3838 import { noteForgeMade } from "../funnel_door.ts";
3939 import { page, redirect } from "../layout.ts";
40 import { claimCodeOf, jsFlagJs } from "./forge-waiting.ts";
4041 import { startRefusalHref, startRefusalOf } from "../start_refusal.ts";
4142 import { pickList } from "../pick.ts";
4243 import { btn, field as formField, row, selectField } from "../ui.ts";
@@ -544,6 +545,7 @@ export function newForgePage(ctx: Ctx): Response {
544545 const response = page({
545546 ctx,
546547 title: "New forge",
548 scriptJs: jsFlagJs,
547549 body: formView(ctx, user, { ...EMPTY, code, name: (ctx.url.searchParams.get("name") ?? "").slice(0, 38), ...fromPack(ctx, user) }, errors, gift, reads),
548550 });
549551 notePhase(ctx.request, "render", performance.now() - rendering);
@@ -614,6 +616,14 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> {
614616 body: formView(ctx, user, values, {}, planView(ctx, user, values, door.body), readsFor(ctx, user)),
615617 });
616618 noteForgeMade(ctx);
619 // A stranger whose script ran goes on to wait for the child with the code in the fragment only.
620 const code = user === undefined && field(form, "js") === "1" ? claimCodeOf(door.body["claimUrl"]) : undefined;
621 if (code !== undefined) {
622 const to = redirect(`/forges/${encodeURIComponent(values.name)}/waiting#${code}`);
623 to.headers.set("cache-control", "no-store");
624 if (values.code !== "") to.headers.append("set-cookie", dropGift(ctx.url, ctx.app.config.url));
625 return to;
626 }
617627 // A stranger from the home page is not handed a link: the browser goes on to the claim form itself (#11242).
618628 const going = user === undefined && field(form, "from") === "home" ? await walkOn(ctx, door.body) : undefined;
619629 if (going !== undefined) return going;
src/web/studio/home.ts +2 −1
@@ -6,6 +6,7 @@
66 * best of what is public (`actions/front.ts`).
77 */
88
9 import { jsFlagJs } from "../pages/forge-waiting.ts";
910 import { UPSTREAM_REPO } from "../../core/upstream.ts";
1011 import { foundryHref } from "../../actions/foundry_door.ts";
1112 import { forgeCeiling } from "../../flow/ceiling.ts";
@@ -926,7 +927,7 @@ bun run src/main.ts</code></pre>
926927 title: "forge: software for what you're building, yours to keep",
927928 description: "Your own forge, with a private AI crew that builds your apps, games and business tools. Open source, and yours to keep.",
928929 body,
929 scriptJs: `${liveClientJs}\n${liveRegionsJs}\n${funnelJs}`,
930 scriptJs: `${liveClientJs}\n${liveRegionsJs}\n${funnelJs}\n${jsFlagJs}`,
930931 jsonLd: siteStructuredData(origin, running().version),
931932 ...(visitor
932933 ? {
test/claim-redirect.test.ts added +82
@@ -0,0 +1,82 @@
1 /**
2 * A stranger who makes a forge: with the script (`js=1`) they are sent to the
3 * waiting page with the code only in the fragment; without it the 200 page
4 * shows the claim link once. The waiting page never holds a code.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { serve, type Servers } from "../src/http/server.ts";
12 import { ok } from "../src/kernel/result.ts";
13 import { bootHostedChild } from "../src/spawn/host.ts";
14 import { usePlacement, useProbe } from "../src/spawn/door.ts";
15 import { claimCodeOf, jsFlagJs } from "../src/web/pages/forge-waiting.ts";
16 import { quietLogs } from "./helpers/globals.ts";
17
18 quietLogs();
19
20 let dir: string;
21 let app: App;
22 let servers: Servers;
23 const AGENT = "Mozilla/5.0 (X11; Linux x86_64) Chrome/130.0 Safari/537.36";
24
25 const make = (fields: Record<string, string>) =>
26 fetch(`${servers.url}/forges/new`, {
27 method: "POST",
28 redirect: "manual",
29 headers: { "user-agent": AGENT, origin: servers.url, "content-type": "application/x-www-form-urlencoded" },
30 body: new URLSearchParams(fields),
31 });
32
33 beforeAll(async () => {
34 dir = await mkdtemp(join(tmpdir(), "forge-claim-redirect-"));
35 app = createApp({ dataDir: dir, port: 0 });
36 servers = await serve(app);
37 useProbe(app, () => async () => true);
38 usePlacement(app, { place: async (p) => ok({ url: `https://${p.name}.fake.test`, bodyId: `fake-${p.name}` }), retire: async () => ok() });
39 }, 30_000);
40
41 afterAll(async () => {
42 await bootHostedChild(app, "redir-js");
43 await bootHostedChild(app, "redir-nojs");
44 servers.stop();
45 app.close();
46 await rm(dir, { recursive: true, force: true });
47 });
48
49 describe("claim redirect", () => {
50 test("with the script: a 303 to the waiting page, the code only in the fragment", async () => {
51 const res = await make({ name: "redir-js", js: "1" });
52 expect(res.status).toBe(303);
53 const to = res.headers.get("location") ?? "";
54 expect(to).toMatch(/^\/forges\/redir-js\/waiting#[A-Za-z0-9_-]{43}$/);
55 expect(res.headers.get("cache-control")).toBe("no-store");
56 expect(await res.text()).not.toContain(to.split("#")[1]!);
57 });
58
59 test("without the script: the page shows the claim link once", async () => {
60 const res = await make({ name: "redir-nojs" });
61 expect(res.status).toBe(201); // the page, as before: created
62 expect(await res.text()).toMatch(/id="claim-link"[^>]*>[^<]*\/claim#[A-Za-z0-9_-]{43}</);
63 });
64
65 test("the waiting page is static, holds no code and reads the fragment by script", async () => {
66 const res = await fetch(`${servers.url}/forges/redir-js/waiting#${"A".repeat(43)}`);
67 expect(res.status).toBe(200);
68 const body = await res.text();
69 expect(body).not.toMatch(/\/claim#/);
70 expect(body).toContain('id="waiting-status"');
71 expect(body).toContain("<noscript>");
72 expect(body).toContain('data-name="redir-js"');
73 expect((await fetch(`${servers.url}/forges/Not_A_Name!/waiting`)).status).toBe(404);
74 });
75
76 test("only a well-formed code is taken; the page's script sets js=1", () => {
77 expect(claimCodeOf(`https://x.test/claim#${"a".repeat(43)}`)).toBe("a".repeat(43));
78 expect(claimCodeOf("https://x.test/claim#short")).toBeUndefined();
79 expect(claimCodeOf(undefined)).toBeUndefined();
80 expect(jsFlagJs).toContain('"js"');
81 });
82 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs