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

An expired forge link offers 'ask for a new link', and asking tells the sender #13656

Merged opened this

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

Merged

scout/forge:scout/13649-an-expired-forge-link-offers-ask-for-a-n → main 6 commits fork 5 threads · 5 unresolved

  • Merged. scout/13649-an-expired-forge-link-offers-ask-for-a-n was merged into main as baf2e0b.

Review

Sign in to review this change.
6 files changed +149 −24
docs/features/claim-renew.md +9 −7
@@ -1,14 +1,16 @@
11 # Ask for a new forge link
22
3 When a forge link has expired, the claim page says so and offers one action: **Ask for a new link**. It records one
4 ask on this forge's own feed, once per link (a repeat answers the same and records nothing). It does not reach the
5 sender, who lives on the parent forge, so the page says the ask is recorded and tells the person to ask whoever sent
6 the link too.
7 Only an expired, unused, unrevoked link can ask; every other state answers the same plain 404 as a made-up link.
3 When a forge link has expired, the claim page says so and offers one action: **Ask for a new link**. Pressing it
4 (no account, same-origin checked, empty body, rate limited) records the ask on this forge's feed and sends the
5 sender, the account that made the forge, one note on the parent forge: which forge, and when the link ended. The
6 note rides the forge's next heartbeat, which the press sends at once. A second press within an hour sends nothing
7 and says it was already sent. Only an expired, unused, unrevoked link can ask; every other state answers the same
8 plain 404 as a made-up link.
89
9 Try it: open `/claim` on a forge whose link has expired and press **Ask for a new link**.
10 Try it: open `/claim` on a forge whose link has expired and press **Ask for a new link**; the sender sees
11 `forge.claim_renewal_note` on their own feed.
1012
1113 The terminal (both doors): the claim link is a web-only handoff for a person with no account yet, so `src/tui` has no
12 claim screen to bring in line. The admins see the event on the same feed as other forge events.
14 claim screen to bring in line.
1315
1416 Pinned by `test/forge-link-expiry.test.ts`.
src/core/event_audience.ts +2
@@ -351,6 +351,8 @@ export function classifiedAudience(kind: string): EventAudience | undefined {
351351 // A person's own ask to the forge that hosts this one, and how it was answered
352352 // (`actions/ask_host.ts`).
353353 kind.startsWith("reach.") ||
354 // A stranger's ask for a new forge link, for the person who made it (`spawn/heartbeat.ts`).
355 kind === "forge.claim_renewal_note" ||
354356 kind.startsWith("thought.")
355357 )
356358 return "actor";
src/design/activity.ts +6
@@ -130,6 +130,12 @@ export function eventVerb(event: ForgeEvent): string {
130130 const why = typeof payload["why"] === "string" ? `: ${payload["why"]}` : "";
131131 return kind === "forge.move_failed" ? `did not move ${name} into a sandbox${why}` : `left ${name} in its own process for an admin to look at${why}`;
132132 }
133 // A stranger asked a spawned forge's sender for a new link (`spawn/heartbeat.ts`).
134 if (kind === "forge.claim_renewal_note") {
135 const name = typeof payload["name"] === "string" ? payload["name"] : "a forge";
136 const expired = typeof payload["expired"] === "string" ? ` expired at ${payload["expired"]}` : " expired";
137 return `was told: ${name}'s forge link${expired}; they asked for a new one`;
138 }
133139 return WORDS[kind] ?? "acted on this repository";
134140 }
135141
src/spawn/heartbeat.ts +51 −1
@@ -74,10 +74,16 @@ export interface Beat {
7474 readonly everyday?: boolean;
7575 /** When its person last told the crew something; null before the first, absent likewise. */
7676 readonly lastTellAt?: string | null;
77 /**
78 * When a stranger last asked this forge's sender for a new forge link, and when that link expired
79 * (ISO); absent when none.
80 */
81 readonly linkAskedAt?: string;
82 readonly linkExpiredAt?: string;
7783 }
7884
7985 const OPTIONAL = new Set([
80 "forgeTip", "severedAt", "mode", "upstreamBehind", "conflict", "spendTodayUsd", "ceilingUsd", "crewHeld", "claimed", "everyday", "lastTellAt",
86 "forgeTip", "severedAt", "mode", "upstreamBehind", "conflict", "spendTodayUsd", "ceilingUsd", "crewHeld", "claimed", "everyday", "lastTellAt", "linkAskedAt", "linkExpiredAt",
8187 ]);
8288 const USD_MAX = 1_000_000;
8389
@@ -132,6 +138,12 @@ export function parseBeat(raw: string): Beat | undefined {
132138 // Strict ISO: it is printed into the parent admin's terminal, so nothing but digits and punctuation.
133139 const toldOk =
134140 told === null || (typeof told === "string" && ISO_TIME.test(told) && !Number.isNaN(Date.parse(told)));
141 // Both or neither, strict ISO: they become words on the sender's page.
142 const askedAt = d["linkAskedAt"];
143 const expiredAt = d["linkExpiredAt"];
144 const isoOk = (v: unknown): v is string => typeof v === "string" && ISO_TIME.test(v) && !Number.isNaN(Date.parse(v));
145 if ((askedAt === undefined) !== (expiredAt === undefined)) return undefined;
146 if (askedAt !== undefined && !(isoOk(askedAt) && isoOk(expiredAt))) return undefined;
135147 if (typeof name !== "string" || !NAME.test(name)) return undefined;
136148 if (typeof at !== "number" || !Number.isSafeInteger(at) || at <= 0) return undefined;
137149 if (typeof version !== "string" || !VERSION.test(version)) return undefined;
@@ -156,6 +168,7 @@ export function parseBeat(raw: string): Beat | undefined {
156168 ...(claimedOk ? { claimed } : {}),
157169 ...(everydayOk ? { everyday } : {}),
158170 ...(told !== undefined && toldOk ? { lastTellAt: told as string | null } : {}),
171 ...(askedAt === undefined ? {} : { linkAskedAt: askedAt as string, linkExpiredAt: expiredAt as string }),
159172 };
160173 }
161174
@@ -236,9 +249,45 @@ async function takeBeat(
236249 const path = beatPath(app, beat.name);
237250 await writeFile(`${path}.tmp`, JSON.stringify({ receivedAt: now, beat }));
238251 await rename(`${path}.tmp`, path);
252 if (beat.linkAskedAt !== undefined && beat.linkExpiredAt !== undefined)
253 await noteTheAsk(app, beat.name, beat.linkAskedAt, beat.linkExpiredAt).catch((error) =>
254 app.log.warn("a child's ask for a new link was not noted", { forge: beat.name, reason: String(error) }),
255 );
239256 return true;
240257 }
241258
259 /**
260 * A child's stranger asked for a new forge link: one note, for the account that made the child,
261 * once per ask (a beat is repeated every ten minutes) and at most one an hour per child. It names the forge and when the link ended.
262 */
263 async function noteTheAsk(app: App, name: string, asked: string, expired: string): Promise<void> {
264 const { childNamed } = await import("../actions/spawn.ts");
265 const child = await childNamed(app, name);
outdated

Failure here is swallowed silently; log it. Also no per-child cap on how many notes a child may make.

266 if (child?.ownerId === undefined) return;
267 const seen = app.db
268 .query("SELECT 1 FROM event WHERE kind = 'forge.claim_renewal_note' AND json_extract(payload, '$.name') = ?1 AND json_extract(payload, '$.asked') = ?2 LIMIT 1")
269 .get(name, asked);
270 if (seen !== null) return;
271 // A child can make asks without end; its sender hears of at most one an hour.
272 const hourAgo = new Date(Date.now() - 3_600_000).toISOString();
273 const lately = app.db
274 .query("SELECT 1 FROM event WHERE kind = 'forge.claim_renewal_note' AND json_extract(payload, '$.name') = ?1 AND created_at > ?2 LIMIT 1")
275 .get(name, hourAgo);
276 if (lately !== null) return;
277 app.bus.append({ kind: "forge.claim_renewal_note", actorId: child.ownerId, payload: { name, asked, expired } });
278 }
279
280 /** The child's latest ask for a new link within the day, as the beat carries it. */
outdated

