@bolyra/receipts 0.6.0 → 0.7.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/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  export { canonicalize } from './canonical';
2
- export { createAuthReceipt } from './receipt';
2
+ export { createAuthReceipt, createCommerceReceipt } from './receipt';
3
3
  export { signReceipt, verifyReceipt, hashPayload } from './sign';
4
- export type { ReceiptPayload, SignedReceipt, ReceiptSignerConfig, AuthReceiptInput, } from './types';
4
+ export type { ReceiptPayload, SignedReceipt, ReceiptSignerConfig, AuthReceiptInput, CommerceReceiptInput, CommerceFields, } from './types';
package/dist/index.js CHANGED
@@ -1,10 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.hashPayload = exports.verifyReceipt = exports.signReceipt = exports.createAuthReceipt = exports.canonicalize = void 0;
3
+ 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");
7
7
  Object.defineProperty(exports, "createAuthReceipt", { enumerable: true, get: function () { return receipt_1.createAuthReceipt; } });
8
+ Object.defineProperty(exports, "createCommerceReceipt", { enumerable: true, get: function () { return receipt_1.createCommerceReceipt; } });
8
9
  var sign_1 = require("./sign");
9
10
  Object.defineProperty(exports, "signReceipt", { enumerable: true, get: function () { return sign_1.signReceipt; } });
10
11
  Object.defineProperty(exports, "verifyReceipt", { enumerable: true, get: function () { return sign_1.verifyReceipt; } });
package/dist/receipt.d.ts CHANGED
@@ -1,5 +1,10 @@
1
- import type { AuthReceiptInput, ReceiptPayload } from './types';
1
+ import type { AuthReceiptInput, CommerceReceiptInput, ReceiptPayload } from './types';
2
2
  export declare function createAuthReceipt(input: AuthReceiptInput, config: {
3
3
  issuer: string;
4
4
  keyId: string;
5
+ issuedAt?: number;
6
+ }): ReceiptPayload;
7
+ export declare function createCommerceReceipt(input: CommerceReceiptInput, config: {
8
+ issuer: string;
9
+ keyId: string;
5
10
  }): ReceiptPayload;
package/dist/receipt.js CHANGED
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createAuthReceipt = createAuthReceipt;
4
+ exports.createCommerceReceipt = createCommerceReceipt;
4
5
  const sha256_1 = require("@noble/hashes/sha256");
5
6
  const utils_1 = require("@noble/hashes/utils");
6
7
  const canonical_1 = require("./canonical");
