@mikeargento/bitgraph-audit 0.14.0 → 0.15.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/src/ingest.ts CHANGED
@@ -24,6 +24,16 @@
24
24
  * is evidence too: the header of the Base block a proof signs as its floor
25
25
  * (commit.slotFloor, enclave v10), listed for the temporal stage.
26
26
  *
27
+ * A BitGraphed file (any bitgraph-carrier version, found by the block at its
28
+ * end, never by name) is read in place: the proof inside its block is recorded
29
+ * as an observed proof from "<path>#proof", exactly like a proof file, so a
30
+ * token spent twice shows in a folder of carried files as it does in a folder
31
+ * of loose receipts; and the bytes before the block are the artifact at
32
+ * <path>. The file's whole bytes are never an artifact. Other evidence a block
33
+ * may carry (floor witnesses, ceilings) is read only when the file is audited
34
+ * on its own. A block that is there but cannot be read is a carrier-corrupt
35
+ * finding: its proof cannot be counted.
36
+ *
27
37
  * Memory: archives are never unpacked to disk and never loaded whole.
28
38
  * Every entry is hashed incrementally as it streams. Only small JSON
29
39
  * candidates (at most MAX_CANDIDATE_JSON_BYTES) are buffered for parsing,
@@ -48,8 +58,17 @@ import { open, readdir, readFile, stat } from "node:fs/promises";
48
58
  import { join } from "node:path";
49
59
  import { createGunzip } from "node:zlib";
50
60
  import { sha256 } from "@noble/hashes/sha256";
51
- import { computeProofHash, computeChainHash, EXPORT_FORMAT, parseExport } from "@mikeargento/bitgraph-verify";
52
- import type { BitGraphProof } from "@mikeargento/bitgraph-verify";
61
+ import {
62
+ computeProofHash,
63
+ computeChainHash,
64
+ EXPORT_FORMAT,
65
+ parseExport,
66
+ parseCarrier,
67
+ CARRIER_MAGIC,
68
+ CARRIER_OVERHEAD,
69
+ MAX_CARRIER_PAYLOAD,
70
+ } from "@mikeargento/bitgraph-verify";
71
+ import type { BitGraphProof, CarrierPayload } from "@mikeargento/bitgraph-verify";
53
72
  import { readTarEntries } from "./tar.js";
54
73
  import { combineEntryDigests } from "./contents-hash.js";
55
74
  import type {
@@ -91,6 +110,19 @@ const MAX_CANDIDATE_JSON_BYTES = 8 * 1024 * 1024;
91
110
  const MAX_EXPORT_JSON_BYTES = 192 * 1024 * 1024;
92
111
  /** How many opening bytes decide whether an entry opens an export object. */
93
112
  const EXPORT_SNIFF_BYTES = 256;
113
+
114
+ /**
115
+ * The most of an entry's end that can hold a BitGraphed file's block: the
116
+ * largest payload a block may declare and the block's fixed bytes. Every
117
+ * entry keeps at most this much of its end while it streams, so a block is
118
+ * found in one pass without holding the file.
119
+ */
120
+ const CARRIER_WINDOW = MAX_CARRIER_PAYLOAD + CARRIER_OVERHEAD;
121
+
122
+ /** A block found at an entry's end. innerSha256Hex is filled by a second read of the bytes before it. */
123
+ type CarrierFound =
124
+ | { kind: "carrier"; payload: CarrierPayload; blockOffset: number; innerSha256Hex?: string }
125
+ | { kind: "corrupt"; reason: string };
94
126
  /** Producers write format first (buildExport); whitespace and one BOM are tolerated. */
95
127
  const EXPORT_OPENING = /^\s*\{\s*"format"\s*:\s*"(bitgraph-export\/[^"\\]{0,64})"/;
96
128
 
