@bolyra/receipts 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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,96 @@
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
+ /**
33
+ * Capability tokens the decision was evaluated over, order as presented
34
+ * (order is significant): the granted set on allow; on deny, the tokens
35
+ * the request was evaluated against.
36
+ */
37
+ capabilities: string[];
38
+ /** Decimal string, exactly as decided. */
39
+ amountUsd: string;
40
+ /** RFC 3339 UTC with exactly 3-digit milliseconds: "2026-08-24T10:00:00.123Z". */
41
+ decisionAt: string;
42
+ /** In-protocol pre-decision challenge nonce, when the transport has one. */
43
+ requestNonce?: string;
44
+ /** External instance reference (e.g. an argentum action_ref), verbatim. */
45
+ actionRef?: string;
46
+ }
47
+ export interface ReceiptInstanceFields {
48
+ /** INSTANCE_REF_PREFIX + lowercase sha256 hex over the domain-tagged canonical preimage. */
49
+ ref: string;
50
+ preimage: InstancePreimage;
51
+ }
52
+ export type InstanceBindingCode = 'absent' | 'ok' | 'malformed_receipt' | 'wrong_kind' | 'malformed_ref' | 'out_of_domain' | 'ref_mismatch';
53
+ export type InstanceBindingResult = {
54
+ ok: true;
55
+ present: false;
56
+ code: 'absent';
57
+ } | {
58
+ ok: true;
59
+ present: true;
60
+ code: 'ok';
61
+ } | {
62
+ ok: false;
63
+ present: false;
64
+ code: 'malformed_receipt';
65
+ detail: string;
66
+ } | {
67
+ ok: false;
68
+ present: true;
69
+ code: Exclude<InstanceBindingCode, 'absent' | 'ok' | 'malformed_receipt'>;
70
+ detail: string;
71
+ };
72
+ export type PreimageValidation = {
73
+ ok: true;
74
+ } | {
75
+ ok: false;
76
+ detail: string;
77
+ };
78
+ /**
79
+ * Enforces the closed canonicalization domain of spec §3.1. Anything outside
80
+ * it is rejected outright — no best-effort canonicalization, one pinned
81
+ * behavior.
82
+ */
83
+ export declare function validateInstancePreimage(value: unknown): PreimageValidation;
84
+ /**
85
+ * ref = "birv1:" + sha256hex( utf8(DST) || 0x00 || utf8(canonicalize(preimage)) )
86
+ *
87
+ * Throws on an out-of-domain preimage: an emitter must never produce a ref
88
+ * whose preimage a verifier is required to reject.
89
+ */
90
+ export declare function computeInstanceRef(preimage: InstancePreimage): string;
91
+ /**
92
+ * The semantic instance-binding check. Assumes nothing about the signature —
93
+ * pair it with verifyReceipt(). Returns ok with present:false when the
94
+ * receipt carries no instance block (the block is optional).
95
+ */
96
+ export declare function verifyInstanceBinding(receipt: SignedReceipt): InstanceBindingResult;
@@ -0,0 +1,184 @@
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
+ // Parsed JSON can hand this function anything — a log line that is not a
130
+ // receipt at all must fail deterministically, never throw.
131
+ const payload = receipt?.payload;
132
+ if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) {
133
+ return {
134
+ ok: false,
135
+ present: false,
136
+ code: 'malformed_receipt',
137
+ detail: 'input has no receipt payload object',
138
+ };
139
+ }
140
+ const instance = receipt.payload.instance;
141
+ if (instance === undefined) {
142
+ return { ok: true, present: false, code: 'absent' };
143
+ }
144
+ if (receipt.payload.kind !== 'bolyra.commerce') {
145
+ return {
146
+ ok: false,
147
+ present: true,
148
+ code: 'wrong_kind',
149
+ detail: `instance binding v1 is scoped to bolyra.commerce receipts, got "${receipt.payload.kind}"`,
150
+ };
151
+ }
152
+ // Parsed JSON can carry any shape here regardless of the TS type; a signed
153
+ // receipt with e.g. "instance": null must fail deterministically, not throw.
154
+ if (typeof instance !== 'object' || instance === null || Array.isArray(instance)) {
155
+ return {
156
+ ok: false,
157
+ present: true,
158
+ code: 'malformed_ref',
159
+ detail: 'instance block must be a JSON object with ref and preimage members',
160
+ };
161
+ }
162
+ if (typeof instance.ref !== 'string' || !REF_PATTERN.test(instance.ref)) {
163
+ return {
164
+ ok: false,
165
+ present: true,
166
+ code: 'malformed_ref',
167
+ detail: 'ref must be "birv1:" followed by 64 lowercase hex characters',
168
+ };
169
+ }
170
+ const validation = validateInstancePreimage(instance.preimage);
171
+ if (!validation.ok) {
172
+ return { ok: false, present: true, code: 'out_of_domain', detail: validation.detail };
173
+ }
174
+ const recomputed = computeInstanceRef(instance.preimage);
175
+ if (recomputed !== instance.ref) {
176
+ return {
177
+ ok: false,
178
+ present: true,
179
+ code: 'ref_mismatch',
180
+ detail: 'recomputed instance ref does not match the carried ref',
181
+ };
182
+ }
183
+ return { ok: true, present: true, code: 'ok' };
184
+ }
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
  }