@@ -18,7 +19,7 @@ function createAuthReceipt(input, config) {
18
19
  return {
19
20
  v: 1,
20
21
  kind: 'bolyra.auth',
21
- issuedAt: Math.floor(Date.now() / 1000),
22
+ issuedAt: config.issuedAt ?? Math.floor(Date.now() / 1000),
22
23
  issuer: config.issuer,
23
24
  keyId: config.keyId,
24
25
  subject: {
@@ -44,3 +45,11 @@ function createAuthReceipt(input, config) {
44
45
  },
45
46
  };
46
47
  }
48
+ function createCommerceReceipt(input, config) {
49
+ const base = createAuthReceipt(input, config);
50
+ return {
51
+ ...base,
52
+ kind: 'bolyra.commerce',
53
+ commerce: input.commerce,
54
+ };
55
+ }
package/dist/types.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export interface ReceiptPayload {
2
2
  v: 1;
3
- kind: 'bolyra.auth';
3
+ kind: 'bolyra.auth' | 'bolyra.commerce';
4
4
  /** Unix seconds when the decision was made. */
5
5
  issuedAt: number;
6
6
  /** Server identifier. */
@@ -36,6 +36,8 @@ export interface ReceiptPayload {
36
36
  /** SHA-256 of canonical JSON of delegationChain (if v=2). */
37
37
  delegationChainHash?: string;
38
38
  };
39
+ /** Present only when kind === 'bolyra.commerce'. */
40
+ commerce?: CommerceFields;
39
41
  }
40
42
  export interface SignedReceipt {
41
43
  /** First 16 hex chars of payloadHash. */
@@ -58,6 +60,13 @@ export interface ReceiptSignerConfig {
58
60
  /** secp256k1 private key, 32 bytes, hex-encoded, 0x-prefixed. */
59
61
  privateKey: string;
60
62
  }
63
+ export interface CommerceFields {
64
+ rail: string;
65
+ amount: number;
66
+ currency: string;
67
+ merchant: string;
68
+ intentHash: string;
69
+ }
61
70
  export interface AuthReceiptInput {
62
71
  /** From BolyraAuthContext or equivalent. */
63
72
  rootDid: string;
@@ -82,3 +91,6 @@ export interface AuthReceiptInput {
82
91
  nonce: string;
83
92
  delegationChain?: unknown[];
84
93
  }
94
+ export interface CommerceReceiptInput extends AuthReceiptInput {
95
+ commerce: CommerceFields;
96
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,326 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k;
5
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k]; } };
8
+ }
9
+ Object.defineProperty(o, k2, desc);
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ o[k2] = m[k];
13
+ }));
14
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
16
+ }) : function(o, v) {
17
+ o["default"] = v;
18
+ });
19
+ var __importStar = (this && this.__importStar) || (function () {
20
+ var ownKeys = function(o) {
21
+ ownKeys = Object.getOwnPropertyNames || function (o) {
22
+ var ar = [];
23
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
24
+ return ar;
25
+ };
26
+ return ownKeys(o);
27
+ };
28
+ return function (mod) {
29
+ if (mod && mod.__esModule) return mod;
30
+ var result = {};
31
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
32
+ __setModuleDefault(result, mod);
33
+ return result;
34
+ };
35
+ })();
36
+ Object.defineProperty(exports, "__esModule", { value: true });
37
+ const fs = __importStar(require("fs"));
38
+ const process = __importStar(require("process"));
39
+ const sign_1 = require("./sign");
40
+ // --- Helpers ---
41
+ function usage() {
42
+ return `Usage: bolyra-receipt-verify <receipt.json> [options]
43
+
44
+ Options:
45
+ --stdin Read receipt JSON from stdin instead of a file
46
+ --signer <address> Expected signer address (optional)
47
+ --max-age <seconds> Maximum receipt age in seconds (default: 86400)
48
+ --help Show this help`;
49
+ }
50
+ function fail(msg) {
51
+ process.stderr.write(msg + '\n');
52
+ process.exit(2);
53
+ }
54
+ function truncate(hex) {
55
+ if (hex.length <= 14)
56
+ return hex;
57
+ return hex.slice(0, 8) + '...' + hex.slice(-4);
58
+ }
59
+ // --- Arg parsing ---
60
+ const args = process.argv.slice(2);
61
+ if (args.includes('--help') || args.includes('-h')) {
62
+ console.log(usage());
63
+ process.exit(0);
64
+ }
65
+ let filePath;
66
+ let expectedSigner;
67
+ let maxAgeSeconds = 86400;
68
+ let useStdin = false;
69
+ for (let i = 0; i < args.length; i++) {
70
+ const arg = args[i];
71
+ if (arg === '--stdin') {
72
+ useStdin = true;
73
+ }
74
+ else if (arg === '--signer') {
75
+ expectedSigner = args[++i];
76
+ if (!expectedSigner)
77
+ fail('--signer requires an address argument');
78
+ }
79
+ else if (arg === '--max-age') {
80
+ const val = args[++i];
81
+ if (!val)
82
+ fail('--max-age requires a number argument');
83
+ maxAgeSeconds = parseInt(val, 10);
84
+ if (Number.isNaN(maxAgeSeconds) || maxAgeSeconds < 0) {
85
+ fail('--max-age must be a non-negative integer');
86
+ }
87
+ }
88
+ else if (arg.startsWith('-')) {
89
+ fail(`Unknown option: ${arg}\n\n${usage()}`);
90
+ }
91
+ else {
92
+ filePath = arg;
93
+ }
94
+ }
95
+ if (!filePath && !useStdin) {
96
+ fail(`No input specified. Provide a file path or use --stdin.\n\n${usage()}`);
97
+ }
98
+ // --- Read input ---
99
+ let rawJson;
100
+ try {
101
+ if (useStdin) {
102
+ rawJson = fs.readFileSync(0, 'utf-8');
103
+ }
104
+ else {
105
+ rawJson = fs.readFileSync(filePath, 'utf-8');
106
+ }
107
+ }
108
+ catch (err) {
109
+ const msg = err instanceof Error ? err.message : String(err);
110
+ fail(`Cannot read input: ${msg}`);
111
+ }
112
+ let receipt;
113
+ try {
114
+ receipt = JSON.parse(rawJson);
115
+ }
116
+ catch {
117
+ fail('Invalid JSON');
118
+ }
119
+ // --- Checks ---
120
+ const checks = [];
121
+ let failed = false;
122
+ function pass(msg) {
123
+ checks.push(`\u2713 ${msg}`);
124
+ }
125
+ function failCheck(msg) {
126
+ checks.push(`\u2717 ${msg}`);
127
+ failed = true;
128
+ }
129
+ // 1. Schema validation
130
+ function validateSchema() {
131
+ if (receipt === null || typeof receipt !== 'object') {
132
+ failCheck('Schema: receipt is not an object');
133
+ return false;
134
+ }
135
+ const p = receipt.payload;
136
+ const s = receipt.signature;
137
+ const errors = [];
138
+ if (!p) {
139
+ errors.push('missing payload');
140
+ }
141
+ if (!s) {
142
+ errors.push('missing signature');
143
+ }
144
+ if (errors.length) {
145
+ failCheck(`Schema: ${errors.join(', ')}`);
146
+ return false;
147
+ }
148
+ if (p.v !== 1)
149
+ errors.push('payload.v !== 1');
150
+ if (p.kind !== 'bolyra.auth' && p.kind !== 'bolyra.commerce') {
151
+ errors.push('payload.kind must be "bolyra.auth" or "bolyra.commerce"');
152
+ }
153
+ if (typeof p.issuedAt !== 'number')
154
+ errors.push('payload.issuedAt not a number');
155
+ if (typeof p.issuer !== 'string' || !p.issuer)
156
+ errors.push('payload.issuer missing');
157
+ if (typeof p.keyId !== 'string' || !p.keyId)
158
+ errors.push('payload.keyId missing');
159
+ // subject
160
+ if (!p.subject) {
161
+ errors.push('payload.subject missing');
162
+ }
163
+ else {
164
+ for (const k of ['rootDid', 'actingDid', 'credentialCommitment', 'effectiveCommitment']) {
165
+ if (typeof p.subject[k] !== 'string' || !p.subject[k]) {
166
+ errors.push(`payload.subject.${k} missing or not a string`);
167
+ }
168
+ }
169
+ }
170
+ // decision
171
+ if (!p.decision) {
172
+ errors.push('payload.decision missing');
173
+ }
174
+ else {
175
+ if (typeof p.decision.allowed !== 'boolean')
176
+ errors.push('decision.allowed not boolean');
177
+ if (typeof p.decision.score !== 'number')
178
+ errors.push('decision.score not a number');
179
+ if (typeof p.decision.permissionBitmask !== 'string' || !p.decision.permissionBitmask)
180
+ errors.push('decision.permissionBitmask missing or not a string');
181
+ if (typeof p.decision.chainDepth !== 'number')
182
+ errors.push('decision.chainDepth not a number');
183
+ }
184
+ // proof
185
+ if (!p.proof) {
186
+ errors.push('payload.proof missing');
187
+ }
188
+ else if (typeof p.proof !== 'object') {
189
+ errors.push('payload.proof not an object');
190
+ }
191
+ else {
192
+ for (const k of ['bundleVersion', 'nonce', 'humanProofHash', 'agentProofHash', 'publicSignalsHash']) {
193
+ if (!(k in p.proof))
194
+ errors.push(`proof.${k} missing`);
195
+ }
196
+ }
197
+ // commerce fields: required for bolyra.commerce, forbidden for bolyra.auth
198
+ if (p.kind === 'bolyra.auth' && p.commerce) {
199
+ errors.push('auth receipt must not contain commerce fields');
200
+ }
201
+ if (p.kind === 'bolyra.commerce') {
202
+ const c = p.commerce;
203
+ if (!c) {
204
+ errors.push('commerce fields missing for bolyra.commerce receipt');
205
+ }
206
+ else {
207
+ if (typeof c.rail !== 'string' || !c.rail)
208
+ errors.push('commerce.rail missing or not a string');
209
+ if (typeof c.amount !== 'number')
210
+ errors.push('commerce.amount not a number');
211
+ if (typeof c.currency !== 'string' || !c.currency)
212
+ errors.push('commerce.currency missing or not a string');
213
+ if (typeof c.merchant !== 'string')
214
+ errors.push('commerce.merchant not a string');
215
+ if (typeof c.intentHash !== 'string' || !/^[0-9a-fA-F]{64}$/.test(c.intentHash)) {
216
+ errors.push('commerce.intentHash must be a 64-char hex string');
217
+ }
218
+ }
219
+ }
220
+ // signature fields
221
+ if (s.alg !== 'ES256K')
222
+ errors.push('signature.alg !== "ES256K"');
223
+ if (s.keyId !== p.keyId)
224
+ errors.push('signature.keyId does not match payload.keyId');
225
+ if (typeof s.signer !== 'string' || !/^0x[0-9a-fA-F]{40}$/.test(s.signer))
226
+ errors.push('signature.signer invalid format');
227
+ if (typeof s.payloadHash !== 'string' || !/^0x[0-9a-fA-F]{64}$/.test(s.payloadHash))
228
+ errors.push('signature.payloadHash invalid format');
229
+ if (typeof s.value !== 'string' || !/^0x[0-9a-fA-F]{130}$/.test(s.value))
230
+ errors.push('signature.value invalid format');
231
+ if (errors.length) {
232
+ failCheck(`Schema: ${errors.join('; ')}`);
233
+ return false;
234
+ }
235
+ pass('Schema valid');
236
+ return true;
237
+ }
238
+ // 2. Timestamp check
239
+ function validateTimestamp() {
240
+ const nowSec = Math.floor(Date.now() / 1000);
241
+ const issuedAt = receipt.payload.issuedAt;
242
+ const allowFutureSeconds = 300;
243
+ const ageSec = nowSec - issuedAt;
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();
250
+ if (issuedAt > nowSec + allowFutureSeconds) {
251
+ failCheck(`Timestamp: ${isoStr} is ${issuedAt - nowSec}s in the future (max skew: ${allowFutureSeconds}s)`);
252
+ return;
253
+ }
254
+ if (ageSec > maxAgeSeconds) {
255
+ failCheck(`Timestamp: ${isoStr} (${ageSec}s ago, max-age: ${maxAgeSeconds}s)`);
256
+ return;
257
+ }
258
+ pass(`Timestamp: ${isoStr} (${ageSec}s ago)`);
259
+ }
260
+ // 3. Hash check
261
+ function validateHash() {
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
+ }
271
+ if (computed !== receipt.signature.payloadHash) {
272
+ failCheck(`Payload hash mismatch (expected ${truncate(receipt.signature.payloadHash)}, got ${truncate(computed)})`);
273
+ return false;
274
+ }
275
+ pass('Payload hash matches');
276
+ return true;
277
+ }
278
+ // 4. ID check
279
+ function validateId() {
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
+ }
285
+ if (receipt.id !== expected) {
286
+ failCheck(`Receipt ID mismatch (expected ${expected}, got ${receipt.id})`);
287
+ return;
288
+ }
289
+ pass('Receipt ID matches');
290
+ }
291
+ // 5. Signature check
292
+ function validateSignature() {
293
+ const ok = (0, sign_1.verifyReceipt)(receipt, expectedSigner);
294
+ if (!ok) {
295
+ failCheck(`Signature invalid${expectedSigner ? ` (expected signer: ${truncate(expectedSigner)})` : ''}`);
296
+ return;
297
+ }
298
+ pass(`Signature valid (signer: ${truncate(receipt.signature.signer)})`);
299
+ }
300
+ // --- Run checks ---
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
+ }
310
+ }
311
+ }
312
+ catch {
313
+ failCheck('Receipt could not be checked');
314
+ }
315
+ // --- Output ---
316
+ for (const line of checks) {
317
+ console.log(line);
318
+ }
319
+ if (failed) {
320
+ console.log('FAIL \u2014 receipt is invalid');
321
+ process.exit(1);
322
+ }
323
+ else {
324
+ console.log('PASS \u2014 receipt is valid');
325
+ process.exit(0);
326
+ }
package/package.json CHANGED
@@ -1,11 +1,15 @@
1
1
  {
2
2
  "name": "@bolyra/receipts",
3
- "version": "0.6.0",
3
+ "version": "0.7.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",
7
+ "bin": {
8
+ "bolyra-receipt-verify": "dist/verify-cli.js"
9
+ },
7
10
  "scripts": {
8
11
  "build": "tsc",
12
+ "prepare": "tsc",
9
13
  "test": "jest --passWithNoTests",
10
14
  "typecheck": "tsc --noEmit"
11
15
  },
@@ -18,6 +22,7 @@
18
22
  "@types/node": "^25.9.1",
19
23
  "jest": "^30.4.2",
20
24
  "ts-jest": "^29.2.0",
25
+ "tsx": "^4.20.0",
21
26
  "@types/jest": "^30.0.0"
22
27
  },
