@ocap/message 1.31.0 → 1.31.2

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,6 +1,14 @@
1
1
  //#region src/canonical-cbor.d.ts
2
+ /**
3
+ * Deterministic container/tag nesting ceiling for canonical CBOR payloads (excluding the
4
+ * stripped top-level tag 55799 prefix). Chosen to sit 4x above `MAX_PREFLIGHT_JSON_DEPTH` (16)
5
+ * and well above OCAP's deepest legitimate proto + JSON/VC nesting (~24 levels), while remaining
6
+ * >25x below V8 / Cloudflare Workers call-stack exhaustion so decode and encode behave
7
+ * deterministically across Node/V8, Bun/JSC, and Workers (#1515).
8
+ */
9
+ declare const MAX_CANONICAL_CBOR_DEPTH = 64;
2
10
  declare function canonicalBytes(type: string, data: Record<string, unknown>): Uint8Array;
3
11
  declare function parseCanonical(type: string, bytes: Uint8Array): Record<string, unknown>;
4
12
  declare const CANONICAL_SELF_DESCRIBE_PREFIX: Uint8Array<ArrayBuffer>;
5
13
  //#endregion
6
- export { CANONICAL_SELF_DESCRIBE_PREFIX, canonicalBytes, parseCanonical };
14
+ export { CANONICAL_SELF_DESCRIBE_PREFIX, MAX_CANONICAL_CBOR_DEPTH, canonicalBytes, parseCanonical };
@@ -1,5 +1,6 @@
1
+ import { Type } from "./node_modules/cborg/lib/token.mjs";
1
2
  import { encode, rfc8949EncodeOptions } from "./node_modules/cborg/lib/encode.mjs";
2
- import { decode } from "./node_modules/cborg/lib/decode.mjs";
3
+ import { Tokeniser, decode } from "./node_modules/cborg/lib/decode.mjs";
3
4
  import { Tagged } from "./node_modules/cborg/lib/tagged.mjs";
4
5
  import "./node_modules/cborg/cborg.mjs";
5
6
  import { enums, fromTypeUrl, getMessageType, toTypeUrl } from "./provider.mjs";
@@ -27,6 +28,60 @@ const SELF_DESCRIBE_PREFIX = new Uint8Array([
27
28
  217,
28
29
  247
29
30
  ]);