Appends a bare event kind that nothing words for a person. Add a plain-language rendering (principle 8) and a test for it.

281 function linkAsk(app: App): { linkAskedAt?: string; linkExpiredAt?: string } {
282 const row = app.db
283 .query<{ payload: string }, [string]>("SELECT payload FROM event WHERE kind = 'forge.claim_renewal_asked' AND created_at > ?1 ORDER BY created_at DESC LIMIT 1")
284 .get(new Date(Date.now() - 86_400_000).toISOString());
285 if (row === null) return {};
286 const p = JSON.parse(row.payload) as { at?: unknown; link?: unknown };
287 const ok = (v: unknown): v is string => typeof v === "string" && ISO_TIME.test(v);
288 return ok(p.at) && ok(p.link) ? { linkAskedAt: p.at, linkExpiredAt: p.link } : {};
289 }
290
242291 /** What a child knows of its parent from `parent.json`, when it has all of it. */
243292 export async function parentLink(
244293 app: App,
@@ -320,6 +369,7 @@ export async function sendBeat(
320369 ...spendReport(app),
321370 ...(forgeHasNoKey(app) ? { crewHeld: NO_KEY_HELD } : {}),
322371 ...progress(app),
372 ...linkAsk(app),
323373 // Only a forge that carries a fork of its parent's code has these to say.
324374 ...(forge === undefined
325375 ? {}
src/web/pages/claim.ts +37 −10
@@ -26,6 +26,7 @@ import { PASSWORD_TOO_LONG, withinPasswordCap } from "../../core/hash-gate.ts";
2626 import { givenEmail, MIN_SIGNUP_PASSWORD, noEmail } from "../../actions/users.ts";
2727 import type { Credential } from "../../auth/webauthn.ts";
2828 import { cookieValue, crossOrigin, type Ctx } from "../../http/context.ts";
29 import { sendBeat } from "../../spawn/heartbeat.ts";
2930 import { STRANGER_MAX } from "../../http/limits.ts";
3031 import { clientAddress } from "../../http/peer.ts";
3132 import { boundedBody, json, str } from "../../http/respond.ts";
@@ -425,29 +426,50 @@ export async function claimOptions(ctx: Ctx): Promise<Response> {
425426 return json(makeOptions(ctx, "claim", username));
426427 }
427428
429 const ASK_WINDOW_MS = 3_600_000;
430
428431 /**
429432 * POST /claim/renew — "Ask for a new link" on an expired link. It records the ask on this forge's
430 * own feed, once per link: a repeat answers the same sentence and records nothing. It does not
431 * reach the sender: they live on the parent forge, and no path from here to them exists, so the
432 * page says "recorded", never "told". Only an expired, unused, unrevoked link of a spawned forge
433 * can ask; every other state answers the same plain 404 as a made-up link.
433 * own feed and sends the sender (the link's maker, on the parent forge) one note with the next
434 * heartbeat, sent now (`spawn/heartbeat.ts`). A second press within an hour records and sends
435 * nothing and says so. The body is empty and nothing of it is echoed; a stranger's presses are
436 * rate limited. Only an expired, unused, unrevoked link of a spawned forge can ask; every other
437 * state answers the same plain 404 as a made-up link.
434438 */
435439 export async function claimRenew(ctx: Ctx): Promise<Response> {
436440 const form = await readForm(ctx);
437441 if (form instanceof Response) return form;
442 const wait = signinAllowed(ctx, `claim-renew:${clientAddress(ctx.request)}`);
443 if (wait !== undefined)
444 return withHeader(page({
outdated

A bare text/plain 429 leaves a person with no page and no way back. Render it in the page shell with plain words.

445 ctx,
446 title: "Too many tries",
447 body: html`<div class="narrow">${pageHead("Too many tries")}<section class="settings-block"><p>You have pressed this a lot. Try again in ${wait} seconds.</p><div class="form-actions"><a href="/">Back to the home page</a></div></section></div>`,
448 }, 429), "retry-after", String(wait));
438449 const spawned = await spawnedOrg(ctx.app);
439450 const link = linkOf(ctx.app.db);
440451 if (spawned === undefined || link === null || link.state !== "ended" || link.revokedAt !== null || link.usedAt !== null)
441452 return dead(ctx, "unknown");
442 const open = ctx.app.db
443 .query("SELECT 1 FROM event WHERE kind = 'forge.claim_renewal_asked' AND json_extract(payload, '$.link') = ?1 LIMIT 1")
444 .get(link.expiresAt ?? "");
445 if (open === null)
446 ctx.app.bus.append({ kind: "forge.claim_renewal_asked", payload: { org: spawned.org.username, link: link.expiresAt ?? "" } });
453 const hourAgo = new Date(Date.now() - ASK_WINDOW_MS).toISOString();
454 const recent = ctx.app.db

Non-blocking: the 429 page has no test; a loop of presses that expects 429 and retry-after would pin it.

455 .query("SELECT 1 FROM event WHERE kind = 'forge.claim_renewal_asked' AND created_at > ?1 LIMIT 1")
456 .get(hourAgo);
457 if (recent === null) {
458 ctx.app.bus.append({
459 kind: "forge.claim_renewal_asked",
460 payload: { org: spawned.org.username, link: link.expiresAt ?? "", at: new Date().toISOString() },
461 });
462 // The note to the sender rides the next beat; send it now, not in a form's wait.
463 void sendBeat(ctx.app).catch(() => false);
outdated

Claims 'has been sent a note' while the beat is still fire-and-forget and may fail. Say 'will be sent', or await the result.

464 }
465 const said =
466 recent === null
467 ? "Your ask is recorded, and a note to the sender of this link will be sent now, and again on the next report if it cannot go out."
468 : "Your ask was already sent within the last hour. Ask the sender for a new link too, if it matters.";
447469 return page({
448470 ctx,
449471 title: "Ask recorded",
450 body: html`<div class="narrow">${pageHead("Ask recorded")}<section class="settings-block"><p id="claim-asked">Your ask is recorded on this forge's feed. It has not reached whoever sent the link, so ask them for a new one too.</p></section></div>`,
472 body: html`<div class="narrow">${pageHead("Ask recorded")}<section class="settings-block"><p id="claim-asked">${said}</p></section></div>`,
451473 });
452474 }
453475
@@ -582,3 +604,8 @@ function claimed(ctx: Ctx, spawned: Spawned, user: User): Response {
582604 sessionCookie(session.token, session.expiresAt, ctx.url, ctx.app.config.url),
583605 );
584606 }
607
608 function withHeader(res: Response, name: string, value: string): Response {
609 res.headers.set(name, value);
610 return res;
611 }

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs