passcontrol 1.3.0 → 1.5.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/cli/verify.mjs CHANGED
@@ -8,13 +8,16 @@
8
8
  // the artifact and the issuer's origin. That is the whole point.
9
9
  import { ed25519 } from "@noble/curves/ed25519";
10
10
  import { sha256 } from "@noble/hashes/sha256";
11
- import { RECEIPT_PROTOCOL, STATEMENT_PROTOCOL } from "./protocols.mjs";
11
+ import { RECEIPT_PROTOCOL, SESSION_PROTOCOL, STATEMENT_PROTOCOL } from "./protocols.mjs";
12
12
 
13
13
  export const RECEIPT_TYP = "passcontrol-receipt+jwt";
14
14
  export const AGENT_TOKEN_TYP = "passcontrol-agent+jwt";
15
15
  export const STATEMENT_TYP = "passcontrol-statement+jws";
16
+ export const SESSION_TYP = "passcontrol-session+jws";
16
17
  // Its own version line, separate from the receipt's — see protocols.mjs.
17
18
  export const STATEMENT_SUPPORTED_VER = STATEMENT_PROTOCOL.maximum;
19
+ // Session seals: their own line too.
20
+ export const SESSION_SUPPORTED_VER = SESSION_PROTOCOL.maximum;
18
21
  // Receipts v2 add Direct Agent identity claims. This is a maximum, not an
19
22
  // equality check: v1 receipts remain independently verifiable forever.
20
23
  export const SUPPORTED_VER = RECEIPT_PROTOCOL.maximum;
@@ -34,12 +37,15 @@ export function matchesIssuer(iss, trusted) {
34
37
  return trusted.some((candidate) => strip(candidate) === strip(iss));
35
38
  }
36
39
 
