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

A child forge reads its parent's releases over HTTPS and says how many it is behind #1728

Closed opened this
Closed without merging

scout/forge:scout/1569-a-child-forge-reads-its-parent-s-release → main 5 commits fork 2 threads · 2 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
11 files changed +569 −1
README.md +13
@@ -151,6 +151,19 @@ Unset, only this machine may say so, and the named header is never read. Everyth
151151 instance _is_ lives under the data directory — the SQLite index, the bare
152152 repos, and the SSH host key, in plain layout. Tar it up and it moves.
153153
154 `FORGE_PARENT_URL` names the forge this one was spawned from. It must be
155 `https://` with no credentials or query (the forge refuses to boot otherwise).
156 The parent serves `/releases.json` as `{"releases":[{"name","url"}]}`, newest
157 first; the child reads it with a 3 s timeout, no redirects and a 256 KB cap,
158 caches it under `FORGE_APP_DATA` for 10 minutes, and says "N releases behind
159 <parent>" on a fork's following card and in the terminal's About card (`I`). A
160 page never waits for the parent: it shows the cached copy and refreshes in the
161 background, and a parent that is down or answering garbage leaves a "could not
162 be reached" with the age of the last copy. Unset, nothing is shown. Read only:
163 taking a release is not done here. This forge publishes its own
164 `/releases.json` (the version names, each linking to that document), so any
165 forge can be a parent. The terminal shows the count, not the release names.
166
154167 ## Health
155168
156169 `GET /api/v1/health` (and the MCP `health` tool) answer a site admin with
docs/FOLLOWING.md +15
@@ -44,6 +44,21 @@ src/weapons.ts" — and offers exactly one thing to do. The forks page shows
4444 each fork's standing as a badge. The JSON is
4545 `GET /api/v1/repos/:owner/:name/following`.
4646
47 ## Releases behind a parent forge
48
49 `FORGE_PARENT_URL` names the forge this one was spawned from. It must be
50 `https://` with no credentials or query (the forge refuses to boot otherwise).
51 The parent serves `/releases.json` as `{"releases":[{"name","url"}]}`, newest
52 first; the child reads it with a 3 s timeout, no redirects and a 256 KB cap,
53 caches it under `FORGE_APP_DATA` for 10 minutes, and says "N releases behind
54 <parent>" on a fork's following card and in the terminal's About card (`I`). A
55 page never waits for the parent: it shows the cached copy and refreshes in the
56 background, and a parent that is down or answering garbage leaves a "could not
57 be reached" with the age of the last copy. Unset, nothing is shown. Read only:
58 taking a release is not done here. This forge publishes its own
59 `/releases.json` (the version names, each linking to that document), so any
60 forge can be a parent. The terminal shows the count, not the release names.
61
4762 ## A frozen parent
4863
4964 A parent can itself be a mirror whose origin was disconnected — a detached
src/app.ts +7
@@ -152,6 +152,13 @@ export interface ForgeConfig {
152152 * `releases/<sha>/` and preflighted (`release/`, #1662).
153153 */
154154 forgeRepo?: string;
155 /**
156 * The forge this one was spawned from (`FORGE_PARENT_URL`): https, no
157 * credentials. Its `/releases.json` is read for the following page.
158 */
159 parentUrl?: string;
160 /** Lets `parentUrl` be plain http. Tests only; boot never sets it. */
161 parentLoopback?: boolean;
155162 /** How many `releases/<sha>/` checkouts to keep (`FORGE_RELEASES_KEEP`). @default 5 */
156163 releasesKeep?: number;
157164 }
src/core/parent_releases.ts added +252
@@ -0,0 +1,252 @@
1 /**
2 * The releases of the forge this one was spawned from, read over HTTPS.
3 *
4 * A child names its parent's URL (`FORGE_PARENT_URL`); the parent answers
5 * `GET <url>/releases.json` with `{ "releases": [{ "name", "url" }] }`,
6 * newest first. Read only: nothing here takes an update.
7 *
8 * The read is bounded (a timeout and a size cap), cached under the data
9 * directory for ten minutes, and never throws. A page never waits for the
10 * parent: it renders what the cache holds at once, and a stale or missing
11 * cache starts a refresh in the background for the next view. A parent that
12 * is down, slow, or answering garbage costs a page nothing: it gets the last
13 * good copy and that copy's age, or an honest "unreachable" when there is
14 * none. A failed try is remembered for a minute so a dead parent is not
15 * asked on every view.
16 */
17
18 import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
19 import { join } from "node:path";
20
21 export const FRESH_MS = 10 * 60_000;
22 export const RETRY_MS = 60_000;
23 const TIMEOUT_MS = 3_000;
24 const MAX_BYTES = 256 * 1024;
25 const MAX_RELEASES = 100;
26
27 export interface ParentRelease {
28 readonly name: string;
29 readonly url: string;
30 }
31
32 export interface ParentReleases {
33 readonly releases: readonly ParentRelease[];
34 /** When the copy shown was fetched, or null when there is none. */
35 readonly fetchedAt: number | null;
36 /** True when the last try failed (a copy may still be shown). */
37 readonly down: boolean;
38 /** True when a refresh has been started and nothing has answered yet. */
39 readonly checking: boolean;
40 }
41
42 /** Why `raw` cannot name a parent, or null. `loopback` allows plain http (tests). */
43 export function parentUrlProblem(raw: string, loopback = false): string | null {
44 let u: URL;
45 try {
46 u = new URL(raw);
47 } catch {
48 return "not a URL";
49 }
50 if (u.protocol !== "https:" && !(loopback && u.protocol === "http:"))
51 return "must be https";
52 if (u.username !== "" || u.password !== "")
53 return "must not carry credentials";
54 if (u.search !== "" || u.hash !== "") return "must not carry a query";
55 return null;
56 }
57
58 /** A release's link: http(s) only (http for loopback tests), no credentials; a fragment is fine. */
59 function link(raw: unknown, loopback: boolean): string | null {
60 if (typeof raw !== "string" || raw.length > 500) return null;
61 let u: URL;
62 try {
63 u = new URL(raw);
64 } catch {
65 return null;
66 }
67 const ok = u.protocol === "https:" || (loopback && u.protocol === "http:");
68 return ok && u.username === "" && u.password === "" ? raw : null;
69 }
70
71 /** The entries of a releases document that are well formed; undefined when it is not one. */
72 export function parseReleases(
73 doc: unknown,
74 loopback = false,
75 ): ParentRelease[] | undefined {
76 if (typeof doc !== "object" || doc === null) return undefined;
77 const list = (doc as { releases?: unknown }).releases;
78 if (!Array.isArray(list)) return undefined;
79 const out: ParentRelease[] = [];
80 for (const e of list.slice(0, MAX_RELEASES)) {
81 if (typeof e !== "object" || e === null) continue;
82 const name = (e as { name?: unknown }).name;
83 const url = link((e as { url?: unknown }).url, loopback);
84 if (typeof name !== "string" || url === null) continue;
85 const n = name.trim();
86 if (n === "" || n.length > 80) continue;
87 out.push({ name: n, url });
88 }
89 return out;
90 }
91
92 /**
93 * How many of the parent's releases (newest first) come after `version`;
outdated

Unknown version returns releases.length, which reads as 'all behind'. Return undefined/unknown and word it honestly.

94 * undefined when `version` is not in the list (an unknown or newer build),
95 * where a count would be a guess.
96 */
97 export function releasesBehind(
98 releases: readonly ParentRelease[],
99 version: string,
100 ): number | undefined {
101 const at = releases.findIndex((r) => r.name === version);
102 return at === -1 ? undefined : at;
103 }
104
105 interface Stored {
106 url: string;
107 fetchedAt: number | null;
108 triedAt: number;
109 ok: boolean;
110 releases: ParentRelease[];
111 }
112
113 function readStored(file: string, url: string): Stored | undefined {
114 try {
115 const s = JSON.parse(readFileSync(file, "utf8")) as Stored;
116 if (s.url !== url || !Array.isArray(s.releases)) return undefined;
117 return s;
118 } catch {
119 return undefined;
120 }
121 }
122
123 async function fetchDoc(url: string, f: typeof fetch): Promise<unknown> {
124 const res = await f(`${url.replace(/\/+$/, "")}/releases.json`, {
125 signal: AbortSignal.timeout(TIMEOUT_MS),
126 redirect: "error",
127 headers: { accept: "application/json" },
128 });
129 if (!res.ok || res.body === null) throw new Error(`status ${res.status}`);
130 const reader = res.body.getReader();
131 const chunks: Uint8Array[] = [];
132 let size = 0;
133 for (;;) {
134 const { done, value } = await reader.read();
135 if (done) break;
136 size += value.byteLength;
137 if (size > MAX_BYTES) {
138 await reader.cancel();
139 throw new Error("too large");
140 }
141 chunks.push(value);
142 }
143 return JSON.parse(Buffer.concat(chunks).toString("utf8"));
144 }
145
146 const refreshing = new Map<string, Promise<void>>();
147
148 /** Reads the parent now and stores the answer; one refresh at a time per cache. */
149 export function refreshParentReleases(
150 dataDir: string,
151 url: string,
152 opts: { now?: number; loopback?: boolean; fetch?: typeof fetch } = {},
153 ): Promise<void> {
154 const file = join(dataDir, "parent-releases.json");
155 const running = refreshing.get(file);
156 if (running !== undefined) return running;
157 const job = (async () => {
158 const now = opts.now ?? Date.now();
159 const kept = readStored(file, url);
160 const copy = kept?.fetchedAt ?? null;
161 let next: Stored;
162 try {
163 const releases = parseReleases(
164 await fetchDoc(url, opts.fetch ?? fetch),
165 opts.loopback ?? false,
166 );
167 if (releases === undefined) throw new Error("not a releases document");
168 next = { url, fetchedAt: now, triedAt: now, ok: true, releases };
169 } catch {
170 next = {
171 url,
172 fetchedAt: copy,
173 triedAt: now,
174 ok: false,
175 releases: copy === null ? [] : (kept?.releases ?? []),
176 };
177 }
178 try {
179 mkdirSync(dataDir, { recursive: true });
180 const tmp = `${file}.${process.pid}.tmp`;
181 writeFileSync(tmp, JSON.stringify(next));
182 renameSync(tmp, file);
183 } catch {
184 // A cache that cannot be written is a cache miss next time, not a failure.
185 }
186 })().finally(() => refreshing.delete(file));
187 refreshing.set(file, job);
188 return job;
189 }
190
191 /**
192 * What the cache holds, at once. A copy older than ten minutes (or none, and
193 * no try in the last minute) starts a refresh in the background; the caller
194 * does not wait for it. The returned promise settles when it has (for tests).
195 */
196 export function parentReleases(
197 dataDir: string,
198 url: string,
199 opts: { now?: number; loopback?: boolean; fetch?: typeof fetch } = {},
200 ): ParentReleases & { refresh: Promise<void> | undefined } {
201 const now = opts.now ?? Date.now();
202 const kept = readStored(join(dataDir, "parent-releases.json"), url);
203 const fetchedAt = kept?.fetchedAt ?? null;
204 const fresh = fetchedAt !== null && now - fetchedAt < FRESH_MS;
205 const tried = kept !== undefined && now - kept.triedAt < RETRY_MS;
206 const refresh =
207 fresh || tried ? undefined : refreshParentReleases(dataDir, url, opts);
208 return {
209 releases: kept?.releases ?? [],
210 fetchedAt,
211 down: kept !== undefined && !kept.ok,
212 checking: refresh !== undefined && kept === undefined,
213 refresh,
214 };
215 }
216
217 /**
218 * The sentence both doors say: how far behind, or why not, and how old the
219 * copy is when the parent cannot be reached.
220 */
221 export function releasesSentence(
222 r: ParentReleases,
223 version: string,
224 host: string,
225 now = Date.now(),
226 ): string {
227 if (r.fetchedAt === null)
228 return r.checking || !r.down
229 ? `Checking ${host} for releases…`
230 : `${host} could not be reached.`;
231 const behind = releasesBehind(r.releases, version);
232 const count =
233 behind === undefined
234 ? `This version (${version}) is not in ${host}'s list of releases.`
235 : behind === 0
236 ? `No releases behind ${host}.`
237 : `${behind} ${behind === 1 ? "release" : "releases"} behind ${host}.`;
238 return r.down
239 ? `${count} ${host} could not be reached; this is a copy from ${ageWords(now - r.fetchedAt)} ago.`
240 : count;
241 }
242
243 /** "3 minutes", "2 hours": the age of a copy, in one phrase. */
244 export function ageWords(ms: number): string {
245 const m = Math.max(0, Math.floor(ms / 60_000));
246 if (m < 1) return "under a minute";
247 if (m < 60) return `${m} minute${m === 1 ? "" : "s"}`;
248 const h = Math.floor(m / 60);
249 if (h < 48) return `${h} hour${h === 1 ? "" : "s"}`;
250 const d = Math.floor(h / 24);
251 return `${d} days`;
252 }
src/http/server.ts +2
@@ -131,6 +131,7 @@ import {
131131 changePassword,
132132 iconPng,
133133 llmsTxt,
134 releasesJson,
134135 robotsTxt,
135136 securityTxt,
136137 sitemapXml,
@@ -546,6 +547,7 @@ export function buildRouter(): Router<Handler> {
546547 router.add("GET", "/llms.txt", llmsTxt);
547548 router.add("GET", "/.well-known/change-password", changePassword);
548549 router.add("GET", "/robots.txt", robotsTxt);
550 router.add("GET", "/releases.json", releasesJson);
549551 router.add("GET", "/sitemap.xml", sitemapXml);
550552 router.add("GET", "/manifest.webmanifest", webManifest);
551553 router.add("GET", "/icons/:spec.png", iconPng);
src/main.ts +9
@@ -4,6 +4,7 @@
44 * environment-only — a handful of variables, all with sane defaults.
55 */
66
7 import { parentUrlProblem } from "./core/parent_releases.ts";
78 import { releaseEnv } from "./release/env.ts";
89 import { createApp } from "./app.ts";
910 import { reconcile } from "./core/reconcile.ts";
@@ -121,8 +122,16 @@ if (turnstileSecret !== "" && turnstileSiteKey === "") {
121122 process.exit(1);
122123 }
123124
125 const parentUrl = (process.env.FORGE_PARENT_URL ?? "").trim();
126 const parentProblem = parentUrl === "" ? null : parentUrlProblem(parentUrl);
127 if (parentProblem !== null) {
128 console.error(`FORGE_PARENT_URL: ${parentProblem}`);
129 process.exit(1);
130 }
131
124132 const app = createApp({
125133 dataDir,
134 ...(parentUrl === "" ? {} : { parentUrl }),
126135 port: Number(process.env.PORT ?? 3000),
127136 ...(process.env.FORGE_HOST === undefined
128137 ? {}
src/tui/screens/about.ts +26
@@ -16,6 +16,8 @@
1616 */
1717
1818 import { isPinned } from "../../core/pins.ts";
19 import { parentReleases, releasesSentence } from "../../core/parent_releases.ts";
20 import { running } from "../../kernel/version.ts";
1921 import type { Repo } from "../../core/repos.ts";
2022 import type { RepoFacts, RepoSource } from "../../view/source.ts";
2123 import type { Ctx, Screen } from "../app/app.ts";
@@ -135,6 +137,28 @@ export function aboutScreen(
135137 };
136138 }
137139
140 /**
141 * The web following card's releases sentence, for a fork on a forge that
142 * names a parent forge: the same words, from the same cache.
143 */
144 export function releasesRow(
145 f: Session,
146 repo: Repo | undefined,
147 ): [string, string][] {
148 const { parentUrl, dataDir, parentLoopback } = f.app.config;
149 if (repo === undefined || repo.forkParentId === null) return [];
150 if (parentUrl === undefined) return [];
151 const view = parentReleases(dataDir, parentUrl, {
152 loopback: parentLoopback === true,
153 });
154 return [
155 [
156 "releases",
157 releasesSentence(view, running().version, new URL(parentUrl).host),
158 ],
159 ];
160 }
161
138162 /**
139163 * The label/value block. A repository we hold gets the clone URLs (the single
140164 * most-copied string on any forge, and the one thing a terminal can hand over
@@ -171,6 +195,7 @@ function aboutFacts(
171195 const upstream = forkOf(f, src);
172196 const fork: [string, string][] =
173197 upstream === "" ? [] : [["fork of", upstream]];
198 const releases = releasesRow(f, repo);
174199 // "browsing" only when it is not the obvious answer: a row that repeats
175200 // the line above it is a row nobody reads.
176201 const browsing: [string, string][] =
@@ -181,6 +206,7 @@ function aboutFacts(
181206 ...browsing,
182207 ...counts,
183208 ...fork,
209 ...releases,
184210 ...originFacts(repo),
185211 ...cloneFacts(f, repo),
186212 ];
src/web/pages/following.ts +50 −1
@@ -31,6 +31,13 @@ import {
3131 type Converge,
3232 } from "../../crew/converge.ts";
3333 import type { Lineage, LineageNode } from "../../core/following.ts";
34 import {
35 parentReleases,
36 releasesBehind,
37 releasesSentence,
38 type ParentReleases,
39 } from "../../core/parent_releases.ts";
40 import { running } from "../../kernel/version.ts";
3441 import { loadRepo, notFoundPage, repoBase, signInFirst } from "../chrome.ts";
3542 import { openProposal, proposeUpstream } from "../../actions/upstream.ts";
3643 import { field, readForm } from "../form.ts";
@@ -98,6 +105,8 @@ export function lineageCard(lineage: Lineage, hereId: string): Html {
98105 export interface Following {
99106 readonly relation: ForkRelation;
100107 readonly converge: Converge | undefined;
108 /** The parent forge's releases, when this forge names a parent forge. */
109 readonly releases: { url: string; view: ParentReleases } | undefined;
101110 }
102111
103112 /** Everything the card needs, for a repo that follows something. */
@@ -114,7 +123,44 @@ export async function followingOf(
114123 relation.state === "diverged" && !relation.clean
115124 ? convergeState(ctx.app, repo, relation.parent)
116125 : undefined;
117 return { relation, converge };
126 const { parentUrl } = ctx.app.config;

Awaiting the parent fetch here puts a network call (up to 3s) in the page's request path. Serve the cached copy and refresh in the background.

127 const releases =
128 parentUrl === undefined
129 ? undefined
130 : {
131 url: parentUrl,
132 view: parentReleases(ctx.app.config.dataDir, parentUrl, {
133 loopback: ctx.app.config.parentLoopback === true,
134 }),
135 };
136 return { relation, converge, releases };
137 }
138
139 /**
140 * "N releases behind <parent>", each with its name and link; or, when the
141 * parent cannot be read, that it cannot and how old the last copy is.
142 * Every field comes from another server and is escaped by `html`.
143 */
144 export function releasesBlock(parentUrl: string, releases: ParentReleases): Html {
145 const host = new URL(parentUrl).host;
146 const version = running().version;
147 const behind = releasesBehind(releases.releases, version);
148 const news = releases.releases.slice(0, behind ?? 0);
149 return html`<div class="following-releases">
150 <p class="following-sentence">
151 ${releasesSentence(releases, version, host)}
152 </p>
153 ${news.length === 0
154 ? null
155 : html`<ul class="list">
156 ${news.map(
157 (r) =>
158 html`<li>
159 <a href="${r.url}" rel="noopener noreferrer">${r.name}</a>
160 </li>`,
161 )}
162 </ul>`}
163 </div>`;
118164 }
119165
120166 function plural(n: number, one: string, many = `${one}s`): string {
@@ -303,6 +349,9 @@ export function followingCard(
303349 >Reconnect it.</a
304350 >`}
305351 </p>
352 ${following.releases === undefined
353 ? null
354 : releasesBlock(following.releases.url, following.releases.view)}
306355 ${when(
307356 actions.length > 0,
308357 () => html`<div class="following-actions">${actions}</div>`,
src/web/standards.ts +19
@@ -6,6 +6,8 @@
66 * /.well-known/change-password where a password manager sends someone
77 * /robots.txt what a crawler may index, and the sitemap
88 * /sitemap.xml every public repository
9 * /releases.json the releases this forge has shipped, newest
10 * first, for a child forge to read
911 * /manifest.webmanifest the forge as an installable app
1012 * /llms.txt the forge for an agent: what it is, how to
1113 * report a problem without an account, how
@@ -18,6 +20,7 @@
1820 * FORGE_SECURITY_CONTACT.
1921 */
2022
23 import releases from "../core/releases.json" with { type: "json" };
2124 import { markPng, type MarkShape } from "../design/mark.ts";
2225 import { BODY_MAX, TITLE_MAX } from "../core/reports.ts";
2326 import { canRead, getRepo, listReposVisibleTo } from "../core/repos.ts";
@@ -88,6 +91,22 @@ export function changePassword(): Response {
8891 });
8992 }
9093
94 /**
95 * GET /releases.json — `{ releases: [{ name, url }] }`, newest first, read
96 * by a child forge (`core/parent_releases.ts`). Public and read-only. The
97 * link of each is this document at that release; there is no page per
98 * release to point at.
99 */
100 export function releasesJson(ctx: Ctx): Response {
101 const body = {
102 releases: releases.releases.map((r) => ({
103 name: r.version,
104 url: `${ctx.url.origin}/releases.json#${encodeURIComponent(r.version)}`,
105 })),
106 };
107 return text(JSON.stringify(body), "application/json");
108 }
109
91110 /** GET /robots.txt */
92111 export function robotsTxt(ctx: Ctx): Response {
93112 return text(
test/following.test.ts +163
@@ -8,6 +8,9 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
88 import { mkdtemp, rm } from "node:fs/promises";
99 import { tmpdir } from "node:os";
1010 import { join } from "node:path";
11 import { parentUrlProblem } from "../src/core/parent_releases.ts";
12 import { Session } from "../src/tui/session.ts";
13 import { releasesRow } from "../src/tui/screens/about.ts";
1114 import { createApp, type App } from "../src/app.ts";
1215 import { addToCrew, createAgent } from "../src/actions/crew.ts";
1316 import { startChecks, type ChecksHandle } from "../src/checks/service.ts";
@@ -486,6 +489,145 @@ describe("a fork that follows its parent", () => {
486489 expect(page).toContain("ahead");
487490 });
488491
492 test("a child forge says how many releases it is behind its parent, and a parent that is down leaves the page up", async () => {
493 let mode: "ok" | "500" | "garbage" = "ok";
494 let asked = 0;
495 const fake = Bun.serve({
496 port: 0,
497 hostname: "127.0.0.1",
498 fetch: async () => {
499 asked++;
500 if (mode === "500") return new Response("boom", { status: 500 });
501 if (mode === "garbage") return new Response("<html>not json");
502 await Bun.sleep(300);
503 return Response.json({
504 releases: [
505 { name: "9.0.2 <b>x</b>", url: "http://127.0.0.1/r/2" },
506 { name: "9.0.1", url: "http://127.0.0.1/r/1" },
507 { name: "9.0.0", url: "http://127.0.0.1/r/0" },
508 { name: "bad", url: "javascript:alert(1)" },
509 ],
510 });
511 },
512 });
513 const config = app.config as { parentUrl?: string; parentLoopback?: boolean };
514 const cache = join(dataDir, "parent-releases.json");
515 const was = process.env.FORGE_VERSION;
516 const flat = (t: string) => t.replace(/\s+/g, " ");
517 const get = () =>
518 fetch(`${base}/bob/game`, {
519 headers: { authorization: `Bearer ${bobToken}`, accept: "text/html" },
520 });
521 const page = async () => flat(await (await get()).text());
522 try {
523 process.env.FORGE_VERSION = "9.0.0";
524 config.parentUrl = `http://127.0.0.1:${fake.port}`;
525 config.parentLoopback = true;
526
527 // The first view does not wait for the parent (it answers in 300 ms).
528 const t0 = performance.now();
529 const first = await page();
530 expect(performance.now() - t0).toBeLessThan(250);
531 expect(first).toContain("Checking 127.0.0.1:");
532 await settled(dataDir);
533 const ok = await page();
534 expect(ok).toContain("2 releases behind");
535 expect(ok).toContain("9.0.2 &lt;b&gt;x&lt;/b&gt;");
536 expect(ok).not.toContain("<b>x</b>");
537 expect(ok).not.toContain("javascript:");
538
539 // Cached for ten minutes: the parent going away changes nothing yet.
540 mode = "500";
541 const before = asked;
542 expect(await page()).toContain("2 releases behind");
543 await settled(dataDir);
544 expect(asked).toBe(before);
545
546 // Past the cache the page is served from the old copy at once, the
547 // refresh fails behind it, and the next view says so with the age.
548 const stored = JSON.parse(await Bun.file(cache).text());
549 stored.fetchedAt -= 3 * 3_600_000;
550 stored.triedAt -= 3 * 3_600_000;
551 await Bun.write(cache, JSON.stringify(stored));
552 expect(await page()).toContain("2 releases behind");
553 await settled(dataDir);
554 const down = await page();
555 expect(down).toContain("2 releases behind");
556 expect(down).toContain(
557 "could not be reached; this is a copy from 3 hours ago",
558 );
559
560 mode = "garbage";
561 stored.triedAt -= 3_600_000;
562 await Bun.write(cache, JSON.stringify(stored));
563 expect((await get()).status).toBe(200);
564 await settled(dataDir);
565 expect(await page()).toContain("could not be reached");
566
567 // A build the parent does not list is not "behind" by any count.
568 process.env.FORGE_VERSION = "1.2.3";
569 expect(await page()).toContain(
570 "This version (1.2.3) is not in 127.0.0.1:",
571 );
572
573 // No copy at all: still a page, and an honest sentence.
574 mode = "500";
575 await Bun.write(cache, "{}");
576 expect((await get()).status).toBe(200);
577 await settled(dataDir);
578 const none = await get();
579 expect(none.status).toBe(200);
580 expect(flat(await none.text())).toContain("could not be reached.");
581 } finally {
582 if (was === undefined) delete process.env.FORGE_VERSION;
583 else process.env.FORGE_VERSION = was;
584 delete config.parentUrl;
585 delete config.parentLoopback;
586 fake.stop(true);
587 }
588 });
589
590 test("the terminal's About card says the same sentence from the same cache", async () => {
591 const fake = Bun.serve({
592 port: 0,
593 hostname: "127.0.0.1",
594 fetch: () =>
595 Response.json({
596 releases: [
597 { name: "8.0.1", url: "http://127.0.0.1/r/1" },
598 { name: "8.0.0", url: "http://127.0.0.1/r/0" },
599 ],
600 }),
601 });
602 const config = app.config as { parentUrl?: string; parentLoopback?: boolean };
603 const was = process.env.FORGE_VERSION;
604 try {
605 process.env.FORGE_VERSION = "8.0.0";
606 config.parentUrl = `http://127.0.0.1:${fake.port}`;
607 config.parentLoopback = true;
608 const session = new Session(app, {
609 sshUsername: "bob",
610 remoteAddress: "127.0.0.1",
611 fingerprint: "SHA256:test",
612 user: bob,
613 });
614 const repo = fresh(fork);
615 expect(releasesRow(session, undefined)).toEqual([]);
616 expect(releasesRow(session, fresh(parent))).toEqual([]);
617 expect(releasesRow(session, repo)[0]![1]).toStartWith("Checking ");
618 await settled(dataDir);
619 expect(releasesRow(session, repo)).toEqual([
620 ["releases", `1 release behind 127.0.0.1:${fake.port}.`],
621 ]);
622 } finally {
623 if (was === undefined) delete process.env.FORGE_VERSION;
624 else process.env.FORGE_VERSION = was;
625 delete config.parentUrl;
626 delete config.parentLoopback;
627 fake.stop(true);
628 }
629 });
630
489631 test("the family is a tree: a fork of a fork nests under it, from any page in it", async () => {
490632 const f = await createUser(app.db, { trusted: true,
491633 username: "fay",
@@ -802,3 +944,24 @@ describe("a landed pull moves the forks, like the push it amounts to", () => {
802944 expect(checked(parent)).toBeGreaterThan(0);
803945 });
804946 });
947
948 /** Waits for a background refresh to rewrite the cache (or 600 ms for none). */
949 async function settled(dir: string): Promise<void> {
950 const file = Bun.file(join(dir, "parent-releases.json"));
951 const text = async () => ((await file.exists()) ? await file.text() : "");
952 const before = await text();
953 for (let i = 0; i < 24; i++) {
954 await Bun.sleep(25);
955 if ((await text()) !== before) return;
956 }
957 }
958
959 describe("a parent URL", () => {
960 test("is https, without credentials", () => {
961 expect(parentUrlProblem("https://parent.example")).toBeNull();
962 expect(parentUrlProblem("http://parent.example")).not.toBeNull();
963 expect(parentUrlProblem("https://u:[email protected]")).not.toBeNull();
964 expect(parentUrlProblem("nonsense")).not.toBeNull();
965 expect(parentUrlProblem("http://127.0.0.1:1", true)).toBeNull();
966 });
967 });
test/standards.test.ts +13
@@ -4,6 +4,8 @@
44 * an installable manifest with real icons, and the metadata a link needs
55 * to unfurl.
66 */
7 import { parseReleases } from "../src/core/parent_releases.ts";
8 import releasesFile from "../src/core/releases.json" with { type: "json" };
79 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
810 import { mkdtemp, rm } from "node:fs/promises";
911 import { tmpdir } from "node:os";
@@ -82,6 +84,17 @@ describe("what the open web expects", () => {
8284 expect(res.headers.get("location")).toBe("/settings/password");
8385 });
8486
87 test("releases.json is the shipped releases, newest first, in the shape a child reads", async () => {
88 const res = await fetch(`${base}/releases.json`);
89 expect(res.status).toBe(200);
90 expect(res.headers.get("content-type")).toContain("application/json");
91 const doc = (await res.json()) as { releases: unknown[] };
92 const read = parseReleases(doc, true);
93 expect(read!.length).toBe(doc.releases.length);
94 expect(read![0]!.name).toBe(releasesFile.releases[0]!.version);
95 expect(read![0]!.url).toStartWith(`${base}/releases.json#`);
96 });
97
8598 test("robots keeps crawlers out of accounts and points at the sitemap", async () => {
8699 const body = await fetch(`${base}/robots.txt`).then((r) => r.text());
87100 expect(body).toContain("User-agent: *");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs