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