37
- async function loadJwks(issuer, fetchImpl) {
40
+ async function loadJwks(issuer, fetchImpl, cache) {
41
+ if (cache?.has(issuer)) return cache.get(issuer);
38
42
  try {
39
43
  const res = await fetchImpl(new URL("/.well-known/jwks.json", issuer).toString());
40
44
  if (!res.ok) return null;
41
45
  const body = await res.json();
42
- return Array.isArray(body?.keys) ? body.keys : [];
46
+ const keys = Array.isArray(body?.keys) ? body.keys : [];
47
+ cache?.set(issuer, keys);
48
+ return keys;
43
49
  } catch {
44
50
  return null;
45
51
  }
@@ -59,7 +65,7 @@ async function loadJwks(issuer, fetchImpl) {
59
65
  async function verifySigned(
60
66
  token,
61
67
  typ,
62
- { issuer, fetch: fetchImpl = fetch },
68
+ { issuer, fetch: fetchImpl = fetch, jwksCache },
63
69
  version = { claim: "ver", max: SUPPORTED_VER }
64
70
  ) {
65
71
  const parts = String(token).split(".");
@@ -88,7 +94,7 @@ async function verifySigned(
88
94
  return { ok: false, reason: "unsupported_version" };
89
95
  }
90
96
 
91
- const keys = await loadJwks(claims.iss, fetchImpl);
97
+ const keys = await loadJwks(claims.iss, fetchImpl, jwksCache);
92
98
  if (!keys) return { ok: false, reason: "jwks_unreachable" };
93
99
 
94
100
  const candidates = keys.filter(
@@ -184,6 +190,204 @@ export async function verifyAgentToken(token, options) {
184
190
  return result;
185
191
  }
186
192
 
193
+ // ── Session seals ────────────────────────────────────────────────────────────
194
+
195
+ /** Leaf and node hashing, the same domain separation as verifyInclusion above. */
196
+ function sessionHash(prefix, ...parts) {
197
+ const total = parts.reduce((sum, p) => sum + p.length, 1);
198
+ const buf = new Uint8Array(total);
199
+ buf[0] = prefix;
200
+ let at = 1;
201
+ for (const p of parts) {
202
+ buf.set(p, at);
203
+ at += p.length;
204
+ }
205
+ return sha256(buf);
206
+ }
207
+
208
+ /** lib/merkle.ts's root: leaves in bundle order, an odd node promoted unchanged. */
209
+ function sessionRoot(bundle) {
210
+ if (bundle.length === 0) return null;
211
+ let level = bundle.map((jws) => sessionHash(0x00, new TextEncoder().encode(jws)));
212
+ while (level.length > 1) {
213
+ const next = [];
214
+ for (let i = 0; i < level.length; i += 2) {
215
+ next.push(level[i + 1] ? sessionHash(0x01, level[i], level[i + 1]) : level[i]);
216
+ }
217
+ level = next;
218
+ }
219
+ return Buffer.from(level[0]).toString("base64url");
220
+ }
221
+
222
+ function decodePayload(jws) {
223
+ try {
224
+ const claims = decodeJson(String(jws).split(".")[1] ?? "");
225
+ return claims && typeof claims === "object" && !Array.isArray(claims) ? claims : null;
226
+ } catch {
227
+ return null;
228
+ }
229
+ }
230
+
231
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : 0);
232
+ const orNull = (v) => (typeof v === "string" ? v : null);
233
+
234
+ /** Tree and model lists, compared as sets: one canonical string each. */
235
+ function canonical(entries, keys) {
236
+ if (!Array.isArray(entries)) return null;
237
+ return JSON.stringify(
238
+ entries
239
+ .map((e) => keys.map((k) => (k.text ? orNull(e?.[k.name]) : num(e?.[k.name]))))
240
+ .sort((a, b) => (JSON.stringify(a) < JSON.stringify(b) ? -1 : JSON.stringify(a) > JSON.stringify(b) ? 1 : 0))
241
+ );
242
+ }
243
+ const TREE_KEYS = [{ name: "agt", text: true }, { name: "par", text: true }, { name: "n" }, { name: "cost" }, { name: "refused" }];
244
+ const MODEL_KEYS = [{ name: "mdl", text: true }, { name: "n" }, { name: "cost" }];
245
+
246
+ /** What the bundle itself adds up to, from the receipts' own claims. */
247
+ function bundleTotals(decoded) {
248
+ const tree = new Map();
249
+ const models = new Map();
250
+ let cost = 0;
251
+ let unp = 0;
252
+ for (const c of decoded) {
253
+ if (!c) continue;
254
+ const ctx = c.ctx && typeof c.ctx === "object" ? c.ctx : {};
255
+ const agt = orNull(ctx.agt);
256
+ const par = orNull(ctx.par);
257
+ const refused = typeof c.res?.status === "string" && c.res.status.startsWith("blocked_") ? 1 : 0;
258
+ const key = JSON.stringify([agt, par]);
259
+ const node = tree.get(key) ?? { agt, par, n: 0, cost: 0, refused: 0 };
260
+ node.n += 1;
261
+ node.cost += num(c.cost);
262
+ node.refused += refused;
263
+ tree.set(key, node);
264
+ const mdl = orNull(c.mdl);
265
+ const m = models.get(JSON.stringify(mdl)) ?? { mdl, n: 0, cost: 0 };
266
+ m.n += 1;
267
+ m.cost += num(c.cost);
268
+ models.set(JSON.stringify(mdl), m);
269
+ cost += num(c.cost);
270
+ if (c.unp === true) unp += 1;
271
+ }
272
+ return { cost, unp, tree: [...tree.values()], mdl: [...models.values()] };
273
+ }
274
+
275
+ /**
276
+ * A journal entry is a receipt id, or `{ id, ... }` as the sidecar writes it. This
277
+ * session's ids (and lines naming no session), and how many named another (`ses`):
278
+ * one sidecar run serves many sessions.
279
+ */
280
+ function journalIds(journal, session) {
281
+ if (!Array.isArray(journal)) return null;
282
+ const ids = [];
283
+ let other = 0;
284
+ for (const entry of journal) {
285
+ const id = typeof entry === "string" ? entry : entry && typeof entry === "object" ? entry.id : undefined;
286
+ if (typeof id !== "string" || id.length === 0) return null;
287
+ const ses = entry && typeof entry === "object" ? entry.ses : undefined;
288
+ if (typeof ses === "string" && ses !== session) {
289
+ other += 1;
290
+ continue;
291
+ }
292
+ ids.push(id);
293
+ }
294
+ return { ids, other };
295
+ }
296
+
297
+ /**
298
+ * Verify a session seal against its bundle and, when given, the user's journal.
299
+ *
300
+ * Four checks: (1) the seal's signature; (2) its root and totals recompute from
301
+ * the bundle; (3) every receipt in the bundle verifies and belongs to this
302
+ * session, agent and window; (4) every receipt id the user's sidecar journaled is
303
+ * in the bundle, directly or through a receipt's `prev` link.
304
+ *
305
+ * Without a journal a seal is no stronger than a statement: `checks.journal` is
306
+ * null and says so. A journaled id that is absent is MISSING, not tampering: the
307
+ * gateway's log write is best-effort, so a lost row and an omission look alike.
308
+ * Receipts in the bundle but not the journal are reported in `unjournaled` and
309
+ * never fail the session.
310
+ */
311
+ export async function verifySession(input, options) {
312
+ const jwksCache = new Map();
313
+ const opts = { ...options, jwksCache };
314
+ const result = {
315
+ ok: false,
316
+ checks: { signature: false, bundle: null, receipts: null, journal: null },
317
+ mismatched: [],
318
+ rejected: [],
319
+ missing: [],
320
+ unjournaled: [],
321
+ otherSessions: 0,
322
+ };
323
+
324
+ const sealed = await verifySigned(input?.seal, SESSION_TYP, opts, { claim: "v", max: SESSION_SUPPORTED_VER });
325
+ if (!sealed.ok) return { ...result, reason: sealed.reason };
326
+ const claims = sealed.claims;
327
+ result.claims = claims;
328
+ result.checks.signature = true;
329
+
330
+ const bundle = Array.isArray(input?.bundle) && input.bundle.every((j) => typeof j === "string") ? input.bundle : null;
331
+ if (!bundle) {
332
+ return { ...result, reason: "malformed_bundle", checks: { ...result.checks, bundle: false } };
333
+ }
334
+
335
+ // 2. The root and every total, recomputed from the bundle.
336
+ const decoded = bundle.map(decodePayload);
337
+ const totals = bundleTotals(decoded);
338
+ if (sessionRoot(bundle) !== (claims.root ?? null)) result.mismatched.push("root");
339
+ if (claims.n !== bundle.length) result.mismatched.push("n");
340
+ if (claims.cost !== totals.cost) result.mismatched.push("cost");
341
+ if (claims.unp !== totals.unp) result.mismatched.push("unp");
342
+ if (canonical(claims.tree, TREE_KEYS) !== canonical(totals.tree, TREE_KEYS)) result.mismatched.push("tree");
343
+ if (canonical(claims.mdl, MODEL_KEYS) !== canonical(totals.mdl, MODEL_KEYS)) result.mismatched.push("mdl");
344
+ result.checks.bundle = result.mismatched.length === 0;
345
+
346
+ // 3. Every receipt verifies, and belongs to this session, agent and window.
347
+ const seen = new Set();
348
+ for (let index = 0; index < bundle.length; index++) {
349
+ const id = orNull(decoded[index]?.jti);
350
+ const verified = await verifyReceipt(bundle[index], opts);
351
+ let reason = verified.ok ? null : verified.reason;
352
+ if (verified.ok) {
353
+ const c = verified.claims;
354
+ const t = Math.floor(num(c.t0) / 1000);
355
+ if (seen.has(c.jti)) reason = "duplicate";
356
+ else if (c.ctx?.ses !== claims.ses?.id) reason = "other_session";
357
+ else if (c.agid !== claims.sub) reason = "other_agent";
358
+ else if (!(t >= num(claims.per?.from) && t < num(claims.per?.to))) reason = "outside_period";
359
+ seen.add(c.jti);
360
+ }
361
+ if (reason) result.rejected.push({ index, id, reason });
362
+ }
363
+ result.checks.receipts = result.rejected.length === 0;
364
+
365
+ // 4. The user's own record.
366
+ if (input.journal !== undefined) {
367
+ const journaled = journalIds(input.journal, claims.ses?.id);
368
+ if (!journaled) {
369
+ result.reason = "malformed_journal";
370
+ result.checks.journal = false;
371
+ } else {
372
+ const inBundle = new Set(decoded.map((c) => orNull(c?.jti)).filter(Boolean));
373
+ const predecessors = new Set(decoded.map((c) => orNull(c?.prev)).filter(Boolean));
374
+ result.otherSessions = journaled.other;
375
+ const ids = new Set(journaled.ids);
376
+ result.missing = [...ids].filter((id) => !inBundle.has(id) && !predecessors.has(id));
377
+ for (const id of inBundle) {
378
+ if (!ids.has(id)) {
379
+ result.unjournaled.push({ id, why: predecessors.has(id) ? "failover_predecessor" : "not_in_journal" });
380
+ }
381
+ }
382
+ result.checks.journal = result.missing.length === 0;
383
+ }
384
+ }
385
+
386
+ const { signature, bundle: b, receipts, journal } = result.checks;
387
+ result.ok = signature && b === true && receipts === true && journal !== false;
388
+ return result;
389
+ }
390
+
187
391
  /** Human-readable one-liners. Kept here so the CLI and its tests agree on wording. */
188
392
  export const FAILURE_REASONS = {
189
393
  malformed: "not a compact JWS",
@@ -195,4 +399,10 @@ export const FAILURE_REASONS = {
195
399
  unsupported_version: "signed by a newer PassControl than this CLI understands",
196
400
  wrong_audience: "minted for a different audience",
197
401
  expired: "expired",
402
+ malformed_bundle: "the bundle is not a list of receipts",
403
+ malformed_journal: "the journal could not be read as a list of receipt ids",
404
+ other_session: "this receipt is not from the sealed session",
405
+ other_agent: "this receipt is from a different agent than the seal names",
406
+ outside_period: "this receipt falls outside the seal's time window",
407
+ duplicate: "the same receipt appears twice in the bundle",
198
408
  };
@@ -53,7 +53,11 @@ export function createVisaClient({
53
53
  });
54
54
 
55
55
  if (!response.ok) {
56
- throw new Error(formatChallengeError(response.status, await response.text()));
56
+ // The status travels with the error: the sidecar waits out a gateway that is
57
+ // not answering yet (5xx) and stops at once on one that refuses (4xx).
58
+ throw Object.assign(new Error(formatChallengeError(response.status, await response.text())), {
59
+ status: response.status,
60
+ });
57
61
  }
58
62
 
59
63
  const data = await response.json();
@@ -0,0 +1,275 @@
1
+ // The sidecar's live feed for `passcontrol watch` (F6): one event per call it relays,
2
+ // served on the sidecar's own loopback listener and kept in memory only.
3
+ //
4
+ // What it carries is what the board shows and nothing else: when, the declared
5
+ // session and sub-agent, the model id, the provider, BOARDED / DENIED / ERROR with
6
+ // the gateway's refusal CODE (never its message), the status, and the latency. No
7
+ // prompt, no response, no message text, no path beyond the provider's name. Nothing
8
+ // is written to disk: the journal (cli/journal.mjs) stays receipt ids only, as D3
9
+ // promised, and this ring buffer dies with the process.
10
+ //
11
+ // Who may read it. The sidecar holds a passport, so it is already bound to loopback
12
+ // by `assertBindHost`; the feed adds the checks a browser would otherwise get around:
13
+ // * GET only, from a loopback peer;
14
+ // * a Host header naming this loopback listener and port exactly, so a page that
15
+ // rebinds its own hostname to 127.0.0.1 is refused (DNS rebinding);
16
+ // * no Origin header, which a browser sends on a cross-origin request;
17
+ // * no CORS grant, ever.
18
+ // A sidecar bound off loopback (`allowNonLoopback`) serves no feed at all.
19
+ //
20
+ // It must never slow or break a call: every write is guarded, a subscriber that
21
+ // cannot keep up is dropped rather than buffered for, and nothing on the proxy
22
+ // path waits on a subscriber.
23
+
24
+ export const WATCH_PATH = "/_passcontrol/watch";
25
+ /** Paths under this prefix are the sidecar's own and are never forwarded. */
26
+ export const LOCAL_PREFIX = "/_passcontrol/";
27
+
28
+ const DECLARED = /^[A-Za-z0-9._:-]{1,128}$/;
29
+ // A model id as the providers and routers spell them: claude-opus-5-5,
30
+ // gpt-5.1-codex, openrouter/anthropic/claude-sonnet-5.5, qwen3:8b, meta-llama/Llama-3@q4.
31
+ const MODEL = /^[A-Za-z0-9._:/@-]{1,100}$/;
32
+ // The gateway's refusal codes are lower-case snake case (`errR(status, code)`).
33
+ const CODE = /^[a-z][a-z0-9_]{1,47}$/;
34
+ const PROVIDER = /^[a-z0-9-]{1,32}$/;
35
+
36
+ /**
37
+ * Bodies larger than this are not parsed for their model: the row shows none. The
38
+ * sidecar already holds the whole body to forward it; parsing it costs about 0.6 ms
39
+ * at 500 KB and 4.5 ms at this cap (measured 2026-10-11, M-series Mac), against a
40
+ * model call that takes seconds.
41
+ */
42
+ const MODEL_PARSE_LIMIT = 4 * 1024 * 1024;
43
+ /** How much of an error body is read to find a refusal code. */
44
+ const REFUSAL_PEEK_BYTES = 8 * 1024;
45
+ /**
46
+ * A subscriber with more than this queued and unsent is dropped. Bytes, not
47
+ * write()'s return value: the replay alone passes the socket's 16 KB high-water
48
+ * mark, and a board that is merely starting up is not a board that cannot keep up.
49
+ */
50
+ const MAX_BUFFERED_BYTES = 1024 * 1024;
51
+
52
+ const held = (pattern, value) => (typeof value === "string" && pattern.test(value) ? value : null);
53
+
54
+ /** The request's top-level `model`, if it is a well-formed model id. */
55
+ export function requestModel(body) {
56
+ if (!body || body.length === 0 || body.length > MODEL_PARSE_LIMIT) return null;
57
+ try {
58
+ const parsed = JSON.parse(body.toString("utf8"));
59
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? held(MODEL, parsed.model) : null;
60
+ } catch {
61
+ return null;
62
+ }
63
+ }
64
+
65
+ /**
66
+ * The gateway's refusal code from an error body, or null. The gateway's own
67
+ * refusals are `{ "error": "<code>" }` with a string; a provider's errors carry an
68
+ * object there, and an Ollama-style string is prose, which fails the pattern.
69
+ */
70
+ export function refusalCode(text) {
71
+ try {
72
+ const parsed = JSON.parse(text);
73
+ return held(CODE, parsed?.error);
74
+ } catch {
75
+ return null;
76
+ }
77
+ }
78
+
79
+ /** `/api/v1/<provider>/...` → provider, else null. */
80
+ export function providerOf(path) {
81
+ const match = /^\/api\/v1\/([^/?#]+)/.exec(String(path ?? ""));
82
+ return match ? held(PROVIDER, match[1]) : null;
83
+ }
84
+
85
+ /** The gateway's budget read, which the board and the status line poll: not a call. */
86
+ export function isBudgetRead(path) {
87
+ return /^\/api\/v1\/self(\?|$)/.test(String(path ?? ""));
88
+ }
89
+
90
+ /** Reads at most `limit` bytes of a (cloned) body, then cancels it. Never throws. */
91
+ export async function peekText(body, limit = REFUSAL_PEEK_BYTES) {
92
+ if (!body) return "";
93
+ const reader = body.getReader();
94
+ const chunks = [];
95
+ let size = 0;
96
+ try {
97
+ while (size < limit) {
98
+ const { done, value } = await reader.read();
99
+ if (done) break;
100
+ chunks.push(value);
101
+ size += value.length;
102
+ }
103
+ } catch {
104
+ // An aborted body has no code to read.
105
+ } finally {
106
+ reader.cancel().catch(() => {});
107
+ }
108
+ return Buffer.concat(chunks.map((c) => Buffer.from(c))).subarray(0, limit).toString("utf8");
109
+ }
110
+
111
+ const LOOPBACK_PEER = /^(127\.\d{1,3}\.\d{1,3}\.\d{1,3}|::1|::ffff:127\.\d{1,3}\.\d{1,3}\.\d{1,3})$/;
112
+ const LOOPBACK_NAMES = new Set(["127.0.0.1", "localhost", "[::1]"]);
113
+
114
+ function hostIsThisListener(hostHeader, port) {
115
+ if (typeof hostHeader !== "string") return false;
116
+ const match = /^(\[[^\]]+\]|[^:]+):(\d+)$/.exec(hostHeader.trim().toLowerCase());
117
+ return Boolean(match && LOOPBACK_NAMES.has(match[1]) && Number(match[2]) === port);
118
+ }
119
+
120
+ function answer(res, status, error, message) {
121
+ const body = JSON.stringify({ error, message });
122
+ res.writeHead(status, {
123
+ "content-type": "application/json",
124
+ "content-length": Buffer.byteLength(body),
125
+ "cache-control": "no-store",
126
+ "x-content-type-options": "nosniff",
127
+ connection: "close",
128
+ });
129
+ res.end(body);
130
+ }
131
+
132
+ /**
133
+ * @param {{ runId: string, capacity?: number, maxSubscribers?: number, enabled?: boolean, now?: () => number }} options
134
+ */
135
+ export function createWatchFeed({ runId, capacity = 200, maxSubscribers = 8, enabled = true, now = () => Date.now() }) {
136
+ const ring = [];
137
+ const subscribers = new Set();
138
+ let seq = 0;
139
+
140
+ function send(res, line) {
141
+ try {
142
+ // A subscriber whose socket is backed up is dropped: buffering for it would
143
+ // grow without bound, and waiting for it would slow calls.
144
+ res.write(line);
145
+ if ((res.writableLength ?? 0) > MAX_BUFFERED_BYTES) drop(res);
146
+ } catch {
147
+ drop(res);
148
+ }
149
+ }
150
+
151
+ function drop(res) {
152
+ subscribers.delete(res);
153
+ try {
154
+ res.destroy();
155
+ } catch {
156
+ // Already gone.
157
+ }
158
+ }
159
+
160
+ function broadcast(event) {
161
+ if (subscribers.size === 0) return;
162
+ let line;
163
+ try {
164
+ line = `${JSON.stringify(event)}\n`;
165
+ } catch {
166
+ return;
167
+ }
168
+ for (const res of [...subscribers]) send(res, line);
169
+ }
170
+
171
+ function remember(record) {
172
+ ring.push(record);
173
+ if (ring.length > capacity) ring.splice(0, ring.length - capacity);
174
+ }
175
+
176
+ /**
177
+ * A call the board will show. `settle` announces it once its outcome is known;
178
+ * `finish` records the total time when the response is done. Either order works:
179
+ * a call that finishes before it is settled is announced with its total.
180
+ * Never throws.
181
+ */
182
+ function begin({ startedAt = now(), lineage = null, model = null, provider = null } = {}) {
183
+ const record = {
184
+ type: "call",
185
+ seq: ++seq,
186
+ at: startedAt,
187
+ ses: held(DECLARED, lineage?.session),
188
+ agent: held(DECLARED, lineage?.agent),
189
+ parent: held(DECLARED, lineage?.parent),
190
+ model: held(MODEL, model),
191
+ provider: held(PROVIDER, provider),
192
+ outcome: null,
193
+ code: null,
194
+ status: null,
195
+ ttfb: null,
196
+ ms: null,
197
+ };
198
+ let announced = false;
199
+ return {
200
+ settle({ outcome, code = null, status, ttfb = null }) {
201
+ try {
202
+ if (announced) return;
203
+ announced = true;
204
+ record.outcome = ["boarded", "denied", "error"].includes(outcome) ? outcome : "error";
205
+ record.code = held(CODE, code);
206
+ record.status = Number.isInteger(status) ? status : null;
207
+ record.ttfb = Math.max(0, Math.round(Number.isFinite(ttfb) ? ttfb : now() - record.at));
208
+ remember(record);
209
+ broadcast(record);
210
+ } catch {
211
+ // The feed is never the reason a call fails.
212
+ }
213
+ },
214
+ finish() {
215
+ try {
216
+ if (record.ms !== null) return;
217
+ record.ms = Math.max(0, Math.round(now() - record.at));
218
+ if (announced) broadcast({ type: "end", seq: record.seq, ms: record.ms });
219
+ } catch {
220
+ // As above.
221
+ }
222
+ },
223
+ };
224
+ }
225
+
226
+ /** A call whose outcome and end are known at once (refusals, upstream failures). */
227
+ function record({ outcome, code = null, status, lineage = null, model = null, provider = null, startedAt = now() }) {
228
+ const call = begin({ startedAt, lineage, model, provider });
229
+ call.finish();
230
+ call.settle({ outcome, code, status, ttfb: now() - startedAt });
231
+ }
232
+
233
+ /** Adds a subscriber, replaying the ring. Exposed for tests; `serve` is the way in. */
234
+ function attach(res) {
235
+ subscribers.add(res);
236
+ send(res, `${JSON.stringify({ type: "hello", feed: "passcontrol-watch", v: 1, run: runId })}\n`);
237
+ for (const r of ring) if (subscribers.has(res)) send(res, `${JSON.stringify(r)}\n`);
238
+ try {
239
+ res.on("close", () => subscribers.delete(res));
240
+ } catch {
241
+ subscribers.delete(res);
242
+ }
243
+ }
244
+
245
+ /** Answers a request for `/_passcontrol/...`. `port` is the listener's bound port. */
246
+ function serve(req, res, { port }) {
247
+ req.resume();
248
+ const pathname = String(req.url ?? "").split("?")[0];
249
+ if (pathname !== WATCH_PATH) return answer(res, 404, "not_found", "Nothing is served here.");
250
+ if (!enabled) {
251
+ return answer(res, 404, "watch_off", "This sidecar is bound off loopback, so it serves no watch feed.");
252
+ }
253
+ if (req.method !== "GET") return answer(res, 405, "method_not_allowed", "The watch feed answers GET only.");
254
+ const loopbackPeer = LOOPBACK_PEER.test(String(req.socket?.remoteAddress ?? ""));
255
+ if (!loopbackPeer || req.headers.origin !== undefined || !hostIsThisListener(req.headers.host, port)) {
256
+ return answer(res, 403, "watch_refused", "The watch feed is for `passcontrol watch` on this machine only.");
257
+ }
258
+ if (subscribers.size >= maxSubscribers) {
259
+ return answer(res, 503, "watch_busy", `Already ${maxSubscribers} boards watching this sidecar.`);
260
+ }
261
+ res.writeHead(200, {
262
+ "content-type": "application/x-ndjson",
263
+ "cache-control": "no-store",
264
+ "x-content-type-options": "nosniff",
265
+ });
266
+ res.socket?.setNoDelay?.(true);
267
+ attach(res);
268
+ }
269
+
270
+ function close() {
271
+ for (const res of [...subscribers]) drop(res);
272
+ }
273
+
274
+ return { begin, record, serve, attach, close, subscriberCount: () => subscribers.size };
275
+ }