@@ -156,13 +188,25 @@ export async function ingestBundle(
156
188
  entriesScanned++;
157
189
  const stream = createReadStream(file.absPath);
158
190
  const hashed = await hashEntryStream(file.relPath, undefined, undefined, stream, exportCap);
191
+ if (hashed.carrier?.kind === "carrier") {
192
+ const n = hashed.carrier.blockOffset;
193
+ hashed.carrier.innerSha256Hex = await hashPrefix(
194
+ n === 0 ? [] : createReadStream(file.absPath, { start: 0, end: n - 1 }),
195
+ n
196
+ );
197
+ }
159
198
  scanned.push(makeScannedEntry(file.relPath, hashed));
160
199
  }
161
200
  } else {
201
+ // A BitGraphed file in an archive: the bytes before its block are hashed on
202
+ // a second pass over the archive, by the entry's place among its files.
203
+ const carriedByOrdinal = new Map<number, CarrierFound & { kind: "carrier" }>();
162
204
  const { stream, close } = openContainerByteStream(bundlePath, container);
163
205
  try {
206
+ let ordinal = -1;
164
207
  for await (const entry of readTarEntries(stream, limits)) {
165
208
  if (entry.kind !== "file") continue;
209
+ ordinal++;
166
210
  entriesScanned++;
167
211
  const normalized = normalizeEntryPath(entry.path);
168
212
  // Every file entry, safe or not, weighs on the bundle-root
@@ -181,11 +225,29 @@ export async function ingestBundle(
181
225
  const slash = normalized.path.indexOf("/");
182
226
  const strippedVariant = slash === -1 ? undefined : normalized.path.slice(slash + 1);
183
227
  const hashed = await hashEntryStream(normalized.path, strippedVariant, entry.size, entry.body, exportCap);
228
+ if (hashed.carrier?.kind === "carrier") carriedByOrdinal.set(ordinal, hashed.carrier);
184
229
  scanned.push(makeScannedEntry(normalized.path, hashed));
185
230
  }
186
231
  } finally {
187
232
  close();
188
233
  }
234
+ if (carriedByOrdinal.size > 0) {
235
+ const second = openContainerByteStream(bundlePath, container);
236
+ try {
237
+ let ordinal = -1;
238
+ for await (const entry of readTarEntries(second.stream, limits)) {
239
+ if (entry.kind !== "file") continue;
240
+ ordinal++;
241
+ const carrier = carriedByOrdinal.get(ordinal);
242
+ if (carrier === undefined) continue;
243
+ carrier.innerSha256Hex = await hashPrefix(entry.body, carrier.blockOffset);
244
+ carriedByOrdinal.delete(ordinal);
245
+ if (carriedByOrdinal.size === 0) break;
246
+ }
247
+ } finally {
248
+ second.close();
249
+ }
250
+ }
189
251
  }
190
252
 
191
253
  // ---------------------------------------------------------------------
@@ -271,6 +333,9 @@ export async function ingestEntries(
271
333
  openAsChunks(entry.open()),
272
334
  MAX_EXPORT_JSON_BYTES
273
335
  );
336
+ if (hashed.carrier?.kind === "carrier") {
337
+ hashed.carrier.innerSha256Hex = await hashPrefix(openAsChunks(entry.open()), hashed.carrier.blockOffset);
338
+ }
274
339
  scanned.push(makeScannedEntry(normalized.path, hashed));
275
340
  sources.set(normalized.path, entry);
276
341
  }
@@ -354,6 +419,7 @@ function finalizeIngest(params: FinalizeParams): IngestResult {
354
419
  entryDigest,
355
420
  ...(entry.json !== undefined ? { json: entry.json } : {}),
356
421
  ...(entry.exportTooLarge !== undefined ? { exportTooLarge: entry.exportTooLarge } : {}),
422
+ ...(entry.carrier !== undefined ? { carrier: entry.carrier } : {}),
357
423
  });
358
424
  }
359
425
  const finalEntries = Array.from(finalByPath.values());
