Repository navigation
Expand file tree
/
Copy pathcli.js
More file actions
1796 lines (1688 loc) · 85.5 KB
/
Copy pathcli.js
File metadata and controls
1796 lines (1688 loc) · 85.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/**
* @veritasacta/verify: unified verifier CLI (v0.5.4)
*
* Verifies Ed25519 signed receipts, VOPRF anonymous-credential tokens,
* Knowledge Unit bundles, and selective-disclosure receipts, all offline,
* all under one binary with one Sigil commitment.
*
* Architecture is modular: this file is the entry point + dispatcher.
* Cryptographic verification lives in src/engines/*.js. Output formatting
* lives in src/output/*.js.
*
* Usage:
* npx @veritasacta/verify receipt.json
* npx @veritasacta/verify receipt.json --key <hex>
* npx @veritasacta/verify receipt.json --jwks <url>
* npx @veritasacta/verify bundle.json --bundle --key <hex>
* npx @veritasacta/verify ku.json --mode ku
* npx @veritasacta/verify receipt.json --disclose field1,field2:salt:value
* npx @veritasacta/verify receipt.json --require-context sensor:temp<18
* npx @veritasacta/verify --self-check
* npx @veritasacta/verify --self-test
* npx @veritasacta/verify --capabilities
*
* Exit codes:
* 0 = signature valid (proven authentic)
* 1 = signature invalid (proven tampered)
* 2 = verifier error (malformed input, missing key, unsupported algorithm)
*
* References:
* - draft-farley-acta-signed-receipts-03
* - draft-farley-acta-knowledge-units-00
* - AIP-0001, AIP-0002, AIP-0003
* - Provisional patents #1-5
*
* @license Apache-2.0
*/
import { readFileSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { detectFormat } from './src/detect.js';
import { parseReceiptJson, parseJsonStrict } from './src/util/strict-json.js';
import { verifyReceipt, verifyBundle, combineChecks } from './src/engines/ed25519-receipt.js';
import { verifyGateTuple, verifyGateBundle } from './src/engines/gate-receipt.js';
import { verifyMacroTrackRecord } from './src/engines/macro-snapshot.js';
import { verifyLegateGovernedReceipt } from './src/engines/legate-governed-receipt.js';
import { verifyLegateProofPack } from './src/engines/legate-proof-pack.js';
import { verifyRepositoryArtifact } from './src/engines/repository-evidence.js';
import { verifyLegateStandard } from './src/engines/legate-standard.js';
import { verifyTrustedContextPack } from './src/engines/trusted-context-pack.js';
import {
CLAIMS_V211_TYPES,
parseClaimsJsonV211Independent,
verifyClaimsArtifactV211,
} from './src/engines/claims-v211.js';
import { verifyVoprfToken } from './src/engines/voprf-token.js';
import { verifyKnowledgeUnit } from './src/engines/knowledge-unit.js';
import {
verifySelectiveDisclosure,
listRedactedFields,
signedLegacyCommitments,
} from './src/engines/selective-disclosure.js';
import {
verifyCommittedReceipt,
loadDisclosuresFromText,
signedCommitment,
} from './src/engines/commitment-mode.js';
import { selfCheck, evaluateLiveContext } from './src/engines/sigil.js';
import {
buildCanonicalAttestation,
buildVerificationReceipt,
} from './src/engines/attestation.js';
import { replayChain, checkPreviousLink, COMPATIBILITY_NOTE } from './src/engines/bulk.js';
import { diffReceipts } from './src/engines/diff.js';
import { runInit, buildNextSteps } from './src/engines/init.js';
import { runProxy } from './src/engines/proxy.js';
import { runDaemon } from './src/engines/daemon.js';
import { verifyPrompt } from './src/engines/prompt.js';
import { exploreChain, renderChainTree } from './src/engines/chain-explore.js';
import { exportCompliance, renderComplianceHTML } from './src/engines/compliance-export.js';
import { startDashboard } from './src/engines/dashboard.js';
import { verifyDelegationChain } from './src/engines/delegation.js';
import { verifyCosignatures } from './src/engines/cosign.js';
import { parseContextArgs } from './src/context/live-context.js';
import { detectTier } from './src/conformance.js';
import { resolveFromJwks, loadJwksResolver } from './src/util/jwks.js';
import { checkKeyWindow, receiptIssuedAt, keyWindowCheck } from './src/util/key-window.js';
import { loadKnownIssuers, labelFor } from './src/util/known-issuers.js';
import { appendAuditEntry, lastChainHash } from './src/util/audit-log.js';
import { fipsStatus, verifiedAlgorithms } from './src/util/fips.js';
import { renderHtmlReport } from './src/output/html-report.js';
import { getError, exitCodeFor } from './src/errors.js';
import { readSigilMonitoredSource } from './src/sigil-policy.js';
import {
formatReceiptResult,
formatBundleResult,
formatGateTupleResult,
formatGateBundleResult,
formatMacroTrackRecordResult,
formatGovernedReceiptResult,
formatTrustedContextPackResult, formatRunManifestResult,
formatKuResult,
formatSelfCheckResult,
green,
red,
yellow,
dim,
bold,
teal,
renderTerminalSigil,
replayHeadline,
} from './src/output/terminal.js';
import { formatAsJson } from './src/output/json.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
const PKG = JSON.parse(readFileSync(join(__dirname, 'package.json'), 'utf-8'));
/** What parseArgs, enforcePinSigil and dispatch return when they refuse the run, having said why on stderr: exit 2. */
const REFUSED = Symbol('refused');
/**
* Exits with `code` once stdout and stderr have taken everything written to them. Every other run ends by returning
* its exit status, and the process then ends by itself once its output is written. Up to 0.11.0 each run ended with
* process.exit(), which ends the process at once, while Node can still be writing stdout to a pipe: a reader such as
* `| jq` got the first 64 KiB of a larger report, and the exit status of a complete one. The proxy exits here because
* its relay goes on reading stdin after the child has exited, which would keep the process alive.
*/
function exitWhenWritten(code) {
process.exitCode = code;
process.stdout.write('', () => process.stderr.write('', () => process.exit(code)));
}
/** Exit 0 means the answer is the good one: valid, and, when companion files were given, bound to all of them. A run manifest that verifies alone is exit 0 and says unbound; one that fails to bind to what was supplied is exit 1, however valid its own signature. */
function exitOk(result) {
if (!result || !result.valid) return false;
if (typeof result.binding === 'string') return result.binding === 'bound' || result.binding === 'manifest_only';
return true;
}
/** The mode line names the Legate artifact that was checked, not the list of what could have been. */
function legateModeLabel(r) {
const t = r && r.artifact_type;
if (t === 'scopeblind.run_manifest.v1') return 'Legate verified run (run manifest), checked offline';
if (t === 'scopeblind.proof_request.v1') return 'Legate signed standard (proof request), checked offline';
if (t === 'scopeblind.admission_decision.v1') return 'Legate recipient decision, checked offline';
if (t === 'scopeblind.action_assurance_bundle.v1') return 'Legate action assurance bundle, checked offline';
if (t === 'scopeblind.run_regrade.v1') return 'Legate second grading (run regrade), checked offline';
return MODE_LABELS['legate-standard'];
}
/** The single-receipt modes, the only ones --previous applies to. */
const RECEIPT_MODES = ['ed25519-browser-legacy', 'ed25519-receipt-v1', 'ed25519-receipt-v2', 'ed25519-passport'];
/** What a result accepted with --allow-carried-key says, in the JSON and the terminal. */
const CARRIED_KEY_NOTICE = 'Checked only against the key the file carries (--allow-carried-key): the signature shows the file matches that key, and proves nothing about who signed it.';
/**
* A key the file carries is never a trust anchor (draft §9.5), so a result that rests only on one is undecidable
* (embedded_key_rejected, exit 2), never valid. `carried` names what was checked only against a key in the file, or
* is null when a key from outside it was applied. --allow-carried-key accepts such a result (exit 0) and marks it
* carriedKeyOnly, with CARRIED_KEY_NOTICE; --strict refuses it even then. Before, these formats exited 0 on the key
* they carry by default and under --strict, so a Gate record signed by any fresh key passed.
*/
function refuseCarriedKey(result, opts, carried) {
// A check that ran and failed stays the outcome (-04 §5.3): only a result that would otherwise pass is refused.
if (!exitOk(result) || !carried) return result;
if (opts.allowCarriedKey && !opts.strict) {
return { ...result, carriedKeyOnly: true, warning: [result.warning, CARRIED_KEY_NOTICE].filter(Boolean).join(' ') };
}
return {
...result,
valid: false,
error: 'embedded_key_rejected',
carriedKeyOnly: true,
detail: opts.strict
? `--strict: ${carried} was checked only against a key it carries, which is not a trust anchor; --strict refuses it even with --allow-carried-key. Pin the key with --key.`
: `${carried} was checked only against a key it carries, which is not a trust anchor. Pin the key with --key; --allow-carried-key accepts it, proving nothing about who signed.`,
...(typeof result.title === 'string' ? { title: 'Not checked: no key from outside the file was given' } : {}),
};
}
const MODE_LABELS = {
'ed25519-browser-legacy': 'Historical browser receipt 1.0 (not draft-03)',
'ed25519-receipt-v1': 'Ed25519 receipt v1 (RFC 8032)',
'ed25519-receipt-v2': 'Ed25519 receipt v2 (RFC 8032 + draft-farley-acta-signed-receipts)',
'ed25519-passport': 'Ed25519 Passport envelope (RFC 8032)',
'ed25519-bundle': 'Ed25519 audit bundle',
'voprf-token': 'VOPRF token (RFC 9497)',
'knowledge-unit': 'Knowledge Unit bundle (draft-farley-acta-knowledge-units)',
'gate-receipt-tuple': 'ScopeBlind Gate receipt tuple (Ed25519 over SHA-256 payload digest)',
'gate-evidence-bundle': 'ScopeBlind Gate evidence bundle (receipt tuples + chain links)',
'macro-track-record': 'ScopeBlind macro-engine track-record bundle (signed snapshots + completeness manifest)',
'legate-governed-receipt': 'Legate governed receipt (Ed25519 over canonical action payload)',
'repository-evidence': 'Exact repository review, receiver readback and recipient acceptance',
'legate-proof-pack': 'Legate adherence / restraint proof pack (Ed25519 over canonical bytes, position-blind)',
'trusted-context-pack': 'ScopeBlind Trusted Context Pack (signed parsed-context attestation)',
'scopeblind-claims-v2.1.1': 'ScopeBlind Verifiable Claims v2.1.1 point-in-time artifact',
'legate-standard': 'Legate signed standard, recipient decision, action assurance bundle, or run manifest (the site\'s own verification core, offline)',
};
// ──────────────────────────────────────────────────────────────────
// CLI argument parsing
// ──────────────────────────────────────────────────────────────────
function parseArgs() {
const args = process.argv.slice(2);
const opts = {
file: null,
publicKey: null,
platformKeys: {},
jwksUrl: null,
requireKeyWindow: false,
trustAnchor: null,
stdin: false,
mode: 'auto',
bundle: false,
json: false,
help: false,
version: false,
verbose: false,
selfTest: false,
selfCheck: false,
capabilities: false,
allowEmbeddedKey: false,
allowCarriedKey: false,
allowLegacyCanonicalization: false,
allowPayloadOnlyLinks: false,
trustBundleKeys: false,
previousFile: null,
requireContext: [],
disclose: [],
disclosureFile: null,
tier: null,
strict: false,
noSigil: false,
attest: false,
attestOrg: null,
attestKey: null,
pinSigil: null,
auditLog: null,
replayChain: null,
emitEat: null,
diff: null,
auditReport: false,
output: null,
emitVerificationReceipt: false,
fips: false,
subcommand: null,
force: false,
proxyTarget: null,
proxyReceiptsDir: null,
daemonSocket: null,
frameworkOverride: null,
historyHead: null,
anchorHead: null,
};
// A verifier that silently discards inputs is not correct, it is quiet.
// Every subcommand takes at most one file; --diff carries a second one as a
// flag. Any further positional is an error, never dropped.
const setFile = (a) => {
if (opts.file == null || opts.file === '') opts.file = a;
else (opts.extraPositionals ??= []).push(a);
};
for (let i = 0; i < args.length; i++) {
const arg = args[i];
const next = () => args[++i];
switch (arg) {
case '--help':
case '-h': opts.help = true; break;
case '--version':
case '-V': opts.version = true; break;
case '--key':
case '-k': opts.publicKey = next(); break;
case '--platform-key': {
const v = next() || '';
const eq = v.indexOf('=');
if (eq < 1 || eq === v.length - 1) { console.error('--platform-key expects <kid>=<hex public key>'); return REFUSED; }
opts.platformKeys[v.slice(0, eq)] = v.slice(eq + 1);
break;
}
case '--known-issuers': opts.knownIssuers = next(); break;
case '--jwks': opts.jwksUrl = next(); break;
case '--require-key-window': opts.requireKeyWindow = true; break;
case '--trust-anchor': opts.trustAnchor = next() ?? ''; break;
case '--history-head': opts.historyHead = next(); break;
case '--anchor-head': opts.anchorHead = next(); break;
case '--stdin': opts.stdin = true; break;
case '--mode': opts.mode = next(); break;
case '--bundle': opts.bundle = true; break;
case '--standard': opts.standardFile = next(); break;
case '--receipts': opts.receiptsFile = next(); break;
case '--calls': opts.callsFile = next(); break;
case '--regrade': (opts.regradeFiles ??= []).push(next()); break;
case '--maintainer-key': opts.maintainerKey = next(); break;
case '--provenance': (opts.provenanceFiles ??= []).push(next()); break;
case '--model-calls': opts.modelCallsFile = next(); break;
case '--model-attestation': opts.modelAttestationFile = next(); break;
case '--json': opts.json = true; break;
case '--verbose':
case '-v': opts.verbose = true; break;
case '--self-test': opts.selfTest = true; break;
case '--self-check': opts.selfCheck = true; break;
case '--capabilities': opts.capabilities = true; break;
case '--allow-legacy-canonicalization': opts.allowLegacyCanonicalization = true; break;
case '--allow-payload-only-links': opts.allowPayloadOnlyLinks = true; break;
case '--previous': opts.previousFile = next() ?? ''; break;
case '--allow-embedded-key': opts.allowEmbeddedKey = true; break;
case '--allow-carried-key': opts.allowCarriedKey = true; break;
case '--trust-bundle-keys': opts.trustBundleKeys = true; break;
case '--require-context': opts.requireContext.push(next()); break;
case '--disclose': opts.disclose.push(next()); break;
case '--disclosure-file': opts.disclosureFile = next() ?? ''; break;
case '--tier': opts.tier = Number(next()); break;
case '--strict': opts.strict = true; break;
case '--no-sigil': opts.noSigil = true; break;
case '--attest': opts.attest = true; break;
case '--attest-org': opts.attestOrg = next(); break;
case '--attest-key': opts.attestKey = next(); break;
case '--pin-sigil': opts.pinSigil = next(); break;
case '--audit-log': opts.auditLog = next(); break;
case '--replay-chain': opts.replayChain = next(); break;
case '--emit-eat': opts.emitEat = 'json'; break;
case '--emit-eat-cbor': opts.emitEat = 'cbor'; break;
case '--diff': opts.diff = next(); break;
case '--audit-report': opts.auditReport = true; break;
case '--output': opts.output = next(); break;
case '--emit-verification-receipt': opts.emitVerificationReceipt = true; break;
case '--fips': opts.fips = true; break;
case '--allow-partial-voprf': opts.allowPartialVoprf = true; break;
case '--force': opts.force = true; break;
case '--target': opts.proxyTarget = next(); break;
case '--framework': opts.frameworkOverride = next(); break;
case '--receipts-dir': opts.proxyReceiptsDir = next(); break;
case '--socket': opts.daemonSocket = next(); break;
case '--prompt-receipt': opts.promptReceipt = next(); break;
case '--sigstore-bundle': opts.sigstoreBundle = next(); break;
case '--expected-hash': opts.expectedHash = next(); break;
case '--search-dir': opts.chainSearchDir = next(); break;
case '--max-depth': opts.chainMaxDepth = Number(next()); break;
case '--profile': opts.profile = next(); break;
case '--start-date': opts.startDate = next(); break;
case '--end-date': opts.endDate = next(); break;
case '--org': opts.organization = next(); break;
case '--port': opts.dashboardPort = Number(next()); break;
case '--bind': opts.dashboardBind = next(); break;
case '--bilateral': opts.proxyBilateral = true; break;
case '--server-key': opts.serverKey = next(); break;
case '--scrub-secrets': opts.scrubSecrets = true; break;
case '--trace-id': opts.traceId = next(); break;
case '--group-by-trace': opts.groupByTrace = true; break;
case 'init':
case 'proxy':
case 'daemon':
case 'prompt':
case 'chain':
case 'compliance':
case 'dashboard':
if (!opts.subcommand) opts.subcommand = arg;
else if (!arg.startsWith('-')) setFile(arg);
break;
case 'explore':
// `verify chain explore <file>` → subcommand stays "chain",
// sub-subcommand captured below
if (opts.subcommand === 'chain') opts.chainVerb = arg;
else if (!arg.startsWith('-')) setFile(arg);
break;
default:
if (!arg.startsWith('-')) setFile(arg);
// unknown flags silently ignored (forward-compat)
}
}
if (opts.extraPositionals) {
const all = [opts.file, ...opts.extraPositionals];
console.error(
`verify: expected one <file.json>, got ${all.length}: ${all.join(', ')}\n` +
` Each receipt is verified by its own invocation. Earlier releases verified only\n` +
` the last file given and silently discarded the rest (exit 2, nothing verified).`
);
return REFUSED;
}
return opts;
}
function printHelp() {
console.log(`
${bold('@veritasacta/verify')} ${PKG.version}: unified verifier for signed receipts, VOPRF tokens, and Knowledge Units
${bold('Usage:')}
npx @veritasacta/verify <file.json> Auto-detect format, verify
(exactly one file per invocation; extra positionals exit 2 rather than being ignored)
npx @veritasacta/verify <file.json> --key <hex> Provide verification key
npx @veritasacta/verify <file.json> --jwks <url> Fetch key from JWKS
npx @veritasacta/verify <file.json> --previous <prev.json> Also check it follows the receipt before it
npx @veritasacta/verify <file.json> --mode receipt|claims|voprf|ku|gate|gate-bundle
npx @veritasacta/verify <bundle.json> --bundle --key <hex> Verify audit bundle
cat receipt.json | npx @veritasacta/verify --stdin Read from stdin
npx @veritasacta/verify <file.json> --json Machine-readable output
${bold('Selective disclosure (AIP-0002 legacy):')}
--disclose field:salt:value Reveal a field and verify its commitment in the _commitments
map the signature covers (an envelope's payload); one that
cannot be applied is undecidable (exit 2)
${bold('Commitment-mode disclosure (draft-farley-acta-signed-receipts-01):')}
--disclosure-file <path.json> Verify Merkle inclusion proofs against committed_fields_root,
read from the signed bytes (an envelope's payload); a file
that cannot be applied is undecidable (exit 2)
${bold('Live-context verification (Sigil claim 2):')}
--require-context clock:±5s
--require-context geofence:inside:<polygon>
--require-context sensor:temp<18
${bold('Subcommands:')}
init Zero-config onboarding wizard (detects framework, generates keys)
proxy --target "<cmd>" Wrap an MCP server; sign every tools/call transparently
daemon Sidecar daemon: sign receipts over a unix socket (any language)
prompt <path> Verify a prompt/skill/system-instruction file's provenance
[--prompt-receipt <r.json> | --sigstore-bundle <b.json> | --expected-hash <hex>]
chain explore <r.json> Walk a receipt chain to its root; verify every hash link
[--search-dir <dir>] [--max-depth N] [--json]
[--allow-payload-only-links]
compliance SOC 2 / ISO 42001 / EU AI Act evidence bundle from a receipt directory
--receipts-dir <dir> [--framework soc2|iso42001|eu-ai-act|all]
[--start-date ISO] [--end-date ISO] [--org "<name>"] [--output audit.html|bundle.json]
dashboard Start local audit dashboard server (loopback only, no telemetry)
[--port 3847] [--bind 127.0.0.1] [--receipts-dir <dir>]
proxy --target "<cmd>" Already-present wrap-and-sign proxy. New flags:
[--bilateral --server-key <file>] Cosign every receipt with a second key
[--scrub-secrets] Redact api_key/token/etc in outgoing args and flag on receipt
[--trace-id <id>] Stamp a workflow trace_id on every receipt
${bold('Options:')}
--key, -k <hex> Ed25519 public key (64 hex chars); for a VOPRF token, the issuer's
compressed P-256 key in base64url
--platform-key <kid>=<hex> Platform key for a connector context (repeatable)
--jwks <url|file> JWKS endpoint or file to take the signing key from, by kid
--previous <file> The receipt this one follows. Fails with chain_break (exit 1)
unless previousReceiptHash is that receipt's draft §6.7 link;
an absent or null link fails too. Checked beside the signature
and the key window, with --key or --jwks
--require-key-window Fail unless the key source gives the key a valid_from /
valid_until window (applied to the signed issued_at either way:
an envelope's payload.issued_at, a flat receipt's issued_at)
--trust-anchor <file> Not implemented, so refused (exit 2): no key was ever read
from the file. Pin the key with --key or --jwks <url|file>
--history-head <hex> Pin the expected macro track-record history head
--anchor-head <hex> Pin the expected signed macro anchor digest
--mode <m> Force mode: receipt|claims|voprf|ku|auto (default: auto)
--bundle Verify as audit bundle
--standard <file> Legate run manifest: the signed standard to check the pins and policy against
--receipts <file> Legate run manifest: the gateway's receipt log (JSONL or array) to check the chain against
--calls <file> Legate run manifest: the calls log (JSONL), one call per receipt, to open the input digests
--maintainer-key <hex|file> Run manifest with --standard: pin the maintainer key that must have signed the standard (a hex key, or a maintainer-key.json); a trust root from outside the files. Refused without --standard (exit 2)
--regrade <file> Legate run manifest: a second grading (scopeblind.run_regrade.v1) to reconcile with the manifest; repeatable: the first is the run's own, any further one a grading made elsewhere
--provenance <path> Legate run manifest: Sigstore provenance bundle(s) (.sigstore.jsonl, or a directory of them), verified here against the pinned trust root; repeatable
--model-calls <file> Legate run manifest: the model-calls log (model-calls.jsonl), each call signed inside the model's TEE
--model-attestation <f> Legate run manifest: the attestation report(s) (model-attestation.json) whose Intel TDX quotes bind the signing keys; verified offline
--stdin Read input from stdin
--json Output JSON
--verbose, -v Detailed verification info
--tier N Require minimum conformance tier (1-5)
--pin-sigil <hex> Require installed Sigil fingerprint to match
--strict Disable all deprecated fallbacks. A result that rests only on a key
the file carries is undecidable (embedded_key_rejected, exit 2), even
with --allow-carried-key
--fips Enforce FIPS-approved algorithms only
--audit-log <file> Append verification event to a local JSONL audit log
--self-test Verify bundled sample artifacts
--self-check Compare monitored verifier source with bundled commitment
--capabilities List supported modes/algorithms/tiers
--allow-legacy-canonicalization Read historical non-JCS receipts, explicitly labelled.
--allow-payload-only-links Read a chain link over the previous receipt's payload
alone as a legacy link, counted and warned: a
compatibility mode for chains verify 0.9.3 and earlier
wrote, not conformant to draft §6.7. --strict disables it
--allow-embedded-key DEPRECATED. Accept keys embedded in payloads.
Removed in v0.6.0.
--allow-carried-key Accept a result that rests only on a key the file carries: a Gate
tuple or bundle, a macro snapshot or track record, a governed receipt,
a proof or context pack, repository evidence, a standard file or a
run manifest checked without --key. Without it such a result is
undecidable (embedded_key_rejected, exit 2); with it, exit 0, and the
output says the signature proves nothing about who signed.
--strict refuses it
--trust-bundle-keys Check an audit bundle's receipts with the keys in its own
verification.signing_keys, reported as keySource "bundle".
Those keys arrive in the file being verified, so they are
not a trust anchor: without this flag, --key or --jwks the
receipts are not checked (no_public_key, exit 2). --strict
disables it
--allow-partial-voprf Treat a partial (structural-only) VOPRF result
as valid. Default fails closed (exit 2).
Full DLEQ verification lands in v0.6.0.
--no-sigil Suppress Sigil art in terminal output
--help, -h
--version, -V
${bold('Bulk / replay / diff:')}
--replay-chain <file> Verify every receipt in a JSONL chain file and the links
between them; a later receipt with no link starts a new chain.
Keys come from --key, or from --jwks by each receipt's kid.
Exits 1 if a line fails or a link breaks, else 2 if a line
could not be checked, else 0
--emit-eat Re-emit the verified receipt as an RFC 9711 EAT claims-set (JSON)
--emit-eat-cbor Same, as CBOR with integer claim keys
--diff <other-file> Show structural diff between two receipts
${bold('Attestation and audit:')}
--attest Emit a signed local-verifier attestation
--attest-org <name> Include this org name in the attestation
--attest-key <file> Override attester key location
(default: ~/.veritasacta-verify/attester.json)
--emit-verification-receipt
Emit a signed verification receipt for the subject
--audit-report Render an HTML audit report
--output <file> Write output to a file (HTML reports, attestations)
${bold('Supported formats:')}
v1 artifacts, v2 artifacts, Passport envelopes, audit bundles,
VOPRF tokens, Knowledge Unit bundles, selective-disclosure receipts,
ScopeBlind Gate receipt tuples and evidence bundles (chain-link checks).
${bold('Exit codes:')}
0 Valid: proven authentic
1 Invalid: proven tampered
2 Undecidable: malformed input, missing key, unsupported algorithm,
or --tier requirement not achieved
A check that ran and failed makes the result invalid (1) even when another
could not run; it is undecidable (2) only when nothing failed, as §5.3 of
the -04 editor's copy (VeritasActa/drafts) has it.
${bold('Standards:')}
RFC 8032 (Ed25519), RFC 8785 (JCS), RFC 9497 (VOPRF),
RFC 7517/7638 (JWK / thumbprint),
draft-farley-acta-signed-receipts-03,
draft-farley-acta-knowledge-units-00,
AIP-0001, AIP-0002, AIP-0003.
${bold('Protocol:')} https://veritasacta.com (open, Apache-2.0)
${bold('Managed:')} https://scopeblind.com (optional, commercial)
`);
}
function printCapabilities() {
console.log(JSON.stringify({
package: PKG.name,
version: PKG.version,
modes: Object.keys(MODE_LABELS),
algorithms: ['ed25519', 'EdDSA', 'voprf-p256-sha256'],
unsupported_but_recognized: ['ed25519+ml-dsa-65', 'ed25519+dilithium3'],
tiers: [1, 2, 3, 4],
max_tier_v0_5_0: 4,
features: [
'ed25519-receipt-verification',
'voprf-token-structural-verification',
'knowledge-unit-bundle-verification',
'selective-disclosure-aip-0002',
'sigil-self-check-claim-1',
'sigil-live-context-claim-2',
'conformance-tier-detection',
'embedded-key-rejection',
'key-validity-window-draft-9.2',
'scopeblind-gate-tuple-verification',
'scopeblind-gate-evidence-bundle-chain-checks',
'scopeblind-claims-v2.1.1-point-in-time-artifact-verification',
],
specs: [
'RFC 8032', 'RFC 8785', 'RFC 9497', 'RFC 7517', 'RFC 7638',
'draft-farley-acta-signed-receipts-03',
'draft-farley-acta-knowledge-units-00',
'AIP-0001', 'AIP-0002', 'AIP-0003',
],
wayfinding: {
protocol: 'https://veritasacta.com',
managed: 'https://scopeblind.com',
},
}, null, 2));
}
// ──────────────────────────────────────────────────────────────────
// Self-check: compare installed bytes with the bundled public commitment
// ──────────────────────────────────────────────────────────────────
async function runSelfCheck() {
const sigilPath = join(__dirname, 'sigil.json');
let sigil;
try {
sigil = JSON.parse(readFileSync(sigilPath, 'utf-8'));
} catch {
console.log(`\n ${red('✗')} No sigil.json found: this verifier has no Sigil commitment.`);
console.log(` This may be a development build or a fork.\n`);
return 2;
}
let installedSourceBytes;
try {
installedSourceBytes = readSigilMonitoredSource(__dirname);
} catch (error) {
console.log(bold('@veritasacta/verify self-check'));
console.log(`\n ${red('✗')} ${error.message}`);
console.log(' Refusing to compare a reduced verifier surface.\n');
return 1;
}
const r = selfCheck({ sigil, installedSourceBytes });
r.projectPublicKey = sigil.project_public_key;
console.log(bold('@veritasacta/verify self-check'));
console.log(formatSelfCheckResult(r));
return r.canonical ? 0 : 1;
}
// ──────────────────────────────────────────────────────────────────
// Self-test: verify bundled samples
// ──────────────────────────────────────────────────────────────────
async function runSelfTest(opts) {
const samplesDir = join(__dirname, 'samples');
const testKey = 'd75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a';
let allPassed = true;
console.log(`\n${bold('@veritasacta/verify self-test')}\n`);
if (!process.env.CI && !process.env.NO_COLOR) {
console.log(renderTerminalSigil(testKey));
console.log('');
}
try {
const receipt = JSON.parse(readFileSync(join(samplesDir, 'sample-receipt.json'), 'utf-8'));
const detected = detectFormat(receipt);
const r = await verifyReceipt(receipt, detected.mode, { publicKey: testKey });
if (r.valid) {
console.log(` ${green('✓')} Sample receipt: ${green('VALID')} (${r.type}, kid: ${r.kid || 'n/a'})`);
} else {
console.log(` ${red('✗')} Sample receipt: ${red('INVALID')} (${r.error})`);
allPassed = false;
}
} catch (e) {
console.log(` ${red('✗')} Sample receipt: ${red(e.message)}`);
allPassed = false;
}
try {
const bundle = JSON.parse(readFileSync(join(samplesDir, 'sample-bundle.json'), 'utf-8'));
const r = await verifyBundle(bundle, { publicKey: testKey });
if (r.valid) {
console.log(` ${green('✓')} Sample bundle: ${green('VALID')} (${r.passed}/${r.total} receipts)`);
} else {
console.log(` ${red('✗')} Sample bundle: ${red('INVALID')} (${r.failed} failed)`);
allPassed = false;
}
} catch (e) {
console.log(` ${red('✗')} Sample bundle: ${red(e.message)}`);
allPassed = false;
}
console.log('');
if (allPassed) {
console.log(` ${green('All self-tests passed.')} The verifier is working correctly.`);
console.log(` ${dim('No ScopeBlind servers were contacted. No accounts required.')}`);
} else {
console.log(` ${red('Some self-tests failed.')} Check the output above.`);
}
console.log('');
return allPassed ? 0 : 1;
}
// ──────────────────────────────────────────────────────────────────
// Dispatch
// ──────────────────────────────────────────────────────────────────
async function readInput(opts) {
if (opts.stdin) {
const chunks = [];
for await (const chunk of process.stdin) chunks.push(chunk);
return Buffer.concat(chunks).toString('utf-8');
}
if (opts.file) return readFileSync(opts.file, 'utf-8');
return null;
}
async function dispatch(input, opts) {
// Forced-mode overrides
let detected = detectFormat(input);
if (opts.mode && opts.mode !== 'auto') {
const forced = opts.mode.toLowerCase();
if (forced === 'receipt') detected.mode = 'ed25519-passport';
else if (forced === 'voprf') detected.mode = 'voprf-token';
else if (forced === 'ku') detected.mode = 'knowledge-unit';
else if (forced === 'bundle') detected.mode = 'ed25519-bundle';
else if (forced === 'gate') detected.mode = 'gate-receipt-tuple';
else if (forced === 'gate-bundle') detected.mode = 'gate-evidence-bundle';
else if (forced === 'macro' || forced === 'macro-track-record') detected.mode = 'macro-track-record';
else if (forced === 'governed') detected.mode = 'legate-governed-receipt';
else if (forced === 'context' || forced === 'context-pack') detected.mode = 'trusted-context-pack';
else if (forced === 'claims' || forced === 'claims-v2.1.1') detected.mode = 'scopeblind-claims-v2.1.1';
else if (forced === 'legate' || forced === 'standard') detected.mode = 'legate-standard';
}
if (opts.bundle) detected.mode = 'ed25519-bundle';
// --previous asserts that one receipt follows another: it applies to a single receipt, never silently to anything else.
if (opts.previousReceipt && !RECEIPT_MODES.includes(detected.mode)) {
console.error(red(`verify: --previous checks the link of one Ed25519 receipt. This file reads as ${MODE_LABELS[detected.mode] || 'no format this verifier knows'}, so it does not apply.`));
console.error(' Nothing was verified (exit 2).');
return REFUSED;
}
// --disclosure-file and --disclose are checked against one receipt's commitments: never silently dropped elsewhere.
if ((opts.disclosureFile !== null || opts.disclose.length > 0) && !RECEIPT_MODES.includes(detected.mode)) {
console.error(red(`verify: ${opts.disclosureFile !== null ? '--disclosure-file' : '--disclose'} checks disclosures against one receipt's commitments. This file reads as ${MODE_LABELS[detected.mode] || 'no format this verifier knows'}, so it does not apply.`));
console.error(' Nothing was verified (exit 2).');
return REFUSED;
}
// --maintainer-key pins the key that signed the standard a run manifest is checked against, so it applies only with
// --standard. Elsewhere it was dropped, and a run manifest or a standard verified as if the pin had held.
if (opts.maintainerKey && !(detected.mode === 'legate-standard' && input?.type === 'scopeblind.run_manifest.v1' && opts.standardFile)) {
console.error(red('verify: --maintainer-key pins the key that signed the standard, and applies to a run manifest checked with --standard <file>. Here it would not be applied.'));
console.error(' To pin the key that signed a standard, a decision or a manifest itself, use --key. Nothing was verified (exit 2).');
return REFUSED;
}
// --trust-bundle-keys names the keys an audit bundle carries: it applies to one, never silently to anything else.
if (opts.trustBundleKeys && detected.mode !== 'ed25519-bundle') {
console.error(red(`verify: --trust-bundle-keys checks an audit bundle with the keys in its verification.signing_keys. This file reads as ${MODE_LABELS[detected.mode] || 'no format this verifier knows'}, so it does not apply.`));
console.error(' Nothing was verified (exit 2).');
return REFUSED;
}
// An audit bundle takes its keys from --jwks receipt by receipt: the key set is read once, and each receipt gets the
// key its own kid names (0.10.27; the bundle used to get the set's first key for every receipt).
if (detected.mode === 'ed25519-bundle' && !opts.publicKey && opts.jwksUrl) {
const loaded = await loadJwksResolver(opts.jwksUrl);
if (loaded.error) return { valid: false, outcome: 'undecidable', error: 'jwks_fetch_failed', format: detected.mode, detail: loaded.error };
return await verifyBundle(input, { ...opts, keyResolver: loaded.resolve });
}
// Resolve JWKS if needed
let publicKey = opts.publicKey;
let keySource = publicKey ? 'provided' : null;
let keyWindow = null;
let jwksFailure = null;
if (!publicKey && opts.jwksUrl) {
const kid = input.kid || input.signature?.kid;
const resolved = await resolveFromJwks(opts.jwksUrl, kid);
if (resolved.key) {
publicKey = resolved.key;
keySource = 'jwks';
keyWindow = resolved.window || null;
} else if (RECEIPT_MODES.includes(detected.mode)) {
// A single receipt still has the checks that need no key run on it, with the key undecidable (§5.3 of the -04
// editor's copy, VeritasActa/drafts).
jwksFailure = resolved.error;
} else {
const result = {
valid: false,
error: 'jwks_fetch_failed',
format: detected.mode,
detail: resolved.error,
};
return result;
}
}
const subOpts = { ...opts, publicKey, ...(publicKey ? { keySource } : {}), ...(jwksFailure ? { allowEmbeddedKey: false } : {}) };
// Route to engine
switch (detected.mode) {
case 'ed25519-bundle': {
return await verifyBundle(input, subOpts);
}
// A key given with --key (or --jwks) is pinned by each of these engines: a record signed with another is
// key_mismatch. Without one, each verifies against the key the file carries, which is refused unless
// --allow-carried-key accepts it.
case 'gate-evidence-bundle': {
const r = verifyGateBundle(input, subOpts);
return refuseCarriedKey({ ...r, modeLabel: MODE_LABELS['gate-evidence-bundle'] }, opts, publicKey ? null : 'the bundle');
}
case 'macro-track-record': {
const r = verifyMacroTrackRecord(input, subOpts);
return refuseCarriedKey({ ...r, modeLabel: MODE_LABELS['macro-track-record'] }, opts, publicKey ? null : 'the track record');
}
case 'gate-receipt-tuple': {
const r = verifyGateTuple(input, subOpts);
return refuseCarriedKey({ ...r, modeLabel: MODE_LABELS['gate-receipt-tuple'] }, opts, publicKey ? null : 'the tuple');
}
case 'legate-governed-receipt': {
const r = verifyLegateGovernedReceipt(input, subOpts);
return refuseCarriedKey({ ...r, modeLabel: MODE_LABELS['legate-governed-receipt'] }, opts, publicKey ? null : 'the receipt');
}
case 'repository-evidence': {
const r = await verifyRepositoryArtifact(input, subOpts);
return refuseCarriedKey({ ...r, modeLabel: MODE_LABELS['repository-evidence'] }, opts, publicKey ? null : 'the evidence');
}
case 'legate-proof-pack': {
const r = verifyLegateProofPack(input, subOpts);
return refuseCarriedKey({ ...r, modeLabel: MODE_LABELS['legate-proof-pack'] }, opts, publicKey ? null : 'the pack');
}
case 'legate-standard': {
// A run manifest binds to a standard and a receipt log; both are optional files beside it.
if (input?.type === 'scopeblind.run_manifest.v1') {
const { readFileSync } = await import('node:fs');
// The files beside a manifest are read as the main input is: a duplicate member is refused, never resolved.
if (opts.standardFile) subOpts.standard = parseJsonStrict(readFileSync(opts.standardFile, 'utf8'));
if (opts.receiptsFile) {
const text = readFileSync(opts.receiptsFile, 'utf8').trim();
subOpts.receipts = text.startsWith('[') ? parseJsonStrict(text) : text.split('\n').filter(Boolean).map((l) => parseJsonStrict(l));
}
if (opts.callsFile) {
const text = readFileSync(opts.callsFile, 'utf8').trim();
subOpts.calls = (text.startsWith('[') ? parseJsonStrict(text) : text.split('\n').filter(Boolean).map((l) => parseJsonStrict(l))).map((c) => ({ tool: c.tool, input: c.input }));
}
if (opts.regradeFiles?.length) { subOpts.regrade = parseJsonStrict(readFileSync(opts.regradeFiles[0], 'utf8')); subOpts.regrades = opts.regradeFiles.slice(1).map((f) => ({ regrade: parseJsonStrict(readFileSync(f, 'utf8')), bytes: readFileSync(f) })); }
// Provenance bundles name exact bytes, so the files as given on the command line are read again as bytes.
if (opts.provenanceFiles?.length) {
const { readdirSync, statSync } = await import('node:fs');
const { join } = await import('node:path');
const paths = opts.provenanceFiles.flatMap((p) => (statSync(p).isDirectory() ? readdirSync(p).filter((f) => /\.sigstore\.jsonl?$/.test(f)).sort().map((f) => join(p, f)) : [p]));
const bundles = paths.flatMap((p) => readFileSync(p, 'utf8').split('\n').filter((l) => l.trim()).map((l) => parseJsonStrict(l)));
const bytes = {};
if (opts.file) bytes.manifest = readFileSync(opts.file);
if (opts.standardFile) bytes.standard = readFileSync(opts.standardFile);
if (opts.receiptsFile) bytes.receipts = readFileSync(opts.receiptsFile);
if (opts.regradeFiles?.[0]) bytes.regrade = readFileSync(opts.regradeFiles[0]);
subOpts.provenance = { bundles, bytes };
if (Array.isArray(subOpts.regrades)) for (const r of subOpts.regrades) r.bundles = bundles;
}
if (opts.modelCallsFile) subOpts.modelCalls = readFileSync(opts.modelCallsFile, 'utf8');
if (opts.modelAttestationFile) { const v = parseJsonStrict(readFileSync(opts.modelAttestationFile, 'utf8')); subOpts.modelAttestations = Array.isArray(v) ? v : [v]; }
// The manifest digests the receipt log and the calls log as files, so the files given are handed over as bytes as well as records.
const fileBytes = {};
if (opts.receiptsFile) fileBytes.receipts = readFileSync(opts.receiptsFile);
if (opts.callsFile) fileBytes.calls = readFileSync(opts.callsFile);
subOpts.bytes = fileBytes;
if (opts.maintainerKey) {
const { existsSync } = await import('node:fs');
let pin = opts.maintainerKey.trim();
if (existsSync(pin)) { const raw = readFileSync(pin, 'utf8').trim(); try { const j = parseJsonStrict(raw); pin = String(j.public_key ?? j.verification_key ?? ''); } catch { pin = raw; } }
if (!/^[0-9a-f]{64}$/i.test(pin)) { console.error('--maintainer-key: expected a 64-hex Ed25519 public key or a maintainer-key.json carrying public_key'); return REFUSED; }
subOpts.pins = { maintainer_key: pin };
}
}
const r = await verifyLegateStandard(input, subOpts);
// A run manifest also rests on a key from outside the files when its harness key is one the standard accepts
// and the standard is signed by the maintainer key pinned with --maintainer-key.
const passed = (id) => Array.isArray(r.checks) && r.checks.some((c) => c.id === id && c.ok);
const pinnedElsewhere = r.artifact_type === 'scopeblind.run_manifest.v1' && passed('maintainer_pin') && passed('harness_key');
return refuseCarriedKey({ ...r, modeLabel: legateModeLabel(r) }, opts, publicKey || pinnedElsewhere ? null : 'the file');
}
case 'trusted-context-pack': {
const r = verifyTrustedContextPack(input, subOpts);
return refuseCarriedKey({ ...r, modeLabel: MODE_LABELS['trusted-context-pack'] }, opts, publicKey ? null : 'the pack');
}
case 'scopeblind-claims-v2.1.1': {
const r = verifyClaimsArtifactV211(input, subOpts);
return { ...r, modeLabel: MODE_LABELS['scopeblind-claims-v2.1.1'] };
}
case 'knowledge-unit': {
const r = await verifyKnowledgeUnit(input, subOpts);
const tier = detectTier({ mode: 'knowledge-unit', payloadFields: {}, valid: r.valid === true });
return { ...r, tier };
}
case 'voprf-token': {
// The engine takes the issuer key as issuerPublicKey; it was handed --key as publicKey, which it never read.
const r = await verifyVoprfToken(input, { ...subOpts, issuerPublicKey: publicKey || undefined });
const tier = detectTier({
mode: 'voprf-token',
valid: r.valid === true,
payloadFields: {
transport_hint: r.transport_hint,
},
voprfVerified: r.valid,
});
return { ...r, tier, modeLabel: MODE_LABELS['voprf-token'] };
}
case 'ed25519-browser-legacy':
case 'ed25519-receipt-v1':
case 'ed25519-receipt-v2':
case 'ed25519-passport': {
const r = await verifyReceipt(input, detected.mode, subOpts);
// Each check's detail as the engine gave it (a malformed encoding, a carried key, the issuer), the JWKS failure in
// place of the signature's when there was one, and below the key window's and the link's.
const details = { ...(r.checkDetails || {}), ...(jwksFailure ? { signature: jwksFailure } : {}) };
if (jwksFailure) r.checks.signature = { result: 'undecidable', code: 'jwks_fetch_failed' };
// Key validity window (-04 §5.5, -03 §9.2): applied whenever the key source carries one, whatever the signature's
// result, and reported either way, so an unchecked window is never read as a valid key.
const kw = checkKeyWindow({ window: keyWindow, issuedAt: receiptIssuedAt(input), keySource: jwksFailure ? null : keySource || r.keySource, require: opts.requireKeyWindow });
r.keyStatus = kw.report;
r.checks.key_window = keyWindowCheck(kw);
details.key_window = kw.detail;
// --previous (-04 §6.7.1): the caller asserts this receipt follows the one supplied, so its link must be that
// receipt's hash. The result says what the link was, whatever the other checks found.
if (opts.previousReceipt) {
let p;
try {
p = checkPreviousLink(input, opts.previousReceipt, { allowPayloadOnlyLinks: opts.allowPayloadOnlyLinks });
} catch (e) {
console.error(red(`verify: --previous ${opts.previousFile}: the receipt does not canonicalize (${e.message}), so it has no draft §6.7 link.`));
console.error(' Nothing was verified (exit 2).');
return REFUSED;
}
r.previous = { file: opts.previousFile, ...p };
r.checks.previous = !p.error ? { result: 'pass' } : { result: exitCodeFor(p.error) === 1 ? 'fail' : 'undecidable', code: p.error };
details.previous = p.detail;
if (p.warning) r.warning = [r.warning, p.warning].filter(Boolean).join(' ');
if (p.result === 'legacy-payload') r.conformant = false;
}
// -04 §5.3: invalid if any check ran and failed, undecidable if none failed and one could not run.
const combined = combineChecks(r.checks);
r.valid = combined.valid;
r.outcome = combined.outcome;
r.error = combined.error;
if (combined.check && details[combined.check]) r.detail = details[combined.check];
// Selective disclosure: attach if commitments present.
// Two formats supported:
// - Legacy AIP-0002 (_commitments map + --disclose field:salt:value)
// - commitment mode, draft §6 (committed_fields_root + --disclosure-file path)
// The committed_fields_root and the _commitments map are read from the signed bytes: an envelope's payload, where
// draft §2.2 puts the root, or the top level of a flat receipt. A disclosure that cannot be applied (a file that
// cannot be read or holds no disclosure, a --disclose value that does not parse, or signed bytes that carry
// nothing to check it against) leaves the receipt undecidable, never valid with the disclosure unread (0.10.27).
// Before, an envelope's root was not found, so a file given with it was never read, and a root or map beside an
// envelope's payload, outside the signature, was checked against instead.
let disclosureResult = null;
const commitment = signedCommitment(input);
// The AIP-0002 _commitments map is read from the signed bytes the same way (0.10.27).
const legacy = signedLegacyCommitments(input);
let disclosures = [];
let notApplied = null;
if (opts.disclosureFile !== null) {
if (!commitment) {
notApplied = 'the receipt\'s signed bytes carry no committed_fields_root (an envelope carries it in its payload), so there is nothing to check a disclosure against';
} else {
try {
disclosures = loadDisclosuresFromText(readFileSync(opts.disclosureFile, 'utf8'));
if (disclosures.length === 0) notApplied = 'the file holds no disclosure';
} catch (err) {
notApplied = `the file cannot be read as disclosures (${err?.message ?? 'unknown'})`;
}
}
}
if (notApplied) notApplied = `--disclosure-file ${opts.disclosureFile || '(no path given)'}: ${notApplied}`;
// --disclose (AIP-0002) applies to a _commitments map in the signed bytes, and every value given must parse.
const legacyDisclosures = parseDisclosures(opts.disclose);
if (!notApplied && opts.disclose.length > 0) {
if (!legacy) {
notApplied = '--disclose: the receipt\'s signed bytes carry no _commitments map (an envelope carries it in its payload), so there is nothing to check a disclosure against';
} else if (legacyDisclosures.length !== opts.disclose.length) {
notApplied = '--disclose: a value is not field:salt:value, so it names no disclosure';
}
}
if (commitment) {
r.committedFieldsRoot = commitment.root;
r.committedFieldNames = commitment.carrier.committed_field_names;
if (r.valid !== false && !notApplied) {
disclosureResult = verifyCommittedReceipt(commitment.carrier, disclosures);
r.disclosedFields = disclosures.map((d) => d.name);
if (!disclosureResult.valid) {
r.valid = false;
r.error = disclosureResult.error || 'commitment_mismatch';
}
}
}
if (legacy) {
// Legacy AIP-0002 path, against the map the signature covers.
r.redactedFields = listRedactedFields(legacy.carrier);
if (r.valid !== false && !notApplied) {
const legacyResult = verifySelectiveDisclosure(legacy.carrier, legacyDisclosures);
disclosureResult = disclosureResult
? { ...legacyResult, valid: disclosureResult.valid && legacyResult.valid, disclosuresVerified: (disclosureResult.disclosuresVerified || 0) + legacyResult.disclosuresVerified }
: legacyResult;
r.disclosedFields = [...(r.disclosedFields || []), ...legacyDisclosures.map((d) => d.field)];
if (!legacyResult.valid) {
r.valid = false;
r.error = r.error || 'commitment_mismatch';
}
}
}
// A failure already counted stays the outcome (-04 §5.3); otherwise a disclosure that could not be applied leaves
// the receipt undecidable.
if (notApplied && r.valid) {
r.valid = false;
r.error = 'disclosure_not_applied';
r.detail = `${notApplied}. Nothing in it was verified.`;
}
// Live-context predicates
if (opts.requireContext.length > 0) {
const preds = parseContextArgs(opts.requireContext);
const ctx = await evaluateLiveContext(preds);