@mikeargento/bitgraph-player 0.5.1 → 0.6.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.
Files changed (50) hide show
  1. package/DOMAIN.md +119 -0
  2. package/README.md +25 -5
  3. package/dist/__tests__/domain.test.d.ts +2 -0
  4. package/dist/__tests__/domain.test.d.ts.map +1 -0
  5. package/dist/__tests__/domain.test.js +265 -0
  6. package/dist/__tests__/domain.test.js.map +1 -0
  7. package/dist/check.d.ts +45 -2
  8. package/dist/check.d.ts.map +1 -1
  9. package/dist/check.js +94 -7
  10. package/dist/check.js.map +1 -1
  11. package/dist/cli.js +194 -12
  12. package/dist/cli.js.map +1 -1
  13. package/dist/domain.d.ts +64 -0
  14. package/dist/domain.d.ts.map +1 -0
  15. package/dist/domain.js +212 -0
  16. package/dist/domain.js.map +1 -0
  17. package/dist/index.d.ts +5 -1
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +2 -0
  20. package/dist/index.js.map +1 -1
  21. package/dist/pin.d.ts +55 -0
  22. package/dist/pin.d.ts.map +1 -0
  23. package/dist/pin.js +126 -0
  24. package/dist/pin.js.map +1 -0
  25. package/dist/play.d.ts +6 -1
  26. package/dist/play.d.ts.map +1 -1
  27. package/dist/play.js +6 -1
  28. package/dist/play.js.map +1 -1
  29. package/dist/sig.d.ts +2 -0
  30. package/dist/sig.d.ts.map +1 -1
  31. package/dist/sig.js +1 -1
  32. package/dist/sig.js.map +1 -1
  33. package/dist/types.d.ts +7 -0
  34. package/dist/types.d.ts.map +1 -1
  35. package/dist/types.js +7 -0
  36. package/dist/types.js.map +1 -1
  37. package/dist/verdict.d.ts +1 -1
  38. package/dist/verdict.js +1 -1
  39. package/dist-web/verify.html +3 -3
  40. package/package.json +4 -3
  41. package/src/__tests__/domain.test.ts +321 -0
  42. package/src/check.ts +149 -9
  43. package/src/cli.ts +199 -12
  44. package/src/domain.ts +245 -0
  45. package/src/index.ts +17 -1
  46. package/src/pin.ts +155 -0
  47. package/src/play.ts +6 -1
  48. package/src/sig.ts +1 -1
  49. package/src/types.ts +8 -0
  50. package/src/verdict.ts +1 -1
