@coffre/conformance 0.1.18 → 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 +180 -14
- package/package.json +5 -4
- package/src/bundle.ts +55 -0
- package/src/checks/surface.ts +79 -0
- package/src/draining.ts +44 -0
- package/src/harness.ts +15 -5
- package/src/suite.ts +3 -1
package/dist/main.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
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 { 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, 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`, ... */
|
|
@@ -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/
|
|
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
|
-
|
|
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
|
};
|
|
@@ -2560,6 +2594,60 @@ async function pagesInBrowser(deployment, admin, browser) {
|
|
|
2560
2594
|
}
|
|
2561
2595
|
return `${PAGES.map(([path]) => path).join(", ")}, signed in, in Chrome: each rendered, no error from their scripts`;
|
|
2562
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
|
+
}
|
|
2563
2651
|
//#endregion
|
|
2564
2652
|
//#region src/checks/surface.ts
|
|
2565
2653
|
async function health(deployment) {
|
|
@@ -2576,6 +2664,82 @@ async function health(deployment) {
|
|
|
2576
2664
|
expect(ready.checkpointed === true, "/readyz passed without a checkpoint covering the heartbeat", ready);
|
|
2577
2665
|
return deployment.beforeFirstBeat ? "/livez, and /readyz only once the heartbeat ran and was checkpointed" : "/livez and /readyz";
|
|
2578
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
|
+
}
|
|
2579
2743
|
//#endregion
|
|
2580
2744
|
//#region src/checks/workloads.ts
|
|
2581
2745
|
/** The service the runs sign in as: a viewer on dev. */
|
|
@@ -2827,8 +2991,10 @@ async function tokensUnlogged(deployment) {
|
|
|
2827
2991
|
async function conform(deployment, options) {
|
|
2828
2992
|
const report = new Report();
|
|
2829
2993
|
await report.check("health", {}, () => health(deployment));
|
|
2994
|
+
await report.check("browser bundle", {}, () => browserBundle(deployment));
|
|
2830
2995
|
const admin = await report.check("sign-in", {}, () => signInAdmin(deployment));
|
|
2831
2996
|
await report.check("page load", { admin }, ({ admin }) => pageLoad(admin));
|
|
2997
|
+
await report.check("security headers", { admin }, ({ admin }) => headers(deployment, admin));
|
|
2832
2998
|
const canaries = await report.check("setup", { admin }, ({ admin }) => setUp(admin));
|
|
2833
2999
|
await report.check("pages in a browser", {
|
|
2834
3000
|
admin,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@coffre/conformance",
|
|
3
|
-
"version": "0.
|
|
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/cli": "0.
|
|
35
|
-
"@coffre/db": "0.
|
|
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
|
-
"
|
|
43
|
+
"vite": "8.1.5",
|
|
44
|
+
"@coffre/client": "0.2.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/surface.ts
CHANGED
|
@@ -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/draining.ts
ADDED
|
@@ -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
|
|
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
|
|
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/
|
|
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',
|
|
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/suite.ts
CHANGED
|
@@ -14,15 +14,17 @@ 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
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));
|