@bolyra/receipts 0.9.0 → 0.10.1

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.
@@ -1 +1,22 @@
1
+ /**
2
+ * Deterministic JSON: object keys sorted, arrays in order.
3
+ *
4
+ * Throws a TypeError when an object that JSON.stringify visits as a member of
5
+ * the value (at any depth, including objects inside arrays) has an OWN key
6
+ * named "__proto__" (JSON.parse creates one from the text `{"__proto__": ...}`).
7
+ * The guard covers plain JSON data. It does not see non-index properties set
8
+ * on an array, or the original object when a `toJSON` method replaces it.
9
+ * The sorted copy below is built by assignment, and assigning to that name
10
+ * sets the copy's prototype instead of creating a key, so the member would be
11
+ * absent from the output. A value with such a member therefore has no exact
12
+ * canonical form here, and it is refused rather than serialized without it.
13
+ *
14
+ * Also throws a TypeError for a number that is not finite, or is negative
15
+ * zero. JSON.stringify writes those as `null` and `0`, so each would share a
16
+ * canonical form with a different value. JSON.parse yields them from ordinary
17
+ * text such as `1e400` and `-0`.
18
+ *
19
+ * Callers that verify (verifyReceipt, verifyReceiptChain) treat the throw as
20
+ * a failed verification; callers that sign or hash propagate it.
21
+ */
1
22
  export declare function canonicalize(obj: unknown): string;
package/dist/canonical.js CHANGED
@@ -1,14 +1,42 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.canonicalize = canonicalize;
4
+ const UNREPRESENTABLE_KEY = '__proto__';
5
+ /**
6
+ * Deterministic JSON: object keys sorted, arrays in order.
7
+ *
8
+ * Throws a TypeError when an object that JSON.stringify visits as a member of
9
+ * the value (at any depth, including objects inside arrays) has an OWN key
10
+ * named "__proto__" (JSON.parse creates one from the text `{"__proto__": ...}`).
11
+ * The guard covers plain JSON data. It does not see non-index properties set
12
+ * on an array, or the original object when a `toJSON` method replaces it.
13
+ * The sorted copy below is built by assignment, and assigning to that name
14
+ * sets the copy's prototype instead of creating a key, so the member would be
15
+ * absent from the output. A value with such a member therefore has no exact
16
+ * canonical form here, and it is refused rather than serialized without it.
17
+ *
18
+ * Also throws a TypeError for a number that is not finite, or is negative
19
+ * zero. JSON.stringify writes those as `null` and `0`, so each would share a
20
+ * canonical form with a different value. JSON.parse yields them from ordinary
21
+ * text such as `1e400` and `-0`.
22
+ *
23
+ * Callers that verify (verifyReceipt, verifyReceiptChain) treat the throw as
24
+ * a failed verification; callers that sign or hash propagate it.
25
+ */
4
26
  function canonicalize(obj) {
5
27
  return JSON.stringify(obj, (_key, value) => {
6
28
  if (value && typeof value === 'object' && !Array.isArray(value)) {
29
+ if (Object.prototype.hasOwnProperty.call(value, UNREPRESENTABLE_KEY)) {
30
+ throw new TypeError('canonicalize: an object has an own "__proto__" key, which has no canonical form');
31
+ }
7
32
  return Object.keys(value).sort().reduce((sorted, k) => {
8
33
  sorted[k] = value[k];
9
34
  return sorted;
10
35
  }, {});
11
36
  }
37
+ if (typeof value === 'number' && (!Number.isFinite(value) || Object.is(value, -0))) {
38
+ throw new TypeError('canonicalize: a number is non-finite or negative zero, which has no canonical form');
39
+ }
12
40
  return value;
13
41
  });
14
42
  }
package/dist/chain.js CHANGED
@@ -153,7 +153,22 @@ function verifyReceiptChain(receipts, options = {}) {
153
153
  }
154
154
  chained += 1;
155
155
  // 3. Link check against the previous CHAINED receipt.