@@ -383,6 +449,8 @@ function finalizeIngest(params: FinalizeParams): IngestResult {
383
449
  let proofFiles = 0;
384
450
  let exactDuplicates = 0;
385
451
  let semanticDuplicates = 0;
452
+ let carriers = 0;
453
+ let corruptCarriers = 0;
386
454
 
387
455
  for (const entry of finalEntries) {
388
456
  if (entry.path === MANIFEST_PATH) {
@@ -390,6 +458,47 @@ function finalizeIngest(params: FinalizeParams): IngestResult {
390
458
  continue;
391
459
  }
392
460
 
461
+ // A BitGraphed file: its proof joins the proof analysis from
462
+ // "<path>#proof", and the bytes before its block are the artifact.
463
+ if (entry.carrier !== undefined) {
464
+ carriers++;
465
+ if (entry.carrier.kind === "corrupt") {
466
+ corruptCarriers++;
467
+ findings.push({
468
+ code: "carrier-corrupt",
469
+ path: entry.path,
470
+ message: `the file ends in a BitGraphed file's block that cannot be read (${entry.carrier.reason}); the proof it holds is not counted`,
471
+ });
472
+ indexArtifact(entry, artifactsByHex);
473
+ continue;
474
+ }
475
+ const proofEntry: FinalEntry = { ...entry, path: `${entry.path}#proof` };
476
+ const carried = entry.carrier.payload.proof as unknown;
477
+ if (isProofShaped(carried)) {
478
+ const version = (carried as Record<string, unknown>)["version"] as string;
479
+ if (version === "bitgraph/1") {
480
+ proofFiles++;
481
+ const outcome = recordMemberProof(proofEntry, carried as Record<string, unknown>, proofsByHash, proofs, findings);
482
+ if (outcome === "exact-duplicate") exactDuplicates++;
483
+ if (outcome === "semantic-duplicate") semanticDuplicates++;
484
+ } else {
485
+ unsupportedVersions.push({ code: "unsupported-version", path: proofEntry.path, version, fileSha256Hex: entry.sha256Hex });
486
+ findings.push({
487
+ code: "unsupported-version",
488
+ path: proofEntry.path,
489
+ message: `the proof inside this BitGraphed file is rejected: version "${version}" is not "bitgraph/1"`,
490
+ details: { version },
491
+ });
492
+ }
493
+ }
494
+ indexArtifact(
495
+ { ...entry, sha256Hex: entry.carrier.innerSha256Hex as string, byteLength: entry.carrier.blockOffset },
496
+ artifactsByHex,
497
+ true
498
+ );
499
+ continue;
500
+ }
501
+
393
502
  // An export too large to parse is still an export: reported, never an
394
503
  // artifact, and never silently checked as nothing.
395
504
  if (entry.exportTooLarge !== undefined) {
@@ -533,6 +642,8 @@ function finalizeIngest(params: FinalizeParams): IngestResult {
533
642
  ...(floorHeaders.length > 0 ? { floorHeaders: floorHeaders.length } : {}),
534
643
  ceilings: ceilings.length + ceilingStatuses.length,
535
644
  exports: exportFiles.length,
645
+ ...(carriers > 0 ? { carriers } : {}),
646
+ ...(corruptCarriers > 0 ? { corruptCarriers } : {}),
536
647
  skippedUnsafePaths,
537
648
  };
538
649
 
@@ -609,7 +720,7 @@ async function* streamArtifactsFor(
609
720
  if (source === undefined) continue;
610
721
  let bytes: Uint8Array;
611
722
  try {
612
- bytes = await readSourceWhole(source);
723
+ bytes = artifactBytesAt(artifact, relPath, await readSourceWhole(source));
613
724
  } catch {
614
725
  continue;
615
726
  }
@@ -626,7 +737,7 @@ async function* streamArtifactsFor(
626
737
  for (const relPath of artifact.paths) {
627
738
  let bytes: Uint8Array;
628
739
  try {
629
- bytes = new Uint8Array(await readFile(join(ingest.bundlePath, ...relPath.split("/"))));
740
+ bytes = artifactBytesAt(artifact, relPath, new Uint8Array(await readFile(join(ingest.bundlePath, ...relPath.split("/")))));
630
741
  } catch {
631
742
  continue;
632
743
  }
@@ -663,7 +774,7 @@ async function* streamArtifactsFor(
663
774
  chunks.push(chunk.slice());
664
775
  total += chunk.length;
665
776
  }
666
- const bytes = concatBytes(chunks, total);
777
+ const bytes = artifactBytesAt(artifact, finalPath, concatBytes(chunks, total));
667
778
  if (toHex(sha256(bytes)) !== artifact.sha256Hex) continue;
668
779
  satisfied.add(artifact.sha256Hex);
669
780
  yield { sha256Hex: artifact.sha256Hex, path: finalPath, bytes };
@@ -768,6 +879,8 @@ interface ScannedEntry {
768
879
  json?: unknown;
769
880
  /** The format an entry opening an export declared, when it ran past the export JSON cap. */
770
881
  exportTooLarge?: string;
882
+ /** A BitGraphed file's block at the entry's end. */
883
+ carrier?: CarrierFound;
771
884
  }
772
885
 
773
886
  interface FinalEntry {
@@ -777,6 +890,7 @@ interface FinalEntry {
777
890
  entryDigest: Uint8Array;
778
891
  json?: unknown;
779
892
  exportTooLarge?: string;
893
+ carrier?: CarrierFound;
780
894
  }
781
895
 
782
896
  interface HashedEntry {
@@ -786,6 +900,7 @@ interface HashedEntry {
786
900
  entryDigestStripped?: Uint8Array;
787
901
  buffered?: Uint8Array;
788
902
  exportTooLarge?: string;
903
+ carrier?: CarrierFound;
789
904
  }
790
905
 
791
906
  /**
@@ -826,6 +941,9 @@ async function hashEntryStream(
826
941
  let headLength = 0;
827
942
  const buffered: Uint8Array[] = [];
828
943
  let total = 0;
944
+ // The entry's end, at most CARRIER_WINDOW bytes past the first chunk kept.
945
+ const tail: Uint8Array[] = [];
946
+ let tailLength = 0;
829
947
  const stop = (): "off" => {
830
948
  buffered.length = 0;
831
949
  return "off";
@@ -845,14 +963,20 @@ async function hashEntryStream(
845
963
  head.set(chunk.subarray(0, take), headLength);
846
964
  headLength += take;
847
965
  }
966
+ // Copy: tar body chunks are views into the container's stream
967
+ // buffers and are not stable after iteration continues.
968
+ const kept = chunk.slice();
969
+ tail.push(kept);
970
+ tailLength += kept.length;
971
+ while (tail.length > 1 && tailLength - (tail[0] as Uint8Array).length >= CARRIER_WINDOW) {
972
+ tailLength -= (tail.shift() as Uint8Array).length;
973
+ }
848
974
  if (mode === "off") continue;
849
975
  if (mode === "sniff" && headLength === head.length) {
850
976
  mode = exportOpening(head) === undefined ? stop() : declaredSize !== undefined && declaredSize > exportCap ? tooLarge() : "export";
851
977
  if (mode === "off") continue;
852
978
  }
853
- // Copy: tar body chunks are views into the container's stream
854
- // buffers and are not stable after iteration continues.
855
- buffered.push(chunk.slice());
979
+ buffered.push(kept);
856
980
  if (mode === "json" && total > MAX_CANDIDATE_JSON_BYTES) {
857
981
  mode = exportOpening(head.subarray(0, headLength)) === undefined ? stop() : "export";
858
982
  }
@@ -864,6 +988,7 @@ async function hashEntryStream(
864
988
  }
865
989
 
866
990
  const keep = mode === "json" || mode === "export";
991
+ const carrier = carrierAtEnd(tail, tailLength, total);
867
992
  return {
868
993
  sha256Hex: toHex(contentHasher.digest()),
869
994
  byteLength: total,
@@ -871,9 +996,41 @@ async function hashEntryStream(
871
996
  ...(strippedHasher !== undefined ? { entryDigestStripped: strippedHasher.digest() } : {}),
872
997
  ...(keep ? { buffered: concatBytes(buffered, total) } : {}),
873
998
  ...(exportTooLarge !== undefined ? { exportTooLarge } : {}),
999
+ ...(carrier !== undefined ? { carrier } : {}),
874
1000
  };
875
1001
  }
876
1002
 
1003
+ /**
1004
+ * The BitGraphed file's block at an entry's end, if its last eight bytes are
1005
+ * the block's magic. The kept end holds the whole block whenever the block is
1006
+ * one a reader accepts, so it is parsed exactly as the whole file would be,
1007
+ * and the block's offset is moved back to the entry's own count.
1008
+ */
1009
+ function carrierAtEnd(tail: Uint8Array[], tailLength: number, total: number): CarrierFound | undefined {
1010
+ const magic = CARRIER_MAGIC.length;
1011
+ if (tailLength < magic) return undefined;
1012
+ const last = tail[tail.length - 1] as Uint8Array;
1013
+ const end = last.length >= magic ? last.subarray(last.length - magic) : concatBytes(tail, tailLength).subarray(tailLength - magic);
1014
+ for (let i = 0; i < magic; i++) if (end[i] !== CARRIER_MAGIC[i]) return undefined;
1015
+ const window = concatBytes(tail, tailLength);
1016
+ const parsed = parseCarrier(window);
1017
+ if (parsed.kind === "none") return undefined;
1018
+ if (parsed.kind === "corrupt") return { kind: "corrupt", reason: parsed.reason };
1019
+ return { kind: "carrier", payload: parsed.payload, blockOffset: total - tailLength + parsed.blockOffset };
1020
+ }
1021
+
1022
+ /** SHA-256 of an entry's first n bytes, reading the rest through. Refuses an entry shorter than n. */
1023
+ async function hashPrefix(chunks: Iterable<Uint8Array> | AsyncIterable<Uint8Array>, n: number): Promise<string> {
1024
+ const hasher = sha256.create();
1025
+ let seen = 0;
1026
+ for await (const chunk of chunks) {
1027
+ if (seen < n) hasher.update(chunk.subarray(0, Math.min(n - seen, chunk.length)));
1028
+ seen += chunk.length;
1029
+ }
1030
+ if (seen < n) throw new Error(`bitgraph-audit: an entry was shorter on its second read (${seen} of ${n} bytes)`);
1031
+ return toHex(hasher.digest());
1032
+ }
1033
+
877
1034
  /** The export format an entry's opening bytes declare ({"format": "bitgraph-export/..."), or undefined. */
878
1035
  function exportOpening(head: Uint8Array): string | undefined {
879
1036
  const start = head.length >= 3 && head[0] === 0xef && head[1] === 0xbb && head[2] === 0xbf ? 3 : 0;
@@ -893,6 +1050,7 @@ function makeScannedEntry(rawPath: string, hashed: HashedEntry): ScannedEntry {
893
1050
  : {}),
894
1051
  ...(json !== undefined ? { json } : {}),
895
1052
  ...(hashed.exportTooLarge !== undefined ? { exportTooLarge: hashed.exportTooLarge } : {}),
1053
+ ...(hashed.carrier !== undefined ? { carrier: hashed.carrier } : {}),
896
1054
  };
897
1055
  }
898
1056
 
@@ -1171,10 +1329,11 @@ function asString(value: unknown): string | undefined {
1171
1329
  // Artifact indexing and matching
1172
1330
  // ---------------------------------------------------------------------------
1173
1331
 
1174
- function indexArtifact(entry: FinalEntry, artifactsByHex: Map<string, ArtifactRecord>): void {
1332
+ function indexArtifact(entry: FinalEntry, artifactsByHex: Map<string, ArtifactRecord>, carried = false): void {
1175
1333
  const existing = artifactsByHex.get(entry.sha256Hex);
1176
1334
  if (existing !== undefined) {
1177
1335
  existing.paths.push(entry.path);
1336
+ if (carried) (existing.carriedPaths ??= []).push(entry.path);
1178
1337
  return;
1179
1338
  }
1180
1339
  artifactsByHex.set(entry.sha256Hex, {
@@ -1182,10 +1341,16 @@ function indexArtifact(entry: FinalEntry, artifactsByHex: Map<string, ArtifactRe
1182
1341
  sha256B64: Buffer.from(entry.sha256Hex, "hex").toString("base64"),
1183
1342
  byteLength: entry.byteLength,
1184
1343
  paths: [entry.path],
1344
+ ...(carried ? { carriedPaths: [entry.path] } : {}),
1185
1345
  matchedProofHashes: [],
1186
1346
  });
1187
1347
  }
1188
1348
 
1349
+ /** An artifact's bytes as read from one of its paths: for a BitGraphed file, the bytes before its block. */
1350
+ function artifactBytesAt(artifact: ArtifactRecord, path: string, bytes: Uint8Array): Uint8Array {
1351
+ return artifact.carriedPaths?.includes(path) === true ? bytes.subarray(0, artifact.byteLength) : bytes;
1352
+ }
1353
+
1189
1354
  /**
1190
1355
  * Strict base64 digest decoding per spec section 6.3: RFC 4648 section 4
1191
1356
  * alphabet with the round-trip property, decoding to exactly 32 bytes.
package/src/types.ts CHANGED
@@ -323,6 +323,11 @@ export interface ArtifactRecord {
323
323
  byteLength: number;
324
324
  /** Every path holding these exact bytes, in observation order. Byte-identical copies create no ambiguity. */
325
325
  paths: string[];
326
+ /**
327
+ * The paths among `paths` that are BitGraphed files: there, these bytes are
328
+ * the file's first byteLength bytes, before its block. Absent when none is.
329
+ */
330
+ carriedPaths?: string[];
326
331
  /** Canonical hashes of every observed proof whose artifact digest equals this content hash. One artifact may satisfy many proofs. */
327
332
  matchedProofHashes: string[];
328
333
  }
@@ -432,6 +437,10 @@ export interface IngestCounts {
432
437
  ceilings?: number;
433
438
  /** Export-shaped files (format "bitgraph-export/..."), checked or rejected. */
434
439
  exports?: number;
440
+ /** BitGraphed files (a bitgraph-carrier block at the end), read or not. Absent when there are none. */
441
+ carriers?: number;
442
+ /** BitGraphed files whose block could not be read, so their proofs are not counted. Absent when there are none. */
443
+ corruptCarriers?: number;
435
444
  /** Container entries skipped for unsafe paths. */
436
445
  skippedUnsafePaths: number;
437
446
  }
@@ -1740,7 +1749,9 @@ export interface AuditResult {
1740
1749
  * block-number mismatch, an invalid candidate anchor, or an unmatched
1741
1750
  * witness), or any floor problem (a floor-* code: a proof signing two
1742
1751
  * floors, a malformed or off-schedule Base floor, a floor header that
1743
- * contradicts the signed floor or matches none). Benign findings are reported but never set exit bits: ingest
1752
+ * contradicts the signed floor or matches none), or any BitGraphed file
1753
+ * whose block cannot be read (carrier-corrupt: its proof is not counted,
1754
+ * so a token it spent cannot be checked). Benign findings are reported but never set exit bits: ingest
1744
1755
  * advisories (duplicate copies, manifest advisories, unsafe paths,
1745
1756
  * embedded proofHash mismatches) and informational anchor findings
1746
1757
  * (anchor-metadata-disagreement, anchor-metadata-only-claim,