@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.
package/esm/message.d.mts CHANGED
@@ -89,9 +89,25 @@ declare function encodeAny(data: AnyData | undefined): typeof Any | undefined;
89
89
  * @returns instanceof google.protobuf.Timestamp
90
90
  */
91
91
  declare function encodeTimestamp(value: string | TimestampData | undefined): typeof Timestamp | undefined;
92
+ /**
93
+ * Whether a google.protobuf.Timestamp can be turned into an ISO date string.
94
+ *
95
+ * `seconds` is an int64 on the wire while a JS Date only holds +/-8.64e15 ms, so a Timestamp can be perfectly
96
+ * valid protobuf and still have no Date (#1458). An unset Timestamp (no truthy `seconds`) is valid: it decodes
97
+ * to an empty string.
98
+ *
99
+ * @public
100
+ * @static
101
+ * @param data
102
+ * @returns false when `decodeTimestamp` has no date to return for a set Timestamp
103
+ */
104
+ declare function isValidTimestamp(data: TimestampData | undefined | null): boolean;
92
105
  /**
93
106
  * Decode google.protobuf.Timestamp message to ISO Date String
94
107
  *
108
+ * Never throws: a Timestamp outside the JS Date range decodes to an empty string, like an unset one.
109
+ * Callers that must tell the two apart (the chain does, see `findFormatProblem`) use `isValidTimestamp`.
110
+ *
95
111
  * FIXME: node strictly equal because we rounded the `nanos` field
96
112
  *
97
113
  * @public
@@ -100,6 +116,52 @@ declare function encodeTimestamp(value: string | TimestampData | undefined): typ
100
116
  * @returns String timestamp
101
117
  */
102
118
  declare function decodeTimestamp(data: TimestampData): string;