package/src/cli.ts CHANGED
@@ -4,7 +4,8 @@
4
4
  /**
5
5
  * bitgraph-play <rule.json> <bundle> [--out <file>] [--summary]
6
6
  * bitgraph-play init <file>... [--out <rule.json>]
7
- * bitgraph-play check <bundle-or-file>... [--json] [--out <file>]
7
+ * bitgraph-play check <bundle-or-file>... [--json] [--out <file>] [--from <domain> [--pins <dir>]]
8
+ * bitgraph-play pin [<domain>] [--forget <domain>] [--pins <dir>] [--yes]
8
9
  *
9
10
  * Evaluate: runs a bitgraph-player/1 rule against a proof bundle
10
11
  * (directory, .tar, .tar.gz, or .tgz) and writes the verdict JSON to
@@ -22,6 +23,13 @@
22
23
  * what bounds it. Human text on stdout by default; --json for the
23
24
  * bitgraph-check/1 report. Offline. See check.ts for the vocabulary.
24
25
  *
26
+ * Pin: fetches https://<domain>/.well-known/bitgraph once (the ONLY
27
+ * network access anywhere in this package, and only when invoked), shows
28
+ * the party and every key's fingerprint, and stores the bytes verbatim
29
+ * after confirmation. `check --from <domain>` then adds one three-valued
30
+ * "domain" line per recording, offline, from the stored pin: TRUE or
31
+ * UNDETERMINED, never FALSE. Format and semantics: DOMAIN.md.
32
+ *
25
33
  * Exit codes: 0 TRUE, 1 FALSE, 2 UNDETERMINED, 3 error (init: 0 or 3).
26
34
  * Diagnostics go to stderr; stdout carries the verdict (or skeleton, or
27
35
  * check report) bytes only.
@@ -35,10 +43,14 @@ import { createHash } from "node:crypto";
35
43
  import { createReadStream, existsSync, writeFileSync } from "node:fs";
36
44
  import { readFile, stat } from "node:fs/promises";
37
45
  import { basename } from "node:path";
46
+ import { createInterface } from "node:readline/promises";
38
47
  import { pipeline } from "node:stream/promises";
39
48
  import type { AuditResult, BundleEntrySource } from "@mikeargento/bitgraph-audit";
40
49
  import { ingestBundle, ingestEntries } from "@mikeargento/bitgraph-audit";
50
+ import type { CheckOptions } from "./check.js";
41
51
  import { checkIngest, renderCheckText, serializeCheckReport } from "./check.js";
52
+ import { checkDomain, diffDomainFiles, domainKeyRefs, DomainFileError, isDomainName } from "./domain.js";
53
+ import { defaultPinsDir, fetchDomainFile, forgetPin, listPins, readPin, writePin } from "./pin.js";
42
54
  import { scaffoldRule } from "./init.js";
43
55
  import type { ScaffoldEntry } from "./init.js";
44
56
  import { play, PlayError } from "./play.js";
@@ -49,8 +61,12 @@ function usage(): number {
49
61
  "usage: bitgraph-play <rule.json> <bundle> [--out <file>] [--summary]\n" +
50
62
  " bitgraph-play init <file>... [--out <rule.json>]\n" +
51
63
  " bitgraph-play check <bundle-or-file>... [--json] [--out <file>]\n" +
52
- ' "--" ends option parsing; a rule file literally named "init" or\n' +
53
- ' "check" is evaluated with: bitgraph-play -- init <bundle>\n' +
64
+ " [--from <domain> [--pins <dir>]]\n" +
65
+ " bitgraph-play pin [<domain>] [--forget <domain>] [--pins <dir>] [--yes]\n" +
66
+ ' "--" ends option parsing; a rule file literally named "init",\n' +
67
+ ' "check" or "pin" is evaluated with: bitgraph-play -- init <bundle>\n' +
68
+ " pin is the only command that touches the network; check --from\n" +
69
+ " reads the stored pin and runs offline\n" +
54
70
  " exit codes: 0 TRUE, 1 FALSE, 2 UNDETERMINED, 3 error\n"
55
71
  );
56
72
  return 3;
@@ -91,10 +107,18 @@ interface ParsedArgs {
91
107
  outFile?: string;
92
108
  summary: boolean;
93
109
  json: boolean;
110
+ from?: string;
111
+ pinsDir?: string;
112
+ forget?: string;
113
+ yes: boolean;
94
114
  }
95
115
 
96
116
  function parseArgs(args: string[]): ParsedArgs | undefined {
97
- const parsed: ParsedArgs = { positional: [], summary: false, json: false };
117
+ const parsed: ParsedArgs = { positional: [], summary: false, json: false, yes: false };
118
+ const valueFor = (i: number): string | undefined => {
119
+ const next = args[i];
120
+ return next === undefined || next.startsWith("-") ? undefined : next;
121
+ };
98
122
  for (let i = 0; i < args.length; i++) {
99
123
  const arg = args[i] as string;
100
124
  if (arg === "--") {
@@ -102,13 +126,27 @@ function parseArgs(args: string[]): ParsedArgs | undefined {
102
126
  parsed.positional.push(...args.slice(i + 1));
103
127
  break;
104
128
  } else if (arg === "--out") {
105
- const next = args[++i];
106
- if (next === undefined || next.startsWith("-")) return undefined;
129
+ const next = valueFor(++i);
130
+ if (next === undefined) return undefined;
107
131
  parsed.outFile = next;
132
+ } else if (arg === "--from") {
133
+ const next = valueFor(++i);
134
+ if (next === undefined) return undefined;
135
+ parsed.from = next;
136
+ } else if (arg === "--pins") {
137
+ const next = valueFor(++i);
138
+ if (next === undefined) return undefined;
139
+ parsed.pinsDir = next;
140
+ } else if (arg === "--forget") {
141
+ const next = valueFor(++i);
142
+ if (next === undefined) return undefined;
143
+ parsed.forget = next;
108
144
  } else if (arg === "--summary") {
109
145
  parsed.summary = true;
110
146
  } else if (arg === "--json") {
111
147
  parsed.json = true;
148
+ } else if (arg === "--yes") {
149
+ parsed.yes = true;
112
150
  } else if (arg.startsWith("-")) {
113
151
  return undefined;
114
152
  } else {
@@ -125,10 +163,43 @@ function parseArgs(args: string[]): ParsedArgs | undefined {
125
163
  * `bitgraph-play check proof.json photo.jpg` works without a folder.
126
164
  */
