@verax-ai/body 0.4.8 → 0.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.
@@ -4,6 +4,7 @@ import { effectDescriptor, samePublicKey, sha256Canonical, thirdPartyReceiptReje
4
4
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
5
5
  import { getDefaultEnvironment, StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
6
6
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
7
+ import { CallToolResultSchema, ListToolsResultSchema } from "@modelcontextprotocol/sdk/types.js";
7
8
  const PREFIX_RE = /^[A-Za-z][A-Za-z0-9_-]{0,31}$/;
8
9
  const CHILD_TOOL_RE = /^[A-Za-z][A-Za-z0-9._-]{0,63}$/;
9
10
  /** Prefixed name a caller may put on extraTools: `prefix.childName`. */
@@ -12,6 +13,19 @@ const EXTRA_NAME_RE = /^[A-Za-z][A-Za-z0-9_-]{0,31}\.[A-Za-z][A-Za-z0-9._-]{0,63
12
13
  // hostile or broken; the body is not a registry for thousands of names.
13
14
  const MAX_CHILD_TOOLS = 256;
14
15
  const MAX_TOOL_BYTES = 64 * 1024;
16
+ /**
17
+ * One message from a child: a line on stdio, an HTTP response body, or one
18
+ * SSE event. A whole `tools/list` answer is one message, so this also caps
19
+ * the list the per-tool bounds are then applied to.
20
+ */
21
+ const MAX_CHILD_MESSAGE_BYTES = 10 * 1024 * 1024;
22
+ const MESSAGE_TOO_LARGE = "downstream-message-too-large";
23
+ function tripOverflow(overflow) {
24
+ if (overflow.hit)
25
+ return;
26
+ overflow.hit = true;
27
+ overflow.detach();
28
+ }
15
29
  function assertEffectKey(pem) {
16
30
  try {
17
31
  if (typeof pem !== "string" || !pem.trim().startsWith("-----BEGIN PUBLIC KEY-----") ||
@@ -157,6 +171,17 @@ export function parseDownstreamJson(raw, bodyPublicKeyPems = []) {
157
171
  }
158
172
  spec.trust = "same-user";
159
173
  }
174
+ if (rec.tools !== undefined) {
175
+ const names = rec.tools;
176
+ if (!Array.isArray(names) ||
177
+ names.length === 0 ||
178
+ names.length > MAX_CHILD_TOOLS ||
179
+ !names.every((n) => typeof n === "string" && CHILD_TOOL_RE.test(n)) ||
180
+ new Set(names).size !== names.length) {
181
+ throw new Error("downstream-tools-invalid");
182
+ }
183
+ spec.tools = [...names];
184
+ }
160
185
  assertStdioTrusted(spec);
161
186
  return spec;
162
187
  }
@@ -227,6 +252,9 @@ function stdioTransport(spec) {
227
252
  cwd: spec.cwd,
228
253
  env,
229
254
  stderr: "pipe",
255
+ // The client's own default is the same number; it is stated here so the
256
+ // bound is this file's and not a dependency's.
257
+ maxBufferSize: MAX_CHILD_MESSAGE_BYTES,
230
258
  });
231
259
  // The SDK types the pipe as Stream; only a Readable can be drained.
232
260
  const stderr = transport.stderr;
@@ -239,10 +267,11 @@ function stdioTransport(spec) {
239
267
  * document — the body's own bearer is never forwarded, for the same
240
268
  * confused-deputy reason the stdio child does not inherit `VERAX_*`.
241
269
  */
242
- function httpTransport(spec) {
270
+ function httpTransport(spec, overflow) {
243
271
  if (spec.url === undefined)
244
272
  throw new Error("downstream-url-invalid");
245
273
  return new StreamableHTTPClientTransport(new URL(spec.url), {
274
+ fetch: boundedFetch(overflow),
246
275
  requestInit: {
247
276
  // The child's address is the operator's document, not a place the
248
277
  // child may name. Following a redirect would rewrite that document
@@ -253,6 +282,60 @@ function httpTransport(spec) {
253
282
  },
254
283
  });
255
284
  }
285
+ /**
286
+ * Counts what a child's response carries as it is read, so an answer over the
287
+ * bound is refused at the bound instead of after it has been held and parsed.
288
+ * A JSON answer is one message. On an event stream each event is one, and an
289
+ * empty line ends it; a stream that ends its lines with a bare CR is counted
290
+ * as a single message.
291
+ */
292
+ function boundedFetch(overflow) {
293
+ return async (url, init) => {
294
+ const res = await fetch(url, init);
295
+ if (res.body === null)
296
+ return res;
297
+ // Events only where every version of the client reads events: a success
298
+ // whose media type is exactly this. An error answer is read whole as text,
299
+ // and so is a JSON answer whose parameters merely mention the name; an
300
+ // empty line inside either must not restart the count.
301
+ const mediaType = (res.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase();
302
+ const events = res.ok && mediaType === "text/event-stream";
303
+ let count = 0;
304
+ let lineEmpty = true;
305
+ const counted = res.body.pipeThrough(new TransformStream({
306
+ transform(chunk, controller) {
307
+ if (!events) {
308
+ count += chunk.byteLength;
309
+ }
310
+ else {
311
+ let at = 0;
312
+ while (at < chunk.byteLength && count <= MAX_CHILD_MESSAGE_BYTES) {
313
+ const newline = chunk.indexOf(0x0a, at);
314
+ const end = newline === -1 ? chunk.byteLength : newline;
315
+ const length = end - at;
316
+ if (length > 1 || (length === 1 && chunk[at] !== 0x0d))
317
+ lineEmpty = false;
318
+ count += length;
319
+ if (newline === -1)
320
+ break;
321
+ count += 1;
322
+ if (lineEmpty)
323
+ count = 0;
324
+ lineEmpty = true;
325
+ at = newline + 1;
326
+ }
327
+ }
328
+ if (count > MAX_CHILD_MESSAGE_BYTES) {
329
+ tripOverflow(overflow);
330
+ controller.error(new Error(MESSAGE_TOO_LARGE));
331
+ return;
332
+ }
333
+ controller.enqueue(chunk);
334
+ },
335
+ }));
336
+ return new Response(counted, { status: res.status, statusText: res.statusText, headers: res.headers });
337
+ };
338
+ }
256
339
  /**
257
340
  * `connect` does not take a timeout option. Race it, close the transport
258
341
  * when the clock wins, and drop the timer so a settled attach cannot keep
@@ -297,33 +380,60 @@ export async function openDownstream(spec) {
297
380
  throw new Error("downstream-transport-missing");
298
381
  }
299
382
  const timeoutMs = spec.timeoutMs ?? 10_000;
300
- const transport = spec.url !== undefined ? httpTransport(spec) : stdioTransport(spec);
383
+ const overflow = { hit: false, detach: () => undefined };
384
+ const transport = spec.url !== undefined ? httpTransport(spec, overflow) : stdioTransport(spec);
301
385
  const client = new Client({ name: "verax-downstream", version: "0.0.0" });
386
+ // Closing the transport ends every call still waiting on this child at once,
387
+ // an event stream included, instead of at its timeout.
388
+ overflow.detach = () => void transport.close().catch(() => undefined);
389
+ // On stdio the client's read buffer enforces the bound and closes the child.
390
+ // This is where it says so; the text is the client's, and the stdio cases
391
+ // of `attack-r26-child-message-bound` fail if it changes.
392
+ client.onerror = (err) => {
393
+ if (/ReadBuffer exceeded maximum size/.test(err.message))
394
+ overflow.hit = true;
395
+ };
302
396
  let listed;
303
397
  try {
304
398
  await connectWithDeadline(client, transport, timeoutMs, spec.prefix);
305
- listed = await client.listTools(undefined, { timeout: timeoutMs });
399
+ // Asked as a plain request, not through client.listTools: that call compiles every
400
+ // outputSchema the child lists into a validator, and client.callTool then runs it
401
+ // on the child's own result inside this process. A child's schema is the child's
402
+ // input; a backtracking pattern in it held the body for seconds per call.
403
+ listed = await client.request({ method: "tools/list" }, ListToolsResultSchema, { timeout: timeoutMs });
306
404
  }
307
405
  catch (err) {
308
406
  await shut(client, transport);
407
+ if (overflow.hit)
408
+ throw new Error(`${MESSAGE_TOO_LARGE}:${spec.prefix}`);
309
409
  throw attachTimeoutError(err, spec.prefix);
310
410
  }
311
411
  if (listed.tools.length > MAX_CHILD_TOOLS) {
312
412
  await shut(client, transport);
313
413
  throw new Error(`downstream-too-many-tools:${spec.prefix}:${listed.tools.length}`);
314
414
  }
415
+ // With a `tools` list the rest of the child's list is never read past its
416
+ // name: no size check, no registry entry, nothing republished.
417
+ const wanted = spec.tools === undefined ? null : new Set(spec.tools);
418
+ const offered = wanted === null ? listed.tools : listed.tools.filter((t) => wanted.has(t.name));
419
+ if (wanted !== null) {
420
+ for (const name of wanted) {
421
+ if (!offered.some((t) => t.name === name)) {
422
+ await shut(client, transport);
423
+ throw new Error(`downstream-tool-missing:${spec.prefix}.${name}`);
424
+ }
425
+ }
426
+ }
315
427
  const tools = [];
316
428
  const seen = new Set();
317
- for (const tool of listed.tools) {
429
+ for (const tool of offered) {
318
430
  if (!CHILD_TOOL_RE.test(tool.name)) {
319
431
  await shut(client, transport);
320
432
  throw new Error(`downstream-child-name-invalid:${tool.name}`);
321
433
  }
322
- const toolBytes = JSON.stringify({
323
- name: tool.name,
324
- description: tool.description,
325
- inputSchema: tool.inputSchema,
326
- }).length;
434
+ // The whole entry as the child sent it, in bytes: a description in three-byte
435
+ // characters, or megabytes in outputSchema or title, count against the bound too.
436
+ const toolBytes = Buffer.byteLength(JSON.stringify(tool), "utf8");
327
437
  if (toolBytes > MAX_TOOL_BYTES) {
328
438
  await shut(client, transport);
329
439
  throw new Error(`downstream-tool-too-large:${spec.prefix}.${tool.name}:${toolBytes}`);
@@ -340,16 +450,21 @@ export async function openDownstream(spec) {
340
450
  ...(typeof tool.description === "string" ? { description: tool.description } : {}),
341
451
  ...(tool.inputSchema !== undefined ? { inputSchema: tool.inputSchema } : {}),
342
452
  fn: async (call, _principal, ref) => {
453
+ // A child that sent one message over the bound is not asked again.
454
+ if (overflow.hit)
455
+ throw new DownstreamCallError(spec.prefix, childName, new Error(MESSAGE_TOO_LARGE));
343
456
  let raw;
344
457
  try {
345
458
  // Mutation check: stub this call and the allow test expecting
346
459
  // "pong":true from the child goes red.
347
- raw = await client.callTool({ name: childName, arguments: call.arguments,
348
- ...(spec.effectKeyPem ? { _meta: { "io.cedulon/decision": { ref, deciderId: "verax-proxy", prefix: spec.prefix } } } : {}),
349
- }, undefined, { timeout: timeoutMs });
460
+ raw = await client.request({ method: "tools/call",
461
+ params: { name: childName, arguments: call.arguments,
462
+ ...(spec.effectKeyPem ? { _meta: { "io.cedulon/decision": { ref, deciderId: "verax-proxy", prefix: spec.prefix } } } : {}),
463
+ },
464
+ }, CallToolResultSchema, { timeout: timeoutMs });
350
465
  }
351
466
  catch (err) {
352
- throw new DownstreamCallError(spec.prefix, childName, err);
467
+ throw new DownstreamCallError(spec.prefix, childName, overflow.hit ? new Error(MESSAGE_TOO_LARGE) : err);
353
468
  }
354
469
  const result = asTextResult(raw);
355
470
  if (result.isError) {
@@ -35,6 +35,7 @@ export function readHeartbeat(stateDir) {
35
35
  return null;
36
36
  }
37
37
  }
38
+ const NOT_A_CLASS = new Set(["checkpoint", "checkpoint-refused", "anchored", "anchor-failed"]);
38
39
  export function readWitnessPulse(stateDir) {
39
40
  const path = join(stateDir, "witness-status.jsonl");
40
41
  if (!existsSync(path))
@@ -44,17 +45,21 @@ export function readWitnessPulse(stateDir) {
44
45
  .split("\n")
45
46
  .map((l) => l.trim())
46
47
  .filter((l) => l !== "");
47
- const last = lines[lines.length - 1];
48
- if (!last)
48
+ // Checkpoint and anchor rows say nothing about the class of the last
49
+ // effect; the row before them does.
50
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
51
+ const row = JSON.parse(lines[i]);
52
+ if (typeof row.result === "string" && NOT_A_CLASS.has(row.result) && row.class === undefined)
53
+ continue;
54
+ if (typeof row.atMs !== "number" || !Number.isFinite(row.atMs))
55
+ return null;
56
+ if (row.result === "signed" || row.class === "same-org") {
57
+ return { class: "same-org", atMs: row.atMs };
58
+ }
59
+ if (row.result === "self-fallback" || row.class === "self") {
60
+ return { class: "self", atMs: row.atMs };
61
+ }
49
62
  return null;
50
- const row = JSON.parse(last);
51
- if (typeof row.atMs !== "number" || !Number.isFinite(row.atMs))
52
- return null;
53
- if (row.result === "signed" || row.class === "same-org") {
54
- return { class: "same-org", atMs: row.atMs };
55
- }
56
- if (row.result === "self-fallback" || row.class === "self") {
57
- return { class: "self", atMs: row.atMs };
58
63
  }
59
64
  return null;
60
65
  }
@@ -1,4 +1,5 @@
1
- import type { FileLedger } from "@verax-ai/proxy";
1
+ import type { FileLedger, RecordSigner } from "@verax-ai/proxy";
2
+ /** v1 rows carry no `v` and no signature. */
2
3
  export type StartRow = {
3
4
  action: "start";
4
5
  atMs: number;
@@ -6,16 +7,54 @@ export type StartRow = {
6
7
  gapMs: number | null;
7
8
  pid: number;
8
9
  };
10
+ /**
11
+ * A v2 row is signed by the record key over its canonical form without
12
+ * `sig`, under a domain tag, and names the SHA-256 of the line before it, so
13
+ * a row changed or removed from the middle is named by `verify`. A row
14
+ * removed from the end leaves nothing to compare.
15
+ */
16
+ export type SignedStartRow = StartRow & {
17
+ v: 2;
18
+ prevStartHash: string | null;
19
+ sig: string;
20
+ };
21
+ /**
22
+ * The last line of the file that is not blank, read from the end. The file
23
+ * gains a row on every start and is never trimmed, so reading all of it to
24
+ * find one line grew with the body's history and, past the longest string
25
+ * the runtime holds, stopped the start. The window doubles until it holds a
26
+ * whole line; a file that is one long line is read whole, as before.
27
+ */
28
+ export declare function lastLine(path: string, windowBytes?: number): string | null;
9
29
  export declare function heartbeatEveryMs(env?: NodeJS.ProcessEnv): number;
10
- /** Separate from halt history: starts are unsigned observations, not controls. */
11
- export declare function recordBodyStart(stateDir: string, atMs: number): void;
30
+ /**
31
+ * Separate from halt history: a start is an observation, not a control.
32
+ * With a signer the row is v2 and signed by the record key; without one it
33
+ * stays an unsigned v1 row.
34
+ */
35
+ export declare function recordBodyStart(stateDir: string, atMs: number, signer?: RecordSigner): void;
12
36
  export declare function startHeartbeat(ledger: FileLedger): () => void;
13
37
  export type StartSummary = {
14
38
  count: number;
15
39
  largestGapMs: number | null;
16
40
  missingPreviousBeat: number[];
17
- unsigned: true;
41
+ /** True when any row is unsigned (v1). */
42
+ unsigned: boolean;
43
+ /** v2 rows, and how many of them verified under `startKey`. */
44
+ signed: number;
45
+ signedVerified: number;
46
+ /** Where the key the signed rows were checked under came from. */
47
+ startKey: "pinned" | "in-ledger" | "none";
48
+ /** Problems that make the ledger not verify: a bad signature, a broken chain, an unsigned row after a signed one. */
49
+ problems: string[];
18
50
  warnings: string[];
19
51
  };
20
- export declare function readStartSummary(stateDir: string): StartSummary;
52
+ /**
53
+ * `publicKeyPem` is the record key the reader trusts: the one they pinned or
54
+ * the one the records carry. Without it signed rows are counted and not
55
+ * checked, the same as other signatures with no key.
56
+ */
57
+ export declare function readStartSummary(stateDir: string, publicKeyPem?: string | null, keySource?: "pinned" | "in-ledger" | "none", opts?: {
58
+ requireSigned?: boolean;
59
+ }): StartSummary;
21
60
  export declare function renderStarts(summary: StartSummary): string;
package/dist/heartbeat.js CHANGED
@@ -1,15 +1,88 @@
1
- import { appendFileSync, readFileSync } from "node:fs";
1
+ import { createHash, createPrivateKey, createPublicKey, sign, verify } from "node:crypto";
2
+ import { appendFileSync, closeSync, fstatSync, openSync, readFileSync, readSync } from "node:fs";
2
3
  import { join } from "node:path";
4
+ import { canonical } from "@cedulon/core";
3
5
  import { readHeartbeat } from "./health-extras.js";
6
+ const START_DOMAIN = "verax-start-v2\n";
7
+ function startSigningBytes(row) {
8
+ return Buffer.from(START_DOMAIN + canonical(row), "utf8");
9
+ }
10
+ function lineHash(line) {
11
+ return createHash("sha256").update(line, "utf8").digest("hex");
12
+ }
13
+ /**
14
+ * The last line of the file that is not blank, read from the end. The file
15
+ * gains a row on every start and is never trimmed, so reading all of it to
16
+ * find one line grew with the body's history and, past the longest string
17
+ * the runtime holds, stopped the start. The window doubles until it holds a
18
+ * whole line; a file that is one long line is read whole, as before.
19
+ */
20
+ export function lastLine(path, windowBytes = 64 * 1024) {
21
+ let fd;
22
+ try {
23
+ fd = openSync(path, "r");
24
+ }
25
+ catch (err) {
26
+ if (err.code === "ENOENT")
27
+ return null;
28
+ throw err;
29
+ }
30
+ try {
31
+ const size = fstatSync(fd).size;
32
+ for (let window = Math.max(1, windowBytes);; window *= 2) {
33
+ const start = Math.max(0, size - window);
34
+ const buf = Buffer.alloc(size - start);
35
+ let read = 0;
36
+ while (read < buf.length) {
37
+ const n = readSync(fd, buf, read, buf.length - read, start + read);
38
+ if (n === 0)
39
+ break;
40
+ read += n;
41
+ }
42
+ // The bytes are cut at a newline, not at a character: a window may begin
43
+ // inside a multi-byte character, and inside a line either way.
44
+ const firstNewline = start === 0 ? -1 : buf.indexOf(0x0a);
45
+ if (start > 0 && firstNewline === -1)
46
+ continue;
47
+ const text = buf.subarray(firstNewline + 1, read).toString("utf8");
48
+ const lines = text.split("\n").filter((l) => l.trim() !== "");
49
+ if (lines.length > 0)
50
+ return lines[lines.length - 1];
51
+ if (start === 0)
52
+ return null;
53
+ }
54
+ }
55
+ finally {
56
+ closeSync(fd);
57
+ }
58
+ }
4
59
  export function heartbeatEveryMs(env = process.env) {
5
60
  const n = Number(env.VERAX_HEARTBEAT_EVERY_MS ?? "10000");
6
61
  return Number.isFinite(n) && n > 0 ? Math.min(2_147_483_647, Math.max(1000, Math.floor(n))) : 10_000;
7
62
  }
8
- /** Separate from halt history: starts are unsigned observations, not controls. */
9
- export function recordBodyStart(stateDir, atMs) {
63
+ /**
64
+ * Separate from halt history: a start is an observation, not a control.
65
+ * With a signer the row is v2 and signed by the record key; without one it
66
+ * stays an unsigned v1 row.
67
+ */
68
+ export function recordBodyStart(stateDir, atMs, signer) {
69
+ const path = join(stateDir, "starts.jsonl");
10
70
  const prevBeatAtMs = readHeartbeat(stateDir)?.atMs ?? null;
11
- const row = { action: "start", atMs, prevBeatAtMs, gapMs: prevBeatAtMs === null ? null : atMs - prevBeatAtMs, pid: process.pid };
12
- appendFileSync(join(stateDir, "starts.jsonl"), `${JSON.stringify(row)}\n`, { encoding: "utf8", mode: 0o600 });
71
+ const base = {
72
+ action: "start",
73
+ atMs,
74
+ prevBeatAtMs,
75
+ gapMs: prevBeatAtMs === null ? null : atMs - prevBeatAtMs,
76
+ pid: process.pid,
77
+ };
78
+ let row = base;
79
+ if (signer) {
80
+ const prev = lastLine(path);
81
+ const unsigned = { v: 2, ...base, prevStartHash: prev === null ? null : lineHash(prev) };
82
+ const sig = sign(null, startSigningBytes(unsigned), createPrivateKey(signer.privateKeyPem)).toString("base64");
83
+ row = { ...unsigned, sig };
84
+ }
85
+ appendFileSync(path, `${JSON.stringify(row)}\n`, { encoding: "utf8", mode: 0o600 });
13
86
  }
14
87
  export function startHeartbeat(ledger) {
15
88
  ledger.pulseHeartbeat("timer");
@@ -25,40 +98,175 @@ export function startHeartbeat(ledger) {
25
98
  timer.unref();
26
99
  return () => clearInterval(timer);
27
100
  }
28
- export function readStartSummary(stateDir) {
29
- const result = { count: 0, largestGapMs: null, missingPreviousBeat: [], unsigned: true, warnings: [] };
101
+ function isStartRow(row) {
102
+ return (!!row &&
103
+ row.action === "start" &&
104
+ Number.isFinite(row.atMs) &&
105
+ Number.isInteger(row.pid) &&
106
+ (row.prevBeatAtMs === null || Number.isFinite(row.prevBeatAtMs)) &&
107
+ (row.gapMs === null || Number.isFinite(row.gapMs)) &&
108
+ (row.prevBeatAtMs === null) === (row.gapMs === null));
109
+ }
110
+ /**
111
+ * Whether a line carries a field only a signed start row has. A line that no
112
+ * longer parses is read as text, so a signed row cut short is not passed as
113
+ * one nothing can read.
114
+ */
115
+ function claimsSigned(parsed, line = "") {
116
+ if (parsed === undefined)
117
+ return /"(?:v|sig|prevStartHash)"\s*:/.test(line);
118
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
119
+ return false;
120
+ const rec = parsed;
121
+ return rec.v !== undefined || rec.sig !== undefined || rec.prevStartHash !== undefined;
122
+ }
123
+ function signedVerifies(row, publicKeyPem) {
124
+ try {
125
+ const { sig, ...rest } = row;
126
+ return verify(null, startSigningBytes(rest), createPublicKey(publicKeyPem), Buffer.from(sig, "base64"));
127
+ }
128
+ catch {
129
+ return false;
130
+ }
131
+ }
132
+ /**
133
+ * `publicKeyPem` is the record key the reader trusts: the one they pinned or
134
+ * the one the records carry. Without it signed rows are counted and not
135
+ * checked, the same as other signatures with no key.
136
+ */
137
+ export function readStartSummary(stateDir, publicKeyPem = null, keySource = publicKeyPem ? "in-ledger" : "none", opts = {}) {
138
+ const result = {
139
+ count: 0,
140
+ largestGapMs: null,
141
+ missingPreviousBeat: [],
142
+ unsigned: false,
143
+ signed: 0,
144
+ signedVerified: 0,
145
+ startKey: publicKeyPem ? keySource : "none",
146
+ problems: [],
147
+ warnings: [],
148
+ };
30
149
  let raw;
31
150
  try {
32
151
  raw = readFileSync(join(stateDir, "starts.jsonl"), "utf8");
33
152
  }
34
153
  catch (err) {
154
+ // A file that is there and cannot be read has not been checked: that is a
155
+ // problem, not a warning. Only a file that is not there is nothing.
35
156
  if (err.code !== "ENOENT")
36
- result.warnings.push("starts.jsonl could not be read");
157
+ result.problems.push("starts.jsonl could not be read");
158
+ if (opts.requireSigned)
159
+ result.problems.push("start-rows-missing: no start row could be read");
37
160
  return result;
38
161
  }
162
+ let prevLine = null;
163
+ let seenSigned = false;
39
164
  for (const [i, line] of raw.split("\n").entries()) {
40
- if (line.trim() === "")
165
+ // The empty piece after the last newline. A line of spaces is not empty:
166
+ // the body does not write one, and it is read like any other line.
167
+ if (line === "")
41
168
  continue;
169
+ const n = i + 1;
170
+ let row;
171
+ let parsed;
42
172
  try {
43
- const row = JSON.parse(line);
44
- if (!row || row.action !== "start" || !Number.isFinite(row.atMs) || !Number.isInteger(row.pid)
45
- || !(row.prevBeatAtMs === null || Number.isFinite(row.prevBeatAtMs))
46
- || !(row.gapMs === null || Number.isFinite(row.gapMs))
47
- || (row.prevBeatAtMs === null) !== (row.gapMs === null))
173
+ parsed = JSON.parse(line);
174
+ row = parsed;
175
+ if (!isStartRow(row))
48
176
  throw new Error("start row shape");
49
- result.count += 1;
50
- if (row.prevBeatAtMs === null)
51
- result.missingPreviousBeat.push(row.atMs);
52
- if (row.gapMs !== null)
53
- result.largestGapMs = result.largestGapMs === null ? row.gapMs : Math.max(result.largestGapMs, row.gapMs);
54
177
  }
55
178
  catch {
56
- result.warnings.push(`starts.jsonl line ${i + 1} is unreadable`);
179
+ // Every line of this file is a start row the body wrote, so a line that
180
+ // does not read as one is a problem, whatever it still looks like.
181
+ // Naming a tampered signed row by the fields it shows is only a better
182
+ // message: the writer of the file can always make a row show none.
183
+ if (claimsSigned(parsed, line)) {
184
+ seenSigned = true;
185
+ result.signed += 1;
186
+ result.problems.push(`signed start row is malformed: starts.jsonl line ${n}`);
187
+ }
188
+ else if (seenSigned) {
189
+ result.problems.push(`starts.jsonl line ${n} is unreadable after a signed start`);
190
+ }
191
+ else if (opts.requireSigned) {
192
+ result.problems.push(`start-row-unreadable: starts.jsonl line ${n}`);
193
+ }
194
+ else {
195
+ result.problems.push(`starts.jsonl line ${n} is not a start row`);
196
+ }
197
+ prevLine = line;
198
+ continue;
199
+ }
200
+ result.count += 1;
201
+ if (row.prevBeatAtMs === null)
202
+ result.missingPreviousBeat.push(row.atMs);
203
+ if (row.gapMs !== null) {
204
+ result.largestGapMs = result.largestGapMs === null ? row.gapMs : Math.max(result.largestGapMs, row.gapMs);
205
+ }
206
+ if (row.v === 2) {
207
+ const signed = row;
208
+ seenSigned = true;
209
+ result.signed += 1;
210
+ const expected = prevLine === null ? null : lineHash(prevLine);
211
+ if (signed.prevStartHash !== expected) {
212
+ result.problems.push(`start chain breaks at starts.jsonl line ${n}: the row before it is not the one it names`);
213
+ }
214
+ // A signed row is accepted in one spelling, the one the body writes. A
215
+ // second copy of a key, padding, or an escape leaves the parsed row and
216
+ // its signature as they were and makes the line say something else to
217
+ // another reader.
218
+ if (JSON.stringify(parsed) !== line) {
219
+ result.problems.push(`signed start row is not written as the body writes it: starts.jsonl line ${n}`);
220
+ }
221
+ if (typeof signed.sig !== "string" || signed.sig === "") {
222
+ result.problems.push(`start row at starts.jsonl line ${n} is v2 with no signature`);
223
+ }
224
+ else if (Buffer.from(signed.sig, "base64").toString("base64") !== signed.sig) {
225
+ // Base64 decoding skips characters outside its alphabet, so the same
226
+ // signature has many spellings; only the one the body writes is read.
227
+ result.problems.push(`start signature is not canonical base64: starts.jsonl line ${n}`);
228
+ }
229
+ else if (publicKeyPem) {
230
+ if (signedVerifies(signed, publicKeyPem))
231
+ result.signedVerified += 1;
232
+ else
233
+ result.problems.push(`start signature does not verify: starts.jsonl line ${n}`);
234
+ }
235
+ }
236
+ else if (claimsSigned(row)) {
237
+ // A version other than 2, or a signature with no version: a row written
238
+ // before signing carries none of these fields.
239
+ seenSigned = true;
240
+ result.signed += 1;
241
+ result.problems.push(`signed start row is malformed: starts.jsonl line ${n}`);
242
+ }
243
+ else {
244
+ result.unsigned = true;
245
+ if (seenSigned)
246
+ result.problems.push(`unsigned start row after a signed one: starts.jsonl line ${n}`);
247
+ // A row with its signature taken off reads as one written before signing.
248
+ // Only a reader who knows the ledger was written signed can refuse it.
249
+ else if (opts.requireSigned)
250
+ result.problems.push(`start-row-unsigned: starts.jsonl line ${n}`);
251
+ }
252
+ prevLine = line;
253
+ }
254
+ if (opts.requireSigned) {
255
+ if (result.count === 0)
256
+ result.problems.push("start-rows-missing: no start row could be read");
257
+ if (result.signed > 0 && result.startKey === "none") {
258
+ result.problems.push("start-rows-not-checked: signed start rows need a record key");
57
259
  }
58
260
  }
59
261
  return result;
60
262
  }
61
263
  export function renderStarts(summary) {
62
- return `starts ${summary.count}; largest gap ${summary.largestGapMs === null ? "none" : `${summary.largestGapMs} ms`}; previous beat missing at ${summary.missingPreviousBeat.join(", ") || "none"}; unsigned (not verified)`
264
+ const signedPart = summary.signed === 0
265
+ ? "unsigned (not verified)"
266
+ : summary.startKey === "none"
267
+ ? `${summary.signed} signed, not checked (no record key)${summary.unsigned ? "; older rows unsigned" : ""}`
268
+ : `${summary.signedVerified} of ${summary.signed} signed verify under the ${summary.startKey === "pinned" ? "pinned" : "in-ledger"} record key${summary.unsigned ? "; older rows unsigned" : ""}`;
269
+ return `starts ${summary.count}; largest gap ${summary.largestGapMs === null ? "none" : `${summary.largestGapMs} ms`}; previous beat missing at ${summary.missingPreviousBeat.join(", ") || "none"}; ${signedPart}`
270
+ + summary.problems.map((p) => `\nproblem ${p}`).join("")
63
271
  + summary.warnings.map((warning) => `\nwarning ${warning}`).join("");
64
272
  }
package/dist/install.d.ts CHANGED
@@ -763,6 +763,14 @@ export declare function ensureTokenParent(dir: string, env?: NodeJS.ProcessEnv,
763
763
  */
764
764
  export declare function restrictToOwnerWin32(target: string, spawn?: ToolSpawn, directory?: boolean): void;
765
765
  export declare function orderTarballs(files: readonly string[]): string[];
766
+ /**
767
+ * Whether this process holds the owner's rights over `file`: the owner is its
768
+ * user, or a group its token holds enabled. An owner reads the security
769
+ * descriptor even under an entry that denies it the file, so a caller who is
770
+ * refused the descriptor is not the owner. Output that names no owner or no
771
+ * user is "unknown", never "other".
772
+ */
773
+ export declare function windowsFileOwner(file: string, exec?: (argv: string[]) => ExecResult): "self" | "other" | "unknown";
766
774
  /** The SID `whoami /user` names for this process. */
767
775
  export declare function windowsInvokingSid(exec?: (argv: string[]) => ExecResult): string | undefined;
768
776
  /**