@coffre/conformance 0.1.17 → 0.2.0

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.
package/dist/main.js CHANGED
@@ -1,12 +1,12 @@
1
1
  import { n as DevIdp, o as defaultGitHubAccount, r as GITHUB_RUN } from "./idp-BeOsuZ3p.js";
2
2
  import { createRequire } from "node:module";
3
- import { dirname, join, resolve } from "node:path";
3
+ import { delimiter, dirname, join, relative, resolve } from "node:path";
4
4
  import { inspect, parseArgs } from "node:util";
5
5
  import { spawn } from "node:child_process";
6
6
  import { createHash, createHmac, createPrivateKey, hkdfSync, randomBytes, randomUUID, sign } from "node:crypto";
7
- import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
8
- import { tmpdir } from "node:os";
9
- import { setTimeout } from "node:timers/promises";
7
+ import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
8
+ import { homedir, tmpdir } from "node:os";
9
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
10
10
  import { DatabaseSync } from "node:sqlite";
11
11
  import pg from "pg";
12
12
  import { postgresConnection } from "@coffre/db/connect";
@@ -47,19 +47,45 @@ const KEYS = {
47
47
  APP_KEY: "Y29mZnJlLWxvY2FsLWF1ZGl0LWNoYWluLWtleS0zMmI="
48
48
  };
49
49
  //#endregion
50
+ //#region src/draining.ts
51
+ /**
52
+ * The built app as `wrangler dev` can run it: its own build, behind an entry
53
+ * that, once the app has answered, reads whatever the request still sends
54
+ * before passing the answer on. Locally, and only there, a Worker built
55
+ * unbundled with static assets fails every request after one whose body it
56
+ * left unread, which every refusal does, and reading it later, after the
57
+ * answer, is too late; deployed, Cloudflare discards such a body, as
58
+ * `vite dev` and `vite preview` do. The app itself must never wait so on what
59
+ * a caller sends; this harness sends only bodies that end. The entry and its
60
+ * config are written beside the build, which the next `vite build`
61
+ * replaces: nothing of them deploys.
62
+ */
63
+ function drainingConfig(server) {
64
+ writeFileSync(join(server, "conformance.js"), [
65
+ "import app from './index.js';",
66
+ "export default {",
67
+ " ...app,",
68
+ " async fetch(request, env, ctx) {",
69
+ " const response = await app.fetch(request, env, ctx);",
70
+ " if (request.body !== null && !request.bodyUsed) await request.arrayBuffer().catch(() => {});",
71
+ " return response;",
72
+ " },",
73
+ "};",
74
+ ""
75
+ ].join("\n"));
76
+ const config = JSON.parse(readFileSync(join(server, "wrangler.json"), "utf8"));
77
+ const path = join(server, "conformance.json");
78
+ writeFileSync(path, JSON.stringify({
79
+ ...config,
80
+ main: "conformance.js"
81
+ }));
82
+ return path;
83
+ }
84
+ if (import.meta.main) console.log(drainingConfig(resolve(process.argv[2])));
85
+ //#endregion
50
86
  //#region ../client/dist/index.js
51
87
  /** The API's error shape, `{ error, message }`, with the HTTP status. */
52
- const COFFRE_ERROR = Symbol.for("@coffre/client:CoffreError");
53
88
  var CoffreError = class extends Error {
54
- /**
55
- * `@coffre/ui`'s prebuilt pages bundle a copy of this class, and a page is
56
- * handed a client the server made with this package's. So `instanceof`
57
- * asks for the mark every copy leaves, rather than for this copy's prototype.
58
- */
59
- static [Symbol.hasInstance](value) {
60
- return typeof value === "object" && value !== null && COFFRE_ERROR in value;
61
- }
62
- [COFFRE_ERROR] = true;
63
89
  status;
64
90
  code;
65
91
  /** The vault's own code when it refused: `no_grant`, `removed`, `bulk_limit`, ... */
@@ -244,7 +270,7 @@ async function until(what, probe, seconds, alive = () => true) {
244
270
  for (let i = 0; i < seconds * 10; i++) {
245
271
  if (!alive()) throw new Failure(`a process exited while waiting for ${what}`);
246
272
  if (await probe().catch(() => false)) return;
247
- await setTimeout(100);
273
+ await setTimeout$1(100);
248
274
  }
249
275
  throw new Failure(`timed out waiting for ${what}`);
250
276
  }
@@ -396,7 +422,7 @@ async function boot(kind, at, options) {
396
422
  for (const { child, exited } of children) if (!exited) try {
397
423
  process.kill(-child.pid, signal);
398
424
  } catch {}
399
- await setTimeout(500);
425
+ await setTimeout$1(500);
400
426
  }
401
427
  await idp.stop().catch(() => {});
402
428
  await cleanup().catch(() => {});
@@ -427,12 +453,13 @@ async function boot(kind, at, options) {
427
453
  "migrate",
428
454
  "--yes"
429
455
  ], { COFFRE_MIGRATE_DATABASE_URL: owner });
456
+ await run(bin("vite"), ["build", "app"]);
430
457
  const state = join(scratch, "state");
