@byollm/conformance 0.1.0-alpha.9 → 0.1.0-alpha.91

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/README.md CHANGED
@@ -1,5 +1,5 @@
1
1
  > [!WARNING]
2
- > **Alpha (`0.1.0-alpha.9`) — under active development. Don't use this yet.**
2
+ > **Alpha (`0.1.0-alpha.91`) — under active development. Don't use this yet.**
3
3
  >
4
4
  > Install it deliberately: `npm install @byollm/conformance@alpha`.
5
5
  >
@@ -11,7 +11,109 @@
11
11
  > npm assigns `latest` on a first publish and won't let it be removed, so a
12
12
  > bare install resolves here too. This notice is the only guard — deliberately
13
13
  > not an npm deprecation, which would read as *abandoned* rather than *early*.
14
- > Ask for `@alpha` explicitly so your lockfile records that you meant to.
14
+ > Ask for `@alpha` explicitly so your lockfile records that you meant to.>
15
+ > **`alpha.15` is a breaking wire change, and it breaks daemons and relays —
16
+ > not app authors.** If you call `app.enqueue(...)` and read results, nothing
17
+ > in your code changes. If you run a daemon or an upstream, every package must
18
+ > move together: a mixed pair refuses on both sides, because both ends parse
19
+ > `.strict()`.
20
+ >
21
+ > What moved, all of it reconciling the frozen `byollm_009` with its code:
22
+ > `JobStub` gains `site` (the site's identity key id) and loses
23
+ > `audienceAllow`; `ResultRequest` gains `leaseId`; `HeartbeatResponse` loses
24
+ > `leases`, which nothing read; `WireErrorCode` gains `not-ready`,
25
+ > `clock-skew` and `forbidden`, and `403` is `forbidden` rather than
26
+ > `unauthorized`. `RESULT_PROVENANCE` is superseded by
27
+ > `PROVENANCE_NAMES_DEVICE`. See `byollm_009` Amendment A.>
28
+ > **`alpha.16` is a breaking wire change — daemons and relays again, not app
29
+ > authors.** `app.enqueue(...)` and reading results are unchanged. All five
30
+ > packages move together: both ends parse `.strict()`, so a mixed pair
31
+ > refuses.
32
+ >
33
+ > What moved, all of it Tier 2 of `cloud_008`: `model`, `backendClass` and
34
+ > `durationMs` come off `ResultRequest` and are sealed **inside** the result
35
+ > envelope as `SealedOutcome = { outcome, ran }` — so a daemon can no longer
36
+ > declare a model it did not sign, and a relay carries neither.
37
+ > `HeartbeatResponse` loses `leases` (nothing read it) and now reports real
38
+ > cancellations instead of an empty list. `WireErrorCode` gains `forbidden`
39
+ > for 403, leaving `unauthorized` at exactly 401. The relay gained a
40
+ > site-plane `cancel` endpoint, honours `stub.deadlineAt`, honours
41
+ > `stub.audience`, and remembers a refusal.>
42
+ > **`alpha.17` is additive** — no wire change. It exports `ReleaseReason`,
43
+ > which `RoutingStore.releaseLeases` names and the package did not export, so
44
+ > the interface was unimplementable outside this repo.>
45
+ > **`alpha.18` is a breaking wire change — daemons and relays, not app
46
+ > authors.** `app.enqueue(...)` and reading results are unchanged. All five
47
+ > packages move together.
48
+ >
49
+ > The **bearer token is gone**: off `PairPollResponse`, off the runner row,
50
+ > off the daemon's pairings file, out of the adapter's schema. It was minted,
51
+ > hashed and stored on two disks and never sent, looked up or compared —
52
+ > `REQUESTS_SIGNED_NOT_BEARER` was enforced by signatures the whole time. If
53
+ > you run the Supabase adapter, apply
54
+ > `20260819000000_drop_runner_token.sql`; `byollm_approve_pairing` now takes
55
+ > one argument. A pairings file written by an older daemon still loads.
56
+ >
57
+ > `model`, `backendClass` and `durationMs` moved **inside** the sealed result
58
+ > (`SealedOutcome = { outcome, ran }`), so a daemon cannot declare a model it
59
+ > did not sign and a relay carries none of them. Writing a `RoutingStore`?
60
+ > `releaseLeases` takes an optional `reason` and `complete` requires
61
+ > `leaseId`, and **an implementation that ignores either still typechecks** —
62
+ > run the store contract tests.>
63
+ > **`alpha.19` is additive on the wire and a behaviour change in every
64
+ > store.** `ResultResponse` gains an optional `duplicate`. Nothing is removed,
65
+ > so an older daemon keeps working — but the *order* two rules are checked in
66
+ > has changed, and a `RoutingStore` implementation must change with it.
67
+ >
68
+ > `complete` now checks **terminal state before holder**, scoped to the device
69
+ > that finished the job: a replay from that device is answered `duplicate:
70
+ > true` with a 2xx, and anyone else gets exactly the refusal they would get
71
+ > for a job that is not terminal. Previously `RESULT_IDEMPOTENT` held only
72
+ > because the lease is nulled on success, so the holder check tripped first —
73
+ > deleting the idempotency branch failed no test. Run the store contract
74
+ > tests; the compiler cannot see this.
75
+
76
+ <!-- release-note 0.1.0-alpha.21 -->
77
+ > [!NOTE]
78
+ > **`0.1.0-alpha.20` is not a complete release — do not pin it.** Four
79
+ > packages published and `@byollm/server` did not: a Sigstore
80
+ > transparency-log 409 on its provenance attestation. The workflow's
81
+ > "already published" guard correctly refuses to resume a partial publish,
82
+ > so `0.1.0-alpha.21` is that release, whole.
83
+ >
84
+ > If you run the Supabase adapter, `alpha.21` needs
85
+ > `20260819010000_completed_by_lease_id.sql`: alpha.19 shipped §3.6's
86
+ > ordering without the column it stores the grant in.
87
+
88
+ <!-- release-note 0.1.0-alpha.40 -->
89
+ **`byollm start` — stop keeping a terminal open.** The daemon can now run
90
+ under your computer's own supervisor and restart itself if it stops: a launchd
91
+ agent on macOS, a `systemd --user` unit on Linux, a logon task on Windows. All
92
+ user-level — no root, no system directories, and `byollm stop` takes it
93
+ away. `byollm status` gained a line saying whether it is actually supervised
94
+ right now, including the state that matters most: installed but not running,
95
+ which looks fine from an app's dashboard and serves nothing.
96
+
97
+ If you are running via `npx`, install properly first (`npm install -g
98
+ byollm@latest`) — `install` refuses to supervise a copy in npx's cache, because
99
+ npm deletes that directory and the service would fail at some later boot.
100
+
101
+ <!-- release-note 0.1.0-alpha.41 -->
102
+ **`onNoRunner` takes a string.** Your fallback answer is your own value, not
103
+ wire data, and handing back a whole result record for it was ceremony — the
104
+ README's own example got the shape wrong, which is how this was found.
105
+
106
+ ```ts
107
+ const { outcome, fallback } = await job.result({
108
+ onNoRunner: () => runOnHostedModel(transcript),
109
+ });
110
+ ```
111
+
112
+ Whatever you return, `result()` labels it `fallback: true` — the stamp is
113
+ applied by the wait, not taken from you, so an answer that did not run on
114
+ somebody's device cannot be reported as though it did (`FALLBACK_LABELED`).
115
+ Both delivery channels do it, polling and Supabase Realtime. Records still
116
+ work; they just get labelled too.
15
117
 
16
118
  # `@byollm/conformance`
17
119
 
@@ -29,7 +131,7 @@ byollm conformance — my server
29
131
  ✓ C001_PAIRING_BINDS_ONE_USER a runner token is bound to exactly the approving user (279ms)
30
132
  ✓ C002_JOB_ROUND_TRIP an enqueued job runs on the owner's daemon and the result comes back (83ms)
31
133
 
32
- 16 checks passed — my server is byollm-compatible.
134
+ 32 checks passed — my server is byollm-compatible.
33
135
  ```
34
136
 
35
137
  ## What it actually does
@@ -79,7 +181,7 @@ Two optional hooks worth knowing about:
79
181
 
80
182
  - **`ownerId`** exists because owner ids are server-namespace-local. A target
81
183
  backed by real auth uses uuids, not names, and a kit that assumed names
82
- round-tripped would be assuming away the very thing the `named` allowlist is
184
+ round-tripped would be assuming away the very thing the `team` allowlist is
83
185
  about.
84
186
  - **`advanceTime`** lets an in-memory server run the lease and TTL checks in
85
187
  milliseconds. A real Postgres cannot fake its clock, so the kit waits for
@@ -95,7 +197,7 @@ Two optional hooks worth knowing about:
95
197
  | `C003_UNKNOWN_KIND_REFUSED` | a daemon is never handed a kind it did not advertise |
96
198
  | `C004_LEASE_RECLAIM` | a job whose runner vanished is offered again, losing nothing |
97
199
  | `C005_AUDIENCE_MATRIX` | all nine audience × offer-scope combinations |
98
- | `C006_NAMED_LOCAL_ALLOWLIST` | `named` runs only once the daemon's own list admits it |
200
+ | `C006_NAMED_LOCAL_ALLOWLIST` | `team` runs only once the daemon's own list admits it |
99
201
  | `C007_SUBSCRIPTION_SELF_LOCK` | a subscription backend refuses others' work at any scope |
100
202
  | `C008_REVOCATION` | a revoked daemon stops mid-queue |
101
203
  | `C009_CANCEL_MID_FLIGHT` | cancel aborts a running job's backend call |
@@ -115,3 +217,17 @@ the gap is **visible in the output** rather than implied away, and a newly
115
217
  added MUST shows up there until someone writes its check.
116
218
 
117
219
  MIT
220
+
221
+ <!-- family:start -->
222
+
223
+ ## The rest of byollm
224
+
225
+ Six packages, and they are only interesting together:
226
+
227
+ - [`byollm`](https://www.npmjs.com/package/byollm) — the daemon — runs models on your own machine and answers for it
228
+ - [`@byollm/protocol`](https://www.npmjs.com/package/@byollm/protocol) — the wire: envelopes, signatures and the closed vocabularies both ends validate against
229
+ - [`@byollm/server`](https://www.npmjs.com/package/@byollm/server) — the SDK a site uses to ask a device for work
230
+ - [`@byollm/relay`](https://www.npmjs.com/package/@byollm/relay) — the broker that holds jobs between a site and a device, and can read neither
231
+ - [`@byollm/control-plane`](https://www.npmjs.com/package/@byollm/control-plane) — who may ask whom, and the policy store behind it
232
+
233
+ <!-- family:end -->
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node
@@ -0,0 +1,25 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ auditDeployment,
4
+ formatPostureReport
5
+ } from "./chunk-2JXKI5TH.js";
6
+
7
+ // src/audit-cli.ts
8
+ var [url, basePath, originAddress] = process.argv.slice(2);
9
+ if (url === void 0) {
10
+ process.stderr.write(
11
+ "usage: byollm-audit-deployment <url> [base-path] [origin-address]\n e.g. byollm-audit-deployment https://hub.byollm.cloud\n"
12
+ );
13
+ process.exit(2);
14
+ }
15
+ var report = await auditDeployment({
16
+ url,
17
+ ...basePath === void 0 ? {} : { basePath },
18
+ // `D008` asks the origin directly. Without it that check says so rather
19
+ // than guessing an address and reporting a posture it never tested.
20
+ ...originAddress === void 0 ? {} : { originAddress }
21
+ });
22
+ process.stdout.write(`
23
+ ${formatPostureReport(report)}`);
24
+ process.exit(report.passed ? 0 : 1);
25
+ //# sourceMappingURL=audit-cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/audit-cli.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { auditDeployment, formatPostureReport } from \"./deployment.js\";\n\n/**\n * `byollm-audit-deployment <url>` — what a stranger can do to a running relay.\n *\n * Distinct from `byollm-certify`, which drives a real daemon against a target\n * that may be an in-process handler. This one has a URL and nothing else,\n * which is exactly what an attacker has, and it exists because eight\n * freeze-gate findings came from a suite in which nothing was ever a stranger.\n *\n * ```bash\n * npx byollm-audit-deployment https://hub.byollm.cloud\n * ```\n *\n * Safe to run against production: nothing writes, nothing floods, and every\n * request is one an ordinary scanner would make.\n */\nconst [url, basePath, originAddress] = process.argv.slice(2);\n\nif (url === undefined) {\n process.stderr.write(\n \"usage: byollm-audit-deployment <url> [base-path] [origin-address]\\n\" +\n \" e.g. byollm-audit-deployment https://hub.byollm.cloud\\n\",\n );\n process.exit(2);\n}\n\nconst report = await auditDeployment({\n url,\n ...(basePath === undefined ? {} : { basePath }),\n // `D008` asks the origin directly. Without it that check says so rather\n // than guessing an address and reporting a posture it never tested.\n ...(originAddress === undefined ? {} : { originAddress }),\n});\nprocess.stdout.write(`\\n${formatPostureReport(report)}`);\nprocess.exit(report.passed ? 0 : 1);\n"],"mappings":";;;;;;;AAkBA,IAAM,CAAC,KAAK,UAAU,aAAa,IAAI,QAAQ,KAAK,MAAM,CAAC;AAE3D,IAAI,QAAQ,QAAW;AACrB,UAAQ,OAAO;AAAA,IACb;AAAA,EAEF;AACA,UAAQ,KAAK,CAAC;AAChB;AAEA,IAAM,SAAS,MAAM,gBAAgB;AAAA,EACnC;AAAA,EACA,GAAI,aAAa,SAAY,CAAC,IAAI,EAAE,SAAS;AAAA;AAAA;AAAA,EAG7C,GAAI,kBAAkB,SAAY,CAAC,IAAI,EAAE,cAAc;AACzD,CAAC;AACD,QAAQ,OAAO,MAAM;AAAA,EAAK,oBAAoB,MAAM,CAAC,EAAE;AACvD,QAAQ,KAAK,OAAO,SAAS,IAAI,CAAC;","names":[]}
@@ -0,0 +1,476 @@
1
+ // src/deployment.ts
2
+ import { connect as tlsConnect } from "tls";
3
+ import { request as httpsRequest } from "https";
4
+ import {
5
+ PROTOCOL_VERSION,
6
+ generateKeys,
7
+ signRequest,
8
+ signSiteRequest
9
+ } from "@byollm/protocol";
10
+ var STUB = {
11
+ id: "posture-probe",
12
+ kind: "llm.generate",
13
+ owner: "nobody",
14
+ audience: "private",
15
+ sizeClass: "small",
16
+ streaming: false,
17
+ // Far enough out that a deployment cannot pass by calling it expired.
18
+ deadlineAt: 41024448e5
19
+ };
20
+ var REFUSED = /* @__PURE__ */ new Set([401, 403, 404]);
21
+ async function refusedByByollm(response) {
22
+ if (!REFUSED.has(response.status)) {
23
+ return { ok: false, why: `answered ${String(response.status)}` };
24
+ }
25
+ let body;
26
+ try {
27
+ body = await response.json();
28
+ } catch {
29
+ return {
30
+ ok: false,
31
+ why: `answered ${String(response.status)} but not as byollm \u2014 something else is serving this path`
32
+ };
33
+ }
34
+ const shaped = typeof body === "object" && body !== null && typeof body.error === "string";
35
+ return shaped ? { ok: true, why: `answered ${String(response.status)}` } : {
36
+ ok: false,
37
+ why: `answered ${String(response.status)} with a body byollm would not send \u2014 something else is serving this path`
38
+ };
39
+ }
40
+ var outcome = (passed, detail) => ({
41
+ passed,
42
+ detail
43
+ });
44
+ var unmeasured = (detail) => ({
45
+ passed: false,
46
+ measured: false,
47
+ detail
48
+ });
49
+ async function servedCertificate(address, host) {
50
+ return new Promise((resolve) => {
51
+ const socket = tlsConnect(
52
+ {
53
+ host: address,
54
+ servername: host,
55
+ port: 443,
56
+ timeout: 15e3,
57
+ rejectUnauthorized: false
58
+ },
59
+ () => {
60
+ const peer = socket.getPeerCertificate();
61
+ const alt = (peer.subjectaltname ?? "").split(",").map((entry) => entry.trim().replace(/^DNS:/, "")).filter((entry) => entry.length > 0);
62
+ const cn = peer.subject.CN;
63
+ socket.end();
64
+ resolve({
65
+ names: alt.length > 0 ? alt : [typeof cn === "string" ? cn : ""],
66
+ validTo: peer.valid_to
67
+ });
68
+ }
69
+ );
70
+ socket.on("error", () => {
71
+ resolve(void 0);
72
+ });
73
+ socket.on("timeout", () => {
74
+ socket.destroy();
75
+ resolve(void 0);
76
+ });
77
+ });
78
+ }
79
+ var POSTURE_CHECKS = Object.freeze([
80
+ {
81
+ id: "D001_SITE_ENQUEUE_REFUSES_UNSIGNED",
82
+ title: "an anonymous caller cannot enqueue work in a site's name",
83
+ cites: ["REQUESTS_SIGNED_NOT_BEARER"],
84
+ async run({ origin, fetch: f }) {
85
+ const response = await f(`${origin}/relay/site/enqueue`, {
86
+ method: "POST",
87
+ headers: { "content-type": "application/json" },
88
+ // The version, because the auditor is a site-plane client like any
89
+ // other (§B.4). Without it the relay refuses on the handshake and
90
+ // this check would report "refused" for a reason that has nothing to
91
+ // do with signatures — success for an unrelated reason, which is the
92
+ // failure this whole file was written against.
93
+ body: JSON.stringify({
94
+ protocolVersion: PROTOCOL_VERSION,
95
+ siteId: "any-site",
96
+ stub: STUB
97
+ })
98
+ });
99
+ const refusal = await refusedByByollm(response);
100
+ return outcome(refusal.ok, `POST /relay/site/enqueue ${refusal.why}`);
101
+ }
102
+ },
103
+ {
104
+ id: "D002_SITE_READS_REFUSE_UNSIGNED",
105
+ title: "an anonymous caller cannot read who is online",
106
+ cites: ["REQUESTS_SIGNED_NOT_BEARER"],
107
+ async run({ origin, fetch: f }) {
108
+ const why = [];
109
+ let ok = true;
110
+ for (const path of ["pending", "results"]) {
111
+ const response = await f(
112
+ `${origin}/relay/site/${path}?siteId=any-site&protocolVersion=${PROTOCOL_VERSION}`
113
+ );
114
+ const refusal = await refusedByByollm(response);
115
+ ok &&= refusal.ok;
116
+ why.push(`${path} ${refusal.why}`);
117
+ }
118
+ return outcome(ok, why.join("; "));
119
+ }
120
+ },
121
+ {
122
+ id: "D003_DAEMON_PLANE_REFUSES_UNSIGNED",
123
+ title: "an anonymous caller cannot claim work",
124
+ cites: ["REQUESTS_SIGNED_NOT_BEARER", "CLAIM_REQUIRES_CAPABILITY"],
125
+ async run({ origin, basePath, fetch: f }) {
126
+ const response = await f(`${origin}${basePath}/claim`, {
127
+ method: "POST",
128
+ headers: { "content-type": "application/json" },
129
+ body: JSON.stringify({
130
+ protocolVersion: PROTOCOL_VERSION,
131
+ runnerId: "nobody",
132
+ max: 1,
133
+ capabilities: [{ kind: "llm.generate", models: ["any"] }]
134
+ })
135
+ });
136
+ const refusal = await refusedByByollm(response);
137
+ return outcome(refusal.ok, `POST ${basePath}/claim ${refusal.why}`);
138
+ }
139
+ },
140
+ {
141
+ id: "D004_REFUSES_A_STRANGER_S_VALID_SIGNATURE",
142
+ title: "a well-formed signature from an unknown key is not enough",
143
+ cites: ["REQUESTS_SIGNED_NOT_BEARER", "KEYS_EXCHANGED_AT_CONSENT"],
144
+ async run({ origin, basePath, fetch: f }) {
145
+ const stranger = generateKeys(Date.now());
146
+ const now = Date.now();
147
+ const siteBody = JSON.stringify({
148
+ protocolVersion: PROTOCOL_VERSION,
149
+ siteId: "any-site",
150
+ stub: STUB
151
+ });
152
+ const siteSignature = signSiteRequest(stranger, {
153
+ endpoint: "enqueue",
154
+ siteId: "any-site",
155
+ issuedAt: now,
156
+ body: siteBody
157
+ });
158
+ const site = await f(`${origin}/relay/site/enqueue`, {
159
+ method: "POST",
160
+ headers: {
161
+ "content-type": "application/json",
162
+ "x-byollm-site": "any-site",
163
+ "x-byollm-issued-at": String(siteSignature.issuedAt),
164
+ "x-byollm-signature": siteSignature.signature
165
+ },
166
+ body: siteBody
167
+ });
168
+ const daemonBody = JSON.stringify({
169
+ protocolVersion: PROTOCOL_VERSION,
170
+ runnerId: "nobody",
171
+ max: 1,
172
+ capabilities: [{ kind: "llm.generate", models: ["any"] }]
173
+ });
174
+ const daemonSignature = signRequest(stranger, {
175
+ endpoint: "claim",
176
+ runnerId: "nobody",
177
+ issuedAt: now,
178
+ body: daemonBody
179
+ });
180
+ const daemon = await f(`${origin}${basePath}/claim`, {
181
+ method: "POST",
182
+ headers: {
183
+ "content-type": "application/json",
184
+ "x-byollm-runner": "nobody",
185
+ "x-byollm-issued-at": String(daemonSignature.issuedAt),
186
+ "x-byollm-signature": daemonSignature.signature
187
+ },
188
+ body: daemonBody
189
+ });
190
+ const siteRefusal = await refusedByByollm(site);
191
+ const daemonRefusal = await refusedByByollm(daemon);
192
+ return outcome(
193
+ siteRefusal.ok && daemonRefusal.ok,
194
+ `signed by a stranger: site ${siteRefusal.why}, daemon ${daemonRefusal.why}`
195
+ );
196
+ }
197
+ },
198
+ {
199
+ id: "D011_VERSION_NAMED_ON_BOTH_PLANES",
200
+ title: "an unknown protocol version is refused by name, not by accident",
201
+ cites: ["VERSION_HANDSHAKE_REQUIRED"],
202
+ async run({ origin, fetch: f }) {
203
+ const probes = [
204
+ {
205
+ where: "daemon",
206
+ response: await f(`${origin}/byollm/claim`, {
207
+ method: "POST",
208
+ headers: { "content-type": "application/json" },
209
+ body: JSON.stringify({ protocolVersion: "99", max: 1 })
210
+ })
211
+ },
212
+ {
213
+ where: "site",
214
+ response: await f(`${origin}/relay/site/enqueue`, {
215
+ method: "POST",
216
+ headers: { "content-type": "application/json" },
217
+ body: JSON.stringify({
218
+ protocolVersion: "99",
219
+ siteId: "any-site",
220
+ stub: STUB
221
+ })
222
+ })
223
+ }
224
+ ];
225
+ const wrong = [];
226
+ for (const probe of probes) {
227
+ let body = {};
228
+ try {
229
+ body = await probe.response.json();
230
+ } catch {
231
+ wrong.push(
232
+ `${probe.where}: answered ${String(probe.response.status)} and not as byollm`
233
+ );
234
+ continue;
235
+ }
236
+ if (body.error !== "unsupported-protocol-version") {
237
+ wrong.push(
238
+ `${probe.where}: answered ${String(probe.response.status)} ${String(body.error)}`
239
+ );
240
+ continue;
241
+ }
242
+ if (!Array.isArray(body.supported)) {
243
+ wrong.push(`${probe.where}: refused without naming what it speaks`);
244
+ }
245
+ }
246
+ return outcome(
247
+ wrong.length === 0,
248
+ wrong.length === 0 ? "both planes name the version they speak" : wrong.join("; ")
249
+ );
250
+ }
251
+ },
252
+ {
253
+ id: "D005_NO_DEBUG_SURFACE",
254
+ title: "the debug page is not on the internet",
255
+ cites: [],
256
+ async run({ origin, basePath, fetch: f }) {
257
+ const paths = ["/debug", `${basePath}/debug`];
258
+ const statuses = [];
259
+ for (const path of paths) {
260
+ const response = await f(`${origin}${path}`);
261
+ statuses.push(response.status);
262
+ }
263
+ return outcome(
264
+ // **Not merely "not 200"** — cloud_009 §3 made the page per-site, so
265
+ // an enabled one answers a probe with no site id `400` rather than
266
+ // rendering. A check that accepted anything but 200 would pass
267
+ // against a deployment whose debug page is one query parameter away,
268
+ // which is finding eleven with a shorter walk.
269
+ //
270
+ // `404` is the only answer that means the route does not exist. The
271
+ // reference relay says exactly that when its debug page is off, and
272
+ // says `400` when it is on and the caller named no site.
273
+ statuses.every((status) => status === 404),
274
+ `debug paths answered ${statuses.map(String).join("/")}`
275
+ );
276
+ }
277
+ },
278
+ {
279
+ id: "D006_NO_PATH_DISPATCH",
280
+ title: "a handler cannot be reached by dressing a path up to look like it",
281
+ cites: ["REQUESTS_SIGNED_NOT_BEARER"],
282
+ async run({ origin, fetch: f }) {
283
+ const response = await f(`${origin}/literally/anything/claim`, {
284
+ method: "POST",
285
+ headers: { "content-type": "application/json" },
286
+ body: JSON.stringify({ protocolVersion: PROTOCOL_VERSION, max: 1 })
287
+ });
288
+ const refusal = await refusedByByollm(response);
289
+ return outcome(
290
+ refusal.ok && response.status === 404,
291
+ `POST /literally/anything/claim ${refusal.why}`
292
+ );
293
+ }
294
+ },
295
+ {
296
+ id: "D007_TLS_ONLY",
297
+ title: "the deployment is reached over TLS, and plaintext is not served",
298
+ cites: [],
299
+ async run({ origin, fetch: f }) {
300
+ if (!origin.startsWith("https://")) {
301
+ return outcome(false, `origin is ${origin} \u2014 this audit saw no TLS`);
302
+ }
303
+ const plain = origin.replace("https://", "http://");
304
+ const response = await f(`${plain}/healthz`, { redirect: "manual" });
305
+ const redirected = response.status >= 300 && response.status < 400 && (response.headers.get("location") ?? "").startsWith("https://");
306
+ return outcome(
307
+ redirected || REFUSED.has(response.status),
308
+ `plaintext answered ${String(response.status)}${redirected ? " and redirects to https" : ""}`
309
+ );
310
+ }
311
+ },
312
+ {
313
+ id: "D008_ORIGIN_NOT_PUBLIC",
314
+ title: "the origin answers the edge, and nobody else",
315
+ cites: [],
316
+ async run({ origin, originAddress }) {
317
+ if (originAddress === void 0) {
318
+ return unmeasured(
319
+ "no origin address given \u2014 this posture was not measured (pass the origin's address as the third argument)"
320
+ );
321
+ }
322
+ const host = new URL(origin).host;
323
+ const status = await new Promise((resolve) => {
324
+ const request = httpsRequest(
325
+ {
326
+ host: originAddress,
327
+ servername: host,
328
+ headers: { host },
329
+ path: "/readyz",
330
+ method: "GET",
331
+ rejectUnauthorized: false,
332
+ timeout: 15e3
333
+ },
334
+ (response) => {
335
+ response.resume();
336
+ resolve(response.statusCode ?? 0);
337
+ }
338
+ );
339
+ request.on("error", () => {
340
+ resolve("refused");
341
+ });
342
+ request.on("timeout", () => {
343
+ request.destroy();
344
+ resolve("refused");
345
+ });
346
+ request.end();
347
+ });
348
+ if (status === "refused") {
349
+ return outcome(true, "the origin address refused the connection");
350
+ }
351
+ return outcome(
352
+ status === 403,
353
+ `the origin answered ${String(status)} to a direct request`
354
+ );
355
+ }
356
+ },
357
+ {
358
+ id: "D009_CERT_NAMES_THE_PINNED_HOST",
359
+ title: "the certificate names the hostname daemons pin",
360
+ cites: [],
361
+ async run({ origin, originAddress }) {
362
+ const host = new URL(origin).host;
363
+ if (originAddress === void 0) {
364
+ return unmeasured(
365
+ "no origin address given \u2014 this posture was not measured. Asking the hostname reads the edge's certificate, which names it by construction and proves nothing about the origin"
366
+ );
367
+ }
368
+ const served = await servedCertificate(originAddress, host);
369
+ const names = served?.names;
370
+ if (names === void 0) {
371
+ return outcome(
372
+ false,
373
+ `could not read a certificate from ${originAddress}`
374
+ );
375
+ }
376
+ const covered = names.some(
377
+ (name) => name === host || name.startsWith("*.") && host.endsWith(name.slice(1))
378
+ );
379
+ return outcome(
380
+ covered,
381
+ covered ? `served a certificate naming ${host}` : `the certificate names ${names.join(", ")} \u2014 not ${host}`
382
+ );
383
+ }
384
+ },
385
+ {
386
+ id: "D010_CERT_HAS_LIFE_LEFT",
387
+ title: "the certificate is not about to expire",
388
+ cites: [],
389
+ async run({ origin, originAddress }) {
390
+ const host = new URL(origin).host;
391
+ if (originAddress === void 0) {
392
+ return unmeasured(
393
+ "no origin address given \u2014 this posture was not measured (the edge's certificate is Cloudflare's to renew, not ours)"
394
+ );
395
+ }
396
+ const served = await servedCertificate(originAddress, host);
397
+ if (served === void 0) {
398
+ return outcome(
399
+ false,
400
+ `could not read a certificate from ${originAddress}`
401
+ );
402
+ }
403
+ const days = Math.round(
404
+ (Date.parse(served.validTo) - Date.now()) / 864e5
405
+ );
406
+ return outcome(
407
+ days > 90,
408
+ `the certificate expires ${served.validTo} (${String(days)} days)`
409
+ );
410
+ }
411
+ }
412
+ ]);
413
+ async function auditDeployment(options) {
414
+ const origin = options.url.replace(/\/+$/, "");
415
+ const context = {
416
+ origin,
417
+ basePath: (options.basePath ?? "/byollm").replace(/\/+$/, ""),
418
+ ...options.originAddress === void 0 ? {} : { originAddress: options.originAddress },
419
+ fetch: options.fetch ?? globalThis.fetch
420
+ };
421
+ const results = [];
422
+ for (const check of POSTURE_CHECKS) {
423
+ let result;
424
+ try {
425
+ result = { ...await check.run(context), ...describe(check) };
426
+ } catch (error) {
427
+ result = {
428
+ ...describe(check),
429
+ passed: false,
430
+ detail: `the probe failed: ${error instanceof Error ? error.message : "unknown"}`
431
+ };
432
+ }
433
+ results.push(result);
434
+ options.onProgress?.(result);
435
+ }
436
+ return {
437
+ origin,
438
+ passed: results.every((result) => result.passed),
439
+ results
440
+ };
441
+ }
442
+ var describe = (check) => ({
443
+ id: check.id,
444
+ title: check.title,
445
+ cites: check.cites
446
+ });
447
+ function formatPostureReport(report) {
448
+ const lines = [`deployment posture \u2014 ${report.origin}`, ""];
449
+ for (const result of report.results) {
450
+ const mark = result.passed ? "ok " : result.measured === false ? "? " : "FAIL";
451
+ lines.push(` ${mark} ${result.id}`);
452
+ lines.push(` ${result.title}`);
453
+ lines.push(` ${result.detail}`);
454
+ if (result.cites.length > 0) {
455
+ lines.push(` cites ${result.cites.join(", ")}`);
456
+ }
457
+ }
458
+ const passed = report.results.filter((result) => result.passed).length;
459
+ const unasked = report.results.filter(
460
+ (result) => result.measured === false
461
+ ).length;
462
+ const breached = report.results.length - passed - unasked;
463
+ lines.push(
464
+ "",
465
+ report.passed ? `${String(passed)}/${String(report.results.length)} \u2014 a stranger got nowhere.` : breached > 0 ? `${String(passed)}/${String(report.results.length)} \u2014 a stranger got somewhere. See FAIL above.` + (unasked > 0 ? ` (${String(unasked)} not measured \u2014 see ? above.)` : "") : `${String(passed)}/${String(report.results.length)} \u2014 nothing was breached, and ${String(unasked)} posture(s) could not be measured. See ? above.`,
466
+ ""
467
+ );
468
+ return lines.join("\n");
469
+ }
470
+
471
+ export {
472
+ POSTURE_CHECKS,
473
+ auditDeployment,
474
+ formatPostureReport
475
+ };
476
+ //# sourceMappingURL=chunk-2JXKI5TH.js.map