@ocap/message 1.31.1 → 1.31.3

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