119
+ /**
120
+ * What stops `formatMessage(type, data)` from producing the JSON form of a message.
121
+ *
122
+ * - `invalid-timestamp`: a Timestamp with no ISO date string (see `isValidTimestamp`). `formatMessage` returns,
123
+ * with `''` for that field.
124
+ * - `unformattable`: `formatMessage` throws, e.g. on a `google.protobuf.Any` that names a registered message
125
+ * while its bytes are not that message (#1482). `error` is what it throws.
126
+ *
127
+ * `path` is the dotted field path, e.g. `itx.data` or `signatures.data.expiredAt`.
128
+ */
129
+ type FormatProblem = {
130
+ kind: 'invalid-timestamp';
131
+ path: string;
132
+ } | {
133
+ kind: 'unformattable';
134
+ path: string;
135
+ error: unknown;
136
+ };
137
+ /**
138
+ * Find the first thing, in field order, that keeps a message from being formatted (see `FormatProblem`).
139
+ *
140
+ * Runs the walk of `formatMessage` itself (same code), including typed `google.protobuf.Any` payloads at any
141
+ * depth, so `null` means `formatMessage(type, data)` returns and every Timestamp in its output is a date.
142
+ * Never throws.
143
+ *
144
+ * @public
145
+ * @static
146
+ * @param type - message type, e.g. `Transaction`
147
+ * @param data - message data in the shape `formatMessage` accepts
148
+ * @returns the first problem, or null when there is none
149
+ */
150
+ declare function findFormatProblem(type: string, data: Record<string, unknown>): FormatProblem | null;
151
+ /**
152
+ * Find the first Timestamp in a message that has no ISO date string (see `isValidTimestamp`).
153
+ *
154
+ * A thin wrapper over `findFormatProblem`. When the message can not be walked up to its first such Timestamp
155
+ * (unknown type, undecodable Any, ...) it throws what `formatMessage` throws: a null result always means that
156
+ * every Timestamp was looked at.
157
+ *
158
+ * @public
159
+ * @static
160
+ * @param type - message type, e.g. `Transaction`
161
+ * @param data - message data in the shape `formatMessage` accepts
162
+ * @returns dotted field path (e.g. `itx.expiredAt`), or null when there is none
163
+ */
164
+ declare function findInvalidTimestamp(type: string, data: Record<string, unknown>): string | null;
103
165
  interface BigIntProtobufMessage extends ProtobufMessage {
104
166
  setValue(v: Uint8Array): void;
105
167
  setMinus(v: boolean): void;
@@ -141,4 +203,4 @@ declare function attachFormatFn(type: string, data: Record<string, unknown>, key
141
203
  */
142
204
  declare function attachExampleFn(type: string, host: Record<string, unknown>, key: string): void;
143
205
  //#endregion
144
- export { AnyData, addProvider, attachExampleFn, attachFormatFn, createMessage, decodeAny, decodeBigInt, decodeTimestamp, encodeAny, encodeBigInt, encodeTimestamp, fakeMessage, formatMessage, fromTypeUrl, getMessageType, toTypeUrl };
206
+ export { AnyData, FormatProblem, addProvider, attachExampleFn, attachFormatFn, createMessage, decodeAny, decodeBigInt, decodeTimestamp, encodeAny, encodeBigInt, encodeTimestamp, fakeMessage, findFormatProblem, findInvalidTimestamp, formatMessage, fromTypeUrl, getMessageType, isValidTimestamp, toTypeUrl };
package/esm/message.mjs CHANGED
@@ -120,6 +120,9 @@ function fakeMessage(type) {
120
120
  * @returns object [almost same structure as input]
121
121
  */
122
122
  function formatMessage(type, data) {
123
+ return formatMessageInternal(type, data);
124
+ }
125
+ function formatMessageInternal(type, data, onInvalidTimestamp, parentPath = "", cursor) {
123
126
  if (!type) return data;
124
127
  if (["json", "vc"].includes(type)) return data;
125
128
  if (typeof data !== "object") return data;
@@ -135,12 +138,14 @@ function formatMessage(type, data) {
135
138
  }
136
139
  Object.keys(fields).forEach((key) => {
137
140
  const { type: subType, keyType, rule } = fields[key];
141
+ const path = parentPath ? `${parentPath}.${key}` : key;
142
+ if (cursor) cursor.path = path;
138
143
  let value = data[key];
139
144
  if (rule === "repeated") value = data[camelCase(`${key}_list`)] || data[key];
140
145
  if (keyType) value = data[camelCase(`${key}_map`)] || data[key];
141
146
  if (value === void 0) return;
142
147
  if (rule === "repeated") {
143
- result[key] = value.map((x) => formatMessage(subType, x));
148
+ result[key] = value.map((x) => formatMessageInternal(subType, x, onInvalidTimestamp, path, cursor));
144
149
  return;
145
150
  }
146
151
  if (keyType) {
@@ -151,7 +156,7 @@ function formatMessage(type, data) {
151
156
  value
152
157
  });
153
158
  result[key] = (value || []).reduce((acc, [k, v]) => {
154
- acc[k] = formatMessage(subType, v);
159
+ acc[k] = formatMessageInternal(subType, v, onInvalidTimestamp, path, cursor);
155
160
  return acc;
156
161
  }, {});
157
162
  return;
@@ -174,6 +179,7 @@ function formatMessage(type, data) {
174
179
  return;
175
180
  }
176
181
  if (subType === "google.protobuf.Timestamp") {
182
+ if (onInvalidTimestamp && !isValidTimestamp(value)) onInvalidTimestamp(path);
177
183
  result[key] = decodeTimestamp(value);
178
184
  return;
179
185
  }
@@ -182,13 +188,13 @@ function formatMessage(type, data) {
182
188
  const decoded = decodeAny(value);
183
189
  result[key] = {
184
190
  type: decoded.type || value.typeUrl,
185
- value: formatMessage(decoded.type || value.typeUrl || "", decoded.value)
191
+ value: formatMessageInternal(decoded.type || value.typeUrl || "", decoded.value, onInvalidTimestamp, path, cursor)
186
192
  };
187
193
  }
188
194
  return;
189
195
  }
190
196
  if (value && typeof value === "object") {
191
- result[key] = formatMessage(subType, value);
197
+ result[key] = formatMessageInternal(subType, value, onInvalidTimestamp, path, cursor);
192
198
  return;
193
199
  }
194
200
  result[key] = value;
@@ -420,9 +426,37 @@ function encodeTimestamp(value) {
420
426
  }
421
427
  return timestamp;
422
428
  }
429
+ const MAX_DATE_MS = 864e13;
430
+ /**
431
+ * Milliseconds since the epoch for a Timestamp with a truthy `seconds`, `null` when `seconds` is unset.
432
+ * `nanos` is rounded up to the next millisecond, as `decodeTimestamp` has always done.
433
+ */
434
+ function timestampToMs(data) {
435
+ if (!data?.seconds) return null;
436
+ return data.seconds * 1e3 + Math.ceil((data.nanos || 0) / 1e6);
437
+ }
438
+ /**
439
+ * Whether a google.protobuf.Timestamp can be turned into an ISO date string.
440
+ *
441
+ * `seconds` is an int64 on the wire while a JS Date only holds +/-8.64e15 ms, so a Timestamp can be perfectly
442
+ * valid protobuf and still have no Date (#1458). An unset Timestamp (no truthy `seconds`) is valid: it decodes
443
+ * to an empty string.
444
+ *
445
+ * @public
446
+ * @static
447
+ * @param data
448
+ * @returns false when `decodeTimestamp` has no date to return for a set Timestamp
449
+ */
450
+ function isValidTimestamp(data) {
451
+ const ms = timestampToMs(data);
452
+ return ms === null || Number.isFinite(ms) && Math.abs(ms) <= MAX_DATE_MS;
453
+ }
423
454
  /**
424
455
  * Decode google.protobuf.Timestamp message to ISO Date String
425
456
  *
457
+ * Never throws: a Timestamp outside the JS Date range decodes to an empty string, like an unset one.
458
+ * Callers that must tell the two apart (the chain does, see `findFormatProblem`) use `isValidTimestamp`.
459
+ *
426
460
  * FIXME: node strictly equal because we rounded the `nanos` field
427
461
  *
428
462
  * @public
@@ -431,12 +465,61 @@ function encodeTimestamp(value) {
431
465
  * @returns String timestamp
432
466
  */
433
467
  function decodeTimestamp(data) {
434
- if (data?.seconds) {
435
- const date = /* @__PURE__ */ new Date();
436
- date.setTime(data.seconds * 1e3 + Math.ceil((data.nanos || 0) / 1e6));
437
- return date.toISOString();
468
+ const ms = timestampToMs(data);
469
+ if (ms === null || !isValidTimestamp(data)) return "";
470
+ const date = /* @__PURE__ */ new Date();
471
+ date.setTime(ms);
472
+ return date.toISOString();
473
+ }
474
+ /**
475
+ * Find the first thing, in field order, that keeps a message from being formatted (see `FormatProblem`).
476
+ *
477
+ * Runs the walk of `formatMessage` itself (same code), including typed `google.protobuf.Any` payloads at any
478
+ * depth, so `null` means `formatMessage(type, data)` returns and every Timestamp in its output is a date.
479
+ * Never throws.
480
+ *
481
+ * @public
482
+ * @static
483
+ * @param type - message type, e.g. `Transaction`
484
+ * @param data - message data in the shape `formatMessage` accepts
485
+ * @returns the first problem, or null when there is none
486
+ */
487
+ function findFormatProblem(type, data) {
488
+ let problem = null;
489
+ const cursor = { path: "" };
490
+ try {
491
+ formatMessageInternal(type, data, (path) => {
492
+ if (problem === null) problem = {
493
+ kind: "invalid-timestamp",
494
+ path
495
+ };
496
+ }, "", cursor);
497
+ } catch (error) {
498
+ if (problem === null) problem = {
499
+ kind: "unformattable",
500
+ path: cursor.path,
501
+ error
502
+ };
438
503
  }
439
- return "";
504
+ return problem;
505
+ }
506
+ /**
507
+ * Find the first Timestamp in a message that has no ISO date string (see `isValidTimestamp`).
508
+ *
509
+ * A thin wrapper over `findFormatProblem`. When the message can not be walked up to its first such Timestamp
510
+ * (unknown type, undecodable Any, ...) it throws what `formatMessage` throws: a null result always means that
511
+ * every Timestamp was looked at.
512
+ *
513
+ * @public
514
+ * @static
515
+ * @param type - message type, e.g. `Transaction`
516
+ * @param data - message data in the shape `formatMessage` accepts
517
+ * @returns dotted field path (e.g. `itx.expiredAt`), or null when there is none
518
+ */
519
+ function findInvalidTimestamp(type, data) {
520
+ const problem = findFormatProblem(type, data);
521
+ if (problem?.kind === "unformattable") throw problem.error;
522
+ return problem ? problem.path : null;
440
523
  }
441
524
  /**
442
525
  * Encode BigUint and BigSint types defined in forge-sdk, double encoding is avoided
@@ -507,4 +590,4 @@ function attachExampleFn(type, host, key) {
507
590
  }
508
591
 
509
592
  //#endregion
510
- export { addProvider, attachExampleFn, attachFormatFn, createMessage, decodeAny, decodeBigInt, decodeTimestamp, encodeAny, encodeBigInt, encodeTimestamp, fakeMessage, formatMessage, fromTypeUrl, getMessageType, toTypeUrl };
593
+ export { addProvider, attachExampleFn, attachFormatFn, createMessage, decodeAny, decodeBigInt, decodeTimestamp, encodeAny, encodeBigInt, encodeTimestamp, fakeMessage, findFormatProblem, findInvalidTimestamp, formatMessage, fromTypeUrl, getMessageType, isValidTimestamp, toTypeUrl };
package/esm/patch.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import { __require } from "./_virtual/rolldown_runtime.mjs";
2
+ import "./reader-guard.mjs";
2
3
  import { require_package } from "./core/message/package.mjs";
3
4
  import assert from "assert";
4
5
  import createDebug from "debug";
@@ -0,0 +1 @@
1
+ export { };
@@ -0,0 +1,62 @@
1
+ import { __require } from "./_virtual/rolldown_runtime.mjs";
2
+
3
+ //#region src/reader-guard.ts
4
+ /**
5
+ * Bounds checks for length-prefixed fields in the `google-protobuf` binary reader.
6
+ *
7
+ * google-protobuf 3.21.0 does not compare the length a field declares with the bytes that are
8
+ * actually left, in three places:
9
+ *
10
+ * - `BinaryReader.readMessage` moves the decoder end to `cursor + declared`. The sub-message loop
11
+ * then keeps calling `nextField()` on bytes that do not exist (they read as `undefined`, i.e. a
12
+ * varint field 0), ~7 bytes per iteration, until it reaches the declared end.
13
+ * - `BinaryDecoder.readString` loops `declared` times over the same missing bytes.
14
+ * - `BinaryReader.readPackedField_` loops until `cursor + declared` and appends one array element
15
+ * per iteration, so inside an over-declared message it also allocates in proportion.
16
+ *
17
+ * A few bytes can therefore declare up to 2^32-1 and keep the event loop busy for tens of seconds
18
+ * (or exhaust memory) before the reader finally fails. See ArcBlock/blockchain#1497.
19
+ *
20
+ * The guards below reject exactly `cursor + declared > end` (and a negative message length) before
21
+ * any of that work starts. They never change a successful decode: in each of these cases the
22
+ * original reader leaves its cursor past the decoder end, and the `nextField()` that every
23
+ * generated `deserializeBinaryFromReader` loop (and `jspb.Map.deserializeBinary`) runs next throws
24
+ * on `cursor <= end` (`goog.asserts` is enabled in the published build). Inputs that decoded before
25
+ * decode to the same object; inputs rejected here could only throw, after the wasted work.
26
+ *
27
+ * This lives on the shared reader prototype instead of in front of individual `deserializeBinary`
28
+ * calls so that every decode in the process is covered, including `Any.value` payloads and map
29
+ * entries decoded later and any generated class used directly.
30
+ */
31
+ const jspb = __require("google-protobuf");
32
+ /**
33
+ * Throw when the length-delimited field at the cursor declares more bytes than are left before the
34
+ * decoder end. Reads the length the same way the wrapped method is about to, then rewinds.
35
+ */
36
+ function assertDeclaredLength(reader, rejectNegative) {
37
+ const decoder = reader.decoder_;
38
+ const cursor = decoder.getCursor();
39
+ const declared = decoder.readUnsignedVarint32();
40
+ const left = decoder.getEnd() - decoder.getCursor();
41
+ decoder.setCursor(cursor);
42
+ if (declared > left || rejectNegative && declared < 0) throw new Error(`protobuf: declared length ${declared} exceeds the ${left} bytes left in the buffer`);
43
+ }
44
+ function guard(name, rejectNegative) {
45
+ const proto = jspb.BinaryReader?.prototype;
46
+ const original = proto?.[name];
47
+ if (typeof original !== "function") throw new Error(`@ocap/message: cannot guard google-protobuf BinaryReader.${name}, the reader layout changed`);
48
+ if (original.__ocapLengthGuard__) return;
49
+ const guarded = function guardedRead(...args) {
50
+ assertDeclaredLength(this, rejectNegative);
51
+ return original.apply(this, args);
52
+ };
53
+ guarded.__ocapLengthGuard__ = true;
54
+ guarded.__original__ = original;
55
+ proto[name] = guarded;
56
+ }
57
+ guard("readMessage", true);
58
+ guard("readString", false);
59
+ guard("readPackedField_", false);
60
+
61
+ //#endregion
62
+ export { };