156
- const actualHash = computeReceiptHash(receipt);
156
+ // A receipt whose content has no canonical form cannot be hashed. It is
157
+ // reported and skipped: `prev` and the head stay at the last hashable
158
+ // receipt, so the following link fails too. This function never throws.
159
+ let actualHash;
160
+ try {
161
+ actualHash = computeReceiptHash(receipt);
162
+ }
163
+ catch {
164
+ issues.push({
165
+ index,
166
+ receiptId: typeof id === 'string' ? id : undefined,
167
+ code: 'malformed-receipt',
168
+ message: `entry #${index} cannot be hashed (its content has no canonical form)`,
169
+ });
170
+ return;
171
+ }
157
172
  if (prev === undefined) {
158
173
  if (chain.seq !== 0 || chain.prevReceiptHash !== exports.GENESIS_PREV_RECEIPT_HASH) {
159
174
  issues.push({
package/dist/index.d.ts CHANGED
@@ -4,4 +4,6 @@ export { signReceipt, verifyReceipt, hashPayload } from './sign';
4
4
  export { GENESIS_PREV_RECEIPT_HASH, ReceiptChain, computeReceiptHash, verifyReceiptChain, } from './chain';
5
5
  export type { ReceiptChainIssue, ReceiptChainIssueCode, ChainVerifyOptions, ChainVerifyResult, } from './chain';
6
6
  export type { ReceiptPayload, ReceiptChainFields, SignedReceipt, ReceiptSignerConfig, AuthReceiptInput, CommerceReceiptInput, CommerceFields, } from './types';
7
+ export { INSTANCE_BINDING_DST, INSTANCE_REF_PREFIX, computeInstanceRef, validateInstancePreimage, verifyInstanceBinding, } from './instance';
8
+ export type { InstancePreimage, ReceiptInstanceFields, InstanceBindingCode, InstanceBindingResult, PreimageValidation, } from './instance';
7
9
  export { parseSignerDiscovery, acceptedSigners, SignerDiscoveryError, type SignerDiscoveryDocument, type DiscoveredSigner, } from './signer-discovery';
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SignerDiscoveryError = exports.acceptedSigners = exports.parseSignerDiscovery = exports.verifyReceiptChain = exports.computeReceiptHash = exports.ReceiptChain = exports.GENESIS_PREV_RECEIPT_HASH = exports.hashPayload = exports.verifyReceipt = exports.signReceipt = exports.createCommerceReceipt = exports.createAuthReceipt = exports.canonicalize = void 0;
3
+ exports.SignerDiscoveryError = exports.acceptedSigners = exports.parseSignerDiscovery = exports.verifyInstanceBinding = exports.validateInstancePreimage = exports.computeInstanceRef = exports.INSTANCE_REF_PREFIX = exports.INSTANCE_BINDING_DST = exports.verifyReceiptChain = exports.computeReceiptHash = exports.ReceiptChain = exports.GENESIS_PREV_RECEIPT_HASH = exports.hashPayload = exports.verifyReceipt = exports.signReceipt = exports.createCommerceReceipt = exports.createAuthReceipt = exports.canonicalize = void 0;
4
4
  var canonical_1 = require("./canonical");
5
5
  Object.defineProperty(exports, "canonicalize", { enumerable: true, get: function () { return canonical_1.canonicalize; } });
6
6
  var receipt_1 = require("./receipt");
@@ -15,6 +15,12 @@ Object.defineProperty(exports, "GENESIS_PREV_RECEIPT_HASH", { enumerable: true,
15
15
  Object.defineProperty(exports, "ReceiptChain", { enumerable: true, get: function () { return chain_1.ReceiptChain; } });
16
16
  Object.defineProperty(exports, "computeReceiptHash", { enumerable: true, get: function () { return chain_1.computeReceiptHash; } });
17
17
  Object.defineProperty(exports, "verifyReceiptChain", { enumerable: true, get: function () { return chain_1.verifyReceiptChain; } });
18
+ var instance_1 = require("./instance");
19
+ Object.defineProperty(exports, "INSTANCE_BINDING_DST", { enumerable: true, get: function () { return instance_1.INSTANCE_BINDING_DST; } });
20
+ Object.defineProperty(exports, "INSTANCE_REF_PREFIX", { enumerable: true, get: function () { return instance_1.INSTANCE_REF_PREFIX; } });
21
+ Object.defineProperty(exports, "computeInstanceRef", { enumerable: true, get: function () { return instance_1.computeInstanceRef; } });
22
+ Object.defineProperty(exports, "validateInstancePreimage", { enumerable: true, get: function () { return instance_1.validateInstancePreimage; } });
23
+ Object.defineProperty(exports, "verifyInstanceBinding", { enumerable: true, get: function () { return instance_1.verifyInstanceBinding; } });
18
24
  var signer_discovery_1 = require("./signer-discovery");
19
25
  Object.defineProperty(exports, "parseSignerDiscovery", { enumerable: true, get: function () { return signer_discovery_1.parseSignerDiscovery; } });
20
26
  Object.defineProperty(exports, "acceptedSigners", { enumerable: true, get: function () { return signer_discovery_1.acceptedSigners; } });
@@ -0,0 +1,87 @@
1
+ import type { SignedReceipt } from './types';
2
+ /**
3
+ * Instance binding for commerce receipts (spec/receipt-instance-binding-v1.md).
4
+ *
5
+ * commerce.intentHash is parameter-shaped: two otherwise identical spend
6
+ * intents produce the same hash, and instance uniqueness comes only from the
7
+ * issuer-generated proof.nonce, which a third party cannot recompute. The
8
+ * instance block closes that gap: an instance-shaped reference any holder of
9
+ * the preimage fields derives independently, with no callback to the issuer.
10
+ *
11
+ * verifyInstanceBinding() is the SEMANTIC check and deliberately separate from
12
+ * verifyReceipt(): signature validity and instance-binding validity are
13
+ * different claims. verifyReceipt() proves the issuer signed the payload; it
14
+ * happily accepts a payload whose instance.ref does not match its own
15
+ * preimage. Every consumer of the instance claim must call both.
16
+ */
17
+ /** Domain-separation tag hashed into the ref, terminated by an explicit 0x00. */
18
+ export declare const INSTANCE_BINDING_DST = "bolyra.receipt.instance/1";
19
+ /** Version marker in the reference string syntax — a verifier never guesses the derivation. */
20
+ export declare const INSTANCE_REF_PREFIX = "birv1:";
21
+ /**
22
+ * The full preimage of instance.ref, carried in the receipt so it is
23
+ * self-contained. Closed schema: exactly these members, every value an ASCII
24
+ * string (or array of ASCII strings) — within that domain the sorted-key
25
+ * canonical JSON is byte-equivalent to RFC 8785.
26
+ */
27
+ export interface InstancePreimage {
28
+ /** Payee / project_key the decision bound to. */
29
+ audience: string;
30
+ /** Binding program discriminator (e.g. "x402", "mpp"). */
31
+ program: string;
32
+ /** Granted capability tokens, order as granted (order is significant). */
33
+ capabilities: string[];
34
+ /** Decimal string, exactly as decided. */
35
+ amountUsd: string;
36
+ /** RFC 3339 UTC with exactly 3-digit milliseconds: "2026-08-24T10:00:00.123Z". */
37
+ decisionAt: string;
38
+ /** In-protocol pre-decision challenge nonce, when the transport has one. */
39
+ requestNonce?: string;
40
+ /** External instance reference (e.g. an argentum action_ref), verbatim. */
41
+ actionRef?: string;
42
+ }
43
+ export interface ReceiptInstanceFields {
44
+ /** INSTANCE_REF_PREFIX + lowercase sha256 hex over the domain-tagged canonical preimage. */
45
+ ref: string;
46
+ preimage: InstancePreimage;
47
+ }
48
+ export type InstanceBindingCode = 'absent' | 'ok' | 'wrong_kind' | 'malformed_ref' | 'out_of_domain' | 'ref_mismatch';
49
+ export type InstanceBindingResult = {
50
+ ok: true;
51
+ present: false;
52
+ code: 'absent';
53
+ } | {
54
+ ok: true;
55
+ present: true;
56
+ code: 'ok';
57
+ } | {
58
+ ok: false;
59
+ present: true;
60
+ code: Exclude<InstanceBindingCode, 'absent' | 'ok'>;
61
+ detail: string;
62
+ };
63
+ export type PreimageValidation = {
64
+ ok: true;
65
+ } | {
66
+ ok: false;
67
+ detail: string;
68
+ };
69
+ /**
70
+ * Enforces the closed canonicalization domain of spec §3.1. Anything outside
71
+ * it is rejected outright — no best-effort canonicalization, one pinned
72
+ * behavior.
73
+ */
74
+ export declare function validateInstancePreimage(value: unknown): PreimageValidation;
75
+ /**
76
+ * ref = "birv1:" + sha256hex( utf8(DST) || 0x00 || utf8(canonicalize(preimage)) )
77
+ *
78
+ * Throws on an out-of-domain preimage: an emitter must never produce a ref
79
+ * whose preimage a verifier is required to reject.
80
+ */
81
+ export declare function computeInstanceRef(preimage: InstancePreimage): string;
82
+ /**
83
+ * The semantic instance-binding check. Assumes nothing about the signature —
84
+ * pair it with verifyReceipt(). Returns ok with present:false when the
85
+ * receipt carries no instance block (the block is optional).
86
+ */
87
+ export declare function verifyInstanceBinding(receipt: SignedReceipt): InstanceBindingResult;
@@ -0,0 +1,173 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.INSTANCE_REF_PREFIX = exports.INSTANCE_BINDING_DST = void 0;
4
+ exports.validateInstancePreimage = validateInstancePreimage;
5
+ exports.computeInstanceRef = computeInstanceRef;
6
+ exports.verifyInstanceBinding = verifyInstanceBinding;
7
+ const sha256_1 = require("@noble/hashes/sha256");
8
+ const utils_1 = require("@noble/hashes/utils");
9
+ const canonical_1 = require("./canonical");
10
+ /**
11
+ * Instance binding for commerce receipts (spec/receipt-instance-binding-v1.md).
12
+ *
13
+ * commerce.intentHash is parameter-shaped: two otherwise identical spend
14
+ * intents produce the same hash, and instance uniqueness comes only from the
15
+ * issuer-generated proof.nonce, which a third party cannot recompute. The
16
+ * instance block closes that gap: an instance-shaped reference any holder of
17
+ * the preimage fields derives independently, with no callback to the issuer.
18
+ *
19
+ * verifyInstanceBinding() is the SEMANTIC check and deliberately separate from
20
+ * verifyReceipt(): signature validity and instance-binding validity are
21
+ * different claims. verifyReceipt() proves the issuer signed the payload; it
22
+ * happily accepts a payload whose instance.ref does not match its own
23
+ * preimage. Every consumer of the instance claim must call both.
24
+ */
25
+ /** Domain-separation tag hashed into the ref, terminated by an explicit 0x00. */
26
+ exports.INSTANCE_BINDING_DST = 'bolyra.receipt.instance/1';
27
+ /** Version marker in the reference string syntax — a verifier never guesses the derivation. */
28
+ exports.INSTANCE_REF_PREFIX = 'birv1:';
29
+ const REF_PATTERN = /^birv1:[0-9a-f]{64}$/;
30
+ const DECISION_AT_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
31
+ /**
32
+ * §3.1.1: audience is a stable machine identifier, pinned tighter than the
33
+ * general ASCII domain — printable ASCII excluding space, 1..256 chars. A
34
+ * syntactic floor, not semantic proof: it rejects the display-name shape
35
+ * ("Acme Corp") without inventing a versioned identifier grammar.
36
+ */
37
+ const AUDIENCE_PATTERN = /^[\x21-\x7e]{1,256}$/;
38
+ // eslint-disable-next-line no-control-regex
39
+ const ASCII_ONLY = /^[\x00-\x7f]*$/;
40
+ const REQUIRED_MEMBERS = ['audience', 'program', 'capabilities', 'amountUsd', 'decisionAt'];
41
+ const OPTIONAL_MEMBERS = ['requestNonce', 'actionRef'];
42
+ const ALLOWED_MEMBERS = new Set([...REQUIRED_MEMBERS, ...OPTIONAL_MEMBERS]);
43
+ const STRING_MEMBERS = ['audience', 'program', 'amountUsd', 'decisionAt', ...OPTIONAL_MEMBERS];
44
+ /**
45
+ * Enforces the closed canonicalization domain of spec §3.1. Anything outside
46
+ * it is rejected outright — no best-effort canonicalization, one pinned
47
+ * behavior.
48
+ */
49
+ function validateInstancePreimage(value) {
50
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
51
+ return { ok: false, detail: 'preimage must be a JSON object' };
52
+ }
53
+ const obj = value;
54
+ for (const member of Object.keys(obj)) {
55
+ if (!ALLOWED_MEMBERS.has(member)) {
56
+ return { ok: false, detail: `unknown member "${member}" (closed schema)` };
57
+ }
58
+ }
59
+ for (const member of REQUIRED_MEMBERS) {
60
+ if (!(member in obj)) {
61
+ return { ok: false, detail: `missing required member "${member}"` };
62
+ }
63
+ }
64
+ for (const member of STRING_MEMBERS) {
65
+ if (!(member in obj))
66
+ continue;
67
+ const v = obj[member];
68
+ if (typeof v !== 'string') {
69
+ return { ok: false, detail: `member "${member}" must be a string` };
70
+ }
71
+ if (!ASCII_ONLY.test(v)) {
72
+ return { ok: false, detail: `member "${member}" must contain only ASCII (0x00..0x7F)` };
73
+ }
74
+ }
75
+ const capabilities = obj.capabilities;
76
+ if (!Array.isArray(capabilities)) {
77
+ return { ok: false, detail: 'member "capabilities" must be an array of strings' };
78
+ }
79
+ for (const cap of capabilities) {
80
+ if (typeof cap !== 'string') {
81
+ return { ok: false, detail: 'every capability must be a string' };
82
+ }
83
+ if (!ASCII_ONLY.test(cap)) {
84
+ return { ok: false, detail: 'every capability must contain only ASCII (0x00..0x7F)' };
85
+ }
86
+ }
87
+ if (!AUDIENCE_PATTERN.test(obj.audience)) {
88
+ return {
89
+ ok: false,
90
+ detail: 'audience must be a stable machine identifier: printable ASCII excluding space (0x21..0x7E), 1..256 characters',
91
+ };
92
+ }
93
+ if (!DECISION_AT_PATTERN.test(obj.decisionAt)) {
94
+ return {
95
+ ok: false,
96
+ detail: 'decisionAt must match YYYY-MM-DDTHH:MM:SS.mmmZ exactly (3-digit ms, UTC Z)',
97
+ };
98
+ }
99
+ return { ok: true };
100
+ }
101
+ function utf8(str) {
102
+ return new TextEncoder().encode(str);
103
+ }
104
+ /**
105
+ * ref = "birv1:" + sha256hex( utf8(DST) || 0x00 || utf8(canonicalize(preimage)) )
106
+ *
107
+ * Throws on an out-of-domain preimage: an emitter must never produce a ref
108
+ * whose preimage a verifier is required to reject.
109
+ */
110
+ function computeInstanceRef(preimage) {
111
+ const validation = validateInstancePreimage(preimage);
112
+ if (!validation.ok) {
113
+ throw new Error(`instance preimage out of domain: ${validation.detail}`);
114
+ }
115
+ const dst = utf8(exports.INSTANCE_BINDING_DST);
116
+ const canonical = utf8((0, canonical_1.canonicalize)(preimage));
117
+ const input = new Uint8Array(dst.length + 1 + canonical.length);
118
+ input.set(dst, 0);
119
+ input[dst.length] = 0x00;
120
+ input.set(canonical, dst.length + 1);
121
+ return exports.INSTANCE_REF_PREFIX + (0, utils_1.bytesToHex)((0, sha256_1.sha256)(input));
122
+ }
123
+ /**
124
+ * The semantic instance-binding check. Assumes nothing about the signature —
125
+ * pair it with verifyReceipt(). Returns ok with present:false when the
126
+ * receipt carries no instance block (the block is optional).
127
+ */
128
+ function verifyInstanceBinding(receipt) {
129
+ const instance = receipt.payload.instance;
130
+ if (instance === undefined) {
131
+ return { ok: true, present: false, code: 'absent' };
132
+ }
133
+ if (receipt.payload.kind !== 'bolyra.commerce') {
134
+ return {
135
+ ok: false,
136
+ present: true,
137
+ code: 'wrong_kind',
138
+ detail: `instance binding v1 is scoped to bolyra.commerce receipts, got "${receipt.payload.kind}"`,
139
+ };
140
+ }
141
+ // Parsed JSON can carry any shape here regardless of the TS type; a signed
142
+ // receipt with e.g. "instance": null must fail deterministically, not throw.
143
+ if (typeof instance !== 'object' || instance === null || Array.isArray(instance)) {
144
+ return {
145
+ ok: false,
146
+ present: true,
147
+ code: 'malformed_ref',
148
+ detail: 'instance block must be a JSON object with ref and preimage members',
149
+ };
150
+ }
151
+ if (typeof instance.ref !== 'string' || !REF_PATTERN.test(instance.ref)) {
152
+ return {
153
+ ok: false,
154
+ present: true,
155
+ code: 'malformed_ref',
156
+ detail: 'ref must be "birv1:" followed by 64 lowercase hex characters',
157
+ };
158
+ }
159
+ const validation = validateInstancePreimage(instance.preimage);
160
+ if (!validation.ok) {
161
+ return { ok: false, present: true, code: 'out_of_domain', detail: validation.detail };
162
+ }
163
+ const recomputed = computeInstanceRef(instance.preimage);
164
+ if (recomputed !== instance.ref) {
165
+ return {
166
+ ok: false,
167
+ present: true,
168
+ code: 'ref_mismatch',
169
+ detail: 'recomputed instance ref does not match the carried ref',
170
+ };
171
+ }
172
+ return { ok: true, present: true, code: 'ok' };
173
+ }
package/dist/types.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { ReceiptInstanceFields } from './instance';
1
2
  /**
2
3
  * Optional hash-chain fields linking a receipt to its predecessor in a log.
3
4
  * Additive and backward-compatible: chain-less receipts remain valid, and
@@ -54,6 +55,14 @@ export interface ReceiptPayload {
54
55
  };
55
56
  /** Present only when kind === 'bolyra.commerce'. */
56
57
  commerce?: CommerceFields;
58
+ /**
59
+ * Optional instance binding (spec/receipt-instance-binding-v1.md).
60
+ * v1 scope: bolyra.commerce receipts only. Lives inside the signed payload
61
+ * so it cannot be rewritten without breaking the ES256K signature; its
62
+ * SEMANTIC validity (ref recomputes from preimage) is a separate claim
63
+ * checked by verifyInstanceBinding(), not by verifyReceipt().
64
+ */
65
+ instance?: ReceiptInstanceFields;
57
66
  /** Present only on hash-chained receipts (written via ReceiptChain). */
58
67
  chain?: ReceiptChainFields;
59
68
  }
@@ -128,6 +128,10 @@ function failCheck(msg) {
128
128
  }
129
129
  // 1. Schema validation
130
130
  function validateSchema() {
131
+ if (receipt === null || typeof receipt !== 'object') {
132
+ failCheck('Schema: receipt is not an object');
133
+ return false;
134
+ }
131
135
  const p = receipt.payload;
132
136
  const s = receipt.signature;
133
137
  const errors = [];
@@ -181,6 +185,9 @@ function validateSchema() {
181
185
  if (!p.proof) {
182
186
  errors.push('payload.proof missing');
183
187
  }
188
+ else if (typeof p.proof !== 'object') {
189
+ errors.push('payload.proof not an object');
190
+ }
184
191
  else {
185
192
  for (const k of ['bundleVersion', 'nonce', 'humanProofHash', 'agentProofHash', 'publicSignalsHash']) {
186
193
  if (!(k in p.proof))
@@ -215,11 +222,11 @@ function validateSchema() {
215
222
  errors.push('signature.alg !== "ES256K"');
216
223
  if (s.keyId !== p.keyId)
217
224
  errors.push('signature.keyId does not match payload.keyId');
218
- if (!/^0x[0-9a-fA-F]{40}$/.test(s.signer ?? ''))
225
+ if (typeof s.signer !== 'string' || !/^0x[0-9a-fA-F]{40}$/.test(s.signer))
219
226
  errors.push('signature.signer invalid format');
220
- if (!/^0x[0-9a-fA-F]{64}$/.test(s.payloadHash ?? ''))
227
+ if (typeof s.payloadHash !== 'string' || !/^0x[0-9a-fA-F]{64}$/.test(s.payloadHash))
221
228
  errors.push('signature.payloadHash invalid format');
222
- if (!/^0x[0-9a-fA-F]{130}$/.test(s.value ?? ''))
229
+ if (typeof s.value !== 'string' || !/^0x[0-9a-fA-F]{130}$/.test(s.value))
223
230
  errors.push('signature.value invalid format');
224
231
  if (errors.length) {
225
232
  failCheck(`Schema: ${errors.join('; ')}`);
@@ -234,7 +241,12 @@ function validateTimestamp() {
234
241
  const issuedAt = receipt.payload.issuedAt;
235
242
  const allowFutureSeconds = 300;
236
243
  const ageSec = nowSec - issuedAt;
237
- const isoStr = new Date(issuedAt * 1000).toISOString();
244
+ const date = new Date(issuedAt * 1000);
245
+ if (!Number.isFinite(date.getTime())) {
246
+ failCheck('Timestamp is outside the supported date range');
247
+ return;
248
+ }
249
+ const isoStr = date.toISOString();
238
250
  if (issuedAt > nowSec + allowFutureSeconds) {
239
251
  failCheck(`Timestamp: ${isoStr} is ${issuedAt - nowSec}s in the future (max skew: ${allowFutureSeconds}s)`);
240
252
  return;
@@ -247,7 +259,15 @@ function validateTimestamp() {
247
259
  }
248
260
  // 3. Hash check
249
261
  function validateHash() {
250
- const computed = (0, sign_1.hashPayload)(receipt.payload);
262
+ let computed;
263
+ try {
264
+ computed = (0, sign_1.hashPayload)(receipt.payload);
265
+ }
266
+ catch {
267
+ // The payload holds a value with no canonical form, so it has no hash.
268
+ failCheck('Payload cannot be canonicalized');
269
+ return false;
270
+ }
251
271
  if (computed !== receipt.signature.payloadHash) {
252
272
  failCheck(`Payload hash mismatch (expected ${truncate(receipt.signature.payloadHash)}, got ${truncate(computed)})`);
253
273
  return false;
@@ -258,6 +278,10 @@ function validateHash() {
258
278
  // 4. ID check
259
279
  function validateId() {
260
280
  const expected = '0x' + receipt.signature.payloadHash.slice(2, 18);
281
+ if (typeof receipt.id !== 'string') {
282
+ failCheck(`Receipt ID is not a string (expected ${expected})`);
283
+ return;
284
+ }
261
285
  if (receipt.id !== expected) {
262
286
  failCheck(`Receipt ID mismatch (expected ${expected}, got ${receipt.id})`);
263
287
  return;
@@ -274,13 +298,20 @@ function validateSignature() {
274
298
  pass(`Signature valid (signer: ${truncate(receipt.signature.signer)})`);
275
299
  }
276
300
  // --- Run checks ---
277
- if (validateSchema()) {
278
- validateTimestamp();
279
- if (validateHash()) {
280
- validateId();
281
- validateSignature();
301
+ // A receipt is untrusted input. Whatever shape it has, the outcome is a list
302
+ // of checks and an exit code, never an uncaught error.
303
+ try {
304
+ if (validateSchema()) {
305
+ validateTimestamp();
306
+ if (validateHash()) {
307
+ validateId();
308
+ validateSignature();
309
+ }
282
310
  }
283
311
  }
312
+ catch {
313
+ failCheck('Receipt could not be checked');
314
+ }
284
315
  // --- Output ---
285
316
  for (const line of checks) {
286
317
  console.log(line);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bolyra/receipts",
3
- "version": "0.9.0",
3
+ "version": "0.10.1",
4
4
  "description": "Signed auth receipts for Bolyra ZKP verification decisions — canonical JSON, secp256k1 sign/verify, EVM-compatible r||s||v signatures.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -10,7 +10,7 @@
10
10
  "scripts": {
11
11
  "build": "tsc",
12
12
  "prepare": "tsc",
13
- "test": "jest --passWithNoTests",
13
+ "test": "jest",
14
14
  "typecheck": "tsc --noEmit"
15
15
  },
16
16
  "dependencies": {
@@ -22,6 +22,7 @@
22
22
  "@types/node": "^25.9.1",
23
23
  "jest": "^30.4.2",
24
24
  "ts-jest": "^29.2.0",
25
+ "tsx": "^4.20.0",
25
26
  "@types/jest": "^30.0.0"
26
27
  },
27
28
  "files": [
@@ -35,7 +36,8 @@
35
36
  "url": "https://github.com/bolyra/bolyra"
36
37
  },
37
38
  "publishConfig": {
38
- "access": "public"
39
+ "access": "public",
40
+ "tag": "release-0.10"
39
41
  },
40
42
  "keywords": [
41
43
  "bolyra",
package/src/canonical.ts CHANGED
@@ -1,11 +1,40 @@
1
+ const UNREPRESENTABLE_KEY = '__proto__';
2
+
3
+ /**
4
+ * Deterministic JSON: object keys sorted, arrays in order.
5
+ *
6
+ * Throws a TypeError when an object that JSON.stringify visits as a member of
7
+ * the value (at any depth, including objects inside arrays) has an OWN key
8
+ * named "__proto__" (JSON.parse creates one from the text `{"__proto__": ...}`).
9
+ * The guard covers plain JSON data. It does not see non-index properties set
10
+ * on an array, or the original object when a `toJSON` method replaces it.
11
+ * The sorted copy below is built by assignment, and assigning to that name
12
+ * sets the copy's prototype instead of creating a key, so the member would be
13
+ * absent from the output. A value with such a member therefore has no exact
14
+ * canonical form here, and it is refused rather than serialized without it.
15
+ *
16
+ * Also throws a TypeError for a number that is not finite, or is negative
17
+ * zero. JSON.stringify writes those as `null` and `0`, so each would share a
18
+ * canonical form with a different value. JSON.parse yields them from ordinary
19
+ * text such as `1e400` and `-0`.
20
+ *
21
+ * Callers that verify (verifyReceipt, verifyReceiptChain) treat the throw as
22
+ * a failed verification; callers that sign or hash propagate it.
23
+ */
1
24
  export function canonicalize(obj: unknown): string {
2
25
  return JSON.stringify(obj, (_key, value) => {
3
26
  if (value && typeof value === 'object' && !Array.isArray(value)) {
27
+ if (Object.prototype.hasOwnProperty.call(value, UNREPRESENTABLE_KEY)) {
28
+ throw new TypeError('canonicalize: an object has an own "__proto__" key, which has no canonical form');
29
+ }
4
30
  return Object.keys(value).sort().reduce((sorted, k) => {
5
31
  sorted[k] = (value as Record<string, unknown>)[k];
6
32
  return sorted;
7
33
  }, {} as Record<string, unknown>);
8
34
  }
35
+ if (typeof value === 'number' && (!Number.isFinite(value) || Object.is(value, -0))) {
36
+ throw new TypeError('canonicalize: a number is non-finite or negative zero, which has no canonical form');
37
+ }
9
38
  return value;
10
39
  });
11
40
  }
package/src/chain.ts CHANGED
@@ -216,7 +216,21 @@ export function verifyReceiptChain(
216
216
  chained += 1;
217
217
 
218
218
  // 3. Link check against the previous CHAINED receipt.
219
- const actualHash = computeReceiptHash(receipt);
219
+ // A receipt whose content has no canonical form cannot be hashed. It is
220
+ // reported and skipped: `prev` and the head stay at the last hashable
221
+ // receipt, so the following link fails too. This function never throws.
222
+ let actualHash: string;
223
+ try {
224
+ actualHash = computeReceiptHash(receipt);
225
+ } catch {
226
+ issues.push({
227
+ index,
228
+ receiptId: typeof id === 'string' ? id : undefined,
229
+ code: 'malformed-receipt',
230
+ message: `entry #${index} cannot be hashed (its content has no canonical form)`,
231
+ });
232
+ return;
233
+ }
220
234
  if (prev === undefined) {
221
235
  if (chain.seq !== 0 || chain.prevReceiptHash !== GENESIS_PREV_RECEIPT_HASH) {
222
236
  issues.push({
package/src/index.ts CHANGED
@@ -22,6 +22,20 @@ export type {
22
22
  CommerceReceiptInput,
23
23
  CommerceFields,
24
24
  } from './types';
25
+ export {
26
+ INSTANCE_BINDING_DST,
27
+ INSTANCE_REF_PREFIX,
28
+ computeInstanceRef,
29
+ validateInstancePreimage,
30
+ verifyInstanceBinding,
31
+ } from './instance';
32
+ export type {
33
+ InstancePreimage,
34
+ ReceiptInstanceFields,
35
+ InstanceBindingCode,
36
+ InstanceBindingResult,
37
+ PreimageValidation,
38
+ } from './instance';
25
39
  export {
26
40
  parseSignerDiscovery,
27
41
  acceptedSigners,
@@ -0,0 +1,222 @@
1
+ import { sha256 } from '@noble/hashes/sha256';
2
+ import { bytesToHex } from '@noble/hashes/utils';
3
+ import { canonicalize } from './canonical';
4
+ import type { SignedReceipt } from './types';
5
+
6
+ /**
7
+ * Instance binding for commerce receipts (spec/receipt-instance-binding-v1.md).
8
+ *
9
+ * commerce.intentHash is parameter-shaped: two otherwise identical spend
10
+ * intents produce the same hash, and instance uniqueness comes only from the
11
+ * issuer-generated proof.nonce, which a third party cannot recompute. The
12
+ * instance block closes that gap: an instance-shaped reference any holder of
13
+ * the preimage fields derives independently, with no callback to the issuer.
14
+ *
15
+ * verifyInstanceBinding() is the SEMANTIC check and deliberately separate from
16
+ * verifyReceipt(): signature validity and instance-binding validity are
17
+ * different claims. verifyReceipt() proves the issuer signed the payload; it
18
+ * happily accepts a payload whose instance.ref does not match its own
19
+ * preimage. Every consumer of the instance claim must call both.
20
+ */
21
+
22
+ /** Domain-separation tag hashed into the ref, terminated by an explicit 0x00. */
23
+ export const INSTANCE_BINDING_DST = 'bolyra.receipt.instance/1';
24
+
25
+ /** Version marker in the reference string syntax — a verifier never guesses the derivation. */
26
+ export const INSTANCE_REF_PREFIX = 'birv1:';
27
+
28
+ const REF_PATTERN = /^birv1:[0-9a-f]{64}$/;
29
+ const DECISION_AT_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
30
+ /**
31
+ * §3.1.1: audience is a stable machine identifier, pinned tighter than the
32
+ * general ASCII domain — printable ASCII excluding space, 1..256 chars. A
33
+ * syntactic floor, not semantic proof: it rejects the display-name shape
34
+ * ("Acme Corp") without inventing a versioned identifier grammar.
35
+ */
36
+ const AUDIENCE_PATTERN = /^[\x21-\x7e]{1,256}$/;
37
+ // eslint-disable-next-line no-control-regex
38
+ const ASCII_ONLY = /^[\x00-\x7f]*$/;
39
+
40
+ /**
41
+ * The full preimage of instance.ref, carried in the receipt so it is
42
+ * self-contained. Closed schema: exactly these members, every value an ASCII
43
+ * string (or array of ASCII strings) — within that domain the sorted-key
44
+ * canonical JSON is byte-equivalent to RFC 8785.
45
+ */
46
+ export interface InstancePreimage {
47
+ /** Payee / project_key the decision bound to. */
48
+ audience: string;
49
+ /** Binding program discriminator (e.g. "x402", "mpp"). */
50
+ program: string;
51
+ /** Granted capability tokens, order as granted (order is significant). */
52
+ capabilities: string[];
53
+ /** Decimal string, exactly as decided. */
54
+ amountUsd: string;
55
+ /** RFC 3339 UTC with exactly 3-digit milliseconds: "2026-08-24T10:00:00.123Z". */
56
+ decisionAt: string;
57
+ /** In-protocol pre-decision challenge nonce, when the transport has one. */
58
+ requestNonce?: string;
59
+ /** External instance reference (e.g. an argentum action_ref), verbatim. */
60
+ actionRef?: string;
61
+ }
62
+
63
+ export interface ReceiptInstanceFields {
64
+ /** INSTANCE_REF_PREFIX + lowercase sha256 hex over the domain-tagged canonical preimage. */
65
+ ref: string;
66
+ preimage: InstancePreimage;
67
+ }
68
+
69
+ export type InstanceBindingCode =
70
+ | 'absent'
71
+ | 'ok'
72
+ | 'wrong_kind'
73
+ | 'malformed_ref'
74
+ | 'out_of_domain'
75
+ | 'ref_mismatch';
76
+
77
+ export type InstanceBindingResult =
78
+ | { ok: true; present: false; code: 'absent' }
79
+ | { ok: true; present: true; code: 'ok' }
80
+ | { ok: false; present: true; code: Exclude<InstanceBindingCode, 'absent' | 'ok'>; detail: string };
81
+
82
+ export type PreimageValidation = { ok: true } | { ok: false; detail: string };
83
+
84
+ const REQUIRED_MEMBERS = ['audience', 'program', 'capabilities', 'amountUsd', 'decisionAt'] as const;
85
+ const OPTIONAL_MEMBERS = ['requestNonce', 'actionRef'] as const;
86
+ const ALLOWED_MEMBERS: ReadonlySet<string> = new Set([...REQUIRED_MEMBERS, ...OPTIONAL_MEMBERS]);
87
+ const STRING_MEMBERS = ['audience', 'program', 'amountUsd', 'decisionAt', ...OPTIONAL_MEMBERS] as const;
88
+
89
+ /**
90
+ * Enforces the closed canonicalization domain of spec §3.1. Anything outside
91
+ * it is rejected outright — no best-effort canonicalization, one pinned
92
+ * behavior.
93
+ */
94
+ export function validateInstancePreimage(value: unknown): PreimageValidation {
95
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
96
+ return { ok: false, detail: 'preimage must be a JSON object' };
97
+ }
98
+ const obj = value as Record<string, unknown>;
99
+
100
+ for (const member of Object.keys(obj)) {
101
+ if (!ALLOWED_MEMBERS.has(member)) {
102
+ return { ok: false, detail: `unknown member "${member}" (closed schema)` };
103
+ }
104
+ }
105
+ for (const member of REQUIRED_MEMBERS) {
106
+ if (!(member in obj)) {
107
+ return { ok: false, detail: `missing required member "${member}"` };
108
+ }
109
+ }
110
+ for (const member of STRING_MEMBERS) {
111
+ if (!(member in obj)) continue;
112
+ const v = obj[member];
113
+ if (typeof v !== 'string') {
114
+ return { ok: false, detail: `member "${member}" must be a string` };
115
+ }
116
+ if (!ASCII_ONLY.test(v)) {
117
+ return { ok: false, detail: `member "${member}" must contain only ASCII (0x00..0x7F)` };
118
+ }
119
+ }
120
+ const capabilities = obj.capabilities;
121
+ if (!Array.isArray(capabilities)) {
122
+ return { ok: false, detail: 'member "capabilities" must be an array of strings' };
123
+ }
124
+ for (const cap of capabilities) {
125
+ if (typeof cap !== 'string') {
126
+ return { ok: false, detail: 'every capability must be a string' };
127
+ }
128
+ if (!ASCII_ONLY.test(cap)) {
129
+ return { ok: false, detail: 'every capability must contain only ASCII (0x00..0x7F)' };
130
+ }
131
+ }
132
+ if (!AUDIENCE_PATTERN.test(obj.audience as string)) {
133
+ return {
134
+ ok: false,
135
+ detail:
136
+ 'audience must be a stable machine identifier: printable ASCII excluding space (0x21..0x7E), 1..256 characters',
137
+ };
138
+ }
139
+ if (!DECISION_AT_PATTERN.test(obj.decisionAt as string)) {
140
+ return {
141
+ ok: false,
142
+ detail: 'decisionAt must match YYYY-MM-DDTHH:MM:SS.mmmZ exactly (3-digit ms, UTC Z)',
143
+ };
144
+ }
145
+ return { ok: true };
146
+ }
147
+
148
+ function utf8(str: string): Uint8Array {
149
+ return new TextEncoder().encode(str);
150
+ }
151
+
152
+ /**
153
+ * ref = "birv1:" + sha256hex( utf8(DST) || 0x00 || utf8(canonicalize(preimage)) )
154
+ *
155
+ * Throws on an out-of-domain preimage: an emitter must never produce a ref
156
+ * whose preimage a verifier is required to reject.
157
+ */
158
+ export function computeInstanceRef(preimage: InstancePreimage): string {
159
+ const validation = validateInstancePreimage(preimage);
160
+ if (!validation.ok) {
161
+ throw new Error(`instance preimage out of domain: ${validation.detail}`);
162
+ }
163
+ const dst = utf8(INSTANCE_BINDING_DST);
164
+ const canonical = utf8(canonicalize(preimage));
165
+ const input = new Uint8Array(dst.length + 1 + canonical.length);
166
+ input.set(dst, 0);
167
+ input[dst.length] = 0x00;
168
+ input.set(canonical, dst.length + 1);
169
+ return INSTANCE_REF_PREFIX + bytesToHex(sha256(input));
170
+ }
171
+
172
+ /**
173
+ * The semantic instance-binding check. Assumes nothing about the signature —
174
+ * pair it with verifyReceipt(). Returns ok with present:false when the
175
+ * receipt carries no instance block (the block is optional).
176
+ */
177
+ export function verifyInstanceBinding(receipt: SignedReceipt): InstanceBindingResult {
178
+ const instance = receipt.payload.instance;
179
+ if (instance === undefined) {
180
+ return { ok: true, present: false, code: 'absent' };
181
+ }
182
+ if (receipt.payload.kind !== 'bolyra.commerce') {
183
+ return {
184
+ ok: false,
185
+ present: true,
186
+ code: 'wrong_kind',
187
+ detail: `instance binding v1 is scoped to bolyra.commerce receipts, got "${receipt.payload.kind}"`,
188
+ };
189
+ }
190
+ // Parsed JSON can carry any shape here regardless of the TS type; a signed
191
+ // receipt with e.g. "instance": null must fail deterministically, not throw.
192
+ if (typeof instance !== 'object' || instance === null || Array.isArray(instance)) {
193
+ return {
194
+ ok: false,
195
+ present: true,
196
+ code: 'malformed_ref',
197
+ detail: 'instance block must be a JSON object with ref and preimage members',
198
+ };
199
+ }
200
+ if (typeof instance.ref !== 'string' || !REF_PATTERN.test(instance.ref)) {
201
+ return {
202
+ ok: false,
203
+ present: true,
204
+ code: 'malformed_ref',
205
+ detail: 'ref must be "birv1:" followed by 64 lowercase hex characters',
206
+ };
207
+ }
208
+ const validation = validateInstancePreimage(instance.preimage);
209
+ if (!validation.ok) {
210
+ return { ok: false, present: true, code: 'out_of_domain', detail: validation.detail };
211
+ }
212
+ const recomputed = computeInstanceRef(instance.preimage);
213
+ if (recomputed !== instance.ref) {
214
+ return {
215
+ ok: false,
216
+ present: true,
217
+ code: 'ref_mismatch',
218
+ detail: 'recomputed instance ref does not match the carried ref',
219
+ };
220
+ }
221
+ return { ok: true, present: true, code: 'ok' };
222
+ }
package/src/types.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import type { ReceiptInstanceFields } from './instance';
2
+
1
3
  /**
2
4
  * Optional hash-chain fields linking a receipt to its predecessor in a log.
3
5
  * Additive and backward-compatible: chain-less receipts remain valid, and
@@ -60,6 +62,15 @@ export interface ReceiptPayload {
60
62
  /** Present only when kind === 'bolyra.commerce'. */
61
63
  commerce?: CommerceFields;
62
64
 
65
+ /**
66
+ * Optional instance binding (spec/receipt-instance-binding-v1.md).
67
+ * v1 scope: bolyra.commerce receipts only. Lives inside the signed payload
68
+ * so it cannot be rewritten without breaking the ES256K signature; its
69
+ * SEMANTIC validity (ref recomputes from preimage) is a separate claim
70
+ * checked by verifyInstanceBinding(), not by verifyReceipt().
71
+ */
72
+ instance?: ReceiptInstanceFields;
73
+
63
74
  /** Present only on hash-chained receipts (written via ReceiptChain). */
64
75
  chain?: ReceiptChainFields;
65
76
  }
package/src/verify-cli.ts CHANGED
@@ -103,6 +103,10 @@ function failCheck(msg: string): void {
103
103
 
104
104
  // 1. Schema validation
105
105
  function validateSchema(): boolean {
106
+ if (receipt === null || typeof receipt !== 'object') {
107
+ failCheck('Schema: receipt is not an object');
108
+ return false;
109
+ }
106
110
  const p = receipt.payload;
107
111
  const s = receipt.signature;
108
112
  const errors: string[] = [];
@@ -143,6 +147,8 @@ function validateSchema(): boolean {
143
147
  // proof
144
148
  if (!p.proof) {
145
149
  errors.push('payload.proof missing');
150
+ } else if (typeof p.proof !== 'object') {
151
+ errors.push('payload.proof not an object');
146
152
  } else {
147
153
  for (const k of ['bundleVersion', 'nonce', 'humanProofHash', 'agentProofHash', 'publicSignalsHash'] as const) {
148
154
  if (!(k in p.proof)) errors.push(`proof.${k} missing`);
@@ -171,9 +177,9 @@ function validateSchema(): boolean {
171
177
  // signature fields
172
178
  if (s.alg !== 'ES256K') errors.push('signature.alg !== "ES256K"');
173
179
  if (s.keyId !== p.keyId) errors.push('signature.keyId does not match payload.keyId');
174
- if (!/^0x[0-9a-fA-F]{40}$/.test(s.signer ?? '')) errors.push('signature.signer invalid format');
175
- if (!/^0x[0-9a-fA-F]{64}$/.test(s.payloadHash ?? '')) errors.push('signature.payloadHash invalid format');
176
- if (!/^0x[0-9a-fA-F]{130}$/.test(s.value ?? '')) errors.push('signature.value invalid format');
180
+ if (typeof s.signer !== 'string' || !/^0x[0-9a-fA-F]{40}$/.test(s.signer)) errors.push('signature.signer invalid format');
181
+ if (typeof s.payloadHash !== 'string' || !/^0x[0-9a-fA-F]{64}$/.test(s.payloadHash)) errors.push('signature.payloadHash invalid format');
182
+ if (typeof s.value !== 'string' || !/^0x[0-9a-fA-F]{130}$/.test(s.value)) errors.push('signature.value invalid format');
177
183
 
178
184
  if (errors.length) {
179
185
  failCheck(`Schema: ${errors.join('; ')}`);
@@ -189,7 +195,12 @@ function validateTimestamp(): void {
189
195
  const issuedAt = receipt.payload.issuedAt;
190
196
  const allowFutureSeconds = 300;
191
197
  const ageSec = nowSec - issuedAt;
192
- const isoStr = new Date(issuedAt * 1000).toISOString();
198
+ const date = new Date(issuedAt * 1000);
199
+ if (!Number.isFinite(date.getTime())) {
200
+ failCheck('Timestamp is outside the supported date range');
201
+ return;
202
+ }
203
+ const isoStr = date.toISOString();
193
204
 
194
205
  if (issuedAt > nowSec + allowFutureSeconds) {
195
206
  failCheck(`Timestamp: ${isoStr} is ${issuedAt - nowSec}s in the future (max skew: ${allowFutureSeconds}s)`);
@@ -204,7 +215,14 @@ function validateTimestamp(): void {
204
215
 
205
216
  // 3. Hash check
206
217
  function validateHash(): boolean {
207
- const computed = hashPayload(receipt.payload);
218
+ let computed: string;
219
+ try {
220
+ computed = hashPayload(receipt.payload);
221
+ } catch {
222
+ // The payload holds a value with no canonical form, so it has no hash.
223
+ failCheck('Payload cannot be canonicalized');
224
+ return false;
225
+ }
208
226
  if (computed !== receipt.signature.payloadHash) {
209
227
  failCheck(`Payload hash mismatch (expected ${truncate(receipt.signature.payloadHash)}, got ${truncate(computed)})`);
210
228
  return false;
@@ -216,6 +234,10 @@ function validateHash(): boolean {
216
234
  // 4. ID check
217
235
  function validateId(): void {
218
236
  const expected = '0x' + receipt.signature.payloadHash.slice(2, 18);
237
+ if (typeof receipt.id !== 'string') {
238
+ failCheck(`Receipt ID is not a string (expected ${expected})`);
239
+ return;
240
+ }
219
241
  if (receipt.id !== expected) {
220
242
  failCheck(`Receipt ID mismatch (expected ${expected}, got ${receipt.id})`);
221
243
  return;
@@ -235,12 +257,18 @@ function validateSignature(): void {
235
257
 
236
258
  // --- Run checks ---
237
259
 
238
- if (validateSchema()) {
239
- validateTimestamp();
240
- if (validateHash()) {
241
- validateId();
242
- validateSignature();
260
+ // A receipt is untrusted input. Whatever shape it has, the outcome is a list
261
+ // of checks and an exit code, never an uncaught error.
262
+ try {
263
+ if (validateSchema()) {
264
+ validateTimestamp();
265
+ if (validateHash()) {
266
+ validateId();
267
+ validateSignature();
268
+ }
243
269
  }
270
+ } catch {
271
+ failCheck('Receipt could not be checked');
244
272
  }
245
273
 
246
274
  // --- Output ---