23
28
  "files": [
@@ -31,7 +36,8 @@
31
36
  "url": "https://github.com/bolyra/bolyra"
32
37
  },
33
38
  "publishConfig": {
34
- "access": "public"
39
+ "access": "public",
40
+ "tag": "release-0.7"
35
41
  },
36
42
  "keywords": [
37
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/index.ts CHANGED
@@ -1,9 +1,11 @@
1
1
  export { canonicalize } from './canonical';
2
- export { createAuthReceipt } from './receipt';
2
+ export { createAuthReceipt, createCommerceReceipt } from './receipt';
3
3
  export { signReceipt, verifyReceipt, hashPayload } from './sign';
4
4
  export type {
5
5
  ReceiptPayload,
6
6
  SignedReceipt,
7
7
  ReceiptSignerConfig,
8
8
  AuthReceiptInput,
9
+ CommerceReceiptInput,
10
+ CommerceFields,
9
11
  } from './types';
package/src/receipt.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { sha256 } from '@noble/hashes/sha256';
2
2
  import { bytesToHex } from '@noble/hashes/utils';
3
3
  import { canonicalize } from './canonical';
4
- import type { AuthReceiptInput, ReceiptPayload } from './types';
4
+ import type { AuthReceiptInput, CommerceReceiptInput, ReceiptPayload } from './types';
5
5
 
6
6
  function sha256Hex(data: string): string {
7
7
  const encoder = new TextEncoder();
@@ -10,7 +10,7 @@ function sha256Hex(data: string): string {
10
10
 
11
11
  export function createAuthReceipt(
12
12
  input: AuthReceiptInput,
13
- config: { issuer: string; keyId: string },
13
+ config: { issuer: string; keyId: string; issuedAt?: number },
14
14
  ): ReceiptPayload {
15
15
  const humanProofHash = sha256Hex(canonicalize(input.humanProof.proof));
16
16
  const agentProofHash = sha256Hex(canonicalize(input.agentProof.proof));
@@ -24,7 +24,7 @@ export function createAuthReceipt(
24
24
  return {
25
25
  v: 1,
26
26
  kind: 'bolyra.auth',
27
- issuedAt: Math.floor(Date.now() / 1000),
27
+ issuedAt: config.issuedAt ?? Math.floor(Date.now() / 1000),
28
28
  issuer: config.issuer,
29
29
  keyId: config.keyId,
30
30
  subject: {
@@ -50,3 +50,15 @@ export function createAuthReceipt(
50
50
  },
51
51
  };
52
52
  }
53
+
54
+ export function createCommerceReceipt(
55
+ input: CommerceReceiptInput,
56
+ config: { issuer: string; keyId: string },
57
+ ): ReceiptPayload {
58
+ const base = createAuthReceipt(input, config);
59
+ return {
60
+ ...base,
61
+ kind: 'bolyra.commerce',
62
+ commerce: input.commerce,
63
+ };
64
+ }
package/src/types.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export interface ReceiptPayload {
2
2
  v: 1;
3
- kind: 'bolyra.auth';
3
+ kind: 'bolyra.auth' | 'bolyra.commerce';
4
4
  /** Unix seconds when the decision was made. */
5
5
  issuedAt: number;
6
6
  /** Server identifier. */
@@ -39,6 +39,9 @@ export interface ReceiptPayload {
39
39
  /** SHA-256 of canonical JSON of delegationChain (if v=2). */
40
40
  delegationChainHash?: string;
41
41
  };
42
+
43
+ /** Present only when kind === 'bolyra.commerce'. */
44
+ commerce?: CommerceFields;
42
45
  }
43
46
 
44
47
  export interface SignedReceipt {
@@ -64,6 +67,14 @@ export interface ReceiptSignerConfig {
64
67
  privateKey: string;
65
68
  }
66
69
 
70
+ export interface CommerceFields {
71
+ rail: string;
72
+ amount: number;
73
+ currency: string;
74
+ merchant: string;
75
+ intentHash: string;
76
+ }
77
+
67
78
  export interface AuthReceiptInput {
68
79
  /** From BolyraAuthContext or equivalent. */
69
80
  rootDid: string;
@@ -84,3 +95,7 @@ export interface AuthReceiptInput {
84
95
  nonce: string;
85
96
  delegationChain?: unknown[];
86
97
  }
98
+
99
+ export interface CommerceReceiptInput extends AuthReceiptInput {
100
+ commerce: CommerceFields;
101
+ }
@@ -0,0 +1,286 @@
1
+ #!/usr/bin/env node
2
+
3
+ import * as fs from 'fs';
4
+ import * as process from 'process';
5
+ import { verifyReceipt, hashPayload } from './sign';
6
+ import type { SignedReceipt } from './types';
7
+
8
+ // --- Helpers ---
9
+
10
+ function usage(): string {
11
+ return `Usage: bolyra-receipt-verify <receipt.json> [options]
12
+
13
+ Options:
14
+ --stdin Read receipt JSON from stdin instead of a file
15
+ --signer <address> Expected signer address (optional)
16
+ --max-age <seconds> Maximum receipt age in seconds (default: 86400)
17
+ --help Show this help`;
18
+ }
19
+
20
+ function fail(msg: string): never {
21
+ process.stderr.write(msg + '\n');
22
+ process.exit(2);
23
+ }
24
+
25
+ function truncate(hex: string): string {
26
+ if (hex.length <= 14) return hex;
27
+ return hex.slice(0, 8) + '...' + hex.slice(-4);
28
+ }
29
+
30
+ // --- Arg parsing ---
31
+
32
+ const args = process.argv.slice(2);
33
+
34
+ if (args.includes('--help') || args.includes('-h')) {
35
+ console.log(usage());
36
+ process.exit(0);
37
+ }
38
+
39
+ let filePath: string | undefined;
40
+ let expectedSigner: string | undefined;
41
+ let maxAgeSeconds = 86400;
42
+ let useStdin = false;
43
+
44
+ for (let i = 0; i < args.length; i++) {
45
+ const arg = args[i];
46
+ if (arg === '--stdin') {
47
+ useStdin = true;
48
+ } else if (arg === '--signer') {
49
+ expectedSigner = args[++i];
50
+ if (!expectedSigner) fail('--signer requires an address argument');
51
+ } else if (arg === '--max-age') {
52
+ const val = args[++i];
53
+ if (!val) fail('--max-age requires a number argument');
54
+ maxAgeSeconds = parseInt(val, 10);
55
+ if (Number.isNaN(maxAgeSeconds) || maxAgeSeconds < 0) {
56
+ fail('--max-age must be a non-negative integer');
57
+ }
58
+ } else if (arg.startsWith('-')) {
59
+ fail(`Unknown option: ${arg}\n\n${usage()}`);
60
+ } else {
61
+ filePath = arg;
62
+ }
63
+ }
64
+
65
+ if (!filePath && !useStdin) {
66
+ fail(`No input specified. Provide a file path or use --stdin.\n\n${usage()}`);
67
+ }
68
+
69
+ // --- Read input ---
70
+
71
+ let rawJson: string;
72
+ try {
73
+ if (useStdin) {
74
+ rawJson = fs.readFileSync(0, 'utf-8');
75
+ } else {
76
+ rawJson = fs.readFileSync(filePath!, 'utf-8');
77
+ }
78
+ } catch (err: unknown) {
79
+ const msg = err instanceof Error ? err.message : String(err);
80
+ fail(`Cannot read input: ${msg}`);
81
+ }
82
+
83
+ let receipt: SignedReceipt;
84
+ try {
85
+ receipt = JSON.parse(rawJson);
86
+ } catch {
87
+ fail('Invalid JSON');
88
+ }
89
+
90
+ // --- Checks ---
91
+
92
+ const checks: string[] = [];
93
+ let failed = false;
94
+
95
+ function pass(msg: string): void {
96
+ checks.push(`\u2713 ${msg}`);
97
+ }
98
+
99
+ function failCheck(msg: string): void {
100
+ checks.push(`\u2717 ${msg}`);
101
+ failed = true;
102
+ }
103
+
104
+ // 1. Schema validation
105
+ function validateSchema(): boolean {
106
+ if (receipt === null || typeof receipt !== 'object') {
107
+ failCheck('Schema: receipt is not an object');
108
+ return false;
109
+ }
110
+ const p = receipt.payload;
111
+ const s = receipt.signature;
112
+ const errors: string[] = [];
113
+
114
+ if (!p) { errors.push('missing payload'); }
115
+ if (!s) { errors.push('missing signature'); }
116
+ if (errors.length) { failCheck(`Schema: ${errors.join(', ')}`); return false; }
117
+
118
+ if (p.v !== 1) errors.push('payload.v !== 1');
119
+ if (p.kind !== 'bolyra.auth' && p.kind !== 'bolyra.commerce') {
120
+ errors.push('payload.kind must be "bolyra.auth" or "bolyra.commerce"');
121
+ }
122
+ if (typeof p.issuedAt !== 'number') errors.push('payload.issuedAt not a number');
123
+ if (typeof p.issuer !== 'string' || !p.issuer) errors.push('payload.issuer missing');
124
+ if (typeof p.keyId !== 'string' || !p.keyId) errors.push('payload.keyId missing');
125
+
126
+ // subject
127
+ if (!p.subject) {
128
+ errors.push('payload.subject missing');
129
+ } else {
130
+ for (const k of ['rootDid', 'actingDid', 'credentialCommitment', 'effectiveCommitment'] as const) {
131
+ if (typeof (p.subject as any)[k] !== 'string' || !(p.subject as any)[k]) {
132
+ errors.push(`payload.subject.${k} missing or not a string`);
133
+ }
134
+ }
135
+ }
136
+
137
+ // decision
138
+ if (!p.decision) {
139
+ errors.push('payload.decision missing');
140
+ } else {
141
+ if (typeof p.decision.allowed !== 'boolean') errors.push('decision.allowed not boolean');
142
+ if (typeof p.decision.score !== 'number') errors.push('decision.score not a number');
143
+ if (typeof p.decision.permissionBitmask !== 'string' || !p.decision.permissionBitmask) errors.push('decision.permissionBitmask missing or not a string');
144
+ if (typeof p.decision.chainDepth !== 'number') errors.push('decision.chainDepth not a number');
145
+ }
146
+
147
+ // proof
148
+ if (!p.proof) {
149
+ errors.push('payload.proof missing');
150
+ } else if (typeof p.proof !== 'object') {
151
+ errors.push('payload.proof not an object');
152
+ } else {
153
+ for (const k of ['bundleVersion', 'nonce', 'humanProofHash', 'agentProofHash', 'publicSignalsHash'] as const) {
154
+ if (!(k in p.proof)) errors.push(`proof.${k} missing`);
155
+ }
156
+ }
157
+
158
+ // commerce fields: required for bolyra.commerce, forbidden for bolyra.auth
159
+ if (p.kind === 'bolyra.auth' && (p as any).commerce) {
160
+ errors.push('auth receipt must not contain commerce fields');
161
+ }
162
+ if (p.kind === 'bolyra.commerce') {
163
+ const c = (p as any).commerce;
164
+ if (!c) {
165
+ errors.push('commerce fields missing for bolyra.commerce receipt');
166
+ } else {
167
+ if (typeof c.rail !== 'string' || !c.rail) errors.push('commerce.rail missing or not a string');
168
+ if (typeof c.amount !== 'number') errors.push('commerce.amount not a number');
169
+ if (typeof c.currency !== 'string' || !c.currency) errors.push('commerce.currency missing or not a string');
170
+ if (typeof c.merchant !== 'string') errors.push('commerce.merchant not a string');
171
+ if (typeof c.intentHash !== 'string' || !/^[0-9a-fA-F]{64}$/.test(c.intentHash)) {
172
+ errors.push('commerce.intentHash must be a 64-char hex string');
173
+ }
174
+ }
175
+ }
176
+
177
+ // signature fields
178
+ if (s.alg !== 'ES256K') errors.push('signature.alg !== "ES256K"');
179
+ if (s.keyId !== p.keyId) errors.push('signature.keyId does not match payload.keyId');
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');
183
+
184
+ if (errors.length) {
185
+ failCheck(`Schema: ${errors.join('; ')}`);
186
+ return false;
187
+ }
188
+ pass('Schema valid');
189
+ return true;
190
+ }
191
+
192
+ // 2. Timestamp check
193
+ function validateTimestamp(): void {
194
+ const nowSec = Math.floor(Date.now() / 1000);
195
+ const issuedAt = receipt.payload.issuedAt;
196
+ const allowFutureSeconds = 300;
197
+ const ageSec = nowSec - issuedAt;
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();
204
+
205
+ if (issuedAt > nowSec + allowFutureSeconds) {
206
+ failCheck(`Timestamp: ${isoStr} is ${issuedAt - nowSec}s in the future (max skew: ${allowFutureSeconds}s)`);
207
+ return;
208
+ }
209
+ if (ageSec > maxAgeSeconds) {
210
+ failCheck(`Timestamp: ${isoStr} (${ageSec}s ago, max-age: ${maxAgeSeconds}s)`);
211
+ return;
212
+ }
213
+ pass(`Timestamp: ${isoStr} (${ageSec}s ago)`);
214
+ }
215
+
216
+ // 3. Hash check
217
+ function validateHash(): boolean {
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
+ }
226
+ if (computed !== receipt.signature.payloadHash) {
227
+ failCheck(`Payload hash mismatch (expected ${truncate(receipt.signature.payloadHash)}, got ${truncate(computed)})`);
228
+ return false;
229
+ }
230
+ pass('Payload hash matches');
231
+ return true;
232
+ }
233
+
234
+ // 4. ID check
235
+ function validateId(): void {
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
+ }
241
+ if (receipt.id !== expected) {
242
+ failCheck(`Receipt ID mismatch (expected ${expected}, got ${receipt.id})`);
243
+ return;
244
+ }
245
+ pass('Receipt ID matches');
246
+ }
247
+
248
+ // 5. Signature check
249
+ function validateSignature(): void {
250
+ const ok = verifyReceipt(receipt, expectedSigner);
251
+ if (!ok) {
252
+ failCheck(`Signature invalid${expectedSigner ? ` (expected signer: ${truncate(expectedSigner)})` : ''}`);
253
+ return;
254
+ }
255
+ pass(`Signature valid (signer: ${truncate(receipt.signature.signer)})`);
256
+ }
257
+
258
+ // --- Run checks ---
259
+
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
+ }
269
+ }
270
+ } catch {
271
+ failCheck('Receipt could not be checked');
272
+ }
273
+
274
+ // --- Output ---
275
+
276
+ for (const line of checks) {
277
+ console.log(line);
278
+ }
279
+
280
+ if (failed) {
281
+ console.log('FAIL \u2014 receipt is invalid');
282
+ process.exit(1);
283
+ } else {
284
+ console.log('PASS \u2014 receipt is valid');
285
+ process.exit(0);
286
+ }