@bolyra/receipts 0.8.0 → 0.8.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({
@@ -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.8.0",
3
+ "version": "0.8.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",
@@ -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.8"
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/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 ---