cursedops 0.21.1 → 0.22.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/package.json +9 -2
  2. package/src/stageLook.ts +295 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursedops",
3
- "version": "0.21.1",
3
+ "version": "0.22.1",
4
4
  "description": "The build-and-ops answers this generation's apps wrote independently and identically: finding a generation's roots — and printing a command that runs when pasted — without knowing a path, the generation's whole-tree laws run over one repo from a checkout or a worktree, macOS launchd agent install/replace/remove and the live port a job serves, the check that a launchd job imports only what the LOCKED versions of its packages export (a lib-preview overlay's extra subpath or name is a job that dies at the next forced reinstall), the scaffolding and verdicts of a deployed smoke (origin probe, the smoke's own environment, a network that lies about DNS, a settled version), the static-serving helpers eight apps copied — the path-traversal guard among them — the API floor that keeps an unmatched /api/... from ever being answered with the app shell, the commit and dirty flag a checkout-served process reports, the Cloudflare Worker deploy toolkit four apps copied (the deploy sequence, exact-set secrets over a pipe, origin-first rollback, the curl edge fetch, the row-for-row D1 import proof, the billed-CPU tail check around a deploy's walk and smoke, and each app's worker:secrets and worker:smoke main as one function of its data), the relay a Worker fronts a Mac-bound app with (the Durable Object, the frames, the Mac's dialer and key rotation — lifted from station for roms — and the signed-in stage walk's skeleton and the relay app's whole worker:deploy), the Worker import-graph and await-port checks every Worker app's suite runs over its own source, and the public-surface ratchet three published libraries each carried a forked copy of. Mechanism only — no app knows its name from here. Bun, zero runtime dependencies (typescript is an optional peer, for public-surface only), ships source.",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -158,6 +158,12 @@
158
158
  "source": "./src/relayStage.ts",
159
159
  "import": "./src/relayStage.ts"
160
160
  },
161
+ "./stage-look": {
162
+ "types": "./src/stageLook.ts",
163
+ "bun": "./src/stageLook.ts",
164
+ "source": "./src/stageLook.ts",
165
+ "import": "./src/stageLook.ts"
166
+ },
161
167
  "./container-deploy": {
162
168
  "types": "./src/containerDeploy.ts",
163
169
  "bun": "./src/containerDeploy.ts",
@@ -181,7 +187,8 @@
181
187
  "public-surface": "./src/publicSurface.ts",
182
188
  "forge-paths": "./src/paths.ts",
183
189
  "forge-client": "./src/stagedClient.ts",
184
- "forge-d1-schema": "./src/d1Schema.ts"
190
+ "forge-d1-schema": "./src/d1Schema.ts",
191
+ "stage-look": "./src/stageLook.ts"
185
192
  },