431
458
  start("wrangler", bin("wrangler"), [
432
459
  "dev",
433
460
  ...[
434
461
  "-c",
435
- "app/wrangler.jsonc",
462
+ drainingConfig(join(dir, "app/dist/server")),
436
463
  "-c",
437
464
  "vault/wrangler.jsonc"
438
465
  ],
@@ -482,6 +509,7 @@ async function boot(kind, at, options) {
482
509
  runtime: () => postgres(runtime),
483
510
  vaultRuntime: () => postgres(vaultRuntime),
484
511
  databaseFile: null,
512
+ clientDir: join(dir, "app/dist/client"),
485
513
  output,
486
514
  stop
487
515
  };
@@ -498,7 +526,12 @@ async function boot(kind, at, options) {
498
526
  ROOT_ADMINS: ROOT_ADMIN
499
527
  });
500
528
  await until("the vault socket", async () => existsSync(socket), 30, alive);
501
- const startServer = () => start("server", process.execPath, ["src/server.ts"], {
529
+ await run(bin("vite"), ["build", "app"]);
530
+ const startServer = () => start("server", bin("srvx"), [
531
+ "--prod",
532
+ "--host=127.0.0.1",
533
+ "app/dist/server/server.js"
534
+ ], {
502
535
  PORT: String(port),
503
536
  PUBLIC_URL: origin,
504
537
  DATABASE_URL: `file:${database}`,
@@ -526,6 +559,7 @@ async function boot(kind, at, options) {
526
559
  runtime: null,
527
560
  vaultRuntime: null,
528
561
  databaseFile: database,
562
+ clientDir: join(dir, "app/dist/client"),
529
563
  output,
530
564
  stop
531
565
  };
@@ -544,6 +578,10 @@ var Browser = class {
544
578
  constructor(origin) {
545
579
  this.origin = origin;
546
580
  }
581
+ /** The cookies coffre left this browser, to hand a real one. */
582
+ cookies() {
583
+ return [...this.#jar];
584
+ }
547
585
  /** Whether coffre left this browser a cookie. */
548
586
  get hasCookies() {
549
587
  return this.#jar.size > 0;
@@ -2152,7 +2190,7 @@ var Cli = class {
2152
2190
  child.kill("SIGKILL");
2153
2191
  throw new Failure(`coffre never got to ${what}`, output);
2154
2192
  }
2155
- await setTimeout(50);
2193
+ await setTimeout$1(50);
2156
2194
  }
2157
2195
  return pattern.exec(output);
2158
2196
  }
@@ -2363,6 +2401,254 @@ async function verifyKeys(cli) {
2363
2401
  return "this deployment's keys pass, vault ID included; a wrong vault key and a malformed app key are each named; no key shown";
2364
2402
  }
2365
2403
  //#endregion
2404
+ //#region src/chrome.ts
2405
+ const NAMES = [
2406
+ "google-chrome",
2407
+ "google-chrome-stable",
2408
+ "chromium",
2409
+ "chromium-browser",
2410
+ "chrome"
2411
+ ];
2412
+ const MAC = ["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "/Applications/Chromium.app/Contents/MacOS/Chromium"];
2413
+ /** A Chrome or Chromium on this machine: on PATH, where macOS keeps it, or Playwright's. */
2414
+ function findChrome() {
2415
+ for (const dir of (process.env.PATH ?? "").split(delimiter)) for (const name of NAMES) if (dir !== "" && existsSync(join(dir, name))) return join(dir, name);
2416
+ for (const path of MAC) if (existsSync(path)) return path;
2417
+ const playwright = join(homedir(), ".cache", "ms-playwright");
2418
+ if (existsSync(playwright)) for (const dir of readdirSync(playwright).filter((name) => name.startsWith("chromium-")).sort().reverse()) for (const build of ["chrome-linux64", "chrome-linux"]) {
2419
+ const path = join(playwright, dir, build, "chrome");
2420
+ if (existsSync(path)) return path;
2421
+ }
2422
+ return null;
2423
+ }
2424
+ var Chrome = class Chrome {
2425
+ #process;
2426
+ #socket;
2427
+ #profile;
2428
+ #next = 0;
2429
+ #pending = /* @__PURE__ */ new Map();
2430
+ #listeners = /* @__PURE__ */ new Set();
2431
+ constructor(process, socket, profile) {
2432
+ this.#process = process;
2433
+ this.#socket = socket;
2434
+ this.#profile = profile;
2435
+ socket.addEventListener("message", (event) => {
2436
+ const message = JSON.parse(String(event.data));
2437
+ if (message.id !== void 0) {
2438
+ const pending = this.#pending.get(message.id);
2439
+ this.#pending.delete(message.id);
2440
+ if (message.error !== void 0) pending?.reject(new Error(message.error.message));
2441
+ else pending?.resolve(message.result ?? {});
2442
+ } else for (const listener of this.#listeners) listener(message);
2443
+ });
2444
+ }
2445
+ /** Chrome at `executable`, headless, with a profile of its own, gone when closed. */
2446
+ static async open(executable) {
2447
+ const profile = mkdtempSync(join(tmpdir(), "coffre-chrome-"));
2448
+ const child = spawn(executable, [
2449
+ "--headless=new",
2450
+ "--remote-debugging-port=0",
2451
+ `--user-data-dir=${profile}`,
2452
+ "--no-first-run",
2453
+ "--no-default-browser-check",
2454
+ "--disable-gpu",
2455
+ "--no-sandbox",
2456
+ "about:blank"
2457
+ ], { stdio: [
2458
+ "ignore",
2459
+ "ignore",
2460
+ "pipe"
2461
+ ] });
2462
+ const url = await new Promise((resolve, reject) => {
2463
+ let output = "";
2464
+ const timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`Chrome did not start: ${output.trim().split("\n").slice(-3).join(" ")}`)), 3e4);
2465
+ child.stderr.setEncoding("utf8").on("data", (chunk) => {
2466
+ output += chunk;
2467
+ const found = /DevTools listening on (ws:\/\/\S+)/.exec(output);
2468
+ if (found !== null) {
2469
+ clearTimeout(timer);
2470
+ resolve(found[1]);
2471
+ }
2472
+ });
2473
+ child.on("error", (error) => {
2474
+ clearTimeout(timer);
2475
+ reject(error);
2476
+ });
2477
+ child.on("exit", (code) => {
2478
+ clearTimeout(timer);
2479
+ reject(/* @__PURE__ */ new Error(`Chrome exited with ${code}: ${output.trim().split("\n").slice(-3).join(" ")}`));
2480
+ });
2481
+ });
2482
+ const socket = new WebSocket(url);
2483
+ await new Promise((resolve, reject) => {
2484
+ socket.addEventListener("open", () => resolve(), { once: true });
2485
+ socket.addEventListener("error", () => reject(/* @__PURE__ */ new Error(`could not reach Chrome at ${url}`)), { once: true });
2486
+ });
2487
+ return new Chrome(child, socket, profile);
2488
+ }
2489
+ #send(method, params = {}, sessionId) {
2490
+ const id = ++this.#next;
2491
+ return new Promise((resolve, reject) => {
2492
+ this.#pending.set(id, {
2493
+ resolve,
2494
+ reject
2495
+ });
2496
+ this.#socket.send(JSON.stringify({
2497
+ id,
2498
+ method,
2499
+ params,
2500
+ sessionId
2501
+ }));
2502
+ });
2503
+ }
2504
+ /**
2505
+ * `url` in a tab of its own, with `cookies` for its origin: the heading it
2506
+ * shows once its scripts have run and settled, and every uncaught error,
2507
+ * console error and failed load along the way.
2508
+ */
2509
+ async load(url, cookies, settle = 2e3) {
2510
+ const { targetId } = await this.#send("Target.createTarget", { url: "about:blank" });
2511
+ const { sessionId } = await this.#send("Target.attachToTarget", {
2512
+ targetId,
2513
+ flatten: true
2514
+ });
2515
+ const errors = [];
2516
+ let loaded;
2517
+ const load = new Promise((resolve) => loaded = resolve);
2518
+ const listener = (message) => {
2519
+ if (message.sessionId !== sessionId) return;
2520
+ const params = message.params ?? {};
2521
+ if (message.method === "Runtime.exceptionThrown") {
2522
+ const details = params.exceptionDetails;
2523
+ errors.push(`${details.exception?.description?.split("\n")[0] ?? details.text}${details.url ? ` (${details.url}:${(details.lineNumber ?? 0) + 1})` : ""}`);
2524
+ } else if (message.method === "Runtime.consoleAPICalled" && params.type === "error") {
2525
+ const args = params.args;
2526
+ errors.push(`console.error: ${args.map((arg) => arg.description ?? String(arg.value)).join(" ")}`);
2527
+ } else if (message.method === "Log.entryAdded") {
2528
+ const entry = params.entry;
2529
+ if (entry.level === "error") errors.push(`${entry.text}${entry.url ? ` (${entry.url})` : ""}`);
2530
+ } else if (message.method === "Page.loadEventFired") loaded();
2531
+ };
2532
+ this.#listeners.add(listener);
2533
+ try {
2534
+ for (const domain of [
2535
+ "Runtime",
2536
+ "Log",
2537
+ "Page",
2538
+ "Network"
2539
+ ]) await this.#send(`${domain}.enable`, {}, sessionId);
2540
+ for (const [name, value] of cookies) await this.#send("Network.setCookie", {
2541
+ name,
2542
+ value,
2543
+ url
2544
+ }, sessionId);
2545
+ await this.#send("Page.navigate", { url }, sessionId);
2546
+ await Promise.race([load, new Promise((resolve) => setTimeout(resolve, 3e4))]);
2547
+ await new Promise((resolve) => setTimeout(resolve, settle));
2548
+ const { result } = await this.#send("Runtime.evaluate", {
2549
+ expression: "document.querySelector('h1')?.textContent?.trim() || null",
2550
+ returnByValue: true
2551
+ }, sessionId);
2552
+ return {
2553
+ heading: result.value,
2554
+ errors
2555
+ };
2556
+ } finally {
2557
+ this.#listeners.delete(listener);
2558
+ await this.#send("Target.closeTarget", { targetId }).catch(() => {});
2559
+ }
2560
+ }
2561
+ async close() {
2562
+ await this.#send("Browser.close").catch(() => {});
2563
+ this.#socket.close();
2564
+ if (this.#process.exitCode === null) {
2565
+ await Promise.race([new Promise((resolve) => this.#process.once("exit", resolve)), new Promise((resolve) => setTimeout(resolve, 5e3))]);
2566
+ this.#process.kill("SIGKILL");
2567
+ }
2568
+ rmSync(this.#profile, {
2569
+ recursive: true,
2570
+ force: true
2571
+ });
2572
+ }
2573
+ };
2574
+ //#endregion
2575
+ //#region src/checks/pages.ts
2576
+ /** Each page, and the heading it shows. */
2577
+ const PAGES = [
2578
+ ["/projects", "Projects"],
2579
+ [`/projects/${PROJECT}`, "Conformance"],
2580
+ ["/audit", "Audit"]
2581
+ ];
2582
+ async function pagesInBrowser(deployment, admin, browser) {
2583
+ const executable = browser ?? findChrome();
2584
+ if (executable === null) throw new Skip("no Chrome or Chromium here: --browser <path> names one");
2585
+ const chrome = await Chrome.open(executable);
2586
+ try {
2587
+ for (const [path, heading] of PAGES) {
2588
+ const loaded = await chrome.load(new URL(path, deployment.origin).href, admin.browser.cookies());
2589
+ expect(loaded.errors.length === 0, `${path}, signed in, reported errors in the browser`, loaded.errors.join("\n"));
2590
+ expect(loaded.heading?.startsWith(heading), `${path}, signed in, shows ${JSON.stringify(loaded.heading)}, not the heading ${JSON.stringify(heading)}`);
2591
+ }
2592
+ } finally {
2593
+ await chrome.close();
2594
+ }
2595
+ return `${PAGES.map(([path]) => path).join(", ")}, signed in, in Chrome: each rendered, no error from their scripts`;
2596
+ }
2597
+ /** What only server code carries. */
2598
+ const MARKERS = [
2599
+ {
2600
+ label: "drizzle-orm",
2601
+ pattern: /drizzle:[A-Z]/
2602
+ },
2603
+ ...[
2604
+ "audit_chain_head",
2605
+ "audit_log",
2606
+ "consumed_tokens",
2607
+ "device_authorizations",
2608
+ "secret_versions",
2609
+ "service_bindings",
2610
+ "vault_grants",
2611
+ "vault_members"
2612
+ ].map((name) => ({
2613
+ label: `the table ${name}`,
2614
+ pattern: new RegExp(`\\b${name}\\b`)
2615
+ })),
2616
+ {
2617
+ label: "pg",
2618
+ pattern: /cloudflare:sockets|pg-protocol|pgpass/
2619
+ },
2620
+ {
2621
+ label: "libsql",
2622
+ pattern: /@libsql|libsql/
2623
+ },
2624
+ {
2625
+ label: "a COFFRE_ variable read",
2626
+ pattern: /env\s*(\.|\[\s*['"`])COFFRE_/
2627
+ }
2628
+ ];
2629
+ /** Files the browser runs or reads as text, whatever their size or how the build emitted them. */
2630
+ const TEXT = /\.(m?js|css|html|json|svg|txt|wasm\.js)$/;
2631
+ /** What each file holds that only the server may: `<file>: <what>`. */
2632
+ function serverCodeIn(files) {
2633
+ return files.flatMap(({ name, code }) => MARKERS.filter(({ pattern }) => pattern.test(code)).map(({ label }) => `${name}: ${label}`));
2634
+ }
2635
+ /** The text files under `dir`, the browser's half of a build, each as the browser reads it. */
2636
+ function clientFiles(dir) {
2637
+ const files = [];
2638
+ const walk = (at) => {
2639
+ for (const entry of readdirSync(at, { withFileTypes: true })) {
2640
+ const path = join(at, entry.name);
2641
+ if (entry.isDirectory()) walk(path);
2642
+ else if (TEXT.test(entry.name)) files.push({
2643
+ name: relative(dir, path),
2644
+ code: new TextDecoder().decode(readFileSync(path))
2645
+ });
2646
+ }
2647
+ };
2648
+ walk(dir);
2649
+ return files;
2650
+ }
2651
+ //#endregion
2366
2652
  //#region src/checks/surface.ts
2367
2653
  async function health(deployment) {
2368
2654
  const { origin } = deployment;
@@ -2378,6 +2664,82 @@ async function health(deployment) {
2378
2664
  expect(ready.checkpointed === true, "/readyz passed without a checkpoint covering the heartbeat", ready);
2379
2665
  return deployment.beforeFirstBeat ? "/livez, and /readyz only once the heartbeat ran and was checkpointed" : "/livez and /readyz";
2380
2666
  }
2667
+ /** The headers coffre sets on everything it answers, but the policy, whose nonce is each response's own. */
2668
+ const SECURED = {
2669
+ "x-frame-options": "DENY",
2670
+ "x-content-type-options": "nosniff",
2671
+ "referrer-policy": "same-origin",
2672
+ "cross-origin-opener-policy": "same-origin",
2673
+ "cross-origin-resource-policy": "same-origin"
2674
+ };
2675
+ /**
2676
+ * coffre's security headers on every kind of response the app gives, each
2677
+ * with a policy whose nonce is its own: pages, signed out and signed in, a
2678
+ * page's redirect to sign in, a page not found, the API's answers and its
2679
+ * refusals, a refusal of a body it never reads, sign-in's redirect to the
2680
+ * provider, and health. What answers each, Start's render or one of coffre's
2681
+ * server routes, all go through coffre's middleware; one it missed would
2682
+ * lack them.
2683
+ */
2684
+ async function headers(deployment, admin) {
2685
+ const anonymous = (path, init = {}) => fetch(`${deployment.origin}${path}`, {
2686
+ redirect: "manual",
2687
+ ...init
2688
+ });
2689
+ const kinds = [
2690
+ ["the sign-in page", () => anonymous("/login")],
2691
+ ["a signed-in page", () => admin.browser.fetch("/projects")],
2692
+ ["a page's redirect to sign in", () => anonymous("/projects")],
2693
+ ["a page not found", () => anonymous("/no-such-page")],
2694
+ ["an API read", () => admin.browser.fetch("/api/me")],
2695
+ ["an API refusal", () => anonymous("/api/me")],
2696
+ ["a path under /api that is not one", () => anonymous("/api/no-such-thing")],
2697
+ ["a refused method, its body unread", () => anonymous("/livez", {
2698
+ method: "POST",
2699
+ body: "x".repeat(65536)
2700
+ })],
2701
+ ["sign-in's redirect to the provider", () => anonymous("/auth/signin/github")],
2702
+ ["a path under /auth that is not one", () => anonymous("/auth/no-such-step")],
2703
+ ["/livez", () => anonymous("/livez")],
2704
+ ["/readyz", () => anonymous("/readyz")]
2705
+ ];
2706
+ const nonces = /* @__PURE__ */ new Set();
2707
+ for (const [kind, request] of kinds) {
2708
+ const response = await request();
2709
+ await response.body?.cancel();
2710
+ const seen = Object.fromEntries(response.headers);
2711
+ for (const [name, value] of Object.entries(SECURED)) expect(response.headers.get(name) === value, `${kind} (${response.status}) has ${name}: ${response.headers.get(name) ?? "none"}, not ${value}`, seen);
2712
+ expect(response.headers.has("cache-control"), `${kind} (${response.status}) has no cache-control`, seen);
2713
+ const nonce = /script-src 'self' 'nonce-([^']+)'/.exec(response.headers.get("content-security-policy") ?? "")?.[1];
2714
+ expect(nonce !== void 0, `${kind} (${response.status}) has no nonce-based Content-Security-Policy`, seen);
2715
+ expect(!nonces.has(nonce), `${kind} (${response.status}) has the nonce of an earlier response`, seen);
2716
+ nonces.add(nonce);
2717
+ }
2718
+ if (deployment.kind === "node") {
2719
+ const asset = clientFiles(deployment.clientDir).find(({ name }) => name.startsWith("_coffre/assets/") && name.endsWith(".js"));
2720
+ expect(asset !== void 0, "the build has no script under _coffre/assets/");
2721
+ const response = await anonymous(`/${asset.name}`);
2722
+ await response.body?.cancel();
2723
+ const seen = Object.fromEntries(response.headers);
2724
+ expect(response.status === 200, `the static file /${asset.name} answered ${response.status}`, seen);
2725
+ expect(response.headers.get("cache-control") === "public, max-age=31536000, immutable", `/${asset.name} is not kept for good`, seen);
2726
+ expect(response.headers.get("x-content-type-options") === "nosniff", `/${asset.name} lacks nosniff`, seen);
2727
+ expect(response.headers.get("cross-origin-resource-policy") === "same-origin", `/${asset.name} lacks a same-origin CORP`, seen);
2728
+ }
2729
+ return `${kinds.length} kinds of response, each with coffre's headers and a nonce of its own${deployment.kind === "node" ? "; static files kept for good, nosniff and same-origin" : ""}`;
2730
+ }
2731
+ /**
2732
+ * Nothing of the server in what the browser loads: the database layer, a
2733
+ * driver, a table only the server knows, a `COFFRE_*` read. Read from the
2734
+ * client files the app's own build wrote, as the browser gets them.
2735
+ */
2736
+ async function browserBundle(deployment) {
2737
+ const files = clientFiles(deployment.clientDir);
2738
+ expect(files.length > 0, `no client files in ${deployment.clientDir}`);
2739
+ const found = serverCodeIn(files);
2740
+ expect(found.length === 0, "what the browser loads holds server code: a page imports something of the server", found.join("\n"));
2741
+ return `${files.length} files the browser loads, none with server code in it`;
2742
+ }
2381
2743
  //#endregion
2382
2744
  //#region src/checks/workloads.ts
2383
2745
  /** The service the runs sign in as: a viewer on dev. */
@@ -2629,9 +2991,15 @@ async function tokensUnlogged(deployment) {
2629
2991
  async function conform(deployment, options) {
2630
2992
  const report = new Report();
2631
2993
  await report.check("health", {}, () => health(deployment));
2994
+ await report.check("browser bundle", {}, () => browserBundle(deployment));
2632
2995
  const admin = await report.check("sign-in", {}, () => signInAdmin(deployment));
2633
2996
  await report.check("page load", { admin }, ({ admin }) => pageLoad(admin));
2997
+ await report.check("security headers", { admin }, ({ admin }) => headers(deployment, admin));
2634
2998
  const canaries = await report.check("setup", { admin }, ({ admin }) => setUp(admin));
2999
+ await report.check("pages in a browser", {
3000
+ admin,
3001
+ canaries
3002
+ }, ({ admin }) => pagesInBrowser(deployment, admin, options.browser));
2635
3003
  const people = await report.check("personas", {
2636
3004
  admin,
2637
3005
  canaries
@@ -2751,6 +3119,8 @@ const USAGE = `usage:
2751
3119
  <dir> the deployment, as \`coffre init\` wrote it (default: here)
2752
3120
  --port <n> coffre's port; the IdP gets the next, wrangler's inspector the one after (3082)
2753
3121
  --bulk-limit <n> the vault's bulkLimit count, when not the default (1000)
3122
+ --browser <path> Chrome or Chromium, to load the pages in (default: one found here;
3123
+ without one, that check is skipped)
2754
3124
  --postgres <url> workers: a Postgres login that may create databases; one is made for the run
2755
3125
  --runtime <url> workers: the same server as coffre_runtime, the login the app runs as
2756
3126
  --vault-runtime <url>
@@ -2769,6 +3139,7 @@ const { values, positionals } = parseArgs({
2769
3139
  type: "string",
2770
3140
  default: "1000"
2771
3141
  },
3142
+ browser: { type: "string" },
2772
3143
  postgres: { type: "string" },
2773
3144
  runtime: { type: "string" },
2774
3145
  "vault-runtime": { type: "string" },
@@ -2803,7 +3174,10 @@ try {
2803
3174
  console.log(` up on ${deployment.origin}`);
2804
3175
  let failed;
2805
3176
  try {
2806
- failed = await conform(deployment, { bulkLimit });
3177
+ failed = await conform(deployment, {
3178
+ bulkLimit,
3179
+ browser: values.browser || null
3180
+ });
2807
3181
  if (failed.length > 0) console.error(`\nThe processes' output, last lines:\n${deployment.output(4e3)}`);
2808
3182
  } finally {
2809
3183
  await deployment.stop();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coffre/conformance",
3
- "version": "0.1.17",
3
+ "version": "0.2.0",
4
4
  "description": "Checks a coffre deployment from outside: what it must never do, whatever code it runs.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -31,8 +31,8 @@
31
31
  "dependencies": {
32
32
  "jose": "6.2.3",
33
33
  "pg": "8.16.3",
34
- "@coffre/db": "0.1.17",
35
- "@coffre/cli": "0.1.17"
34
+ "@coffre/cli": "0.2.0",
35
+ "@coffre/db": "0.2.0"
36
36
  },
37
37
  "devDependencies": {
38
38
  "@types/node": "26.1.1",
@@ -40,7 +40,8 @@
40
40
  "oauth4webapi": "3.8.8",
41
41
  "tsdown": "0.23.0",
42
42
  "typescript": "5.9.3",
43
- "@coffre/client": "0.1.17"
43
+ "vite": "8.1.5",
44
+ "@coffre/client": "0.2.0"
44
45
  },
45
46
  "scripts": {
46
47
  "build": "tsdown",
package/src/browser.ts CHANGED
@@ -10,6 +10,11 @@ export class Browser {
10
10
  this.origin = origin;
11
11
  }
12
12
 
13
+ /** The cookies coffre left this browser, to hand a real one. */
14
+ cookies(): [string, string][] {
15
+ return [...this.#jar];
16
+ }
17
+
13
18
  /** Whether coffre left this browser a cookie. */
14
19
  get hasCookies(): boolean {
15
20
  return this.#jar.size > 0;
package/src/bundle.ts ADDED
@@ -0,0 +1,55 @@
1
+ // What the browser loads, held to holding nothing of the server: the
2
+ // client files a deployment's build wrote, read as the browser would get
3
+ // them. A page that imports across the line otherwise just grows by the
4
+ // database layer, with no error, since a bundler keeps a module whose top
5
+ // level has side effects, such as `pgTable(…)`, even when nothing uses its
6
+ // exports.
7
+ import { readdirSync, readFileSync } from 'node:fs';
8
+ import { join, relative } from 'node:path';
9
+
10
+ /**
11
+ * The schema's tables whose names could appear in no page: those with an
12
+ * underscore. Single words such as `secrets` are in the pages' own copy.
13
+ * A test holds this to the schema (@coffre/db).
14
+ */
15
+ export const SERVER_TABLES = [
16
+ 'audit_chain_head',
17
+ 'audit_log',
18
+ 'consumed_tokens',
19
+ 'device_authorizations',
20
+ 'secret_versions',
21
+ 'service_bindings',
22
+ 'vault_grants',
23
+ 'vault_members',
24
+ ];
25
+
26
+ /** What only server code carries. */
27
+ const MARKERS: { label: string; pattern: RegExp }[] = [
28
+ { label: 'drizzle-orm', pattern: /drizzle:[A-Z]/ },
29
+ ...SERVER_TABLES.map((name) => ({ label: `the table ${name}`, pattern: new RegExp(`\\b${name}\\b`) })),
30
+ { label: 'pg', pattern: /cloudflare:sockets|pg-protocol|pgpass/ },
31
+ { label: 'libsql', pattern: /@libsql|libsql/ },
32
+ { label: 'a COFFRE_ variable read', pattern: /env\s*(\.|\[\s*['"`])COFFRE_/ },
33
+ ];
34
+
35
+ /** Files the browser runs or reads as text, whatever their size or how the build emitted them. */
36
+ const TEXT = /\.(m?js|css|html|json|svg|txt|wasm\.js)$/;
37
+
38
+ /** What each file holds that only the server may: `<file>: <what>`. */
39
+ export function serverCodeIn(files: { name: string; code: string }[]): string[] {
40
+ return files.flatMap(({ name, code }) => MARKERS.filter(({ pattern }) => pattern.test(code)).map(({ label }) => `${name}: ${label}`));
41
+ }
42
+
43
+ /** The text files under `dir`, the browser's half of a build, each as the browser reads it. */
44
+ export function clientFiles(dir: string): { name: string; code: string }[] {
45
+ const files: { name: string; code: string }[] = [];
46
+ const walk = (at: string) => {
47
+ for (const entry of readdirSync(at, { withFileTypes: true })) {
48
+ const path = join(at, entry.name);
49
+ if (entry.isDirectory()) walk(path);
50
+ else if (TEXT.test(entry.name)) files.push({ name: relative(dir, path), code: new TextDecoder().decode(readFileSync(path)) });
51
+ }
52
+ };
53
+ walk(dir);
54
+ return files;
55
+ }
@@ -0,0 +1,33 @@
1
+ // coffre's pages in a real browser, signed in: each renders its heading,
2
+ // and its scripts run without an error. What a bundler does to the code a
3
+ // page receives shows only there: wrangler's keep_names once wrapped the
4
+ // functions seroval writes into a page in an `__name` that only the Worker
5
+ // had, and a signed-in page rendered, then went blank.
6
+ import { Chrome, findChrome } from '../chrome.ts';
7
+ import type { Deployment } from '../harness.ts';
8
+ import { expect, Skip } from '../report.ts';
9
+ import { type Person, PROJECT } from './people.ts';
10
+
11
+ /** Each page, and the heading it shows. */
12
+ const PAGES = [
13
+ ['/projects', 'Projects'],
14
+ [`/projects/${PROJECT}`, 'Conformance'],
15
+ ['/audit', 'Audit'],
16
+ ] as const;
17
+
18
+ export async function pagesInBrowser(deployment: Deployment, admin: Person, browser: string | null): Promise<string> {
19
+ const executable = browser ?? findChrome();
20
+ if (executable === null) throw new Skip('no Chrome or Chromium here: --browser <path> names one');
21
+ const chrome = await Chrome.open(executable);
22
+ try {
23
+ for (const [path, heading] of PAGES) {
24
+ const loaded = await chrome.load(new URL(path, deployment.origin).href, admin.browser.cookies());
25
+ expect(loaded.errors.length === 0, `${path}, signed in, reported errors in the browser`, loaded.errors.join('\n'));
26
+ // The heading, then what may follow it in the h1, such as a project's slug.
27
+ expect(loaded.heading?.startsWith(heading), `${path}, signed in, shows ${JSON.stringify(loaded.heading)}, not the heading ${JSON.stringify(heading)}`);
28
+ }
29
+ } finally {
30
+ await chrome.close();
31
+ }
32
+ return `${PAGES.map(([path]) => path).join(', ')}, signed in, in Chrome: each rendered, no error from their scripts`;
33
+ }
@@ -1,7 +1,9 @@
1
1
  // Health: up, and ready only once the scheduled job has beaten and the
2
2
  // vault has checkpointed it. What else anyone on the network sees, its
3
3
  // headers among it, `coffre verify instance` checks, here as anywhere.
4
+ import { clientFiles, serverCodeIn } from '../bundle.ts';
4
5
  import type { Deployment } from '../harness.ts';
6
+ import type { Person } from './people.ts';
5
7
  import { expect, until } from '../report.ts';
6
8
 
7
9
  export async function health(deployment: Deployment): Promise<string> {
@@ -20,3 +22,80 @@ export async function health(deployment: Deployment): Promise<string> {
20
22
  expect(ready.checkpointed === true, '/readyz passed without a checkpoint covering the heartbeat', ready);
21
23
  return deployment.beforeFirstBeat ? '/livez, and /readyz only once the heartbeat ran and was checkpointed' : '/livez and /readyz';
22
24
  }
25
+
26
+ /** The headers coffre sets on everything it answers, but the policy, whose nonce is each response's own. */
27
+ const SECURED: Record<string, string> = {
28
+ 'x-frame-options': 'DENY',
29
+ 'x-content-type-options': 'nosniff',
30
+ 'referrer-policy': 'same-origin',
31
+ 'cross-origin-opener-policy': 'same-origin',
32
+ 'cross-origin-resource-policy': 'same-origin',
33
+ };
34
+
35
+ /**
36
+ * coffre's security headers on every kind of response the app gives, each
37
+ * with a policy whose nonce is its own: pages, signed out and signed in, a
38
+ * page's redirect to sign in, a page not found, the API's answers and its
39
+ * refusals, a refusal of a body it never reads, sign-in's redirect to the
40
+ * provider, and health. What answers each, Start's render or one of coffre's
41
+ * server routes, all go through coffre's middleware; one it missed would
42
+ * lack them.
43
+ */
44
+ export async function headers(deployment: Deployment, admin: Person): Promise<string> {
45
+ const anonymous = (path: string, init: RequestInit = {}) => fetch(`${deployment.origin}${path}`, { redirect: 'manual', ...init });
46
+ const kinds: [string, () => Promise<Response>][] = [
47
+ ['the sign-in page', () => anonymous('/login')],
48
+ ['a signed-in page', () => admin.browser.fetch('/projects')],
49
+ ["a page's redirect to sign in", () => anonymous('/projects')],
50
+ ['a page not found', () => anonymous('/no-such-page')],
51
+ ['an API read', () => admin.browser.fetch('/api/me')],
52
+ ['an API refusal', () => anonymous('/api/me')],
53
+ ['a path under /api that is not one', () => anonymous('/api/no-such-thing')],
54
+ ['a refused method, its body unread', () => anonymous('/livez', { method: 'POST', body: 'x'.repeat(64 * 1024) })],
55
+ ["sign-in's redirect to the provider", () => anonymous('/auth/signin/github')],
56
+ ['a path under /auth that is not one', () => anonymous('/auth/no-such-step')],
57
+ ['/livez', () => anonymous('/livez')],
58
+ ['/readyz', () => anonymous('/readyz')],
59
+ ];
60
+ const nonces = new Set<string>();
61
+ for (const [kind, request] of kinds) {
62
+ const response = await request();
63
+ await response.body?.cancel();
64
+ const seen = Object.fromEntries(response.headers);
65
+ for (const [name, value] of Object.entries(SECURED)) {
66
+ expect(response.headers.get(name) === value, `${kind} (${response.status}) has ${name}: ${response.headers.get(name) ?? 'none'}, not ${value}`, seen);
67
+ }
68
+ expect(response.headers.has('cache-control'), `${kind} (${response.status}) has no cache-control`, seen);
69
+ const nonce = /script-src 'self' 'nonce-([^']+)'/.exec(response.headers.get('content-security-policy') ?? '')?.[1];
70
+ expect(nonce !== undefined, `${kind} (${response.status}) has no nonce-based Content-Security-Policy`, seen);
71
+ expect(!nonces.has(nonce), `${kind} (${response.status}) has the nonce of an earlier response`, seen);
72
+ nonces.add(nonce);
73
+ }
74
+ // On Node the app serves its static files itself, which keep for good and are never sniffed; on
75
+ // Workers, Cloudflare serves them, before the Worker runs.
76
+ if (deployment.kind === 'node') {
77
+ const asset = clientFiles(deployment.clientDir).find(({ name }) => name.startsWith('_coffre/assets/') && name.endsWith('.js'));
78
+ expect(asset !== undefined, 'the build has no script under _coffre/assets/');
79
+ const response = await anonymous(`/${asset.name}`);
80
+ await response.body?.cancel();
81
+ const seen = Object.fromEntries(response.headers);
82
+ expect(response.status === 200, `the static file /${asset.name} answered ${response.status}`, seen);
83
+ expect(response.headers.get('cache-control') === 'public, max-age=31536000, immutable', `/${asset.name} is not kept for good`, seen);
84
+ expect(response.headers.get('x-content-type-options') === 'nosniff', `/${asset.name} lacks nosniff`, seen);
85
+ expect(response.headers.get('cross-origin-resource-policy') === 'same-origin', `/${asset.name} lacks a same-origin CORP`, seen);
86
+ }
87
+ return `${kinds.length} kinds of response, each with coffre's headers and a nonce of its own${deployment.kind === 'node' ? '; static files kept for good, nosniff and same-origin' : ''}`;
88
+ }
89
+
90
+ /**
91
+ * Nothing of the server in what the browser loads: the database layer, a
92
+ * driver, a table only the server knows, a `COFFRE_*` read. Read from the
93
+ * client files the app's own build wrote, as the browser gets them.
94
+ */
95
+ export async function browserBundle(deployment: Deployment): Promise<string> {
96
+ const files = clientFiles(deployment.clientDir);
97
+ expect(files.length > 0, `no client files in ${deployment.clientDir}`);
98
+ const found = serverCodeIn(files);
99
+ expect(found.length === 0, 'what the browser loads holds server code: a page imports something of the server', found.join('\n'));
100
+ return `${files.length} files the browser loads, none with server code in it`;
101
+ }
package/src/chrome.ts ADDED
@@ -0,0 +1,171 @@
1
+ // A real browser, for what only one shows: coffre's pages as they render
2
+ // and hydrate, their scripts run. Headless Chrome, driven over the DevTools
3
+ // protocol with Node's own WebSocket, so that conformance depends on no
4
+ // browser package; the machine's Chrome or Chromium does.
5
+ import { spawn, type ChildProcess } from 'node:child_process';
6
+ import { existsSync, mkdtempSync, readdirSync, rmSync } from 'node:fs';
7
+ import { homedir, tmpdir } from 'node:os';
8
+ import { delimiter, join } from 'node:path';
9
+
10
+ /** What a page did, loaded: the heading it shows, and every error its scripts and console reported. */
11
+ export type Loaded = { heading: string | null; errors: string[] };
12
+
13
+ const NAMES = ['google-chrome', 'google-chrome-stable', 'chromium', 'chromium-browser', 'chrome'];
14
+ const MAC = ['/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/Applications/Chromium.app/Contents/MacOS/Chromium'];
15
+
16
+ /** A Chrome or Chromium on this machine: on PATH, where macOS keeps it, or Playwright's. */
17
+ export function findChrome(): string | null {
18
+ for (const dir of (process.env.PATH ?? '').split(delimiter)) {
19
+ for (const name of NAMES) if (dir !== '' && existsSync(join(dir, name))) return join(dir, name);
20
+ }
21
+ for (const path of MAC) if (existsSync(path)) return path;
22
+ const playwright = join(homedir(), '.cache', 'ms-playwright');
23
+ if (existsSync(playwright)) {
24
+ for (const dir of readdirSync(playwright).filter((name) => name.startsWith('chromium-')).sort().reverse()) {
25
+ for (const build of ['chrome-linux64', 'chrome-linux']) {
26
+ const path = join(playwright, dir, build, 'chrome');
27
+ if (existsSync(path)) return path;
28
+ }
29
+ }
30
+ }
31
+ return null;
32
+ }
33
+
34
+ type Message = { id?: number; method?: string; params?: Record<string, unknown>; result?: Record<string, unknown>; error?: { message: string }; sessionId?: string };
35
+
36
+ export class Chrome {
37
+ readonly #process: ChildProcess;
38
+ readonly #socket: WebSocket;
39
+ readonly #profile: string;
40
+ #next = 0;
41
+ readonly #pending = new Map<number, { resolve: (result: Record<string, unknown>) => void; reject: (error: Error) => void }>();
42
+ readonly #listeners = new Set<(message: Message) => void>();
43
+
44
+ private constructor(process: ChildProcess, socket: WebSocket, profile: string) {
45
+ this.#process = process;
46
+ this.#socket = socket;
47
+ this.#profile = profile;
48
+ socket.addEventListener('message', (event) => {
49
+ const message = JSON.parse(String(event.data)) as Message;
50
+ if (message.id !== undefined) {
51
+ const pending = this.#pending.get(message.id);
52
+ this.#pending.delete(message.id);
53
+ if (message.error !== undefined) pending?.reject(new Error(message.error.message));
54
+ else pending?.resolve(message.result ?? {});
55
+ } else {
56
+ for (const listener of this.#listeners) listener(message);
57
+ }
58
+ });
59
+ }
60
+
61
+ /** Chrome at `executable`, headless, with a profile of its own, gone when closed. */
62
+ static async open(executable: string): Promise<Chrome> {
63
+ const profile = mkdtempSync(join(tmpdir(), 'coffre-chrome-'));
64
+ const child = spawn(
65
+ executable,
66
+ [
67
+ '--headless=new',
68
+ '--remote-debugging-port=0',
69
+ `--user-data-dir=${profile}`,
70
+ '--no-first-run',
71
+ '--no-default-browser-check',
72
+ '--disable-gpu',
73
+ // Only coffre's own pages are loaded; CI's runners have no user namespaces for Chrome's sandbox.
74
+ '--no-sandbox',
75
+ 'about:blank',
76
+ ],
77
+ { stdio: ['ignore', 'ignore', 'pipe'] },
78
+ );
79
+ const url = await new Promise<string>((resolve, reject) => {
80
+ let output = '';
81
+ const timer = setTimeout(() => reject(new Error(`Chrome did not start: ${output.trim().split('\n').slice(-3).join(' ')}`)), 30_000);
82
+ child.stderr!.setEncoding('utf8').on('data', (chunk: string) => {
83
+ output += chunk;
84
+ const found = /DevTools listening on (ws:\/\/\S+)/.exec(output);
85
+ if (found !== null) {
86
+ clearTimeout(timer);
87
+ resolve(found[1]!);
88
+ }
89
+ });
90
+ child.on('error', (error) => {
91
+ clearTimeout(timer);
92
+ reject(error);
93
+ });
94
+ child.on('exit', (code) => {
95
+ clearTimeout(timer);
96
+ reject(new Error(`Chrome exited with ${code}: ${output.trim().split('\n').slice(-3).join(' ')}`));
97
+ });
98
+ });
99
+ const socket = new WebSocket(url);
100
+ await new Promise<void>((resolve, reject) => {
101
+ socket.addEventListener('open', () => resolve(), { once: true });
102
+ socket.addEventListener('error', () => reject(new Error(`could not reach Chrome at ${url}`)), { once: true });
103
+ });
104
+ return new Chrome(child, socket, profile);
105
+ }
106
+
107
+ #send(method: string, params: Record<string, unknown> = {}, sessionId?: string): Promise<Record<string, unknown>> {
108
+ const id = ++this.#next;
109
+ return new Promise((resolve, reject) => {
110
+ this.#pending.set(id, { resolve, reject });
111
+ this.#socket.send(JSON.stringify({ id, method, params, sessionId }));
112
+ });
113
+ }
114
+
115
+ /**
116
+ * `url` in a tab of its own, with `cookies` for its origin: the heading it
117
+ * shows once its scripts have run and settled, and every uncaught error,
118
+ * console error and failed load along the way.
119
+ */
120
+ async load(url: string, cookies: [string, string][], settle = 2_000): Promise<Loaded> {
121
+ const { targetId } = (await this.#send('Target.createTarget', { url: 'about:blank' })) as { targetId: string };
122
+ const { sessionId } = (await this.#send('Target.attachToTarget', { targetId, flatten: true })) as { sessionId: string };
123
+ const errors: string[] = [];
124
+ let loaded!: () => void;
125
+ const load = new Promise<void>((resolve) => (loaded = resolve));
126
+ const listener = (message: Message) => {
127
+ if (message.sessionId !== sessionId) return;
128
+ const params = message.params ?? {};
129
+ if (message.method === 'Runtime.exceptionThrown') {
130
+ const details = params.exceptionDetails as { text: string; exception?: { description?: string }; url?: string; lineNumber?: number };
131
+ errors.push(`${details.exception?.description?.split('\n')[0] ?? details.text}${details.url ? ` (${details.url}:${(details.lineNumber ?? 0) + 1})` : ''}`);
132
+ } else if (message.method === 'Runtime.consoleAPICalled' && params.type === 'error') {
133
+ const args = params.args as { value?: unknown; description?: string }[];
134
+ errors.push(`console.error: ${args.map((arg) => arg.description ?? String(arg.value)).join(' ')}`);
135
+ } else if (message.method === 'Log.entryAdded') {
136
+ const entry = params.entry as { level: string; text: string; url?: string };
137
+ if (entry.level === 'error') errors.push(`${entry.text}${entry.url ? ` (${entry.url})` : ''}`);
138
+ } else if (message.method === 'Page.loadEventFired') {
139
+ loaded();
140
+ }
141
+ };
142
+ this.#listeners.add(listener);
143
+ try {
144
+ for (const domain of ['Runtime', 'Log', 'Page', 'Network']) await this.#send(`${domain}.enable`, {}, sessionId);
145
+ for (const [name, value] of cookies) await this.#send('Network.setCookie', { name, value, url }, sessionId);
146
+ await this.#send('Page.navigate', { url }, sessionId);
147
+ await Promise.race([load, new Promise((resolve) => setTimeout(resolve, 30_000))]);
148
+ // What streams in after the load, and hydration, have their time: the page may render, then fail.
149
+ await new Promise((resolve) => setTimeout(resolve, settle));
150
+ const { result } = (await this.#send(
151
+ 'Runtime.evaluate',
152
+ { expression: "document.querySelector('h1')?.textContent?.trim() || null", returnByValue: true },
153
+ sessionId,
154
+ )) as { result: { value: string | null } };
155
+ return { heading: result.value, errors };
156
+ } finally {
157
+ this.#listeners.delete(listener);
158
+ await this.#send('Target.closeTarget', { targetId }).catch(() => {});
159
+ }
160
+ }
161
+
162
+ async close(): Promise<void> {
163
+ await this.#send('Browser.close').catch(() => {});
164
+ this.#socket.close();
165
+ if (this.#process.exitCode === null) {
166
+ await Promise.race([new Promise((resolve) => this.#process.once('exit', resolve)), new Promise((resolve) => setTimeout(resolve, 5_000))]);
167
+ this.#process.kill('SIGKILL');
168
+ }
169
+ rmSync(this.#profile, { recursive: true, force: true });
170
+ }
171
+ }
@@ -0,0 +1,44 @@
1
+ // The built Workers app as `wrangler dev` can run it, for conformance and
2
+ // for the restore drill (scripts/restore-drill.sh), which runs this file:
3
+ //
4
+ // node packages/conformance/src/draining.ts examples/workers/app/dist/server
5
+ //
6
+ // prints the config to pass `wrangler dev -c`.
7
+ import { readFileSync, writeFileSync } from 'node:fs';
8
+ import { join, resolve } from 'node:path';
9
+
10
+ /**
11
+ * The built app as `wrangler dev` can run it: its own build, behind an entry
12
+ * that, once the app has answered, reads whatever the request still sends
13
+ * before passing the answer on. Locally, and only there, a Worker built
14
+ * unbundled with static assets fails every request after one whose body it
15
+ * left unread, which every refusal does, and reading it later, after the
16
+ * answer, is too late; deployed, Cloudflare discards such a body, as
17
+ * `vite dev` and `vite preview` do. The app itself must never wait so on what
18
+ * a caller sends; this harness sends only bodies that end. The entry and its
19
+ * config are written beside the build, which the next `vite build`
20
+ * replaces: nothing of them deploys.
21
+ */
22
+ export function drainingConfig(server: string): string {
23
+ writeFileSync(
24
+ join(server, 'conformance.js'),
25
+ [
26
+ "import app from './index.js';",
27
+ 'export default {',
28
+ ' ...app,',
29
+ ' async fetch(request, env, ctx) {',
30
+ ' const response = await app.fetch(request, env, ctx);',
31
+ ' if (request.body !== null && !request.bodyUsed) await request.arrayBuffer().catch(() => {});',
32
+ ' return response;',
33
+ ' },',
34
+ '};',
35
+ '',
36
+ ].join('\n'),
37
+ );
38
+ const config = JSON.parse(readFileSync(join(server, 'wrangler.json'), 'utf8')) as Record<string, unknown>;
39
+ const path = join(server, 'conformance.json');
40
+ writeFileSync(path, JSON.stringify({ ...config, main: 'conformance.js' }));
41
+ return path;
42
+ }
43
+
44
+ if (import.meta.main) console.log(drainingConfig(resolve(process.argv[2]!)));
package/src/harness.ts CHANGED
@@ -1,12 +1,12 @@
1
1
  // Run a deployment made like `coffre init` makes one, unedited: settings go
2
- // in as the environment its wrangler.jsonc or server.env would give it, with
2
+ // in as the environment its wrangler.jsonc or .env would give it, with
3
3
  // GitHub's URLs pointed at a stand-in IdP running in this process.
4
4
  //
5
5
  // workers two Workers under `wrangler dev`, on a Postgres database of
6
6
  // their own, created for the run and dropped after, each through
7
7
  // its own login
8
- // node the server and its vault process, on one SQLite file in a temp
9
- // dir
8
+ // node the app's build under srvx and its vault process, on one SQLite
9
+ // file in a temp dir
10
10
  //
11
11
  // Ports: coffre on `port`, the IdP on the next, wrangler's inspector on the
12
12
  // one after.
@@ -20,6 +20,7 @@ import { setTimeout as sleep } from 'node:timers/promises';
20
20
 
21
21
  import { postgres, sqlite, using, type Sql } from './database.ts';
22
22
  import { KEYS } from './fixtures.ts';
23
+ import { drainingConfig } from './draining.ts';
23
24
  import { DevIdp } from './idp/index.ts';
24
25
  import { Failure, until } from './report.ts';
25
26
 
@@ -53,6 +54,8 @@ export type Deployment = {
53
54
  vaultRuntime: (() => Promise<Sql>) | null;
54
55
  /** The file holding the database, when it is one. */
55
56
  databaseFile: string | null;
57
+ /** The browser's half of the app's build: its static files. */
58
+ clientDir: string;
56
59
  /** The processes' output: all of it, or the last `tail` characters of each. */
57
60
  output(tail?: number): string;
58
61
  stop(): Promise<void>;
@@ -198,10 +201,12 @@ export async function boot(kind: Kind, at: string, options: HarnessOptions): Pro
198
201
  // `coffre migrate`, in its folder, the owner's URL in its environment.
199
202
  // A fresh log has no heartbeat: only the scheduled job can make /readyz pass.
200
203
  await run(process.execPath, [deploymentCli(dir), 'migrate', '--yes'], { COFFRE_MIGRATE_DATABASE_URL: owner });
204
+ // The app as it deploys: its Start app, built by its own Vite, which wrangler runs unbundled.
205
+ await run(bin('vite'), ['build', 'app']);
201
206
  const state = join(scratch, 'state');
202
207
  start('wrangler', bin('wrangler'), [
203
208
  'dev',
204
- ...['-c', 'app/wrangler.jsonc', '-c', 'vault/wrangler.jsonc'],
209
+ ...['-c', drainingConfig(join(dir, 'app/dist/server')), '-c', 'vault/wrangler.jsonc'],
205
210
  ...['--ip', '127.0.0.1', '--port', String(port), '--inspector-port', String(port + 2)],
206
211
  ...['--persist-to', state, '--show-interactive-dev-session=false'],
207
212
  // Not in wrangler.jsonc's vars, so not taken from the environment.
@@ -236,6 +241,7 @@ export async function boot(kind: Kind, at: string, options: HarnessOptions): Pro
236
241
  runtime: () => postgres(runtime),
237
242
  vaultRuntime: () => postgres(vaultRuntime),
238
243
  databaseFile: null,
244
+ clientDir: join(dir, 'app/dist/client'),
239
245
  output,
240
246
  stop,
241
247
  };
@@ -253,8 +259,11 @@ export async function boot(kind: Kind, at: string, options: HarnessOptions): Pro
253
259
  ROOT_ADMINS: ROOT_ADMIN,
254
260
  });
255
261
  await until('the vault socket', async () => existsSync(socket), 30, alive);
262
+ // The pages as they run: the deployment's Start app, built by its own Vite.
263
+ await run(bin('vite'), ['build', 'app']);
264
+ // As `pnpm start` runs it: the app's build, under srvx.
256
265
  const startServer = () =>
257
- start('server', process.execPath, ['src/server.ts'], {
266
+ start('server', bin('srvx'), ['--prod', '--host=127.0.0.1', 'app/dist/server/server.js'], {
258
267
  PORT: String(port),
259
268
  PUBLIC_URL: origin,
260
269
  DATABASE_URL: `file:${database}`,
@@ -284,6 +293,7 @@ export async function boot(kind: Kind, at: string, options: HarnessOptions): Pro
284
293
  runtime: null,
285
294
  vaultRuntime: null,
286
295
  databaseFile: database,
296
+ clientDir: join(dir, 'app/dist/client'),
287
297
  output,
288
298
  stop,
289
299
  };
package/src/main.ts CHANGED
@@ -17,6 +17,8 @@ const USAGE = `usage:
17
17
  <dir> the deployment, as \`coffre init\` wrote it (default: here)
18
18
  --port <n> coffre's port; the IdP gets the next, wrangler's inspector the one after (3082)
19
19
  --bulk-limit <n> the vault's bulkLimit count, when not the default (1000)
20
+ --browser <path> Chrome or Chromium, to load the pages in (default: one found here;
21
+ without one, that check is skipped)
20
22
  --postgres <url> workers: a Postgres login that may create databases; one is made for the run
21
23
  --runtime <url> workers: the same server as coffre_runtime, the login the app runs as
22
24
  --vault-runtime <url>
@@ -30,6 +32,7 @@ const { values, positionals } = parseArgs({
30
32
  options: {
31
33
  port: { type: 'string', default: '3082' },
32
34
  'bulk-limit': { type: 'string', default: '1000' },
35
+ browser: { type: 'string' },
33
36
  postgres: { type: 'string' },
34
37
  runtime: { type: 'string' },
35
38
  'vault-runtime': { type: 'string' },
@@ -63,7 +66,7 @@ try {
63
66
  console.log(` up on ${deployment.origin}`);
64
67
  let failed: string[];
65
68
  try {
66
- failed = await conform(deployment, { bulkLimit });
69
+ failed = await conform(deployment, { bulkLimit, browser: values.browser || null });
67
70
  if (failed.length > 0) console.error(`\nThe processes' output, last lines:\n${deployment.output(4000)}`);
68
71
  } finally {
69
72
  await deployment.stop();
package/src/suite.ts CHANGED
@@ -13,16 +13,20 @@ import { editedGeneration, forgedCredential, forgedIdentity, forgedApproval } fr
13
13
  import { canaryScan } from './checks/canaries.ts';
14
14
  import { Cli, cliLogin, verifyAsOwner, verifyAsUser, verifyInterrupted, verifyKeys, verifyLeftovers, verifyWithToken } from './checks/cli.ts';
15
15
  import { pageLoad, personas, setUp, setUpLive, signInAdmin } from './checks/people.ts';
16
- import { health } from './checks/surface.ts';
16
+ import { pagesInBrowser } from './checks/pages.ts';
17
+ import { browserBundle, headers, health } from './checks/surface.ts';
17
18
  import { cliSignsIn, exchangesLimited, runSignsIn, runsRefused, runUnbound, spentOnce, tokensUnlogged, trustRun } from './checks/workloads.ts';
18
19
 
19
20
  /** The names of the checks that failed. */
20
- export async function conform(deployment: Deployment, options: { bulkLimit: number }): Promise<string[]> {
21
+ export async function conform(deployment: Deployment, options: { bulkLimit: number; browser: string | null }): Promise<string[]> {
21
22
  const report = new Report();
22
23
  await report.check('health', {}, () => health(deployment));
24
+ await report.check('browser bundle', {}, () => browserBundle(deployment));
23
25
  const admin = await report.check('sign-in', {}, () => signInAdmin(deployment));
24
26
  await report.check('page load', { admin }, ({ admin }) => pageLoad(admin));
27
+ await report.check('security headers', { admin }, ({ admin }) => headers(deployment, admin));
25
28
  const canaries = await report.check('setup', { admin }, ({ admin }) => setUp(admin));
29
+ await report.check('pages in a browser', { admin, canaries }, ({ admin }) => pagesInBrowser(deployment, admin, options.browser));
26
30
  const people = await report.check('personas', { admin, canaries }, ({ admin }) => personas(deployment, admin));
27
31
  const all = { people, canaries };
28
32