31
+ /**
32
+ * Deterministic container/tag nesting ceiling for canonical CBOR payloads (excluding the
33
+ * stripped top-level tag 55799 prefix). Chosen to sit 4x above `MAX_PREFLIGHT_JSON_DEPTH` (16)
34
+ * and well above OCAP's deepest legitimate proto + JSON/VC nesting (~24 levels), while remaining
35
+ * >25x below V8 / Cloudflare Workers call-stack exhaustion so decode and encode behave
36
+ * deterministically across Node/V8, Bun/JSC, and Workers (#1515).
37
+ */
38
+ const MAX_CANONICAL_CBOR_DEPTH = 64;
39
+ function assertCborDepth(depth) {
40
+ if (depth > MAX_CANONICAL_CBOR_DEPTH) throw new Error(`canonical-cbor: nesting depth exceeds maximum (${MAX_CANONICAL_CBOR_DEPTH})`);
41
+ }
42
+ /**
43
+ * Stream-level CBOR tokenizer wrapper that tracks active definite-length container (`array`,
44
+ * `map`) and `tag` nesting depth in O(1) per token, halting `cborg.decode` *before* its recursive
45
+ * `tokensToObject` walker can blow the JS call stack (#1515).
46
+ */
47
+ var BoundedDepthTokenizer = class {
48
+ constructor(data, options, maxDepth) {
49
+ this.remaining = [];
50
+ this.inner = new Tokeniser(data, options);
51
+ this.byteLength = data.length;
52
+ this.maxDepth = maxDepth;
53
+ }
54
+ done() {
55
+ return this.inner.done();
56
+ }
57
+ pos() {
58
+ return this.inner.pos();
59
+ }
60
+ next() {
61
+ const token = this.inner.next();
62
+ if (this.remaining.length > 0) this.remaining[this.remaining.length - 1] -= 1;
63
+ let isContainerOrTag = false;
64
+ let childSlots = 0;
65
+ if (Type.equals(token.type, Type.array)) {
66
+ isContainerOrTag = true;
67
+ const count = token.value;
68
+ childSlots = count > this.byteLength ? this.byteLength + 1 : count;
69
+ } else if (Type.equals(token.type, Type.map)) {
70
+ isContainerOrTag = true;
71
+ const count = token.value;
72
+ childSlots = count > this.byteLength ? this.byteLength * 2 + 2 : count * 2;
73
+ } else if (Type.equals(token.type, Type.tag)) {
74
+ isContainerOrTag = true;
75
+ childSlots = 1;
76
+ }
77
+ if (isContainerOrTag) {
78
+ if (this.remaining.length + 1 > this.maxDepth) throw new Error(`canonical-cbor: nesting depth exceeds maximum (${this.maxDepth})`);
79
+ }
80
+ if (childSlots > 0) this.remaining.push(childSlots);
81
+ else while (this.remaining.length > 0 && this.remaining[this.remaining.length - 1] === 0) this.remaining.pop();
82
+ return token;
83
+ }
84
+ };
30
85
  const SCALAR_INT_TYPES = new Set([
31
86
  "int32",
32
87
  "sint32",
@@ -51,6 +106,33 @@ function getFields(type) {
51
106
  function isEnumType(type) {
52
107
  return Object.prototype.hasOwnProperty.call(enums, type);
53
108
  }
109
+ const TypedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype);
110
+ const typedArrayBufferGetter = Object.getOwnPropertyDescriptor(TypedArrayPrototype, "buffer").get;
111
+ const typedArrayByteOffsetGetter = Object.getOwnPropertyDescriptor(TypedArrayPrototype, "byteOffset").get;
112
+ const typedArrayByteLengthGetter = Object.getOwnPropertyDescriptor(TypedArrayPrototype, "byteLength").get;
113
+ const dataViewBufferGetter = Object.getOwnPropertyDescriptor(DataView.prototype, "buffer").get;
114
+ const dataViewByteOffsetGetter = Object.getOwnPropertyDescriptor(DataView.prototype, "byteOffset").get;
115
+ const dataViewByteLengthGetter = Object.getOwnPropertyDescriptor(DataView.prototype, "byteLength").get;
116
+ const arrayBufferByteLengthGetter = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get;
117
+ function toPlainBytes(value) {
118
+ if (ArrayBuffer.isView(value)) {
119
+ if (value instanceof DataView) {
120
+ const buf$1 = dataViewBufferGetter.call(value);
121
+ const offset$1 = dataViewByteOffsetGetter.call(value);
122
+ const length$1 = dataViewByteLengthGetter.call(value);
123
+ return new Uint8Array(buf$1, offset$1, length$1);
124
+ }
125
+ const buf = typedArrayBufferGetter.call(value);
126
+ const offset = typedArrayByteOffsetGetter.call(value);
127
+ const length = typedArrayByteLengthGetter.call(value);
128
+ return new Uint8Array(buf, offset, length);
129
+ }
130
+ if (value instanceof ArrayBuffer) {
131
+ const length = arrayBufferByteLengthGetter.call(value);
132
+ return new Uint8Array(value, 0, length);
133
+ }
134
+ return null;
135
+ }
54
136
  function stripBignumLeadingZeros(bytes) {
55
137
  let start = 0;
56
138
  while (start < bytes.length - 1 && bytes[start] === 0) start += 1;
@@ -67,14 +149,16 @@ function normalizeBigIntWrapper(value, type) {
67
149
  if (value === void 0 || value === null) return null;
68
150
  if (typeof value === "object" && value !== null && "value" in value) {
69
151
  const wrapped = value;
70
- if (wrapped.value === void 0 || wrapped.value === null) return null;
71
- const rawBytes = toUint8Array(wrapped.value);
72
- if (!rawBytes || rawBytes.length === 0) return null;
152
+ const wrappedVal = wrapped.value;
153
+ if (wrappedVal === void 0 || wrappedVal === null) return null;
154
+ const converted = toPlainBytes(wrappedVal) ?? toUint8Array(wrappedVal);
155
+ const rawBytes = converted ? toPlainBytes(converted) ?? converted : null;
156
+ if (!rawBytes || rawBytes.byteLength === 0) return null;
73
157
  const trimmed = stripBignumLeadingZeros(rawBytes);
74
- if (trimmed.length === 1 && trimmed[0] === 0) return null;
158
+ if (trimmed.byteLength === 1 && trimmed[0] === 0) return null;
75
159
  return {
76
160
  bytes: trimmed,
77
- negative: type === "BigSint" && wrapped.minus === true
161
+ negative: type === "BigSint" && Boolean(wrapped.minus)
78
162
  };
79
163
  }
80
164
  if (typeof value === "bigint") {
@@ -121,8 +205,11 @@ function isDefaultScalar(value, type) {
121
205
  if (type === "string") return value === "";
122
206
  if (type === "bytes") {
123
207
  if (typeof value === "string") return value.length === 0;
208
+ const direct = toPlainBytes(value);
209
+ if (direct !== null) return direct.byteLength === 0;
124
210
  const bytes = toUint8Array(value);
125
- return !bytes || bytes.length === 0;
211
+ const plain = bytes ? toPlainBytes(bytes) ?? bytes : null;
212
+ return !plain || plain.byteLength === 0;
126
213
  }
127
214
  if (isEnumType(type)) return value === 0 || value === "" || value === void 0;
128
215
  return false;
@@ -142,10 +229,13 @@ function encodeTimestampValue(value) {
142
229
  throw new Error(`canonical-cbor: unsupported timestamp input type ${typeof value}`);
143
230
  }
144
231
  function resolveAnyTypeUrl(value) {
145
- const typeUrl = value.typeUrl || value.type_url || toTypeUrl(value.type);
232
+ const rawTypeUrl = value.typeUrl;
233
+ const rawTypeUrlSnake = value.type_url;
234
+ const rawType = value.type;
235
+ const typeUrl = rawTypeUrl || rawTypeUrlSnake || toTypeUrl(rawType);
146
236
  if (!typeUrl) throw new Error("canonical-cbor: Any value missing typeUrl/type");
147
237
  const type = fromTypeUrl(typeUrl);
148
- const wasUnwrapped = !value.typeUrl && !value.type_url && typeof value.type === "string";
238
+ const wasUnwrapped = !rawTypeUrl && !rawTypeUrlSnake && typeof rawType === "string";
149
239
  return {
150
240
  typeUrl,
151
241
  type,
@@ -153,28 +243,132 @@ function resolveAnyTypeUrl(value) {
153
243
  wasUnwrapped
154
244
  };
155
245
  }
156
- function normalizeOpaquePayload(value) {
246
+ function isPlainObject(value) {
247
+ const proto = Object.getPrototypeOf(value);
248
+ return proto === null || proto === Object.prototype;
249
+ }
250
+ function assertNotForbiddenOpaqueKey(key) {
251
+ if (key === "__proto__" || key === "constructor" || key === "prototype") throw new Error(`canonical-cbor: forbidden map key "${key}"`);
252
+ }
253
+ function defineOwnDataProperty(target, key, value) {
254
+ Object.defineProperty(target, key, {
255
+ value,
256
+ enumerable: true,
257
+ writable: true,
258
+ configurable: true
259
+ });
260
+ }
261
+ function normalizePassthroughMapKey(key) {
262
+ if (typeof key === "string" || typeof key === "boolean") return key;
263
+ if (typeof key === "number") {
264
+ if (!Number.isFinite(key)) throw new Error("canonical-cbor: invalid non-finite number map key in passthrough payload");
265
+ if (Object.is(key, -0)) return 0;
266
+ return key;
267
+ }
268
+ if (typeof key === "bigint") {
269
+ if (key >= BigInt(Number.MIN_SAFE_INTEGER) && key <= BigInt(Number.MAX_SAFE_INTEGER)) return Number(key);
270
+ return key;
271
+ }
272
+ throw new Error("canonical-cbor: unsupported non-scalar map key in passthrough payload");
273
+ }
274
+ function normalizeOpaquePayload(value, depth) {
275
+ if (value === null || value === void 0) return value;
276
+ if (value instanceof Date) return new Date(Date.prototype.getTime.call(value)).toISOString();
277
+ const bytes = toPlainBytes(value);
278
+ if (bytes !== null) return bytes;
279
+ if (value instanceof Tagged) throw new Error("canonical-cbor: CBOR tags are not allowed in opaque payloads");
280
+ if (Array.isArray(value)) {
281
+ const nextDepth = depth + 1;
282
+ assertCborDepth(nextDepth);
283
+ const len = value.length;
284
+ const out = new Array(len);
285
+ for (let i = 0; i < len; i += 1) out[i] = normalizeOpaquePayload(value[i], nextDepth);
286
+ return out;
287
+ }
288
+ if (value instanceof Map) {
289
+ const nextDepth = depth + 1;
290
+ assertCborDepth(nextDepth);
291
+ const out = {};
292
+ for (const [k, v] of value.entries()) {
293
+ if (typeof k !== "string") throw new Error("canonical-cbor: opaque map keys must be strings");
294
+ assertNotForbiddenOpaqueKey(k);
295
+ if (v === void 0) continue;
296
+ if (Object.hasOwn(out, k)) throw new Error(`canonical-cbor: duplicate map key "${k}" in opaque payload`);
297
+ defineOwnDataProperty(out, k, normalizeOpaquePayload(v, nextDepth));
298
+ }
299
+ return out;
300
+ }
301
+ if (typeof value === "object") {
302
+ if (!isPlainObject(value)) throw new Error("canonical-cbor: unsupported object type in opaque payload");
303
+ const nextDepth = depth + 1;
304
+ assertCborDepth(nextDepth);
305
+ const out = {};
306
+ for (const k of Object.keys(value)) {
307
+ assertNotForbiddenOpaqueKey(k);
308
+ const v = value[k];
309
+ if (v === void 0) continue;
310
+ defineOwnDataProperty(out, k, normalizeOpaquePayload(v, nextDepth));
311
+ }
312
+ return out;
313
+ }
314
+ return value;
315
+ }
316
+ function materializePassthroughValue(value, depth) {
157
317
  if (value === null || value === void 0) return value;
158
- if (value instanceof Date) return value.toISOString();
159
- if (value instanceof Uint8Array) return value;
160
- if (Array.isArray(value)) return value.map(normalizeOpaquePayload);
318
+ const bytes = toPlainBytes(value);
319
+ if (bytes !== null) return bytes;
320
+ if (value instanceof Tagged) {
321
+ assertCborDepth(depth + 1);
322
+ const tagNum = value.tag;
323
+ if (tagNum !== TAG_POSITIVE_BIGNUM && tagNum !== TAG_NEGATIVE_BIGNUM) throw new Error(`canonical-cbor: unsupported CBOR tag ${String(tagNum)} in passthrough payload`);
324
+ const rawTagVal = value.value;
325
+ if (!(rawTagVal instanceof Uint8Array)) throw new Error("canonical-cbor: BigInt bignum tag value must be byte string");
326
+ const tagBytes = toPlainBytes(rawTagVal);
327
+ if (!tagBytes || tagBytes.byteLength === 0 || tagBytes[0] === 0) throw new Error("canonical-cbor: non-canonical bignum (empty or leading zero byte)");
328
+ return new Tagged(tagNum, tagBytes);
329
+ }
330
+ if (Array.isArray(value)) {
331
+ const nextDepth = depth + 1;
332
+ assertCborDepth(nextDepth);
333
+ const len = value.length;
334
+ const out = new Array(len);
335
+ for (let i = 0; i < len; i += 1) out[i] = materializePassthroughValue(value[i], nextDepth);
336
+ return out;
337
+ }
338
+ if (value instanceof Map) {
339
+ const nextDepth = depth + 1;
340
+ assertCborDepth(nextDepth);
341
+ const out = /* @__PURE__ */ new Map();
342
+ for (const [k, v] of value.entries()) {
343
+ const normKey = normalizePassthroughMapKey(k);
344
+ if (out.has(normKey)) throw new Error("canonical-cbor: duplicate map key in passthrough payload");
345
+ out.set(normKey, materializePassthroughValue(v, nextDepth));
346
+ }
347
+ return out;
348
+ }
161
349
  if (typeof value === "object") {
350
+ if (!isPlainObject(value)) throw new Error("canonical-cbor: unsupported object type in passthrough payload");
351
+ const nextDepth = depth + 1;
352
+ assertCborDepth(nextDepth);
162
353
  const out = {};
163
- for (const [k, v] of Object.entries(value)) {
354
+ for (const k of Object.keys(value)) {
355
+ assertNotForbiddenOpaqueKey(k);
356
+ const v = value[k];
164
357
  if (v === void 0) continue;
165
- out[k] = normalizeOpaquePayload(v);
358
+ defineOwnDataProperty(out, k, materializePassthroughValue(v, nextDepth));
166
359
  }
167
360
  return out;
168
361
  }
169
362
  return value;
170
363
  }
171
- function encodeAnyValue(value) {
364
+ function encodeAnyValue(value, depth) {
365
+ assertCborDepth(depth);
172
366
  const { typeUrl, type, inner, wasUnwrapped } = resolveAnyTypeUrl(value);
173
367
  const map = /* @__PURE__ */ new Map();
174
368
  map.set(0, typeUrl);
175
369
  if (typeUrl === "json" || typeUrl === "vc" || typeUrl === "fg:x:address") {
176
370
  const payload = wasUnwrapped ? inner : value.value ?? inner;
177
- map.set(1, normalizeOpaquePayload(payload));
371
+ map.set(1, normalizeOpaquePayload(payload, depth));
178
372
  return map;
179
373
  }
180
374
  let innerObj = {};
@@ -195,12 +389,13 @@ function encodeAnyValue(value) {
195
389
  }
196
390
  }
197
391
  try {
198
- const encoded = encodeMessageFields(type, innerObj);
392
+ const encoded = encodeMessageFields(type, innerObj, depth);
199
393
  for (const [id, val] of encoded.entries()) map.set(id, val);
200
394
  } catch (err) {
201
395
  if (err instanceof Error && err.message.startsWith("canonical-cbor: unknown message type")) {
202
- if ("value" in value) {
203
- map.set(1, value.value);
396
+ if (wasUnwrapped || "value" in value) {
397
+ const rawPassthrough = wasUnwrapped ? inner : value.value;
398
+ map.set(1, materializePassthroughValue(rawPassthrough, depth));
204
399
  return map;
205
400
  }
206
401
  }
@@ -208,26 +403,37 @@ function encodeAnyValue(value) {
208
403
  }
209
404
  return map;
210
405
  }
211
- function encodeFieldValue(value, field) {
406
+ function encodeFieldValue(value, field, depth) {
212
407
  const type = field.type;
213
408
  if (field.keyType !== void 0) throw new Error(`canonical-cbor: map<${field.keyType},${type}> fields are not supported yet`);
214
409
  if (field.rule === "repeated") {
215
410
  if (!Array.isArray(value)) throw new Error(`canonical-cbor: repeated field expects array, got ${typeof value}`);
411
+ const len = value.length;
412
+ if (len === 0) return void 0;
413
+ const arrayDepth = depth + 1;
414
+ assertCborDepth(arrayDepth);
216
415
  const itemField = {
217
416
  id: field.id,
218
417
  type
219
418
  };
220
- return value.map((item) => encodeFieldValue(item, itemField));
419
+ const out = new Array(len);
420
+ for (let i = 0; i < len; i += 1) {
421
+ const item = value[i];
422
+ if (item === void 0) throw new Error("canonical-cbor: repeated field cannot contain undefined elements");
423
+ out[i] = encodeFieldValue(item, itemField, arrayDepth);
424
+ }
425
+ return out;
221
426
  }
222
427
  if (BIGINT_WRAPPER_TYPES.has(type)) {
223
428
  const parsed = normalizeBigIntWrapper(value, type);
224
429
  if (!parsed) return void 0;
430
+ assertCborDepth(depth + 1);
225
431
  return new Tagged(parsed.negative ? TAG_NEGATIVE_BIGNUM : TAG_POSITIVE_BIGNUM, parsed.bytes);
226
432
  }
227
433
  if (TIMESTAMP_TYPES.has(type)) return encodeTimestampValue(value);
228
434
  if (ANY_TYPES.has(type)) {
229
435
  if (value === void 0 || value === null) return void 0;
230
- return encodeAnyValue(value);
436
+ return encodeAnyValue(value, depth + 1);
231
437
  }
232
438
  if (isEnumType(type)) {
233
439
  if (typeof value === "string") {
@@ -242,17 +448,23 @@ function encodeFieldValue(value, field) {
242
448
  if (type === "bool") return Boolean(value);
243
449
  if (type === "string") return String(value);
244
450
  if (type === "bytes") {
245
- if (value instanceof Uint8Array) return value;
246
- return toUint8Array(value) ?? new Uint8Array();
451
+ const direct = toPlainBytes(value);
452
+ if (direct !== null) return direct.byteLength === 0 ? void 0 : direct;
453
+ const converted = toUint8Array(value);
454
+ const bytes = converted ? toPlainBytes(converted) ?? converted : null;
455
+ if (!bytes || bytes.byteLength === 0) return void 0;
456
+ return bytes;
247
457
  }
248
458
  if (typeof value !== "object" || value === null) throw new Error(`canonical-cbor: expected object for nested ${type}, got ${typeof value}`);
249
- return encodeMessageFields(type, value);
459
+ return encodeMessageFields(type, value, depth + 1);
250
460
  }
251
- function encodeMessageFields(type, data) {
461
+ function encodeMessageFields(type, data, depth) {
462
+ assertCborDepth(depth);
252
463
  if (BIGINT_WRAPPER_TYPES.has(type)) {
253
464
  const parsed = normalizeBigIntWrapper(data, type);
254
465
  const out$1 = /* @__PURE__ */ new Map();
255
466
  if (!parsed) return out$1;
467
+ assertCborDepth(depth + 1);
256
468
  const tag = parsed.negative ? TAG_NEGATIVE_BIGNUM : TAG_POSITIVE_BIGNUM;
257
469
  out$1.set(1, new Tagged(tag, parsed.bytes));
258
470
  if (type === "BigSint" && parsed.negative) out$1.set(2, true);
@@ -270,12 +482,13 @@ function encodeMessageFields(type, data) {
270
482
  if (spec.rule === "repeated") {
271
483
  if (value === null) continue;
272
484
  if (!Array.isArray(value)) throw new Error(`canonical-cbor: repeated field "${name}" expects array, got ${typeof value}`);
273
- if (value.length === 0) continue;
274
- out.set(spec.id, encodeFieldValue(value, spec));
485
+ const encodedRepeated = encodeFieldValue(value, spec, depth);
486
+ if (encodedRepeated === void 0) continue;
487
+ out.set(spec.id, encodedRepeated);
275
488
  continue;
276
489
  }
277
490
  if (isDefaultScalar(value, spec.type)) continue;
278
- const encoded = encodeFieldValue(value, spec);
491
+ const encoded = encodeFieldValue(value, spec, depth);
279
492
  if (encoded === void 0) continue;
280
493
  out.set(spec.id, encoded);
281
494
  }
@@ -283,7 +496,7 @@ function encodeMessageFields(type, data) {
283
496
  }
284
497
  function canonicalBytes(type, data) {
285
498
  if (!data || typeof data !== "object") throw new Error("canonical-cbor: data must be an object");
286
- return encode(new Tagged(TAG_SELF_DESCRIBE, encodeMessageFields(type, data)), rfc8949EncodeOptions);
499
+ return encode(new Tagged(TAG_SELF_DESCRIBE, encodeMessageFields(type, data, 1)), rfc8949EncodeOptions);
287
500
  }
288
501
  function buildDecodeIndex(type) {
289
502
  const fields = getFields(type);
@@ -294,17 +507,27 @@ function buildDecodeIndex(type) {
294
507
  });
295
508
  return { idToName };
296
509
  }
297
- function mapsToPlainObjects(value) {
510
+ function mapsToPlainObjects(value, depth) {
511
+ if (value instanceof Tagged) throw new Error("canonical-cbor: CBOR tags are not allowed in opaque payloads");
298
512
  if (value instanceof Map) {
513
+ const nextDepth = depth + 1;
514
+ assertCborDepth(nextDepth);
299
515
  const obj = {};
300
516
  for (const [k, v] of value.entries()) {
301
- const key = String(k);
302
- if (key === "__proto__" || key === "constructor" || key === "prototype") throw new Error(`canonical-cbor: forbidden map key "${key}"`);
303
- obj[key] = mapsToPlainObjects(v);
517
+ if (typeof k !== "string") throw new Error("canonical-cbor: opaque map keys must be strings");
518
+ assertNotForbiddenOpaqueKey(k);
519
+ defineOwnDataProperty(obj, k, mapsToPlainObjects(v, nextDepth));
304
520
  }
305
521
  return obj;
306
522
  }
307
- if (Array.isArray(value)) return value.map(mapsToPlainObjects);
523
+ if (Array.isArray(value)) {
524
+ const nextDepth = depth + 1;
525
+ assertCborDepth(nextDepth);
526
+ const len = value.length;
527
+ const out = new Array(len);
528
+ for (let i = 0; i < len; i += 1) out[i] = mapsToPlainObjects(value[i], nextDepth);
529
+ return out;
530
+ }
308
531
  return value;
309
532
  }
310
533
  function assertCanonicalIntMapKeys(payload) {
@@ -316,13 +539,14 @@ function assertCanonicalIntMapKeys(payload) {
316
539
  prevId = id;
317
540
  }
318
541
  }
319
- function decodeAnyValue(payload) {
542
+ function decodeAnyValue(payload, depth) {
543
+ assertCborDepth(depth);
320
544
  assertCanonicalIntMapKeys(payload);
321
545
  const typeUrl = payload.get(0);
322
546
  if (!typeUrl || typeof typeUrl !== "string") throw new Error("canonical-cbor: Any payload missing typeUrl at key 0");
323
547
  if (typeUrl === "json" || typeUrl === "vc" || typeUrl === "fg:x:address") return {
324
548
  typeUrl,
325
- value: mapsToPlainObjects(payload.get(1))
549
+ value: mapsToPlainObjects(payload.get(1), depth)
326
550
  };
327
551
  const innerType = fromTypeUrl(typeUrl);
328
552
  let innerFields;
@@ -341,7 +565,7 @@ function decodeAnyValue(payload) {
341
565
  const decoded = decodeFieldValue(payload.get(1), {
342
566
  id: 1,
343
567
  type: innerType
344
- });
568
+ }, depth);
345
569
  if (decoded && typeof decoded === "object" && "value" in decoded) Object.assign(innerObj, decoded);
346
570
  else innerObj.value = decoded;
347
571
  }
@@ -353,21 +577,24 @@ function decodeAnyValue(payload) {
353
577
  const descriptor = Object.entries(innerFields).find(([, f]) => f.id === id);
354
578
  if (!descriptor) continue;
355
579
  const [name, spec] = descriptor;
356
- innerObj[name] = decodeFieldValue(raw, spec);
580
+ innerObj[name] = decodeFieldValue(raw, spec, depth);
357
581
  }
358
582
  return innerObj;
359
583
  }
360
- function decodeFieldValue(raw, field) {
584
+ function decodeFieldValue(raw, field, depth) {
361
585
  const type = field.type;
362
586
  if (field.rule === "repeated") {
363
587
  if (!Array.isArray(raw)) return raw;
588
+ const arrayDepth = depth + 1;
589
+ assertCborDepth(arrayDepth);
364
590
  const itemField = {
365
591
  id: field.id,
366
592
  type
367
593
  };
368
- return raw.map((item) => decodeFieldValue(item, itemField));
594
+ return raw.map((item) => decodeFieldValue(item, itemField, arrayDepth));
369
595
  }
370
596
  if (raw instanceof Tagged) {
597
+ assertCborDepth(depth + 1);
371
598
  if (raw.tag !== TAG_POSITIVE_BIGNUM && raw.tag !== TAG_NEGATIVE_BIGNUM) throw new Error(`canonical-cbor: BigInt wrapper expects tag 2/3, got ${raw.tag}`);
372
599
  if (!(raw.value instanceof Uint8Array)) throw new Error("canonical-cbor: BigInt bignum tag value must be byte string");
373
600
  const bytes = raw.value;
@@ -385,7 +612,7 @@ function decodeFieldValue(raw, field) {
385
612
  }
386
613
  if (ANY_TYPES.has(type)) {
387
614
  if (!(raw instanceof Map)) throw new Error("canonical-cbor: Any expected nested map");
388
- return decodeAnyValue(raw);
615
+ return decodeAnyValue(raw, depth + 1);
389
616
  }
390
617
  if (isEnumType(type)) return typeof raw === "bigint" ? Number(raw) : raw;
391
618
  if (SCALAR_INT_TYPES.has(type)) return raw;
@@ -393,10 +620,11 @@ function decodeFieldValue(raw, field) {
393
620
  if (type === "bool") return Boolean(raw);
394
621
  if (type === "string") return String(raw);
395
622
  if (type === "bytes") return raw;
396
- if (raw instanceof Map) return decodeMessageMap(type, raw);
623
+ if (raw instanceof Map) return decodeMessageMap(type, raw, depth + 1);
397
624
  return raw;
398
625
  }
399
- function decodeMessageMap(type, payload) {
626
+ function decodeMessageMap(type, payload, depth) {
627
+ assertCborDepth(depth);
400
628
  assertCanonicalIntMapKeys(payload);
401
629
  if (BIGINT_WRAPPER_TYPES.has(type)) {
402
630
  const out$1 = {};
@@ -404,7 +632,7 @@ function decodeMessageMap(type, payload) {
404
632
  const decoded = decodeFieldValue(payload.get(1), {
405
633
  id: 1,
406
634
  type
407
- });
635
+ }, depth);
408
636
  if (decoded && typeof decoded === "object" && "value" in decoded) Object.assign(out$1, decoded);
409
637
  else out$1.value = decoded;
410
638
  }
@@ -416,28 +644,48 @@ function decodeMessageMap(type, payload) {
416
644
  for (const [id, raw] of payload.entries()) {
417
645
  const entry = ctx.idToName.get(id);
418
646
  if (!entry) continue;
419
- const value = decodeFieldValue(raw, entry.field);
647
+ const value = decodeFieldValue(raw, entry.field, depth);
420
648
  out[entry.name] = value;
421
649
  if (entry.field.rule === "repeated") out[`${entry.name}List`] = value;
422
650
  else if (entry.field.keyType !== void 0) out[`${entry.name}Map`] = value;
423
651
  }
424
652
  return out;
425
653
  }
654
+ function createCanonicalBignumTagDecoder(tag) {
655
+ return (decodeContent) => {
656
+ const inner = decodeContent();
657
+ if (!(inner instanceof Uint8Array)) throw new Error("canonical-cbor: BigInt bignum tag value must be byte string");
658
+ if (inner.length === 0 || inner[0] === 0) throw new Error("canonical-cbor: non-canonical bignum (empty or leading zero byte)");
659
+ return new Tagged(tag, inner);
660
+ };
661
+ }
426
662
  function parseCanonical(type, bytes) {
427
663
  if (!bytes || !(bytes instanceof Uint8Array)) throw new Error("canonical-cbor: input must be Uint8Array");
428
- if (bytes.length < 3 || bytes[0] !== SELF_DESCRIBE_PREFIX[0] || bytes[1] !== SELF_DESCRIBE_PREFIX[1] || bytes[2] !== SELF_DESCRIBE_PREFIX[2]) throw new Error("canonical-cbor: missing self-describe tag 55799 prefix");
429
- const tags = { ...Tagged.preserve(TAG_POSITIVE_BIGNUM, TAG_NEGATIVE_BIGNUM) };
430
- const decoded = decode(bytes.subarray(SELF_DESCRIBE_PREFIX.length), {
664
+ const plainInput = toPlainBytes(bytes);
665
+ if (!plainInput || plainInput.byteLength < 3 || plainInput[0] !== SELF_DESCRIBE_PREFIX[0] || plainInput[1] !== SELF_DESCRIBE_PREFIX[1] || plainInput[2] !== SELF_DESCRIBE_PREFIX[2]) throw new Error("canonical-cbor: missing self-describe tag 55799 prefix");
666
+ const tags = {
667
+ [TAG_POSITIVE_BIGNUM]: createCanonicalBignumTagDecoder(TAG_POSITIVE_BIGNUM),
668
+ [TAG_NEGATIVE_BIGNUM]: createCanonicalBignumTagDecoder(TAG_NEGATIVE_BIGNUM)
669
+ };
670
+ const subBytes = new Uint8Array(plainInput.buffer, plainInput.byteOffset + SELF_DESCRIBE_PREFIX.length, plainInput.byteLength - SELF_DESCRIBE_PREFIX.length);
671
+ const decodeOptions = {
431
672
  tags,
432
673
  useMaps: true,
433
674
  strict: true,
434
675
  rejectDuplicateMapKeys: true,
435
- allowIndefinite: false
676
+ allowIndefinite: false,
677
+ allowUndefined: true,
678
+ allowBigInt: true
679
+ };
680
+ const tokenizer = new BoundedDepthTokenizer(subBytes, decodeOptions, MAX_CANONICAL_CBOR_DEPTH);
681
+ const decoded = decode(subBytes, {
682
+ ...decodeOptions,
683
+ tokenizer
436
684
  });
437
685
  if (!(decoded instanceof Map)) throw new Error("canonical-cbor: payload is not a CBOR map");
438
- return decodeMessageMap(type, decoded);
686
+ return decodeMessageMap(type, decoded, 1);
439
687
  }
440
688
  const CANONICAL_SELF_DESCRIBE_PREFIX = SELF_DESCRIBE_PREFIX;
441
689
 
442
690
  //#endregion
443
- export { CANONICAL_SELF_DESCRIBE_PREFIX, canonicalBytes, parseCanonical };
691
+ export { CANONICAL_SELF_DESCRIBE_PREFIX, MAX_CANONICAL_CBOR_DEPTH, canonicalBytes, parseCanonical };
package/esm/cbor.d.mts CHANGED
@@ -1,8 +1,8 @@
1
- import { CANONICAL_SELF_DESCRIBE_PREFIX, canonicalBytes, parseCanonical } from "./canonical-cbor.mjs";
1
+ import { CANONICAL_SELF_DESCRIBE_PREFIX, MAX_CANONICAL_CBOR_DEPTH, canonicalBytes, parseCanonical } from "./canonical-cbor.mjs";
2
2
 
3
3
  //#region src/cbor.d.ts
4
4
 
5
5
  declare function encodeTx(params: Record<string, unknown>): Uint8Array;
6
6
  declare function decodeTx(bytes: Uint8Array): Record<string, unknown>;
7
7
  //#endregion
8
- export { CANONICAL_SELF_DESCRIBE_PREFIX, canonicalBytes, decodeTx, encodeTx, parseCanonical };
8
+ export { CANONICAL_SELF_DESCRIBE_PREFIX, MAX_CANONICAL_CBOR_DEPTH, canonicalBytes, decodeTx, encodeTx, parseCanonical };
package/esm/cbor.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { CANONICAL_SELF_DESCRIBE_PREFIX, canonicalBytes, parseCanonical } from "./canonical-cbor.mjs";
1
+ import { CANONICAL_SELF_DESCRIBE_PREFIX, MAX_CANONICAL_CBOR_DEPTH, canonicalBytes, parseCanonical } from "./canonical-cbor.mjs";
2
2
  import "./provider-init-schema.mjs";
3
3
 
4
4
  //#region src/cbor.ts
@@ -10,4 +10,4 @@ function decodeTx(bytes) {
10
10
  }
11
11
 
12
12
  //#endregion
13
- export { CANONICAL_SELF_DESCRIBE_PREFIX, canonicalBytes, decodeTx, encodeTx, parseCanonical };
13
+ export { CANONICAL_SELF_DESCRIBE_PREFIX, MAX_CANONICAL_CBOR_DEPTH, canonicalBytes, decodeTx, encodeTx, parseCanonical };
package/esm/index.d.mts CHANGED
@@ -1,3 +1,3 @@
1
1
  import { addProvider, fromTypeUrl, getMessageType, toTypeUrl } from "./provider.mjs";
2
- import { AnyData, attachExampleFn, attachFormatFn, createMessage, decodeAny, decodeBigInt, decodeTimestamp, encodeAny, encodeBigInt, encodeTimestamp, fakeMessage, formatMessage } from "./message.mjs";
3
- export { type AnyData, addProvider, attachExampleFn, attachFormatFn, createMessage, decodeAny, decodeBigInt, decodeTimestamp, encodeAny, encodeBigInt, encodeTimestamp, fakeMessage, formatMessage, fromTypeUrl, getMessageType, toTypeUrl };
2
+ import { AnyData, FormatProblem, attachExampleFn, attachFormatFn, createMessage, decodeAny, decodeBigInt, decodeTimestamp, encodeAny, encodeBigInt, encodeTimestamp, fakeMessage, findFormatProblem, findInvalidTimestamp, formatMessage, isValidTimestamp } from "./message.mjs";
3
+ export { type AnyData, type FormatProblem, addProvider, attachExampleFn, attachFormatFn, createMessage, decodeAny, decodeBigInt, decodeTimestamp, encodeAny, encodeBigInt, encodeTimestamp, fakeMessage, findFormatProblem, findInvalidTimestamp, formatMessage, fromTypeUrl, getMessageType, isValidTimestamp, toTypeUrl };
package/esm/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { addProvider, fromTypeUrl, getMessageType, toTypeUrl } from "./provider.mjs";
2
2
  import "./patch.mjs";
3
3
  import "./provider-init.mjs";
4
- import { attachExampleFn, attachFormatFn, createMessage, decodeAny, decodeBigInt, decodeTimestamp, encodeAny, encodeBigInt, encodeTimestamp, fakeMessage, formatMessage } from "./message.mjs";
4
+ import { attachExampleFn, attachFormatFn, createMessage, decodeAny, decodeBigInt, decodeTimestamp, encodeAny, encodeBigInt, encodeTimestamp, fakeMessage, findFormatProblem, findInvalidTimestamp, formatMessage, isValidTimestamp } from "./message.mjs";
5
5
 
6
- export { addProvider, attachExampleFn, attachFormatFn, createMessage, decodeAny, decodeBigInt, decodeTimestamp, encodeAny, encodeBigInt, encodeTimestamp, fakeMessage, formatMessage, fromTypeUrl, getMessageType, toTypeUrl };
6
+ export { addProvider, attachExampleFn, attachFormatFn, createMessage, decodeAny, decodeBigInt, decodeTimestamp, encodeAny, encodeBigInt, encodeTimestamp, fakeMessage, findFormatProblem, findInvalidTimestamp, formatMessage, fromTypeUrl, getMessageType, isValidTimestamp, toTypeUrl };