@coffre/conformance 0.1.18 → 0.3.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.
@@ -907,8 +907,8 @@ var OidcProvider = class {
907
907
  * `permissions: id-token: write`, to the bearer of `requestToken`. Locally,
908
908
  * `POST /workloads/token` mints one, for trying the CLI by hand:
909
909
  *
910
- * COFFRE_ID_TOKEN=$(curl -s -X POST http://127.0.0.1:8081/workloads/token \
911
- * -d aud=http://127.0.0.1:3000 | jq -r .token)
910
+ * curl -s -X POST http://127.0.0.1:8081/workloads/token -d aud=http://127.0.0.1:3000 | jq -r .token |
911
+ * coffre login http://127.0.0.1:3000 --service <name> --id-token
912
912
  */
913
913
  var WorkloadIssuer = class {
914
914
  #origin;
package/dist/idp.d.ts CHANGED
@@ -21,8 +21,8 @@ interface Route {
21
21
  * `permissions: id-token: write`, to the bearer of `requestToken`. Locally,
22
22
  * `POST /workloads/token` mints one, for trying the CLI by hand:
23
23
  *
24
- * COFFRE_ID_TOKEN=$(curl -s -X POST http://127.0.0.1:8081/workloads/token \
25
- * -d aud=http://127.0.0.1:3000 | jq -r .token)
24
+ * curl -s -X POST http://127.0.0.1:8081/workloads/token -d aud=http://127.0.0.1:3000 | jq -r .token |
25
+ * coffre login http://127.0.0.1:3000 --service <name> --id-token
26
26
  */
27
27
  export declare class WorkloadIssuer {
28
28
  #private;
package/dist/idp.js CHANGED
@@ -1,2 +1,2 @@
1
- import { a as PERSONAS, i as WorkloadIssuer, n as DevIdp, r as GITHUB_RUN, t as DEFAULT_CLIENT } from "./idp-BeOsuZ3p.js";
1
+ import { a as PERSONAS, i as WorkloadIssuer, n as DevIdp, r as GITHUB_RUN, t as DEFAULT_CLIENT } from "./idp-Dyaj6k5N.js";
2
2
  export { DEFAULT_CLIENT, DevIdp, GITHUB_RUN, PERSONAS, WorkloadIssuer };
package/dist/main.js CHANGED
@@ -1,10 +1,10 @@
1
- import { n as DevIdp, o as defaultGitHubAccount, r as GITHUB_RUN } from "./idp-BeOsuZ3p.js";
1
+ import { n as DevIdp, o as defaultGitHubAccount, r as GITHUB_RUN } from "./idp-Dyaj6k5N.js";
2
2
  import { createRequire } from "node:module";
3
- import { delimiter, 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, readdirSync, rmSync } from "node:fs";
7
+ import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
8
8
  import { homedir, tmpdir } from "node:os";
9
9
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
10
10
  import { DatabaseSync } from "node:sqlite";
@@ -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`, ... */
@@ -338,7 +364,7 @@ async function boot(kind, at, options) {
338
364
  const output = (tail = Infinity) => children.map((entry) => `--- ${entry.name}\n${Buffer.concat(entry.output).toString("utf8").slice(-tail)}`).join("\n");
339
365
  const logs = () => output(4e3);
340
366
  const alive = () => !children.some((entry) => entry.daemon && entry.exited);
341
- function start(name, command, args, env, daemon = true) {
367
+ function start(name, command, args, env, daemon = true, input) {
342
368
  const child = spawn(command, args, {
343
369
  cwd: dir,
344
370
  env: {
@@ -347,11 +373,15 @@ async function boot(kind, at, options) {
347
373
  },
348
374
  detached: true,
349
375
  stdio: [
350
- "ignore",
376
+ input === void 0 ? "ignore" : "pipe",
351
377
  "pipe",
352
378
  "pipe"
353
379
  ]
354
380
  });
381
+ if (input !== void 0) {
382
+ child.stdin.on("error", () => {});
383
+ child.stdin.end(input);
384
+ }
355
385
  const entry = {
356
386
  name,
357
387
  child,
@@ -369,8 +399,8 @@ async function boot(kind, at, options) {
369
399
  children.push(entry);
370
400
  return entry;
371
401
  }
372
- async function run(command, args, env = {}) {
373
- const entry = start(args[0] ?? command, command, args, env, false);
402
+ async function run(command, args, env = {}, input) {
403
+ const entry = start(args[0] ?? command, command, args, env, false, input);
374
404
  if (await new Promise((done) => {
375
405
  entry.child.once("exit", done);
376
406
  entry.child.once("error", done);
@@ -426,13 +456,14 @@ async function boot(kind, at, options) {
426
456
  deploymentCli(dir),
427
457
  "migrate",
428
458
  "--yes"
429
- ], { COFFRE_MIGRATE_DATABASE_URL: owner });
459
+ ], {}, `${owner}\n`);
460
+ await run(bin("vite"), ["build", "app"]);
430
461
  const state = join(scratch, "state");
431
462
  start("wrangler", bin("wrangler"), [
432
463
  "dev",
433
464
  ...[
434
465
  "-c",
435
- "app/wrangler.jsonc",
466
+ drainingConfig(join(dir, "app/dist/server")),
436
467
  "-c",
437
468
  "vault/wrangler.jsonc"
438
469
  ],
@@ -482,6 +513,7 @@ async function boot(kind, at, options) {
482
513
  runtime: () => postgres(runtime),
483
514
  vaultRuntime: () => postgres(vaultRuntime),
484
515
  databaseFile: null,
516
+ clientDir: join(dir, "app/dist/client"),
485
517
  output,
486
518
  stop
487
519
  };
@@ -498,7 +530,12 @@ async function boot(kind, at, options) {
498
530
  ROOT_ADMINS: ROOT_ADMIN
499
531
  });
500
532
  await until("the vault socket", async () => existsSync(socket), 30, alive);
501
- const startServer = () => start("server", process.execPath, ["src/server.ts"], {
533
+ await run(bin("vite"), ["build", "app"]);
534
+ const startServer = () => start("server", bin("srvx"), [
535
+ "--prod",
536
+ "--host=127.0.0.1",
537
+ "app/dist/server/server.js"
538
+ ], {
502
539
  PORT: String(port),
503
540
  PUBLIC_URL: origin,
504
541
  DATABASE_URL: `file:${database}`,
@@ -526,6 +563,7 @@ async function boot(kind, at, options) {
526
563
  runtime: null,
527
564
  vaultRuntime: null,
528
565
  databaseFile: database,
566
+ clientDir: join(dir, "app/dist/client"),
529
567
  output,
530
568
  stop
531
569
  };
@@ -2208,16 +2246,19 @@ function marks(output) {
2208
2246
  /** The token's run, from CI: as no one, then as the token, which is no owner and skips verification. */
2209
2247
  async function verifyWithToken(cli, live) {
2210
2248
  const { canary } = live;
2249
+ const login = await cli.run([
2250
+ "login",
2251
+ cli.origin,
2252
+ "--token"
2253
+ ], {}, `${live.token}\n`);
2254
+ expect(login.code === 0, `coffre login --token exited ${login.code}`, login.output);
2211
2255
  const run = await cli.run([
2212
2256
  "verify",
2213
2257
  "instance",
2214
2258
  cli.origin,
2215
2259
  "--canary",
2216
2260
  `${canary.project}/${canary.environment}/${canary.key}`
2217
- ], {
2218
- COFFRE_TOKEN: live.token,
2219
- COFFRE_CONFORMANCE_CANARY: canary.value
2220
- });
2261
+ ], {}, `${canary.value}\n`);
2221
2262
  const seen = marks(run.output);
2222
2263
  expect(run.code === 0, `coffre verify instance with a token exited ${run.code}`, run.output);
2223
2264
  expect(seen["token verification"] === "–", "a token that is no owner did not skip verification", run.output);
@@ -2317,24 +2358,22 @@ async function verifyLeftovers(cli, admin, setups, before, kept) {
2317
2358
  return `the second run found all; ${PROBE.service} holds no credential; the CLI's session signed in; ${place}/${kept.key} untouched; nothing else changed; ${entries.length} entries by ${PROBE.service} stay`;
2318
2359
  }
2319
2360
  /**
2320
- * `coffre verify keys`, with the admin's session: this deployment's keys
2321
- * pass, from the environment; a wrong vault key fails and the right app key
2322
- * passes, from stdin; a malformed app key fails. No key is ever printed.
2361
+ * `coffre verify keys`, with the admin's session, the keys piped in: this
2362
+ * deployment's pass; a wrong vault key fails and the right app key passes;
2363
+ * a malformed app key fails. No key is ever printed.
2323
2364
  */
2324
2365
  async function verifyKeys(cli) {
2325
2366
  const wrong = Buffer.alloc(32, 7).toString("base64");
2326
2367
  const runs = [
2327
2368
  {
2328
- env: {
2329
- COFFRE_VAULT_KEY: KEYS.VAULT_KEY,
2330
- COFFRE_APP_KEY: KEYS.APP_KEY,
2331
- COFFRE_VAULT_KEY_ID: KEYS.VAULT_KEY_ID
2332
- },
2369
+ args: ["--vault-id", KEYS.VAULT_KEY_ID],
2370
+ input: `${KEYS.VAULT_KEY}\n${KEYS.APP_KEY}\n`,
2333
2371
  code: 0,
2334
2372
  vault: "✓",
2335
2373
  app: "✓"
2336
2374
  },
2337
2375
  {
2376
+ args: [],
2338
2377
  input: `${wrong}\n${KEYS.APP_KEY}\n`,
2339
2378
  code: 1,
2340
2379
  vault: "✗",
@@ -2342,18 +2381,20 @@ async function verifyKeys(cli) {
2342
2381
  said: /✗ vault key +not this instance's vault key/
2343
2382
  },
2344
2383
  {
2345
- env: {
2346
- COFFRE_VAULT_KEY: KEYS.VAULT_KEY,
2347
- COFFRE_APP_KEY: "not-a-key"
2348
- },
2384
+ args: [],
2385
+ input: `${KEYS.VAULT_KEY}\nnot-a-key\n`,
2349
2386
  code: 1,
2350
2387
  vault: "✓",
2351
2388
  app: "✗",
2352
2389
  said: /✗ app key +not an app key/
2353
2390
  }
2354
2391
  ];
2355
- for (const { env, input, code, vault, app, said } of runs) {
2356
- const run = await cli.run(["verify", "keys"], env, input);
2392
+ for (const { args, input, code, vault, app, said } of runs) {
2393
+ const run = await cli.run([
2394
+ "verify",
2395
+ "keys",
2396
+ ...args
2397
+ ], {}, input);
2357
2398
  const seen = marks(run.output);
2358
2399
  expect(run.code === code && seen["vault key"] === vault && seen["app key"] === app, `coffre verify keys exited ${run.code}`, run.output);
2359
2400
  if (said !== void 0) expect(said.test(run.output), "it did not say which key is not right", run.output);
@@ -2366,6 +2407,146 @@ async function verifyKeys(cli) {
2366
2407
  }
2367
2408
  return "this deployment's keys pass, vault ID included; a wrong vault key and a malformed app key are each named; no key shown";
2368
2409
  }
2410
+ /**
2411
+ * Everything the API does, the CLI does: with the admin's `coffre login`
2412
+ * session, a project and its environment, a secret set and renamed, a
2413
+ * service admitted and granted, a token issued into a 0600 file, then
2414
+ * piped to `coffre login --token` in a CLI of the service's own, read
2415
+ * with, revoked after its preview, and refused from then on; the grant
2416
+ * revoked, the secret and the project archived. No token shows in what
2417
+ * either prints.
2418
+ */
2419
+ async function manageByCli(cli) {
2420
+ const steps = [];
2421
+ const ci = new Cli(cli.origin);
2422
+ const as = (who, label) => async (args, input, code = 0) => {
2423
+ const run = await who.run(args, {}, input);
2424
+ expect(run.code === code, `coffre ${args.join(" ")}${label} exited ${run.code}, not ${code}`, run.output);
2425
+ steps.push(`${args.slice(0, 2).join(" ")}${label}`);
2426
+ return run.output;
2427
+ };
2428
+ const [coffre, service] = [as(cli, ""), as(ci, ", as the service")];
2429
+ try {
2430
+ const value = `cli-value-${randomBytes(8).toString("hex")}`;
2431
+ await coffre([
2432
+ "projects",
2433
+ "create",
2434
+ "conformance-cli",
2435
+ "--name",
2436
+ "CLI"
2437
+ ]);
2438
+ await coffre([
2439
+ "environments",
2440
+ "create",
2441
+ "conformance-cli/ci"
2442
+ ]);
2443
+ await coffre(["set", "conformance-cli/ci/API_KEY"], value);
2444
+ await coffre([
2445
+ "rename",
2446
+ "conformance-cli/ci/API_KEY",
2447
+ "API_TOKEN"
2448
+ ]);
2449
+ const refused = await coffre([
2450
+ "grant",
2451
+ "conformance-cli",
2452
+ "conformance-deploy",
2453
+ "--role",
2454
+ "viewer",
2455
+ "--env",
2456
+ "ci",
2457
+ "--service"
2458
+ ], void 0, 1);
2459
+ expect(refused.includes("admit them first, `coffre admit conformance-deploy --service`"), "grant to a service not yet admitted did not say to admit it", refused);
2460
+ const admitted = await coffre([
2461
+ "admit",
2462
+ "conformance-deploy",
2463
+ "--service"
2464
+ ]);
2465
+ expect(admitted.includes("next: coffre grant <project> conformance-deploy"), "admit --service did not say what comes next", admitted);
2466
+ await coffre([
2467
+ "grant",
2468
+ "conformance-cli",
2469
+ "conformance-deploy",
2470
+ "--role",
2471
+ "viewer",
2472
+ "--env",
2473
+ "ci",
2474
+ "--service"
2475
+ ]);
2476
+ const file = join(cli.home, "ci-token");
2477
+ const wrote = await coffre([
2478
+ "tokens",
2479
+ "issue",
2480
+ "conformance-deploy",
2481
+ "--label",
2482
+ "conformance",
2483
+ "--expires-in",
2484
+ "1",
2485
+ "--output-file",
2486
+ file
2487
+ ]);
2488
+ const token = readFileSync(file, "utf8").trim();
2489
+ expect(/^coffre_svc_/.test(token) && (statSync(file).mode & 511) === 384, "the token file is not a 0600 file holding a service token", statSync(file).mode);
2490
+ expect(!wrote.includes(token), "tokens issue --output-file printed the token");
2491
+ expect(!(await service([
2492
+ "login",
2493
+ cli.origin,
2494
+ "--token"
2495
+ ], `${token}\n`)).includes(token), "coffre login --token printed the token");
2496
+ const read = await service(["get", "conformance-cli/ci/API_TOKEN"]);
2497
+ expect(read.trim() === value, "the issued token did not read the renamed secret", read);
2498
+ const [listed] = JSON.parse(await coffre([
2499
+ "tokens",
2500
+ "conformance-deploy",
2501
+ "--json"
2502
+ ]));
2503
+ expect(listed?.label === "conformance", "tokens --json does not list the issued token", listed);
2504
+ const preview = await coffre([
2505
+ "tokens",
2506
+ "revoke",
2507
+ "conformance-deploy",
2508
+ listed.id
2509
+ ]);
2510
+ expect(/Nothing changed\. Re-run with --apply/.test(preview), "tokens revoke without --apply did not preview", preview);
2511
+ await service(["get", "conformance-cli/ci/API_TOKEN"]);
2512
+ await coffre([
2513
+ "tokens",
2514
+ "revoke",
2515
+ "conformance-deploy",
2516
+ listed.id,
2517
+ "--apply"
2518
+ ]);
2519
+ const gone = await service(["get", "conformance-cli/ci/API_TOKEN"], void 0, 1);
2520
+ expect(/does not know this service token/.test(gone), "a revoked token was not refused plainly", gone);
2521
+ await coffre([
2522
+ "revoke",
2523
+ "conformance-cli",
2524
+ "conformance-deploy",
2525
+ "--env",
2526
+ "ci",
2527
+ "--service"
2528
+ ]);
2529
+ await coffre(["archive", "conformance-cli/ci/API_TOKEN"]);
2530
+ const keys = JSON.parse(await coffre([
2531
+ "list",
2532
+ "conformance-cli/ci",
2533
+ "--json"
2534
+ ]));
2535
+ expect(keys.length === 1 && keys[0].key === "API_TOKEN" && keys[0].archived, "the renamed secret is not listed, archived", keys);
2536
+ await coffre([
2537
+ "projects",
2538
+ "archive",
2539
+ "conformance-cli"
2540
+ ]);
2541
+ const projects = JSON.parse(await coffre(["projects", "--json"]));
2542
+ expect(projects.find(({ slug }) => slug === "conformance-cli")?.archivedAt !== null, "the project is not archived", projects);
2543
+ const sessions = JSON.parse(await coffre(["sessions", "--json"]));
2544
+ expect(sessions.some(({ kind, current }) => kind === "cli" && current), "sessions --json does not mark this CLI's session", sessions);
2545
+ return `${steps.length} commands: ${[...new Set(steps)].join(", ")}; the token only in its 0600 file and piped to login, refused once revoked`;
2546
+ } finally {
2547
+ ci.remove();
2548
+ }
2549
+ }
2369
2550
  //#endregion
2370
2551
  //#region src/chrome.ts
2371
2552
  const NAMES = [
@@ -2560,6 +2741,60 @@ async function pagesInBrowser(deployment, admin, browser) {
2560
2741
  }
2561
2742
  return `${PAGES.map(([path]) => path).join(", ")}, signed in, in Chrome: each rendered, no error from their scripts`;
2562
2743
  }
2744
+ /** What only server code carries. */
2745
+ const MARKERS = [
2746
+ {
2747
+ label: "drizzle-orm",
2748
+ pattern: /drizzle:[A-Z]/
2749
+ },
2750
+ ...[
2751
+ "audit_chain_head",
2752
+ "audit_log",
2753
+ "consumed_tokens",
2754
+ "device_authorizations",
2755
+ "secret_versions",
2756
+ "service_bindings",
2757
+ "vault_grants",
2758
+ "vault_members"
2759
+ ].map((name) => ({
2760
+ label: `the table ${name}`,
2761
+ pattern: new RegExp(`\\b${name}\\b`)
2762
+ })),
2763
+ {
2764
+ label: "pg",
2765
+ pattern: /cloudflare:sockets|pg-protocol|pgpass/
2766
+ },
2767
+ {
2768
+ label: "libsql",
2769
+ pattern: /@libsql|libsql/
2770
+ },
2771
+ {
2772
+ label: "a COFFRE_ variable read",
2773
+ pattern: /env\s*(\.|\[\s*['"`])COFFRE_/
2774
+ }
2775
+ ];
2776
+ /** Files the browser runs or reads as text, whatever their size or how the build emitted them. */
2777
+ const TEXT = /\.(m?js|css|html|json|svg|txt|wasm\.js)$/;
2778
+ /** What each file holds that only the server may: `<file>: <what>`. */
2779
+ function serverCodeIn(files) {
2780
+ return files.flatMap(({ name, code }) => MARKERS.filter(({ pattern }) => pattern.test(code)).map(({ label }) => `${name}: ${label}`));
2781
+ }
2782
+ /** The text files under `dir`, the browser's half of a build, each as the browser reads it. */
2783
+ function clientFiles(dir) {
2784
+ const files = [];
2785
+ const walk = (at) => {
2786
+ for (const entry of readdirSync(at, { withFileTypes: true })) {
2787
+ const path = join(at, entry.name);
2788
+ if (entry.isDirectory()) walk(path);
2789
+ else if (TEXT.test(entry.name)) files.push({
2790
+ name: relative(dir, path),
2791
+ code: new TextDecoder().decode(readFileSync(path))
2792
+ });
2793
+ }
2794
+ };
2795
+ walk(dir);
2796
+ return files;
2797
+ }
2563
2798
  //#endregion
2564
2799
  //#region src/checks/surface.ts
2565
2800
  async function health(deployment) {
@@ -2576,6 +2811,82 @@ async function health(deployment) {
2576
2811
  expect(ready.checkpointed === true, "/readyz passed without a checkpoint covering the heartbeat", ready);
2577
2812
  return deployment.beforeFirstBeat ? "/livez, and /readyz only once the heartbeat ran and was checkpointed" : "/livez and /readyz";
2578
2813
  }
2814
+ /** The headers coffre sets on everything it answers, but the policy, whose nonce is each response's own. */
2815
+ const SECURED = {
2816
+ "x-frame-options": "DENY",
2817
+ "x-content-type-options": "nosniff",
2818
+ "referrer-policy": "same-origin",
2819
+ "cross-origin-opener-policy": "same-origin",
2820
+ "cross-origin-resource-policy": "same-origin"
2821
+ };
2822
+ /**
2823
+ * coffre's security headers on every kind of response the app gives, each
2824
+ * with a policy whose nonce is its own: pages, signed out and signed in, a
2825
+ * page's redirect to sign in, a page not found, the API's answers and its
2826
+ * refusals, a refusal of a body it never reads, sign-in's redirect to the
2827
+ * provider, and health. What answers each, Start's render or one of coffre's
2828
+ * server routes, all go through coffre's middleware; one it missed would
2829
+ * lack them.
2830
+ */
2831
+ async function headers(deployment, admin) {
2832
+ const anonymous = (path, init = {}) => fetch(`${deployment.origin}${path}`, {
2833
+ redirect: "manual",
2834
+ ...init
2835
+ });
2836
+ const kinds = [
2837
+ ["the sign-in page", () => anonymous("/login")],
2838
+ ["a signed-in page", () => admin.browser.fetch("/projects")],
2839
+ ["a page's redirect to sign in", () => anonymous("/projects")],
2840
+ ["a page not found", () => anonymous("/no-such-page")],
2841
+ ["an API read", () => admin.browser.fetch("/api/me")],
2842
+ ["an API refusal", () => anonymous("/api/me")],
2843
+ ["a path under /api that is not one", () => anonymous("/api/no-such-thing")],
2844
+ ["a refused method, its body unread", () => anonymous("/livez", {
2845
+ method: "POST",
2846
+ body: "x".repeat(65536)
2847
+ })],
2848
+ ["sign-in's redirect to the provider", () => anonymous("/auth/signin/github")],
2849
+ ["a path under /auth that is not one", () => anonymous("/auth/no-such-step")],
2850
+ ["/livez", () => anonymous("/livez")],
2851
+ ["/readyz", () => anonymous("/readyz")]
2852
+ ];
2853
+ const nonces = /* @__PURE__ */ new Set();
2854
+ for (const [kind, request] of kinds) {
2855
+ const response = await request();
2856
+ await response.body?.cancel();
2857
+ const seen = Object.fromEntries(response.headers);
2858
+ 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);
2859
+ expect(response.headers.has("cache-control"), `${kind} (${response.status}) has no cache-control`, seen);
2860
+ const nonce = /script-src 'self' 'nonce-([^']+)'/.exec(response.headers.get("content-security-policy") ?? "")?.[1];
2861
+ expect(nonce !== void 0, `${kind} (${response.status}) has no nonce-based Content-Security-Policy`, seen);
2862
+ expect(!nonces.has(nonce), `${kind} (${response.status}) has the nonce of an earlier response`, seen);
2863
+ nonces.add(nonce);
2864
+ }
2865
+ if (deployment.kind === "node") {
2866
+ const asset = clientFiles(deployment.clientDir).find(({ name }) => name.startsWith("_coffre/assets/") && name.endsWith(".js"));
2867
+ expect(asset !== void 0, "the build has no script under _coffre/assets/");
2868
+ const response = await anonymous(`/${asset.name}`);
2869
+ await response.body?.cancel();
2870
+ const seen = Object.fromEntries(response.headers);
2871
+ expect(response.status === 200, `the static file /${asset.name} answered ${response.status}`, seen);
2872
+ expect(response.headers.get("cache-control") === "public, max-age=31536000, immutable", `/${asset.name} is not kept for good`, seen);
2873
+ expect(response.headers.get("x-content-type-options") === "nosniff", `/${asset.name} lacks nosniff`, seen);
2874
+ expect(response.headers.get("cross-origin-resource-policy") === "same-origin", `/${asset.name} lacks a same-origin CORP`, seen);
2875
+ }
2876
+ 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" : ""}`;
2877
+ }
2878
+ /**
2879
+ * Nothing of the server in what the browser loads: the database layer, a
2880
+ * driver, a table only the server knows, a `COFFRE_*` read. Read from the
2881
+ * client files the app's own build wrote, as the browser gets them.
2882
+ */
2883
+ async function browserBundle(deployment) {
2884
+ const files = clientFiles(deployment.clientDir);
2885
+ expect(files.length > 0, `no client files in ${deployment.clientDir}`);
2886
+ const found = serverCodeIn(files);
2887
+ expect(found.length === 0, "what the browser loads holds server code: a page imports something of the server", found.join("\n"));
2888
+ return `${files.length} files the browser loads, none with server code in it`;
2889
+ }
2579
2890
  //#endregion
2580
2891
  //#region src/checks/workloads.ts
2581
2892
  /** The service the runs sign in as: a viewer on dev. */
@@ -2748,38 +3059,47 @@ async function runsRefused(deployment, admin) {
2748
3059
  return `${cases.length + 1} refused, each for its reason, none saying what the binding expects, none logged: ${cases.map(([what]) => what).join(", ")}, for another service`;
2749
3060
  }
2750
3061
  /**
2751
- * The CLI, as a CI job runs it: on GitHub Actions, with the runner's
2752
- * token endpoint and nothing else; elsewhere, with the token in
2753
- * COFFRE_ID_TOKEN. It keeps the credential in memory, and prints neither.
3062
+ * The CLI, as a CI job runs it, as a service by its ID token: on GitHub
3063
+ * Actions, `--service` and the runner's token endpoint, nothing else and
3064
+ * nothing kept; elsewhere, the token piped to `coffre login --service
3065
+ * --id-token`, whose credential the next command uses. No token printed.
2754
3066
  */
2755
3067
  async function cliSignsIn(deployment, canaries) {
2756
3068
  const issuer = deployment.idp.workloads;
2757
3069
  const cli = new Cli(deployment.origin);
2758
3070
  try {
2759
- const base = {
2760
- COFFRE_API_URL: deployment.origin,
2761
- COFFRE_SERVICE: RUNNER
2762
- };
2763
- const given = await mint(deployment);
2764
- const runs = {
2765
- "on GitHub Actions": {
2766
- ...base,
2767
- ACTIONS_ID_TOKEN_REQUEST_URL: issuer.requestUrl,
2768
- ACTIONS_ID_TOKEN_REQUEST_TOKEN: issuer.requestToken
2769
- },
2770
- "with COFFRE_ID_TOKEN": {
2771
- ...base,
2772
- COFFRE_ID_TOKEN: given
2773
- }
2774
- };
2775
- for (const [where, env] of Object.entries(runs)) {
2776
- const run = await cli.run(["get", `${DEV}/API_KEY`], env);
3071
+ const read = async (where, args, env, secrets) => {
3072
+ const run = await cli.run([
3073
+ ...args,
3074
+ "get",
3075
+ `${DEV}/API_KEY`
3076
+ ], env);
2777
3077
  expect(run.code === 0, `coffre get ${where} exited ${run.code}`, run.output);
2778
3078
  expect(run.output.trim() === canaries[`${DEV}/API_KEY`], `coffre get ${where} did not print the value`);
2779
- expect(!run.output.includes(given) && !run.output.includes(issuer.requestToken) && !/coffre_svc_/.test(run.output), `coffre get ${where} printed a token`);
2780
- }
2781
- expect(!existsSync(join(cli.home, ".coffre", "credentials.json")), "the CLI kept a credential on disk");
2782
- return `\`coffre get\` as ${RUNNER}, on GitHub Actions and with COFFRE_ID_TOKEN; no token printed, nothing written`;
3079
+ expect(!secrets.some((secret) => run.output.includes(secret)) && !/coffre_svc_/.test(run.output), `coffre get ${where} printed a token`);
3080
+ };
3081
+ await read("on GitHub Actions", [
3082
+ "--url",
3083
+ deployment.origin,
3084
+ "--service",
3085
+ RUNNER
3086
+ ], {
3087
+ ACTIONS_ID_TOKEN_REQUEST_URL: issuer.requestUrl,
3088
+ ACTIONS_ID_TOKEN_REQUEST_TOKEN: issuer.requestToken
3089
+ }, [issuer.requestToken]);
3090
+ expect(!existsSync(join(cli.home, ".coffre", "credentials.json")), "the CLI kept a credential on disk, for one command");
3091
+ const given = await mint(deployment);
3092
+ const login = await cli.run([
3093
+ "login",
3094
+ deployment.origin,
3095
+ "--service",
3096
+ RUNNER,
3097
+ "--id-token"
3098
+ ], {}, `${given}\n`);
3099
+ expect(login.code === 0, `coffre login --service --id-token exited ${login.code}`, login.output);
3100
+ expect(!login.output.includes(given) && !/coffre_svc_/.test(login.output), "coffre login --service printed a token");
3101
+ await read("after coffre login --service --id-token", [], {}, [given]);
3102
+ return `\`coffre --service ${RUNNER} get\` on GitHub Actions, nothing kept; \`coffre login --service --id-token\` with the token piped in, then \`coffre get\`; no token printed`;
2783
3103
  } finally {
2784
3104
  cli.remove();
2785
3105
  }
@@ -2827,8 +3147,10 @@ async function tokensUnlogged(deployment) {
2827
3147
  async function conform(deployment, options) {
2828
3148
  const report = new Report();
2829
3149
  await report.check("health", {}, () => health(deployment));
3150
+ await report.check("browser bundle", {}, () => browserBundle(deployment));
2830
3151
  const admin = await report.check("sign-in", {}, () => signInAdmin(deployment));
2831
3152
  await report.check("page load", { admin }, ({ admin }) => pageLoad(admin));
3153
+ await report.check("security headers", { admin }, ({ admin }) => headers(deployment, admin));
2832
3154
  const canaries = await report.check("setup", { admin }, ({ admin }) => setUp(admin));
2833
3155
  await report.check("pages in a browser", {
2834
3156
  admin,
@@ -2887,6 +3209,7 @@ async function conform(deployment, options) {
2887
3209
  live
2888
3210
  }, ({ admin, owner, before, first, second, live }) => verifyLeftovers(owner, admin, [first, second], before, live.canary));
2889
3211
  await report.check("verify keys", { owner }, ({ owner }) => verifyKeys(owner));
3212
+ await report.check("manage by CLI", { owner }, ({ owner }) => manageByCli(owner));
2890
3213
  } finally {
2891
3214
  for (const cli of clis) cli.remove();
2892
3215
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coffre/conformance",
3
- "version": "0.1.18",
3
+ "version": "0.3.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/cli": "0.1.18",
35
- "@coffre/db": "0.1.18"
34
+ "@coffre/cli": "0.3.0",
35
+ "@coffre/db": "0.3.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.18"
43
+ "vite": "8.1.5",
44
+ "@coffre/client": "0.3.0"
44
45
  },
45
46
  "scripts": {
46
47
  "build": "tsdown",
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
+ }
package/src/checks/cli.ts CHANGED
@@ -1,12 +1,13 @@
1
1
  // `coffre verify`, as an operator runs it against this deployment: the
2
2
  // CLI's own entry, as @coffre/cli ships it, in a child process with a home
3
3
  // of its own and none of this process's COFFRE_ variables. `verify
4
- // instance` with a token from CI; signed in with `coffre login`, as a user,
4
+ // instance` with a token from CI, signed in with `coffre login --token`; with `coffre login`, as a user,
5
5
  // who is turned away, and as the admin, twice, then interrupted, its
6
6
  // session left signed in each time; and `verify keys` with this
7
7
  // deployment's keys, a wrong one and a malformed one.
8
8
  import { spawn } from 'node:child_process';
9
- import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
9
+ import { randomBytes } from 'node:crypto';
10
+ import { existsSync, mkdtempSync, readFileSync, rmSync, statSync } from 'node:fs';
10
11
  import { createRequire } from 'node:module';
11
12
  import { tmpdir } from 'node:os';
12
13
  import { dirname, join } from 'node:path';
@@ -117,10 +118,10 @@ function marks(output: string): Record<string, string> {
117
118
  /** The token's run, from CI: as no one, then as the token, which is no owner and skips verification. */
118
119
  export async function verifyWithToken(cli: Cli, live: { token: string; canary: Canary }): Promise<string> {
119
120
  const { canary } = live;
120
- const run = await cli.run(['verify', 'instance', cli.origin, '--canary', `${canary.project}/${canary.environment}/${canary.key}`], {
121
- COFFRE_TOKEN: live.token,
122
- COFFRE_CONFORMANCE_CANARY: canary.value,
123
- });
121
+ // As a CI step does: the token piped to `coffre login --token`, then the canary's value to the check.
122
+ const login = await cli.run(['login', cli.origin, '--token'], {}, `${live.token}\n`);
123
+ expect(login.code === 0, `coffre login --token exited ${login.code}`, login.output);
124
+ const run = await cli.run(['verify', 'instance', cli.origin, '--canary', `${canary.project}/${canary.environment}/${canary.key}`], {}, `${canary.value}\n`);
124
125
  const seen = marks(run.output);
125
126
  expect(run.code === 0, `coffre verify instance with a token exited ${run.code}`, run.output);
126
127
  expect(seen['token verification'] === '–', 'a token that is no owner did not skip verification', run.output);
@@ -219,19 +220,20 @@ export async function verifyLeftovers(cli: Cli, admin: Person, setups: string[],
219
220
  }
220
221
 
221
222
  /**
222
- * `coffre verify keys`, with the admin's session: this deployment's keys
223
- * pass, from the environment; a wrong vault key fails and the right app key
224
- * passes, from stdin; a malformed app key fails. No key is ever printed.
223
+ * `coffre verify keys`, with the admin's session, the keys piped in: this
224
+ * deployment's pass; a wrong vault key fails and the right app key passes;
225
+ * a malformed app key fails. No key is ever printed.
225
226
  */
226
227
  export async function verifyKeys(cli: Cli): Promise<string> {
227
228
  const wrong = Buffer.alloc(32, 7).toString('base64');
228
- const runs: { env?: Record<string, string>; input?: string; code: number; vault: string; app: string; said?: RegExp }[] = [
229
- { env: { COFFRE_VAULT_KEY: KEYS.VAULT_KEY, COFFRE_APP_KEY: KEYS.APP_KEY, COFFRE_VAULT_KEY_ID: KEYS.VAULT_KEY_ID }, code: 0, vault: '✓', app: '✓' },
230
- { input: `${wrong}\n${KEYS.APP_KEY}\n`, code: 1, vault: '✗', app: '✓', said: /✗ vault key +not this instance's vault key/ },
231
- { env: { COFFRE_VAULT_KEY: KEYS.VAULT_KEY, COFFRE_APP_KEY: 'not-a-key' }, code: 1, vault: '✓', app: '✗', said: /✗ app key +not an app key/ },
229
+ // Piped in, as a script does: the vault key's line, then the app key's.
230
+ const runs: { args: string[]; input: string; code: number; vault: string; app: string; said?: RegExp }[] = [
231
+ { args: ['--vault-id', KEYS.VAULT_KEY_ID], input: `${KEYS.VAULT_KEY}\n${KEYS.APP_KEY}\n`, code: 0, vault: '✓', app: '✓' },
232
+ { args: [], input: `${wrong}\n${KEYS.APP_KEY}\n`, code: 1, vault: '✗', app: '✓', said: /✗ vault key +not this instance's vault key/ },
233
+ { args: [], input: `${KEYS.VAULT_KEY}\nnot-a-key\n`, code: 1, vault: '✓', app: '✗', said: /✗ app key +not an app key/ },
232
234
  ];
233
- for (const { env, input, code, vault, app, said } of runs) {
234
- const run = await cli.run(['verify', 'keys'], env, input);
235
+ for (const { args, input, code, vault, app, said } of runs) {
236
+ const run = await cli.run(['verify', 'keys', ...args], {}, input);
235
237
  const seen = marks(run.output);
236
238
  expect(run.code === code && seen['vault key'] === vault && seen['app key'] === app, `coffre verify keys exited ${run.code}`, run.output);
237
239
  if (said !== undefined) expect(said.test(run.output), 'it did not say which key is not right', run.output);
@@ -239,3 +241,69 @@ export async function verifyKeys(cli: Cli): Promise<string> {
239
241
  }
240
242
  return "this deployment's keys pass, vault ID included; a wrong vault key and a malformed app key are each named; no key shown";
241
243
  }
244
+
245
+ /**
246
+ * Everything the API does, the CLI does: with the admin's `coffre login`
247
+ * session, a project and its environment, a secret set and renamed, a
248
+ * service admitted and granted, a token issued into a 0600 file, then
249
+ * piped to `coffre login --token` in a CLI of the service's own, read
250
+ * with, revoked after its preview, and refused from then on; the grant
251
+ * revoked, the secret and the project archived. No token shows in what
252
+ * either prints.
253
+ */
254
+ export async function manageByCli(cli: Cli): Promise<string> {
255
+ const steps: string[] = [];
256
+ const ci = new Cli(cli.origin);
257
+ const as = (who: Cli, label: string) => async (args: string[], input?: string, code = 0): Promise<string> => {
258
+ const run = await who.run(args, {}, input);
259
+ expect(run.code === code, `coffre ${args.join(' ')}${label} exited ${run.code}, not ${code}`, run.output);
260
+ steps.push(`${args.slice(0, 2).join(' ')}${label}`);
261
+ return run.output;
262
+ };
263
+ const [coffre, service] = [as(cli, ''), as(ci, ', as the service')];
264
+ try {
265
+ const value = `cli-value-${randomBytes(8).toString('hex')}`;
266
+ await coffre(['projects', 'create', 'conformance-cli', '--name', 'CLI']);
267
+ await coffre(['environments', 'create', 'conformance-cli/ci']);
268
+ await coffre(['set', 'conformance-cli/ci/API_KEY'], value);
269
+ await coffre(['rename', 'conformance-cli/ci/API_KEY', 'API_TOKEN']);
270
+ const refused = await coffre(['grant', 'conformance-cli', 'conformance-deploy', '--role', 'viewer', '--env', 'ci', '--service'], undefined, 1);
271
+ expect(refused.includes('admit them first, `coffre admit conformance-deploy --service`'), 'grant to a service not yet admitted did not say to admit it', refused);
272
+ const admitted = await coffre(['admit', 'conformance-deploy', '--service']);
273
+ expect(admitted.includes('next: coffre grant <project> conformance-deploy'), 'admit --service did not say what comes next', admitted);
274
+ await coffre(['grant', 'conformance-cli', 'conformance-deploy', '--role', 'viewer', '--env', 'ci', '--service']);
275
+
276
+ const file = join(cli.home, 'ci-token');
277
+ const wrote = await coffre(['tokens', 'issue', 'conformance-deploy', '--label', 'conformance', '--expires-in', '1', '--output-file', file]);
278
+ const token = readFileSync(file, 'utf8').trim();
279
+ expect(/^coffre_svc_/.test(token) && (statSync(file).mode & 0o777) === 0o600, 'the token file is not a 0600 file holding a service token', statSync(file).mode);
280
+ expect(!wrote.includes(token), 'tokens issue --output-file printed the token');
281
+ // The token as CI uses it: piped to `coffre login --token`.
282
+ const signedIn = await service(['login', cli.origin, '--token'], `${token}\n`);
283
+ expect(!signedIn.includes(token), 'coffre login --token printed the token');
284
+ const read = await service(['get', 'conformance-cli/ci/API_TOKEN']);
285
+ expect(read.trim() === value, 'the issued token did not read the renamed secret', read);
286
+
287
+ const [listed] = JSON.parse(await coffre(['tokens', 'conformance-deploy', '--json'])) as { id: string; label: string }[];
288
+ expect(listed?.label === 'conformance', 'tokens --json does not list the issued token', listed);
289
+ const preview = await coffre(['tokens', 'revoke', 'conformance-deploy', listed!.id]);
290
+ expect(/Nothing changed\. Re-run with --apply/.test(preview), 'tokens revoke without --apply did not preview', preview);
291
+ await service(['get', 'conformance-cli/ci/API_TOKEN']);
292
+ await coffre(['tokens', 'revoke', 'conformance-deploy', listed!.id, '--apply']);
293
+ const gone = await service(['get', 'conformance-cli/ci/API_TOKEN'], undefined, 1);
294
+ expect(/does not know this service token/.test(gone), 'a revoked token was not refused plainly', gone);
295
+
296
+ await coffre(['revoke', 'conformance-cli', 'conformance-deploy', '--env', 'ci', '--service']);
297
+ await coffre(['archive', 'conformance-cli/ci/API_TOKEN']);
298
+ const keys = JSON.parse(await coffre(['list', 'conformance-cli/ci', '--json'])) as { key: string; archived: boolean }[];
299
+ expect(keys.length === 1 && keys[0]!.key === 'API_TOKEN' && keys[0]!.archived, 'the renamed secret is not listed, archived', keys);
300
+ await coffre(['projects', 'archive', 'conformance-cli']);
301
+ const projects = JSON.parse(await coffre(['projects', '--json'])) as { slug: string; archivedAt: string | null }[];
302
+ expect(projects.find(({ slug }) => slug === 'conformance-cli')?.archivedAt !== null, 'the project is not archived', projects);
303
+ const sessions = JSON.parse(await coffre(['sessions', '--json'])) as { kind: string; current: boolean }[];
304
+ expect(sessions.some(({ kind, current }) => kind === 'cli' && current), "sessions --json does not mark this CLI's session", sessions);
305
+ return `${steps.length} commands: ${[...new Set(steps)].join(', ')}; the token only in its 0600 file and piped to login, refused once revoked`;
306
+ } finally {
307
+ ci.remove();
308
+ }
309
+ }
@@ -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
+ }
@@ -149,28 +149,30 @@ export async function runsRefused(deployment: Deployment, admin: Person): Promis
149
149
  }
150
150
 
151
151
  /**
152
- * The CLI, as a CI job runs it: on GitHub Actions, with the runner's
153
- * token endpoint and nothing else; elsewhere, with the token in
154
- * COFFRE_ID_TOKEN. It keeps the credential in memory, and prints neither.
152
+ * The CLI, as a CI job runs it, as a service by its ID token: on GitHub
153
+ * Actions, `--service` and the runner's token endpoint, nothing else and
154
+ * nothing kept; elsewhere, the token piped to `coffre login --service
155
+ * --id-token`, whose credential the next command uses. No token printed.
155
156
  */
156
157
  export async function cliSignsIn(deployment: Deployment, canaries: Canaries): Promise<string> {
157
158
  const issuer = deployment.idp.workloads;
158
159
  const cli = new Cli(deployment.origin);
159
160
  try {
160
- const base = { COFFRE_API_URL: deployment.origin, COFFRE_SERVICE: RUNNER };
161
- const given = await mint(deployment);
162
- const runs = {
163
- 'on GitHub Actions': { ...base, ACTIONS_ID_TOKEN_REQUEST_URL: issuer.requestUrl, ACTIONS_ID_TOKEN_REQUEST_TOKEN: issuer.requestToken },
164
- 'with COFFRE_ID_TOKEN': { ...base, COFFRE_ID_TOKEN: given },
165
- };
166
- for (const [where, env] of Object.entries(runs)) {
167
- const run = await cli.run(['get', `${DEV}/API_KEY`], env);
161
+ const read = async (where: string, args: string[], env: Record<string, string>, secrets: string[]) => {
162
+ const run = await cli.run([...args, 'get', `${DEV}/API_KEY`], env);
168
163
  expect(run.code === 0, `coffre get ${where} exited ${run.code}`, run.output);
169
164
  expect(run.output.trim() === canaries[`${DEV}/API_KEY`], `coffre get ${where} did not print the value`);
170
- expect(!run.output.includes(given) && !run.output.includes(issuer.requestToken) && !/coffre_svc_/.test(run.output), `coffre get ${where} printed a token`);
171
- }
172
- expect(!existsSync(join(cli.home, '.coffre', 'credentials.json')), 'the CLI kept a credential on disk');
173
- return `\`coffre get\` as ${RUNNER}, on GitHub Actions and with COFFRE_ID_TOKEN; no token printed, nothing written`;
165
+ expect(!secrets.some((secret) => run.output.includes(secret)) && !/coffre_svc_/.test(run.output), `coffre get ${where} printed a token`);
166
+ };
167
+ await read('on GitHub Actions', ['--url', deployment.origin, '--service', RUNNER], { ACTIONS_ID_TOKEN_REQUEST_URL: issuer.requestUrl, ACTIONS_ID_TOKEN_REQUEST_TOKEN: issuer.requestToken }, [issuer.requestToken]);
168
+ expect(!existsSync(join(cli.home, '.coffre', 'credentials.json')), 'the CLI kept a credential on disk, for one command');
169
+
170
+ const given = await mint(deployment);
171
+ const login = await cli.run(['login', deployment.origin, '--service', RUNNER, '--id-token'], {}, `${given}\n`);
172
+ expect(login.code === 0, `coffre login --service --id-token exited ${login.code}`, login.output);
173
+ expect(!login.output.includes(given) && !/coffre_svc_/.test(login.output), 'coffre login --service printed a token');
174
+ await read('after coffre login --service --id-token', [], {}, [given]);
175
+ return `\`coffre --service ${RUNNER} get\` on GitHub Actions, nothing kept; \`coffre login --service --id-token\` with the token piped in, then \`coffre get\`; no token printed`;
174
176
  } finally {
175
177
  cli.remove();
176
178
  }
@@ -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>;
@@ -107,14 +110,18 @@ export async function boot(kind: Kind, at: string, options: HarnessOptions): Pro
107
110
  const logs = () => output(4000);
108
111
  const alive = () => !children.some((entry) => entry.daemon && entry.exited);
109
112
 
110
- function start(name: string, command: string, args: string[], env: Record<string, string>, daemon = true): Child {
113
+ function start(name: string, command: string, args: string[], env: Record<string, string>, daemon = true, input?: string): Child {
111
114
  const child = spawn(command, args, {
112
115
  cwd: dir,
113
116
  env: { ...shell, ...env },
114
117
  // Its own process group, so stopping it stops what it started (workerd).
115
118
  detached: true,
116
- stdio: ['ignore', 'pipe', 'pipe'],
119
+ stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'],
117
120
  });
121
+ if (input !== undefined) {
122
+ child.stdin!.on('error', () => {});
123
+ child.stdin!.end(input);
124
+ }
118
125
  const entry: Child = { name, child, daemon, exited: false, output: [] };
119
126
  child.stdout!.on('data', (chunk: Buffer) => entry.output.push(chunk));
120
127
  child.stderr!.on('data', (chunk: Buffer) => entry.output.push(chunk));
@@ -128,8 +135,8 @@ export async function boot(kind: Kind, at: string, options: HarnessOptions): Pro
128
135
  return entry;
129
136
  }
130
137
 
131
- async function run(command: string, args: string[], env: Record<string, string> = {}): Promise<void> {
132
- const entry = start(args[0] ?? command, command, args, env, false);
138
+ async function run(command: string, args: string[], env: Record<string, string> = {}, input?: string): Promise<void> {
139
+ const entry = start(args[0] ?? command, command, args, env, false, input);
133
140
  const code = await new Promise((done) => {
134
141
  entry.child.once('exit', done);
135
142
  entry.child.once('error', done);
@@ -195,13 +202,15 @@ export async function boot(kind: Kind, at: string, options: HarnessOptions): Pro
195
202
  sql.exec(`DROP DATABASE IF EXISTS ${name} WITH (FORCE)`),
196
203
  );
197
204
  // As the deployment's pipeline does before it deploys: its own CLI's
198
- // `coffre migrate`, in its folder, the owner's URL in its environment.
205
+ // `coffre migrate`, in its folder, the owner's URL piped in.
199
206
  // A fresh log has no heartbeat: only the scheduled job can make /readyz pass.
200
- await run(process.execPath, [deploymentCli(dir), 'migrate', '--yes'], { COFFRE_MIGRATE_DATABASE_URL: owner });
207
+ await run(process.execPath, [deploymentCli(dir), 'migrate', '--yes'], {}, `${owner}\n`);
208
+ // The app as it deploys: its Start app, built by its own Vite, which wrangler runs unbundled.
209
+ await run(bin('vite'), ['build', 'app']);
201
210
  const state = join(scratch, 'state');
202
211
  start('wrangler', bin('wrangler'), [
203
212
  'dev',
204
- ...['-c', 'app/wrangler.jsonc', '-c', 'vault/wrangler.jsonc'],
213
+ ...['-c', drainingConfig(join(dir, 'app/dist/server')), '-c', 'vault/wrangler.jsonc'],
205
214
  ...['--ip', '127.0.0.1', '--port', String(port), '--inspector-port', String(port + 2)],
206
215
  ...['--persist-to', state, '--show-interactive-dev-session=false'],
207
216
  // Not in wrangler.jsonc's vars, so not taken from the environment.
@@ -236,6 +245,7 @@ export async function boot(kind: Kind, at: string, options: HarnessOptions): Pro
236
245
  runtime: () => postgres(runtime),
237
246
  vaultRuntime: () => postgres(vaultRuntime),
238
247
  databaseFile: null,
248
+ clientDir: join(dir, 'app/dist/client'),
239
249
  output,
240
250
  stop,
241
251
  };
@@ -253,8 +263,11 @@ export async function boot(kind: Kind, at: string, options: HarnessOptions): Pro
253
263
  ROOT_ADMINS: ROOT_ADMIN,
254
264
  });
255
265
  await until('the vault socket', async () => existsSync(socket), 30, alive);
266
+ // The pages as they run: the deployment's Start app, built by its own Vite.
267
+ await run(bin('vite'), ['build', 'app']);
268
+ // As `pnpm start` runs it: the app's build, under srvx.
256
269
  const startServer = () =>
257
- start('server', process.execPath, ['src/server.ts'], {
270
+ start('server', bin('srvx'), ['--prod', '--host=127.0.0.1', 'app/dist/server/server.js'], {
258
271
  PORT: String(port),
259
272
  PUBLIC_URL: origin,
260
273
  DATABASE_URL: `file:${database}`,
@@ -284,6 +297,7 @@ export async function boot(kind: Kind, at: string, options: HarnessOptions): Pro
284
297
  runtime: null,
285
298
  vaultRuntime: null,
286
299
  databaseFile: database,
300
+ clientDir: join(dir, 'app/dist/client'),
287
301
  output,
288
302
  stop,
289
303
  };
@@ -16,8 +16,8 @@ import { readParams, sendJson, type Route } from './http.ts';
16
16
  * `permissions: id-token: write`, to the bearer of `requestToken`. Locally,
17
17
  * `POST /workloads/token` mints one, for trying the CLI by hand:
18
18
  *
19
- * COFFRE_ID_TOKEN=$(curl -s -X POST http://127.0.0.1:8081/workloads/token \
20
- * -d aud=http://127.0.0.1:3000 | jq -r .token)
19
+ * curl -s -X POST http://127.0.0.1:8081/workloads/token -d aud=http://127.0.0.1:3000 | jq -r .token |
20
+ * coffre login http://127.0.0.1:3000 --service <name> --id-token
21
21
  */
22
22
  export class WorkloadIssuer {
23
23
  readonly #origin: () => string;
package/src/suite.ts CHANGED
@@ -11,18 +11,20 @@ import { accessAuthorship, memberTampering, noAuditNoAccess, sealingRace } from
11
11
  import { refusedCheckpoint, missingCheckpoint, middleCut } from './checks/readiness.ts';
12
12
  import { editedGeneration, forgedCredential, forgedIdentity, forgedApproval } from './checks/signin.ts';
13
13
  import { canaryScan } from './checks/canaries.ts';
14
- import { Cli, cliLogin, verifyAsOwner, verifyAsUser, verifyInterrupted, verifyKeys, verifyLeftovers, verifyWithToken } from './checks/cli.ts';
14
+ import { Cli, cliLogin, manageByCli, verifyAsOwner, verifyAsUser, verifyInterrupted, verifyKeys, verifyLeftovers, verifyWithToken } from './checks/cli.ts';
15
15
  import { pageLoad, personas, setUp, setUpLive, signInAdmin } from './checks/people.ts';
16
16
  import { pagesInBrowser } from './checks/pages.ts';
17
- import { health } from './checks/surface.ts';
17
+ import { browserBundle, headers, health } from './checks/surface.ts';
18
18
  import { cliSignsIn, exchangesLimited, runSignsIn, runsRefused, runUnbound, spentOnce, tokensUnlogged, trustRun } from './checks/workloads.ts';
19
19
 
20
20
  /** The names of the checks that failed. */
21
21
  export async function conform(deployment: Deployment, options: { bulkLimit: number; browser: string | null }): Promise<string[]> {
22
22
  const report = new Report();
23
23
  await report.check('health', {}, () => health(deployment));
24
+ await report.check('browser bundle', {}, () => browserBundle(deployment));
24
25
  const admin = await report.check('sign-in', {}, () => signInAdmin(deployment));
25
26
  await report.check('page load', { admin }, ({ admin }) => pageLoad(admin));
27
+ await report.check('security headers', { admin }, ({ admin }) => headers(deployment, admin));
26
28
  const canaries = await report.check('setup', { admin }, ({ admin }) => setUp(admin));
27
29
  await report.check('pages in a browser', { admin, canaries }, ({ admin }) => pagesInBrowser(deployment, admin, options.browser));
28
30
  const people = await report.check('personas', { admin, canaries }, ({ admin }) => personas(deployment, admin));
@@ -50,6 +52,7 @@ export async function conform(deployment: Deployment, options: { bulkLimit: numb
50
52
  verifyLeftovers(owner, admin, [first, second], before, live.canary),
51
53
  );
52
54
  await report.check('verify keys', { owner }, ({ owner }) => verifyKeys(owner));
55
+ await report.check('manage by CLI', { owner }, ({ owner }) => manageByCli(owner));
53
56
  } finally {
54
57
  for (const cli of clis) cli.remove();
55
58
  }