186
193
  "files": [
187
194
  "src",
@@ -0,0 +1,295 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * `cursedops/stage-look` — open `<app>-stage` in a real browser as its signed-in owner (forge task 3881).
4
+ *
5
+ * Rule 9 says every batch SEES its change on the stage, signed in, at 390 and 1440. Only collections
6
+ * had a tool for it (`apps/collections/scripts/stage-look.ts`), and it needed a walk's cookie jar
7
+ * first; batch 2026-10-28T0812 hand-built the same look twice more, for photos and family, and lost
8
+ * ~40 minutes to it. This is the seam those three shared:
9
+ *
10
+ * - **The host is pinned to what 1.1.1.1 says.** This Mac's resolver can hold a NEGATIVE answer for
11
+ * a stage hostname (`awaitLocalResolve`'s header in `relay-stage`), so Chromium is told the address.
12
+ * - 🔴 **Cloudflare Access headers go to the stage's own origin ONLY** ({@link isStageRequest}). Sent
13
+ * to binary-server too they turn every media fetch into a CORS preflight it refuses.
14
+ * - **Sign-in is the stage's own door**: `grantStageOwner` (auth-stage's emailed second factor) and
15
+ * the app's `/api/auth/sso/callback?grant=…`. Never production's accounts service.
16
+ * - **A reaped binary-server sandbox is SAID, not screenshotted.** Its images answer 404, or 503 with
17
+ * `x-bs-edge-cache: STAGE-ORIGIN-DOWN`; {@link brokenMediaOf} names them, and the CLI exits 1
18
+ * with the recovery (`apps/binary-server` → `bun run sandbox:up`, then upload again).
19
+ *
20
+ * cursedops has no runtime dependencies, so playwright is the CALLER's: pass `chromium`, or let the
21
+ * look resolve `playwright` from the working directory (the app it is run in).
22
+ *
23
+ * CLI, from an app's directory (or `bun $FORGE/tools/stage-look.ts <app> …` from anywhere):
24
+ *
25
+ * stage-look <app> [path] [--out <dir>] → <dir>/stage-<app>-390.png, …-1440.png
26
+ */
27
+ import { spawnSync } from "node:child_process";
28
+ import { existsSync, mkdirSync, readFileSync } from "node:fs";
29
+ import { join } from "node:path";
30
+ import { grantStageOwner } from "cursedops/relay-stage";
31
+ import { forgeCodeRoot, requireForgeState } from "cursedops/roots";
32
+
33
+ /** `https://<app>-stage.cursedalchemy.com` — every stage's public origin. */
34
+ export const stageOrigin = (app: string): string => `https://${app}-stage.cursedalchemy.com`;
35
+
36
+ /** The route matcher the Access headers ride on: the stage's own origin, nothing else. */
37
+ export const isStageRequest =
38
+ (origin: string) =>
39
+ (url: URL): boolean =>
40
+ url.origin === origin;
41
+
42
+ /** `CF-Access-Client-Id` / `-Secret` from `$FORGE_STATE/secrets/cloudflare-access.env`. Throws when either is missing. */
43
+ export function accessHeaders(state: string): Record<string, string> {
44
+ const file = join(state, "secrets", "cloudflare-access.env");
45
+ const text = existsSync(file) ? readFileSync(file, "utf8") : "";
46
+ const read = (key: string): string =>
47
+ (text.split("\n").find((l) => l.startsWith(`${key}=`)) ?? "")
48
+ .slice(key.length + 1)
49
+ .trim()
50
+ .replace(/^['"]|['"]$/g, "");
51
+ const id = read("CF_ACCESS_CLIENT_ID");
52
+ const secret = read("CF_ACCESS_CLIENT_SECRET");
53
+ if (!id || !secret) throw new Error(`${file} must declare CF_ACCESS_CLIENT_ID and CF_ACCESS_CLIENT_SECRET — the stage sits behind Cloudflare Access.`);
54
+ return { "CF-Access-Client-Id": id, "CF-Access-Client-Secret": secret };
55
+ }
56
+
57
+ /** `dig +short <host> @1.1.1.1`'s output. */
58
+ export type Dig = (host: string) => string;
59
+ const realDig: Dig = (host) => spawnSync("dig", ["+short", host, "@1.1.1.1"], { encoding: "utf8", timeout: 15_000 }).stdout ?? "";
60
+
61
+ /** Chromium's `--host-resolver-rules` pinning `host` to 1.1.1.1's first IPv4 answer; none when it gave none. */
62
+ export function pinnedResolverArgs(host: string, dig: Dig = realDig): string[] {
63
+ const ip = dig(host)
64
+ .split("\n")
65
+ .map((l) => l.trim())
66
+ .find((l) => /^\d+\.\d+\.\d+\.\d+$/.test(l));
67
+ return ip ? [`--host-resolver-rules=MAP ${host} ${ip}`] : [];
68
+ }
69
+
70
+ /** A response as the look reads it — the slice of playwright's `Response` it needs. */
71
+ export interface LookResponse {
72
+ url(): string;
73
+ status(): number;
74
+ headers(): Record<string, string>;
75
+ request(): { resourceType(): string };
76
+ }
77
+
78
+ /** An image or media answer that says the stage's bytes are gone: a 404, or the edge's `STAGE-ORIGIN-DOWN`. */
79
+ export function brokenMediaOf(r: LookResponse): string | null {
80
+ const kind = r.request().resourceType();
81
+ if (kind !== "image" && kind !== "media") return null;
82
+ const edge = r.headers()["x-bs-edge-cache"] ?? "";
83
+ // The URL without its query: a media URL carries a signed token, and this line lands in logs.
84
+ const url = r.url().split("?")[0];
85
+ if (edge === "STAGE-ORIGIN-DOWN" || r.status() === 404 || r.status() === 503) return `${r.status()}${edge ? ` ${edge}` : ""} ${url}`;
86
+ return null;
87
+ }
88
+
89
+ /**
90
+ * A read of the page's OWN that the stage failed — a same-origin `/api/` answer of 5xx — as
91
+ * `<status> <path>`. A look shot over one is a picture of an error card or a skeleton, not of the
92
+ * change (forge task 3914: station's `#/deploys` read 503 "station's Mac is not connected", because a
93
+ * relay stage has a Mac end only while its `worker:stage-walk` runs).
94
+ */
95
+ export function failedReadOf(r: Pick<LookResponse, "url" | "status">, origin: string): string | null {
96
+ const url = new URL(r.url());
97
+ if (url.origin !== origin || !url.pathname.startsWith("/api/") || r.status() < 500) return null;
98
+ return `${r.status()} ${url.pathname}`;
99
+ }
100
+
101
+ /** How long the network may stay busy before the look goes on without it — a player streams for good. */
102
+ export const IDLE_CEILING_MS = 15_000;
103
+ /** How long a page's pending regions (`aria-busy="true"`, cursedbelt's skeletons) may read before the look gives up. */
104
+ export const SETTLE_CEILING_MS = 90_000;
105
+
106
+ /** The slice of a playwright `Page` that {@link settle} drives. */
107
+ export interface SettlePage {
108
+ waitForLoadState(state: "networkidle", options: { timeout: number }): Promise<unknown>;
109
+ evaluate<T>(fn: () => T): Promise<T>;
110
+ }
111
+
112
+ export interface Settled {
113
+ /** False when the network never went quiet inside {@link IDLE_CEILING_MS} — said, never fatal. */
114
+ idle: boolean;
115
+ /** The pending regions still reading at the ceiling, by their text; empty when the page settled. */
116
+ busy: string[];
117
+ ms: number;
118
+ }
119
+
120
+ /**
121
+ * Wait until the page has DRAWN, not until the network is quiet: both of the looks that went wrong
122
+ * waited for `networkidle` alone. music's never came (its player keeps a stream open), so the look threw;
123
+ * station's `#/deploys` came while its read was still in flight, so the look shot four skeleton tiles
124
+ * and "Reading the apps' deploys…" (forge task 3914). So: `networkidle` with a ceiling, then every
125
+ * `aria-busy="true"` region gone on two reads in a row, up to {@link SETTLE_CEILING_MS} — and what is
126
+ * still busy then is SAID, so a look of a loading state never reads as a look of the page.
127
+ */
128
+ export async function settle(
129
+ page: SettlePage,
130
+ options: { idleMs?: number; settleMs?: number; pollMs?: number; sleep?: (ms: number) => Promise<unknown>; now?: () => number } = {},
131
+ ): Promise<Settled> {
132
+ const { idleMs = IDLE_CEILING_MS, settleMs = SETTLE_CEILING_MS, pollMs = 500, sleep = Bun.sleep, now = Date.now } = options;
133
+ const start = now();
134
+ const idle = await page.waitForLoadState("networkidle", { timeout: idleMs }).then(
135
+ () => true,
136
+ () => false,
137
+ );
138
+ const pending = () =>
139
+ page.evaluate(() =>
140
+ [...document.querySelectorAll('[aria-busy="true"]')].map((el) => (el.textContent ?? "").replace(/\s+/g, " ").trim().slice(0, 80) || el.tagName.toLowerCase()),
141
+ );
142
+ let quiet = 0;
143
+ let busy: string[] = [];
144
+ while (true) {
145
+ busy = await pending();
146
+ quiet = busy.length === 0 ? quiet + 1 : 0;
147
+ if (quiet >= 2) return { idle, busy: [], ms: now() - start };
148
+ if (now() - start >= settleMs) return { idle, busy, ms: now() - start };
149
+ await sleep(pollMs);
150
+ }
151
+ }
152
+
153
+ /** The slices of playwright this drives. Structural, so cursedops needs no dependency on it. */
154
+ interface LookRoute {
155
+ request(): { headers(): Record<string, string> };
156
+ continue(options: { headers: Record<string, string> }): Promise<unknown>;
157
+ }
158
+ interface LookPage {
159
+ goto(url: string, options?: { waitUntil?: "load" | "networkidle" }): Promise<{ status(): number } | null>;
160
+ on(event: "response", listener: (r: LookResponse) => void): unknown;
161
+ }
162
+ interface LookContext {
163
+ route(match: (url: URL) => boolean, handler: (route: LookRoute) => Promise<unknown>): Promise<unknown>;
164
+ newPage(): Promise<LookPage>;
165
+ close(): Promise<unknown>;
166
+ }
167
+ interface LookBrowser {
168
+ newContext(options: Record<string, unknown>): Promise<LookContext>;
169
+ close(): Promise<unknown>;
170
+ }
171
+ export interface LookChromium {
172
+ launch(options: { args: string[] }): Promise<LookBrowser>;
173
+ }
174
+
175
+ export interface StageLookSpec {
176
+ app: string;
177
+ /** 390 is a phone (touch, DPR 3, 844 tall); anything else a desktop 900 tall. */
178
+ width: number;
179
+ /** Defaults: the roots above the working directory. */
180
+ forge?: string;
181
+ state?: string;
182
+ /** playwright's `chromium`; default: `playwright` resolved from the working directory. */
183
+ chromium?: LookChromium;
184
+ /** Extra Chromium flags — collections' audio daemon, say. */
185
+ args?: string[];
186
+ /** Seams for the suite. */
187
+ grant?: () => { ok: boolean; grant: string };
188
+ dig?: Dig;
189
+ headers?: Record<string, string>;
190
+ }
191
+
192
+ export interface StageLook<Page> {
193
+ page: Page;
194
+ /** The stage's origin, for `page.goto(`${origin}${path}`)`. */
195
+ origin: string;
196
+ /** Every broken image/media answer so far ({@link brokenMediaOf}). */
197
+ brokenMedia: () => string[];
198
+ close: () => Promise<unknown>;
199
+ }
200
+
201
+ async function defaultChromium(): Promise<LookChromium> {
202
+ const at = Bun.resolveSync("playwright", process.cwd());
203
+ return ((await import(at)) as { chromium: LookChromium }).chromium;
204
+ }
205
+
206
+ /**
207
+ * A page on `<app>-stage`, signed in as its owner, with Access headers on the stage's requests only.
208
+ * `Page` is the caller's playwright `Page` — the look builds it, so the cast is the caller's word.
209
+ */
210
+ export async function openStagePage<Page = LookPage>(spec: StageLookSpec): Promise<StageLook<Page>> {
211
+ const cwd = process.cwd();
212
+ const forge = spec.forge ?? forgeCodeRoot(cwd);
213
+ if (!forge) throw new Error(`no forge.env above ${cwd} — run the look from inside the generation`);
214
+ const origin = stageOrigin(spec.app);
215
+ const access = spec.headers ?? accessHeaders(spec.state ?? requireForgeState(cwd));
216
+ const chromium = spec.chromium ?? (await defaultChromium());
217
+ const browser = await chromium.launch({ args: [...(spec.args ?? []), ...pinnedResolverArgs(new URL(origin).hostname, spec.dig)] });
218
+ try {
219
+ const phone = spec.width < 768;
220
+ const context = await browser.newContext({
221
+ viewport: { width: spec.width, height: phone ? 844 : 900 },
222
+ ...(phone ? { isMobile: true, hasTouch: true, deviceScaleFactor: 3 } : {}),
223
+ });
224
+ await context.route(isStageRequest(origin), (route) => route.continue({ headers: { ...route.request().headers(), ...access } }));
225
+ const page = await context.newPage();
226
+ const broken: string[] = [];
227
+ page.on("response", (r) => {
228
+ const b = brokenMediaOf(r);
229
+ if (b) broken.push(b);
230
+ });
231
+ const granted = (spec.grant ?? (() => grantStageOwner({ forge, app: spec.app })))();
232
+ if (!granted.ok) throw new Error(`auth-stage gave no grant for ${spec.app} — its output above says why`);
233
+ const back = await page.goto(`${origin}/api/auth/sso/callback?grant=${encodeURIComponent(granted.grant)}`, { waitUntil: "load" });
234
+ if (back && back.status() >= 400) throw new Error(`${origin}'s sign-in callback answered ${back.status()}`);
235
+ return { page: page as Page, origin, brokenMedia: () => [...broken], close: () => browser.close() };
236
+ } catch (e) {
237
+ await browser.close();
238
+ throw e;
239
+ }
240
+ }
241
+
242
+ /** Shoot `path` at 390 and 1440. Exit 1 when the page or its media is broken, so a look never passes on broken tiles. */
243
+ async function main(argv: string[]): Promise<number> {
244
+ const outAt = argv.indexOf("--out");
245
+ const out = outAt >= 0 ? argv[outAt + 1] : undefined;
246
+ const [app, path = "/"] = outAt >= 0 ? argv.filter((_, i) => i !== outAt && i !== outAt + 1) : argv;
247
+ if (!app || (outAt >= 0 && !out)) {
248
+ console.error("usage: stage-look <app> [path] [--out <dir>] (run in the app's directory, or `bun $FORGE/tools/stage-look.ts <app> …`)");
249
+ return 2;
250
+ }
251
+ const dir = out ?? join(process.env.FORGE_BATCH_TMP ?? requireForgeState(process.cwd()), "stage-look");
252
+ mkdirSync(dir, { recursive: true });
253
+ let bad = false;
254
+ for (const width of [390, 1440]) {
255
+ type ShotPage = LookPage & SettlePage & { screenshot(o: { path: string; fullPage?: boolean }): Promise<unknown>; url(): string };
256
+ const look = await openStagePage<ShotPage>({ app, width });
257
+ try {
258
+ const failed: string[] = [];
259
+ look.page.on("response", (r) => {
260
+ const f = failedReadOf(r, look.origin);
261
+ if (f && !failed.includes(f)) failed.push(f);
262
+ });
263
+ const res = await look.page.goto(`${look.origin}${path}`, { waitUntil: "load" });
264
+ const settled = await settle(look.page);
265
+ const shot = join(dir, `stage-${app}-${width}.png`);
266
+ await look.page.screenshot({ path: shot });
267
+ // 🔴 `null` is not a failure: the sign-in callback already landed on `/`, so a `/#/deploys` is a
268
+ // same-document hash change, which playwright answers with no response (forge task 3914's `?`).
269
+ console.log(`${width}: ${res?.status() ?? "same document"} ${look.page.url()} → ${shot} (drawn in ${(settled.ms / 1000).toFixed(1)} s)`);
270
+ if (res && res.status() >= 400) bad = true;
271
+ if (!settled.idle) console.log(` · the network never went quiet in ${IDLE_CEILING_MS / 1000} s (a stream or a poll) — the look waited on the page's own pending regions instead`);
272
+ if (settled.busy.length) {
273
+ bad = true;
274
+ console.error(` 🔴 still READING after ${SETTLE_CEILING_MS / 1000} s — this shot is the loading state, not the page: ${settled.busy.slice(0, 3).join(" · ")}`);
275
+ }
276
+ if (failed.length) {
277
+ bad = true;
278
+ console.error(` 🔴 the stage failed ${failed.length} of the page's own read(s) — the shot shows what it does without them: ${failed.slice(0, 5).join(", ")}`);
279
+ console.error(" a 503 on a relay app's stage is often its Mac end being down — that end is up only while its `worker:stage-walk` runs");
280
+ }
281
+ const broken = look.brokenMedia();
282
+ if (broken.length) {
283
+ bad = true;
284
+ console.error(` 🔴 ${broken.length} image/media answer(s) broken — the stage's binary-server sandbox was likely reaped:`);
285
+ for (const b of broken.slice(0, 5)) console.error(` ${b}`);
286
+ console.error(" recover: cd \"$FORGE/apps/binary-server\" && bun run sandbox:up — then upload the fixture again");
287
+ }
288
+ } finally {
289
+ await look.close();
290
+ }
291
+ }
292
+ return bad ? 1 : 0;
293
+ }
294
+
295
+ if (import.meta.main) process.exit(await main(process.argv.slice(2)));