127
165
  async function runCheck(args: ParsedArgs): Promise<number> {
128
- if (args.summary) return usage();
166
+ if (args.summary || args.yes || args.forget !== undefined) return usage();
167
+ if (args.pinsDir !== undefined && args.from === undefined) return usage();
129
168
  const targets = args.positional;
130
169
  if (targets.length === 0) return usage();
131
170
 
171
+ // Resolve the pin before touching the bundle: a missing pin should fail
172
+ // in milliseconds, with its remedy, not after a long ingest. check
173
+ // itself NEVER fetches; the pin was the one network step, already done.
174
+ let options: CheckOptions | undefined;
175
+ if (args.from !== undefined) {
176
+ const domain = args.from.toLowerCase();
177
+ if (!isDomainName(domain)) {
178
+ process.stderr.write(`error: not a domain name: ${args.from}\n`);
179
+ return 3;
180
+ }
181
+ const pinsDir = args.pinsDir ?? defaultPinsDir();
182
+ let pin;
183
+ try {
184
+ pin = readPin(domain, pinsDir);
185
+ } catch (err) {
186
+ process.stderr.write(`error: the stored pin for ${domain} is malformed`);
187
+ if (err instanceof DomainFileError && err.issues[0] !== undefined) {
188
+ process.stderr.write(`: ${err.issues[0]}`);
189
+ }
190
+ process.stderr.write(`\n pin it again: bitgraph-play pin ${domain}\n`);
191
+ return 3;
192
+ }
193
+ if (pin === undefined) {
194
+ process.stderr.write(
195
+ `error: no pin for ${domain}\n` +
196
+ ` pin it once (the only step that needs the network): bitgraph-play pin ${domain}\n`
197
+ );
198
+ return 3;
199
+ }
200
+ options = { from: checkDomain(pin.file) };
201
+ }
202
+
132
203
  let ingest;
133
204
  try {
134
205
  const single = targets.length === 1 ? await stat(targets[0] as string) : undefined;
@@ -153,7 +224,7 @@ async function runCheck(args: ParsedArgs): Promise<number> {
153
224
  return 3;
154
225
  }
155
226
 
156
- const report = await checkIngest(ingest);
227
+ const report = await checkIngest(ingest, options);
157
228
  const bytes = args.json ? serializeCheckReport(report) : renderCheckText(report);
158
229
  if (args.outFile !== undefined) {
159
230
  writeFileSync(args.outFile, bytes);
@@ -169,7 +240,7 @@ function looksLikeArchive(path: string): boolean {
169
240
  }
170
241
 
171
242
  async function runInit(args: ParsedArgs): Promise<number> {
172
- if (args.summary || args.json) return usage();
243
+ if (args.summary || args.json || args.from !== undefined || args.pinsDir !== undefined || args.yes || args.forget !== undefined) return usage();
173
244
  const files = args.positional;
174
245
  if (files.length === 0) return usage();
175
246
  if (args.outFile !== undefined && existsSync(args.outFile)) {
@@ -225,7 +296,8 @@ async function runInit(args: ParsedArgs): Promise<number> {
225
296
  }
226
297
 
227
298
  async function runEvaluate(args: ParsedArgs): Promise<number> {
228
- if (args.json || args.positional.length !== 2) return usage();
299
+ if (args.json || args.from !== undefined || args.pinsDir !== undefined || args.yes || args.forget !== undefined) return usage();
300
+ if (args.positional.length !== 2) return usage();
229
301
  const [rulePath, bundlePath] = args.positional as [string, string];
230
302
 
231
303
  let result;
@@ -252,12 +324,126 @@ async function runEvaluate(args: ParsedArgs): Promise<number> {
252
324
  return result.exitCode;
253
325
  }
254
326
 
327
+ /**
328
+ * pin: the only command in this package that touches the network, and
329
+ * only when invoked. Conversational output goes to stderr (there are no
330
+ * report bytes); the pin listing, which IS the output, goes to stdout.
331
+ */
332
+ async function runPin(args: ParsedArgs): Promise<number> {
333
+ if (args.summary || args.json || args.outFile !== undefined || args.from !== undefined) return usage();
334
+ const pinsDir = args.pinsDir ?? defaultPinsDir();
335
+
336
+ if (args.forget !== undefined) {
337
+ if (args.positional.length !== 0) return usage();
338
+ const domain = args.forget.toLowerCase();
339
+ if (!isDomainName(domain)) {
340
+ process.stderr.write(`error: not a domain name: ${args.forget}\n`);
341
+ return 3;
342
+ }
343
+ if (forgetPin(domain, pinsDir)) {
344
+ process.stderr.write(`forgot ${domain}\n`);
345
+ return 0;
346
+ }
347
+ process.stderr.write(`error: no pin for ${domain}\n`);
348
+ return 3;
349
+ }
350
+
351
+ if (args.positional.length === 0) {
352
+ const pins = listPins(pinsDir);
353
+ if (pins.length === 0) {
354
+ process.stderr.write(
355
+ "no pins yet\n pin a domain (the only step that needs the network): bitgraph-play pin <domain>\n"
356
+ );
357
+ return 0;
358
+ }
359
+ for (const pin of pins) {
360
+ process.stdout.write(
361
+ pin.malformed
362
+ ? `${pin.domain} (malformed pin; pin it again or --forget it)\n`
363
+ : `${pin.domain} ${pin.party as string} ${pin.keyCount as number} key(s) pinned ${pin.pinnedAt.toISOString().slice(0, 10)}\n`
364
+ );
365
+ }
366
+ return 0;
367
+ }
368
+
369
+ if (args.positional.length !== 1) return usage();
370
+ const domain = (args.positional[0] as string).toLowerCase();
371
+
372
+ let fetched;
373
+ try {
374
+ fetched = await fetchDomainFile(domain);
375
+ } catch (err) {
376
+ if (err instanceof DomainFileError) {
377
+ process.stderr.write(
378
+ `error: the file at https://${domain}/.well-known/bitgraph is not a valid bitgraph-domain/1 file:\n`
379
+ );
380
+ for (const issue of err.issues) process.stderr.write(` - ${issue}\n`);
381
+ } else {
382
+ process.stderr.write(`error: ${(err as Error).message}\n`);
383
+ }
384
+ return 3;
385
+ }
386
+
387
+ const refs = domainKeyRefs(fetched.file);
388
+ const nameWidth = refs.reduce((w, r) => Math.max(w, r.name.length), 4);
389
+ process.stderr.write(`\n${domain} · ${fetched.file.party}\n`);
390
+ for (const ref of refs) {
391
+ process.stderr.write(` ${ref.name.padEnd(nameWidth)} ${ref.key.alg.padEnd(7)} ${ref.fingerprint}\n`);
392
+ }
393
+
394
+ let existing;
395
+ let existingMalformed = false;
396
+ try {
397
+ existing = readPin(domain, pinsDir);
398
+ } catch {
399
+ existingMalformed = true;
400
+ }
401
+ if (existingMalformed) {
402
+ process.stderr.write(`\nthe stored pin for ${domain} is malformed and will be replaced\n`);
403
+ } else if (existing !== undefined) {
404
+ const diff = diffDomainFiles(existing.file, fetched.file);
405
+ const changes: string[] = [];
406
+ if (diff.partyChanged !== undefined) {
407
+ changes.push(` party: "${diff.partyChanged.before}" is now "${diff.partyChanged.after}"`);
408
+ }
409
+ for (const ref of diff.added) changes.push(` + ${ref.name} ${ref.key.alg} ${ref.fingerprint}`);
410
+ for (const ref of diff.removed) changes.push(` - ${ref.name} ${ref.key.alg} ${ref.fingerprint}`);
411
+ for (const ch of diff.changed) changes.push(` ~ ${ch.name} now ${ch.after.key.alg} ${ch.after.fingerprint}`);
412
+ const pinnedOn = existing.pinnedAt.toISOString().slice(0, 10);
413
+ process.stderr.write(
414
+ changes.length === 0
415
+ ? `\nunchanged since the stored pin (${pinnedOn})\n`
416
+ : `\nchanges since the stored pin (${pinnedOn}):\n${changes.join("\n")}\n`
417
+ );
418
+ }
419
+
420
+ if (!args.yes) {
421
+ if (!process.stdin.isTTY) {
422
+ process.stderr.write("\nerror: not a terminal; pass --yes to pin non-interactively\n");
423
+ return 3;
424
+ }
425
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
426
+ const answer = (await rl.question(`\npin ${refs.length} key(s) for ${domain}? [y/N] `)).trim().toLowerCase();
427
+ rl.close();
428
+ if (answer !== "y" && answer !== "yes") {
429
+ process.stderr.write("not pinned\n");
430
+ return 3;
431
+ }
432
+ }
433
+
434
+ const path = writePin(domain, fetched.bytes, pinsDir);
435
+ process.stderr.write(
436
+ `pinned: ${path}\nchecks now run offline: bitgraph-play check <export> --from ${domain}\n`
437
+ );
438
+ return 0;
439
+ }
440
+
255
441
  async function main(): Promise<number> {
256
442
  const argv = process.argv.slice(2);
257
443
  // "--" as the first token forces evaluate mode: parseArgs treats
258
444
  // everything after it as positional, so a rule file literally named
259
- // "init" or "check" is reachable as `bitgraph-play -- init <bundle>`.
260
- const subcommand = argv[0] === "init" || argv[0] === "check" ? argv[0] : undefined;
445
+ // "init", "check" or "pin" is reachable as `bitgraph-play -- init <bundle>`.
446
+ const subcommand = argv[0] === "init" || argv[0] === "check" || argv[0] === "pin" ? argv[0] : undefined;
261
447
  if (subcommand !== undefined && existsSync(subcommand)) {
262
448
  // Both readings are plausible here; a silent pick would hand a
263
449
  // 0.1.1 caller a skeleton with exit 0 where the published contract
@@ -273,6 +459,7 @@ async function main(): Promise<number> {
273
459
  if (parsed === undefined) return usage();
274
460
  if (subcommand === "init") return runInit(parsed);
275
461
  if (subcommand === "check") return runCheck(parsed);
462
+ if (subcommand === "pin") return runPin(parsed);
276
463
  return runEvaluate(parsed);
277
464
  }
278
465
 
package/src/domain.ts ADDED
@@ -0,0 +1,245 @@
1
+ // Copyright (c) 2024-2026 Mike Argento. Licensed under the MIT License. See LICENSE.
2
+
3
+ /**
4
+ * BitGraph Domain: a party's own domain publishing the keys that record
5
+ * for it. The file (`bitgraph-domain/1`) is served at
6
+ * `https://<domain>/.well-known/bitgraph` and is the party speaking for
7
+ * itself, never BitGraph speaking about the party: parsing enforces
8
+ * well-formedness only, and adopting the statement is the reader's act
9
+ * (see pin.ts). The format is DOMAIN.md; evaluation semantics (SPEC.md
10
+ * sections 1 through 9) are untouched by everything in this module.
11
+ *
12
+ * The file shares SPEC section 9.1's trusted-key grammar, so an entry
13
+ * pastes into a format 2 rule's `trustedKeys` unchanged, and a key's
14
+ * fingerprint is the lowercase hex SHA-256 of the decoded key bytes,
15
+ * which for es256 is exactly the `keyId` actor proofs carry. Fingerprints
16
+ * are always derived here and never read from the file, so a domain
17
+ * cannot claim a key it does not show.
18
+ */
19
+
20
+ import { createHash } from "node:crypto";
21
+ import type { CheckDomain } from "./check.js";
22
+ import { decodeDigestBytes } from "./rule.js";
23
+ import type { TrustedKey } from "./sig.js";
24
+ import { decodeB64Strict, keyObjectFor, parseSigFile, verifySigFile } from "./sig.js";
25
+
26
+ export const DOMAIN_FILE_VERSION = "bitgraph-domain/1";
27
+ export const DOMAIN_WELL_KNOWN_PATH = "/.well-known/bitgraph";
28
+ export const DOMAIN_FILE_MAX_BYTES = 65_536;
29
+
30
+ export interface DomainFile {
31
+ version: "bitgraph-domain/1";
32
+ /** Lowercase hostname; the binding. Must equal the domain the reader asked for. */
33
+ domain: string;
34
+ /** The name the domain gives itself. Display only. */
35
+ party: string;
36
+ /** SPEC §9.1 trusted-key bodies, named. */
37
+ keys: Record<string, TrustedKey>;
38
+ }
39
+
40
+ export class DomainFileError extends Error {
41
+ readonly issues: readonly string[];
42
+ constructor(issues: string[]) {
43
+ super(issues[0] ?? "invalid domain file");
44
+ this.name = "DomainFileError";
45
+ this.issues = issues;
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Lowercase registrable hostname: dot-separated LDH labels, at least two,
51
+ * no scheme, no port, no path. Also the safety property the pin store
52
+ * rests on: a name this grammar accepts contains no path separators.
53
+ */
54
+ const LABEL = "[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?";
55
+ const DOMAIN_RE = new RegExp(`^${LABEL}(?:\\.${LABEL})+$`);
56
+
57
+ export function isDomainName(s: string): boolean {
58
+ return s.length > 0 && s.length <= 253 && DOMAIN_RE.test(s);
59
+ }
60
+
61
+ function isPlainObject(v: unknown): v is Record<string, unknown> {
62
+ return typeof v === "object" && v !== null && !Array.isArray(v);
63
+ }
64
+
65
+ /**
66
+ * Parse and validate a bitgraph-domain/1 file. Strict: unknown fields are
67
+ * errors (additions are a new format version), and key material that does
68
+ * not decode is refused here rather than stored, so a pin can never hold
69
+ * keys that silently match nothing. Throws DomainFileError with every
70
+ * issue found.
71
+ */
72
+ export function parseDomainFile(input: Uint8Array | string, expectedDomain?: string): DomainFile {
73
+ const issues: string[] = [];
74
+ const text = typeof input === "string" ? input : Buffer.from(input).toString("utf8");
75
+ if (typeof input !== "string" && input.length > DOMAIN_FILE_MAX_BYTES) {
76
+ throw new DomainFileError([`file is ${input.length} bytes; the cap is ${DOMAIN_FILE_MAX_BYTES}`]);
77
+ }
78
+
79
+ let raw: unknown;
80
+ try {
81
+ raw = JSON.parse(text);
82
+ } catch (err) {
83
+ throw new DomainFileError([`not JSON: ${(err as Error).message}`]);
84
+ }
85
+ if (!isPlainObject(raw)) throw new DomainFileError(["not a JSON object"]);
86
+
87
+ for (const k of Object.keys(raw)) {
88
+ if (!["version", "domain", "party", "keys"].includes(k)) {
89
+ issues.push(`unknown field "${k}" (additions are a new format version)`);
90
+ }
91
+ }
92
+
93
+ if (raw["version"] !== DOMAIN_FILE_VERSION) {
94
+ issues.push(`"version" must be exactly "${DOMAIN_FILE_VERSION}"`);
95
+ }
96
+
97
+ const domain = raw["domain"];
98
+ if (typeof domain !== "string" || !isDomainName(domain)) {
99
+ issues.push(`"domain" must be a lowercase hostname (no scheme, no port, no path)`);
100
+ } else if (expectedDomain !== undefined && domain !== expectedDomain) {
101
+ issues.push(
102
+ `the file names domain "${domain}" but was requested for "${expectedDomain}"; refusing to store one party's file under another party's name`
103
+ );
104
+ }
105
+
106
+ const party = raw["party"];
107
+ if (typeof party !== "string" || party.trim().length === 0) {
108
+ issues.push(`"party" is required: the name the domain gives itself`);
109
+ }
110
+
111
+ const keys = Object.create(null) as Record<string, TrustedKey>;
112
+ const rawKeys = raw["keys"];
113
+ if (!isPlainObject(rawKeys) || Object.keys(rawKeys).length === 0) {
114
+ issues.push(`"keys" must be an object naming at least one key`);
115
+ } else {
116
+ for (const [name, entry] of Object.entries(rawKeys)) {
117
+ const where = `keys.${name}`;
118
+ if (!/^[A-Za-z0-9_.-]+$/.test(name) || /^[0-9]+$/.test(name)) {
119
+ issues.push(`${where}: key name must match [A-Za-z0-9_.-]+ with at least one non-digit`);
120
+ continue;
121
+ }
122
+ if (!isPlainObject(entry)) {
123
+ issues.push(`${where}: must be an object`);
124
+ continue;
125
+ }
126
+ for (const k of Object.keys(entry)) {
127
+ if (k !== "alg" && k !== "publicKey") issues.push(`${where}: unknown field "${k}"`);
128
+ }
129
+ const alg = entry["alg"];
130
+ const publicKey = entry["publicKey"];
131
+ if (alg !== "ed25519" && alg !== "es256") {
132
+ issues.push(`${where}: "alg" must be "ed25519" or "es256"`);
133
+ continue;
134
+ }
135
+ if (typeof publicKey !== "string" || publicKey.length === 0) {
136
+ issues.push(`${where}: "publicKey" is required and must be a non-empty string`);
137
+ continue;
138
+ }
139
+ const key: TrustedKey = { alg, publicKey };
140
+ if (keyObjectFor(key) === undefined) {
141
+ issues.push(
142
+ `${where}: key material does not decode as ${alg} (${alg === "es256" ? "SPKI DER for P-256" : "raw 32-byte key"}, standard base64)`
143
+ );
144
+ continue;
145
+ }
146
+ keys[name] = key;
147
+ }
148
+ }
149
+
150
+ if (issues.length > 0) throw new DomainFileError(issues);
151
+ return { version: DOMAIN_FILE_VERSION, domain: domain as string, party: (party as string).trim(), keys };
152
+ }
153
+
154
+ /**
155
+ * Lowercase hex SHA-256 of the decoded publicKey bytes. For es256 this is
156
+ * exactly the actor keyId (hex SHA-256 of the SPKI DER). Undefined when
157
+ * the material does not decode, which parseDomainFile refuses anyway.
158
+ */
159
+ export function keyFingerprint(key: TrustedKey): string | undefined {
160
+ const material = decodeB64Strict(key.publicKey);
161
+ if (material === undefined) return undefined;
162
+ return createHash("sha256").update(material).digest("hex");
163
+ }
164
+
165
+ export interface DomainKeyRef {
166
+ name: string;
167
+ key: TrustedKey;
168
+ fingerprint: string;
169
+ }
170
+
171
+ /** Every key with its derived fingerprint, name order. */
172
+ export function domainKeyRefs(file: DomainFile): DomainKeyRef[] {
173
+ const refs: DomainKeyRef[] = [];
174
+ for (const name of Object.keys(file.keys).sort()) {
175
+ const key = file.keys[name] as TrustedKey;
176
+ const fingerprint = keyFingerprint(key);
177
+ if (fingerprint !== undefined) refs.push({ name, key, fingerprint });
178
+ }
179
+ return refs;
180
+ }
181
+
182
+ export interface DomainDiff {
183
+ partyChanged?: { before: string; after: string };
184
+ added: DomainKeyRef[];
185
+ removed: DomainKeyRef[];
186
+ changed: { name: string; before: DomainKeyRef; after: DomainKeyRef }[];
187
+ unchanged: number;
188
+ }
189
+
190
+ /** What a re-pin would change, for showing before asking. */
191
+ export function diffDomainFiles(before: DomainFile, after: DomainFile): DomainDiff {
192
+ const beforeRefs = new Map(domainKeyRefs(before).map((r) => [r.name, r]));
193
+ const afterRefs = new Map(domainKeyRefs(after).map((r) => [r.name, r]));
194
+ const diff: DomainDiff = { added: [], removed: [], changed: [], unchanged: 0 };
195
+ if (before.party !== after.party) diff.partyChanged = { before: before.party, after: after.party };
196
+ for (const [name, ref] of afterRefs) {
197
+ const prior = beforeRefs.get(name);
198
+ if (prior === undefined) diff.added.push(ref);
199
+ else if (prior.key.alg !== ref.key.alg || prior.key.publicKey !== ref.key.publicKey) {
200
+ diff.changed.push({ name, before: prior, after: ref });
201
+ } else diff.unchanged += 1;
202
+ }
203
+ for (const [name, ref] of beforeRefs) {
204
+ if (!afterRefs.has(name)) diff.removed.push(ref);
205
+ }
206
+ return diff;
207
+ }
208
+
209
+ /**
210
+ * The check-report adapter: what `check --from` consults per recording.
211
+ * Defined as an interface in check.ts so the check module (which also
212
+ * builds verify.html) never imports the crypto this module uses; the CLI
213
+ * hands the report builder this object.
214
+ */
215
+ export function checkDomain(file: DomainFile): CheckDomain {
216
+ const actorNames = new Map<string, string>();
217
+ for (const ref of domainKeyRefs(file)) {
218
+ if (ref.key.alg !== "es256") continue;
219
+ if (!actorNames.has(ref.fingerprint)) actorNames.set(ref.fingerprint, ref.name);
220
+ }
221
+ const sigKeys = domainKeyRefs(file)
222
+ .map((ref) => ({ name: ref.name, key: ref.key, keyObject: keyObjectFor(ref.key) }))
223
+ .filter((k) => k.keyObject !== undefined);
224
+
225
+ return {
226
+ domain: file.domain,
227
+ party: file.party,
228
+ keyCount: Object.keys(file.keys).length,
229
+ actorKeyName: (keyId: string): string | undefined => actorNames.get(keyId.toLowerCase()),
230
+ signatureKeyName: (targetSha256Hex: string, evidence: ReadonlyMap<string, Uint8Array>): string | undefined => {
231
+ // Deterministic: candidates in ascending content-hash order, keys in
232
+ // name order; the first verifying pair decides (SPEC §9.4 discipline).
233
+ for (const sha256Hex of [...evidence.keys()].sort()) {
234
+ const sig = parseSigFile(evidence.get(sha256Hex) as Uint8Array);
235
+ if (sig === undefined) continue;
236
+ for (const k of sigKeys) {
237
+ if (verifySigFile(sig, k.key, k.keyObject as NonNullable<typeof k.keyObject>, targetSha256Hex, decodeDigestBytes)) {
238
+ return k.name;
239
+ }
240
+ }
241
+ }
242
+ return undefined;
243
+ },
244
+ };
245
+ }
package/src/index.ts CHANGED
@@ -46,4 +46,20 @@ export type { Evaluation } from "./evaluate.js";
46
46
  export { buildVerdict, serializeVerdict, playerVersion, PLAYER_VERSION } from "./verdict.js";
47
47
 
48
48
  export { checkIngest, buildCheckReport, renderCheckText, serializeCheckReport, KNOWN_ENCLAVE_MEASUREMENTS } from "./check.js";
49
- export type { CheckReport, CheckRecording, CheckAnchor, CheckLine, CheckBounds, CheckBound, CheckOptions } from "./check.js";
49
+ export type { CheckReport, CheckRecording, CheckAnchor, CheckLine, CheckBounds, CheckBound, CheckOptions, CheckDomain } from "./check.js";
50
+
51
+ export {
52
+ parseDomainFile,
53
+ isDomainName,
54
+ keyFingerprint,
55
+ domainKeyRefs,
56
+ diffDomainFiles,
57
+ checkDomain,
58
+ DomainFileError,
59
+ DOMAIN_FILE_VERSION,
60
+ DOMAIN_WELL_KNOWN_PATH,
61
+ DOMAIN_FILE_MAX_BYTES,
62
+ } from "./domain.js";
63
+ export type { DomainFile, DomainKeyRef, DomainDiff } from "./domain.js";
64
+ export { defaultPinsDir, readPin, writePin, forgetPin, listPins, fetchDomainFile } from "./pin.js";
65
+ export type { StoredPin, PinListEntry, FetchLike } from "./pin.js";