@@ -37,6 +37,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
37
37
  const fs = __importStar(require("fs"));
38
38
  const process = __importStar(require("process"));
39
39
  const sign_1 = require("./sign");
40
+ const instance_1 = require("./instance");
40
41
  // --- Helpers ---
41
42
  function usage() {
42
43
  return `Usage: bolyra-receipt-verify <receipt.json> [options]
@@ -273,12 +274,27 @@ function validateSignature() {
273
274
  }
274
275
  pass(`Signature valid (signer: ${truncate(receipt.signature.signer)})`);
275
276
  }
277
+ // 6. Instance binding (spec/receipt-instance-binding-v1.md §4): signature
278
+ // validity and instance-binding validity are different claims — a
279
+ // signer-issued receipt with a forged instance.ref passes verifyReceipt()
280
+ // in check 5 and MUST still fail here.
281
+ function validateInstance() {
282
+ const result = (0, instance_1.verifyInstanceBinding)(receipt);
283
+ if (!result.ok) {
284
+ failCheck(`Instance binding invalid [${result.code}] ${result.detail}`);
285
+ return;
286
+ }
287
+ if (result.present) {
288
+ pass(`Instance binding valid (${receipt.payload.instance.ref})`);
289
+ }
290
+ }
276
291
  // --- Run checks ---
277
292
  if (validateSchema()) {
278
293
  validateTimestamp();
279
294
  if (validateHash()) {
280
295
  validateId();
281
296
  validateSignature();
297
+ validateInstance();
282
298
  }
283
299
  }
284
300
  // --- Output ---
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bolyra/receipts",
3
- "version": "0.9.0",
3
+ "version": "0.11.0",
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": {
@@ -18,11 +18,12 @@
18
18
  "@noble/hashes": "^1.7.0"
19
19
  },
20
20
  "devDependencies": {
21
- "typescript": "^5.5.0",
21
+ "@types/jest": "^30.0.0",
22
22
  "@types/node": "^25.9.1",
23
23
  "jest": "^30.4.2",
24
24
  "ts-jest": "^29.2.0",
25
- "@types/jest": "^30.0.0"
25
+ "tsx": "^4.20.0",
26
+ "typescript": "^5.5.0"
26
27
  },
27
28
  "files": [
28
29
  "dist/",
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,244 @@
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
+ /**
52
+ * Capability tokens the decision was evaluated over, order as presented
53
+ * (order is significant): the granted set on allow; on deny, the tokens
54
+ * the request was evaluated against.
55
+ */
56
+ capabilities: string[];
57
+ /** Decimal string, exactly as decided. */
58
+ amountUsd: string;
59
+ /** RFC 3339 UTC with exactly 3-digit milliseconds: "2026-08-24T10:00:00.123Z". */
60
+ decisionAt: string;
61
+ /** In-protocol pre-decision challenge nonce, when the transport has one. */
62
+ requestNonce?: string;
63
+ /** External instance reference (e.g. an argentum action_ref), verbatim. */
64
+ actionRef?: string;
65
+ }
66
+
67
+ export interface ReceiptInstanceFields {
68
+ /** INSTANCE_REF_PREFIX + lowercase sha256 hex over the domain-tagged canonical preimage. */
69
+ ref: string;
70
+ preimage: InstancePreimage;
71
+ }
72
+
73
+ export type InstanceBindingCode =
74
+ | 'absent'
75
+ | 'ok'
76
+ | 'malformed_receipt'
77
+ | 'wrong_kind'
78
+ | 'malformed_ref'
79
+ | 'out_of_domain'
80
+ | 'ref_mismatch';
81
+
82
+ export type InstanceBindingResult =
83
+ | { ok: true; present: false; code: 'absent' }
84
+ | { ok: true; present: true; code: 'ok' }
85
+ | { ok: false; present: false; code: 'malformed_receipt'; detail: string }
86
+ | {
87
+ ok: false;
88
+ present: true;
89
+ code: Exclude<InstanceBindingCode, 'absent' | 'ok' | 'malformed_receipt'>;
90
+ detail: string;
91
+ };
92
+
93
+ export type PreimageValidation = { ok: true } | { ok: false; detail: string };
94
+
95
+ const REQUIRED_MEMBERS = ['audience', 'program', 'capabilities', 'amountUsd', 'decisionAt'] as const;
96
+ const OPTIONAL_MEMBERS = ['requestNonce', 'actionRef'] as const;
97
+ const ALLOWED_MEMBERS: ReadonlySet<string> = new Set([...REQUIRED_MEMBERS, ...OPTIONAL_MEMBERS]);
98
+ const STRING_MEMBERS = ['audience', 'program', 'amountUsd', 'decisionAt', ...OPTIONAL_MEMBERS] as const;
99
+
100
+ /**
101
+ * Enforces the closed canonicalization domain of spec §3.1. Anything outside
102
+ * it is rejected outright — no best-effort canonicalization, one pinned
103
+ * behavior.
104
+ */
105
+ export function validateInstancePreimage(value: unknown): PreimageValidation {
106
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
107
+ return { ok: false, detail: 'preimage must be a JSON object' };
108
+ }
109
+ const obj = value as Record<string, unknown>;
110
+
111
+ for (const member of Object.keys(obj)) {
112
+ if (!ALLOWED_MEMBERS.has(member)) {
113
+ return { ok: false, detail: `unknown member "${member}" (closed schema)` };
114
+ }
115
+ }
116
+ for (const member of REQUIRED_MEMBERS) {
117
+ if (!(member in obj)) {
118
+ return { ok: false, detail: `missing required member "${member}"` };
119
+ }
120
+ }
121
+ for (const member of STRING_MEMBERS) {
122
+ if (!(member in obj)) continue;
123
+ const v = obj[member];
124
+ if (typeof v !== 'string') {
125
+ return { ok: false, detail: `member "${member}" must be a string` };
126
+ }
127
+ if (!ASCII_ONLY.test(v)) {
128
+ return { ok: false, detail: `member "${member}" must contain only ASCII (0x00..0x7F)` };
129
+ }
130
+ }
131
+ const capabilities = obj.capabilities;
132
+ if (!Array.isArray(capabilities)) {
133
+ return { ok: false, detail: 'member "capabilities" must be an array of strings' };
134
+ }
135
+ for (const cap of capabilities) {
136
+ if (typeof cap !== 'string') {
137
+ return { ok: false, detail: 'every capability must be a string' };
138
+ }
139
+ if (!ASCII_ONLY.test(cap)) {
140
+ return { ok: false, detail: 'every capability must contain only ASCII (0x00..0x7F)' };
141
+ }
142
+ }
143
+ if (!AUDIENCE_PATTERN.test(obj.audience as string)) {
144
+ return {
145
+ ok: false,
146
+ detail:
147
+ 'audience must be a stable machine identifier: printable ASCII excluding space (0x21..0x7E), 1..256 characters',
148
+ };
149
+ }
150
+ if (!DECISION_AT_PATTERN.test(obj.decisionAt as string)) {
151
+ return {
152
+ ok: false,
153
+ detail: 'decisionAt must match YYYY-MM-DDTHH:MM:SS.mmmZ exactly (3-digit ms, UTC Z)',
154
+ };
155
+ }
156
+ return { ok: true };
157
+ }
158
+
159
+ function utf8(str: string): Uint8Array {
160
+ return new TextEncoder().encode(str);
161
+ }
162
+
163
+ /**
164
+ * ref = "birv1:" + sha256hex( utf8(DST) || 0x00 || utf8(canonicalize(preimage)) )
165
+ *
166
+ * Throws on an out-of-domain preimage: an emitter must never produce a ref
167
+ * whose preimage a verifier is required to reject.
168
+ */
169
+ export function computeInstanceRef(preimage: InstancePreimage): string {
170
+ const validation = validateInstancePreimage(preimage);
171
+ if (!validation.ok) {
172
+ throw new Error(`instance preimage out of domain: ${validation.detail}`);
173
+ }
174
+ const dst = utf8(INSTANCE_BINDING_DST);
175
+ const canonical = utf8(canonicalize(preimage));
176
+ const input = new Uint8Array(dst.length + 1 + canonical.length);
177
+ input.set(dst, 0);
178
+ input[dst.length] = 0x00;
179
+ input.set(canonical, dst.length + 1);
180
+ return INSTANCE_REF_PREFIX + bytesToHex(sha256(input));
181
+ }
182
+
183
+ /**
184
+ * The semantic instance-binding check. Assumes nothing about the signature —
185
+ * pair it with verifyReceipt(). Returns ok with present:false when the
186
+ * receipt carries no instance block (the block is optional).
187
+ */
188
+ export function verifyInstanceBinding(receipt: SignedReceipt): InstanceBindingResult {
189
+ // Parsed JSON can hand this function anything — a log line that is not a
190
+ // receipt at all must fail deterministically, never throw.
191
+ const payload = (receipt as { payload?: unknown } | null | undefined)?.payload;
192
+ if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) {
193
+ return {
194
+ ok: false,
195
+ present: false,
196
+ code: 'malformed_receipt',
197
+ detail: 'input has no receipt payload object',
198
+ };
199
+ }
200
+ const instance = receipt.payload.instance;
201
+ if (instance === undefined) {
202
+ return { ok: true, present: false, code: 'absent' };
203
+ }
204
+ if (receipt.payload.kind !== 'bolyra.commerce') {
205
+ return {
206
+ ok: false,
207
+ present: true,
208
+ code: 'wrong_kind',
209
+ detail: `instance binding v1 is scoped to bolyra.commerce receipts, got "${receipt.payload.kind}"`,
210
+ };
211
+ }
212
+ // Parsed JSON can carry any shape here regardless of the TS type; a signed
213
+ // receipt with e.g. "instance": null must fail deterministically, not throw.
214
+ if (typeof instance !== 'object' || instance === null || Array.isArray(instance)) {
215
+ return {
216
+ ok: false,
217
+ present: true,
218
+ code: 'malformed_ref',
219
+ detail: 'instance block must be a JSON object with ref and preimage members',
220
+ };
221
+ }
222
+ if (typeof instance.ref !== 'string' || !REF_PATTERN.test(instance.ref)) {
223
+ return {
224
+ ok: false,
225
+ present: true,
226
+ code: 'malformed_ref',
227
+ detail: 'ref must be "birv1:" followed by 64 lowercase hex characters',
228
+ };
229
+ }
230
+ const validation = validateInstancePreimage(instance.preimage);
231
+ if (!validation.ok) {
232
+ return { ok: false, present: true, code: 'out_of_domain', detail: validation.detail };
233
+ }
234
+ const recomputed = computeInstanceRef(instance.preimage);
235
+ if (recomputed !== instance.ref) {
236
+ return {
237
+ ok: false,
238
+ present: true,
239
+ code: 'ref_mismatch',
240
+ detail: 'recomputed instance ref does not match the carried ref',
241
+ };
242
+ }
243
+ return { ok: true, present: true, code: 'ok' };
244
+ }
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
@@ -3,6 +3,7 @@
3
3
  import * as fs from 'fs';
4
4
  import * as process from 'process';
5
5
  import { verifyReceipt, hashPayload } from './sign';
6
+ import { verifyInstanceBinding } from './instance';
6
7
  import type { SignedReceipt } from './types';
7
8
 
8
9
  // --- Helpers ---
@@ -233,6 +234,21 @@ function validateSignature(): void {
233
234
  pass(`Signature valid (signer: ${truncate(receipt.signature.signer)})`);
234
235
  }
235
236
 
237
+ // 6. Instance binding (spec/receipt-instance-binding-v1.md §4): signature
238
+ // validity and instance-binding validity are different claims — a
239
+ // signer-issued receipt with a forged instance.ref passes verifyReceipt()
240
+ // in check 5 and MUST still fail here.
241
+ function validateInstance(): void {
242
+ const result = verifyInstanceBinding(receipt);
243
+ if (!result.ok) {
244
+ failCheck(`Instance binding invalid [${result.code}] ${result.detail}`);
245
+ return;
246
+ }
247
+ if (result.present) {
248
+ pass(`Instance binding valid (${receipt.payload.instance!.ref})`);
249
+ }
250
+ }
251
+
236
252
  // --- Run checks ---
237
253
 
238
254
  if (validateSchema()) {
@@ -240,6 +256,7 @@ if (validateSchema()) {
240
256
  if (validateHash()) {
241
257
  validateId();
242
258
  validateSignature();
259
+ validateInstance();
243
260
  }
244
261
  }
245
262