@open-e2ee/signal-protocol-sdk 0.1.0-alpha.8 → 0.1.0

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.
Files changed (205) hide show
  1. package/ADAPTERS.md +12 -12
  2. package/ARCHITECTURE.md +3 -3
  3. package/CHANGELOG.md +461 -0
  4. package/README.md +25 -15
  5. package/SECURITY.md +1 -1
  6. package/client/README.md +2 -2
  7. package/device/README.md +3 -1
  8. package/dist/client/client.d.ts +6 -6
  9. package/dist/client/client.js +6 -6
  10. package/dist/client/compose.d.ts +2 -2
  11. package/dist/client/index.d.ts +2 -2
  12. package/dist/device/expo-metadata.d.ts +26 -0
  13. package/dist/device/expo-metadata.d.ts.map +1 -0
  14. package/dist/device/expo-metadata.js +33 -0
  15. package/dist/device/expo-metadata.js.map +1 -0
  16. package/dist/device/index.d.ts +1 -1
  17. package/dist/device/index.d.ts.map +1 -1
  18. package/dist/device/index.js +5 -1
  19. package/dist/device/index.js.map +1 -1
  20. package/dist/device/provisioning.d.ts +4 -12
  21. package/dist/device/provisioning.d.ts.map +1 -1
  22. package/dist/device/provisioning.js +4 -21
  23. package/dist/device/provisioning.js.map +1 -1
  24. package/dist/index.d.ts +5 -5
  25. package/dist/index.js +5 -5
  26. package/dist/internal/crypto/symmetric/aes.d.ts.map +1 -1
  27. package/dist/internal/crypto/symmetric/aes.js +27 -30
  28. package/dist/internal/crypto/symmetric/aes.js.map +1 -1
  29. package/dist/internal/encoding/proto/primitives.d.ts +261 -6
  30. package/dist/internal/encoding/proto/primitives.d.ts.map +1 -1
  31. package/dist/internal/encoding/proto/primitives.js +468 -6
  32. package/dist/internal/encoding/proto/primitives.js.map +1 -1
  33. package/dist/internal/encoding/proto/sender-key-message.d.ts +4 -3
  34. package/dist/internal/encoding/proto/sender-key-message.d.ts.map +1 -1
  35. package/dist/internal/encoding/proto/sender-key-message.js +97 -76
  36. package/dist/internal/encoding/proto/sender-key-message.js.map +1 -1
  37. package/dist/internal/encoding/proto/signal-message.d.ts +7 -2
  38. package/dist/internal/encoding/proto/signal-message.d.ts.map +1 -1
  39. package/dist/internal/encoding/proto/signal-message.js +194 -110
  40. package/dist/internal/encoding/proto/signal-message.js.map +1 -1
  41. package/dist/internal/groups/manager.d.ts +24 -5
  42. package/dist/internal/groups/manager.d.ts.map +1 -1
  43. package/dist/internal/groups/manager.js +33 -11
  44. package/dist/internal/groups/manager.js.map +1 -1
  45. package/dist/internal/groups/server-engine.d.ts +29 -14
  46. package/dist/internal/groups/server-engine.d.ts.map +1 -1
  47. package/dist/internal/groups/server-engine.js +63 -14
  48. package/dist/internal/groups/server-engine.js.map +1 -1
  49. package/dist/internal/manager/manager.d.ts +2 -2
  50. package/dist/internal/protocol/sealed-sender/proto/index.d.ts +50 -4
  51. package/dist/internal/protocol/sealed-sender/proto/index.d.ts.map +1 -1
  52. package/dist/internal/protocol/sealed-sender/proto/index.js +273 -151
  53. package/dist/internal/protocol/sealed-sender/proto/index.js.map +1 -1
  54. package/dist/internal/protocol/spqr/ml-kem-braid/serialize.d.ts +7 -1
  55. package/dist/internal/protocol/spqr/ml-kem-braid/serialize.d.ts.map +1 -1
  56. package/dist/internal/protocol/spqr/ml-kem-braid/serialize.js +334 -151
  57. package/dist/internal/protocol/spqr/ml-kem-braid/serialize.js.map +1 -1
  58. package/dist/layers.d.ts +2 -2
  59. package/dist/layers.d.ts.map +1 -1
  60. package/dist/layers.js +2 -2
  61. package/dist/layers.js.map +1 -1
  62. package/dist/local/store/index.d.ts +3 -3
  63. package/dist/local/store/index.d.ts.map +1 -1
  64. package/dist/local/store/index.js +4 -4
  65. package/dist/local/store/index.js.map +1 -1
  66. package/dist/local/store/{mock → memory}/adapter.d.ts +10 -10
  67. package/dist/local/store/memory/adapter.d.ts.map +1 -0
  68. package/dist/local/store/{mock → memory}/adapter.js +5 -5
  69. package/dist/local/store/memory/adapter.js.map +1 -0
  70. package/dist/local/store/{mock → memory}/failures.d.ts +6 -6
  71. package/dist/local/store/memory/failures.d.ts.map +1 -0
  72. package/dist/local/store/{mock → memory}/failures.js +6 -6
  73. package/dist/local/store/memory/failures.js.map +1 -0
  74. package/dist/local/store/memory/index.d.ts +11 -0
  75. package/dist/local/store/memory/index.d.ts.map +1 -0
  76. package/dist/local/store/memory/index.js +7 -0
  77. package/dist/local/store/memory/index.js.map +1 -0
  78. package/dist/local/store/node/adapter.d.ts +53 -4
  79. package/dist/local/store/node/adapter.d.ts.map +1 -1
  80. package/dist/local/store/node/adapter.js +456 -9
  81. package/dist/local/store/node/adapter.js.map +1 -1
  82. package/dist/local/store/node/database.d.ts +68 -0
  83. package/dist/local/store/node/database.d.ts.map +1 -1
  84. package/dist/local/store/node/database.js +201 -18
  85. package/dist/local/store/node/database.js.map +1 -1
  86. package/dist/local/store/react-native/adapter.d.ts.map +1 -1
  87. package/dist/local/store/react-native/adapter.js +69 -1
  88. package/dist/local/store/react-native/adapter.js.map +1 -1
  89. package/dist/local/store/react-native/backend-conformance.d.ts +66 -0
  90. package/dist/local/store/react-native/backend-conformance.d.ts.map +1 -0
  91. package/dist/local/store/react-native/backend-conformance.js +326 -0
  92. package/dist/local/store/react-native/backend-conformance.js.map +1 -0
  93. package/dist/local/store/react-native/index.d.ts +9 -4
  94. package/dist/local/store/react-native/index.d.ts.map +1 -1
  95. package/dist/local/store/react-native/index.js +2 -0
  96. package/dist/local/store/react-native/index.js.map +1 -1
  97. package/dist/local/store/react-native/reference-backend.d.ts +42 -0
  98. package/dist/local/store/react-native/reference-backend.d.ts.map +1 -0
  99. package/dist/local/store/react-native/reference-backend.js +177 -0
  100. package/dist/local/store/react-native/reference-backend.js.map +1 -0
  101. package/dist/local/store/react-native/storage.d.ts +9 -0
  102. package/dist/local/store/react-native/storage.d.ts.map +1 -1
  103. package/dist/local/store/web/adapter.d.ts +11 -1
  104. package/dist/local/store/web/adapter.d.ts.map +1 -1
  105. package/dist/local/store/web/adapter.js +196 -33
  106. package/dist/local/store/web/adapter.js.map +1 -1
  107. package/dist/local/store/web/index.d.ts +3 -2
  108. package/dist/local/store/web/index.d.ts.map +1 -1
  109. package/dist/local/store/web/index.js.map +1 -1
  110. package/dist/local/vault/index.d.ts +5 -1
  111. package/dist/local/vault/index.d.ts.map +1 -1
  112. package/dist/local/vault/index.js +1 -1
  113. package/dist/local/vault/index.js.map +1 -1
  114. package/dist/remote/relay/convex/backend.d.ts +9 -6
  115. package/dist/remote/relay/convex/backend.d.ts.map +1 -1
  116. package/dist/remote/relay/convex/backend.js +4 -1
  117. package/dist/remote/relay/convex/backend.js.map +1 -1
  118. package/dist/remote/relay/convex/component/_generated/component.d.ts +10 -7
  119. package/dist/remote/relay/convex/component/_generated/component.d.ts.map +1 -1
  120. package/dist/remote/relay/convex/component/certificates.d.ts.map +1 -1
  121. package/dist/remote/relay/convex/component/certificates.js +26 -31
  122. package/dist/remote/relay/convex/component/certificates.js.map +1 -1
  123. package/dist/remote/relay/convex/component/cleanup.d.ts +6 -0
  124. package/dist/remote/relay/convex/component/cleanup.d.ts.map +1 -1
  125. package/dist/remote/relay/convex/component/cleanup.js +19 -0
  126. package/dist/remote/relay/convex/component/cleanup.js.map +1 -1
  127. package/dist/remote/relay/convex/component/crons.d.ts.map +1 -1
  128. package/dist/remote/relay/convex/component/crons.js +1 -0
  129. package/dist/remote/relay/convex/component/crons.js.map +1 -1
  130. package/dist/remote/relay/convex/component/groups.d.ts +9 -6
  131. package/dist/remote/relay/convex/component/groups.d.ts.map +1 -1
  132. package/dist/remote/relay/convex/component/groups.js +21 -11
  133. package/dist/remote/relay/convex/component/groups.js.map +1 -1
  134. package/dist/remote/relay/convex/component/messages.d.ts.map +1 -1
  135. package/dist/remote/relay/convex/component/messages.js +90 -16
  136. package/dist/remote/relay/convex/component/messages.js.map +1 -1
  137. package/dist/remote/relay/convex/component/schema.d.ts +15 -1
  138. package/dist/remote/relay/convex/component/schema.js +21 -0
  139. package/dist/remote/relay/convex/component/schema.js.map +1 -1
  140. package/dist/remote/relay/convex/group-server.d.ts +6 -5
  141. package/dist/remote/relay/convex/group-server.d.ts.map +1 -1
  142. package/dist/remote/relay/convex/group-server.js +14 -10
  143. package/dist/remote/relay/convex/group-server.js.map +1 -1
  144. package/dist/remote/relay/convex/relay.d.ts +2 -2
  145. package/dist/remote/relay/convex/relay.d.ts.map +1 -1
  146. package/dist/remote/relay/convex/relay.js +10 -7
  147. package/dist/remote/relay/convex/relay.js.map +1 -1
  148. package/dist/remote/relay/index.d.ts +1 -1
  149. package/dist/remote/relay/index.d.ts.map +1 -1
  150. package/dist/remote/relay/index.js +2 -2
  151. package/dist/remote/relay/index.js.map +1 -1
  152. package/dist/remote/relay/{mock → memory}/adapter.d.ts +19 -19
  153. package/dist/remote/relay/memory/adapter.d.ts.map +1 -0
  154. package/dist/remote/relay/{mock → memory}/adapter.js +24 -19
  155. package/dist/remote/relay/memory/adapter.js.map +1 -0
  156. package/dist/remote/relay/{mock → memory}/failures.d.ts +5 -5
  157. package/dist/remote/relay/memory/failures.d.ts.map +1 -0
  158. package/dist/remote/relay/{mock → memory}/failures.js +1 -1
  159. package/dist/remote/relay/memory/failures.js.map +1 -0
  160. package/dist/remote/relay/{mock → memory}/group-server.d.ts +1 -1
  161. package/dist/remote/relay/memory/group-server.d.ts.map +1 -0
  162. package/dist/remote/relay/{mock → memory}/group-server.js +1 -1
  163. package/dist/remote/relay/memory/group-server.js.map +1 -0
  164. package/dist/remote/relay/memory/index.d.ts +11 -0
  165. package/dist/remote/relay/memory/index.d.ts.map +1 -0
  166. package/dist/remote/relay/memory/index.js +7 -0
  167. package/dist/remote/relay/memory/index.js.map +1 -0
  168. package/dist/remote/relay/types.d.ts +25 -6
  169. package/dist/remote/relay/types.d.ts.map +1 -1
  170. package/dist/types/errors.d.ts +33 -0
  171. package/dist/types/errors.d.ts.map +1 -1
  172. package/dist/types/errors.js +36 -0
  173. package/dist/types/errors.js.map +1 -1
  174. package/docs/ASSURANCE.md +50 -15
  175. package/docs/CLIENT_COMPOSITION.md +3 -3
  176. package/docs/GETTING_STARTED.md +11 -11
  177. package/docs/PACKAGE_SURFACE.md +10 -8
  178. package/docs/RECIPES.md +12 -12
  179. package/local/store/README.md +98 -9
  180. package/local/store/{mock → memory}/README.md +8 -8
  181. package/local/store/node/README.md +6 -8
  182. package/local/store/react-native/README.md +34 -2
  183. package/local/store/web/README.md +30 -3
  184. package/package.json +13 -10
  185. package/remote/README.md +7 -7
  186. package/remote/relay/README.md +5 -5
  187. package/remote/relay/{mock → memory}/README.md +8 -8
  188. package/dist/local/store/mock/adapter.d.ts.map +0 -1
  189. package/dist/local/store/mock/adapter.js.map +0 -1
  190. package/dist/local/store/mock/failures.d.ts.map +0 -1
  191. package/dist/local/store/mock/failures.js.map +0 -1
  192. package/dist/local/store/mock/index.d.ts +0 -11
  193. package/dist/local/store/mock/index.d.ts.map +0 -1
  194. package/dist/local/store/mock/index.js +0 -7
  195. package/dist/local/store/mock/index.js.map +0 -1
  196. package/dist/remote/relay/mock/adapter.d.ts.map +0 -1
  197. package/dist/remote/relay/mock/adapter.js.map +0 -1
  198. package/dist/remote/relay/mock/failures.d.ts.map +0 -1
  199. package/dist/remote/relay/mock/failures.js.map +0 -1
  200. package/dist/remote/relay/mock/group-server.d.ts.map +0 -1
  201. package/dist/remote/relay/mock/group-server.js.map +0 -1
  202. package/dist/remote/relay/mock/index.d.ts +0 -11
  203. package/dist/remote/relay/mock/index.d.ts.map +0 -1
  204. package/dist/remote/relay/mock/index.js +0 -7
  205. package/dist/remote/relay/mock/index.js.map +0 -1
@@ -8,7 +8,7 @@
8
8
  *
9
9
  * @module ml-kem-braid/serialize
10
10
  */
11
- import protobuf from 'protobufjs';
11
+ import { ProtoReader, concatFields, encodeBoolField, encodeBytesField, encodeEnumField, encodeMessageField, encodeRepeatedBytesField, encodeRepeatedMessageField, encodeUint32Field, encodeUint64Field, } from '../../../encoding/proto/primitives.js';
12
12
  import { assertBraidChunkIndex, assertBraidEncoderCursor } from './chunk-domain.js';
13
13
  import { MessageType, PROTOCOL_CONSTANTS } from './types.js';
14
14
  const MAX_WIRE_INPUT_BYTES = 64 * 1024;
@@ -241,102 +241,302 @@ export function deserializeMessageBinary(bytes) {
241
241
  // =============================================================================
242
242
  // Protobuf Format Serialization
243
243
  // =============================================================================
244
- // Lazy-loaded protobuf root
245
- let protoRoot = null;
246
- let V1MsgType = null;
247
- let AuthenticatorType = null;
248
- let PolynomialEncoderType = null;
249
- let PolynomialDecoderType = null;
250
244
  /**
251
- * Initialize protobuf types (loads .proto file)
252
- */
253
- async function initProto() {
254
- if (protoRoot)
255
- return;
256
- // Use protobufjs reflection API to define types inline
257
- // This avoids file system access which may not work in all environments
258
- protoRoot = new protobuf.Root();
259
- // Define Version enum (V_0 = 0, V_1 = 1)
260
- const Version = new protobuf.Enum('Version', {
261
- V_0: 0, // Reserved; runtime requires V_1
262
- V_1: 1, // ML-KEM Braid (post-quantum)
263
- });
264
- // Define Chunk message
265
- const Chunk = new protobuf.Type('Chunk')
266
- .add(new protobuf.Field('index', 1, 'uint32'))
267
- .add(new protobuf.Field('data', 2, 'bytes'));
268
- // Define ChunkEntry message
269
- const ChunkEntry = new protobuf.Type('ChunkEntry')
270
- .add(new protobuf.Field('index', 1, 'uint32'))
271
- .add(new protobuf.Field('data', 2, 'bytes'));
272
- // Define VersionCapability message (for negotiation)
273
- const VersionCapability = new protobuf.Type('VersionCapability')
274
- .add(new protobuf.Field('maxVersion', 1, 'Version'))
275
- .add(new protobuf.Field('minVersion', 2, 'Version'));
276
- // Define V1Msg message with oneof and optional version capability
277
- const V1Msg = new protobuf.Type('V1Msg')
278
- .add(new protobuf.Field('epoch', 1, 'uint64'))
279
- .add(new protobuf.Field('index', 2, 'uint32'))
280
- .add(new protobuf.OneOf('innerMsg')
281
- .add(new protobuf.Field('hdr', 3, 'Chunk'))
282
- .add(new protobuf.Field('ek', 4, 'Chunk'))
283
- .add(new protobuf.Field('ekCt1Ack', 5, 'Chunk'))
284
- .add(new protobuf.Field('ct1Ack', 6, 'bool'))
285
- .add(new protobuf.Field('ct1', 7, 'Chunk'))
286
- .add(new protobuf.Field('ct2', 8, 'Chunk')))
287
- .add(new protobuf.Field('versionCapability', 9, 'VersionCapability'));
288
- // Define Authenticator message
289
- const Authenticator = new protobuf.Type('Authenticator')
290
- .add(new protobuf.Field('rootKey', 1, 'bytes'))
291
- .add(new protobuf.Field('macKey', 2, 'bytes'));
292
- // Define PolynomialEncoder message
293
- const PolynomialEncoder = new protobuf.Type('PolynomialEncoder')
294
- .add(new protobuf.Field('idx', 1, 'uint32'))
295
- .add(new protobuf.Field('pts', 2, 'bytes', 'repeated'))
296
- .add(new protobuf.Field('polys', 3, 'bytes', 'repeated'))
297
- .add(new protobuf.Field('messageSize', 4, 'uint32'));
298
- // Define PolynomialDecoder message
299
- const PolynomialDecoder = new protobuf.Type('PolynomialDecoder')
300
- .add(new protobuf.Field('ptsNeeded', 1, 'uint32'))
301
- .add(new protobuf.Field('polys', 2, 'uint32'))
302
- .add(new protobuf.Field('chunks', 3, 'ChunkEntry', 'repeated'))
303
- .add(new protobuf.Field('isComplete', 4, 'bool'))
304
- .add(new protobuf.Field('messageSize', 5, 'uint32'));
305
- // Add all types to root
306
- protoRoot.add(Version);
307
- protoRoot.add(Chunk);
308
- protoRoot.add(ChunkEntry);
309
- protoRoot.add(VersionCapability);
310
- protoRoot.add(V1Msg);
311
- protoRoot.add(Authenticator);
312
- protoRoot.add(PolynomialEncoder);
313
- protoRoot.add(PolynomialDecoder);
314
- // Resolve nested type references
315
- V1MsgType = protoRoot.lookupType('V1Msg');
316
- AuthenticatorType = protoRoot.lookupType('Authenticator');
317
- PolynomialEncoderType = protoRoot.lookupType('PolynomialEncoder');
318
- PolynomialDecoderType = protoRoot.lookupType('PolynomialDecoder');
245
+ * Field numbers from `proto/pq_ratchet.proto`. They are frozen: the same wire
246
+ * is read by the reference implementation, and `Authenticator`,
247
+ * `PolynomialEncoder`, and `PolynomialDecoder` are the persisted ratchet
248
+ * state, so an installed client must keep decoding what it wrote yesterday.
249
+ */
250
+ const V1MSG_FIELDS = {
251
+ epoch: 1,
252
+ index: 2,
253
+ hdr: 3,
254
+ ek: 4,
255
+ ekCt1Ack: 5,
256
+ ct1Ack: 6,
257
+ ct1: 7,
258
+ ct2: 8,
259
+ versionCapability: 9,
260
+ };
261
+ const CHUNK_FIELDS = { index: 1, data: 2 };
262
+ const VERSION_CAPABILITY_FIELDS = { maxVersion: 1, minVersion: 2 };
263
+ const AUTHENTICATOR_FIELDS = { rootKey: 1, macKey: 2 };
264
+ const POLYNOMIAL_ENCODER_FIELDS = { idx: 1, pts: 2, polys: 3, messageSize: 4 };
265
+ const POLYNOMIAL_DECODER_FIELDS = {
266
+ ptsNeeded: 1,
267
+ polys: 2,
268
+ chunks: 3,
269
+ isComplete: 4,
270
+ messageSize: 5,
271
+ };
272
+ /** `Version.V_1`; `V_0 = 0` is reserved and the runtime never emits it. */
273
+ const VERSION_V1 = 1;
274
+ /**
275
+ * The `V1Msg.inner_msg` oneof, in field order. Setting one arm clears the
276
+ * others, on encode and on decode alike: a message that arrives carrying two
277
+ * arms keeps only the last one on the wire.
278
+ */
279
+ const V1MSG_ONEOF_ARMS = ['hdr', 'ek', 'ekCt1Ack', 'ct1Ack', 'ct1', 'ct2'];
280
+ function assertProtoBytes(value, label) {
281
+ if (!(value instanceof Uint8Array)) {
282
+ throw new Error(`${label} must be a Uint8Array`);
283
+ }
284
+ }
285
+ function assertProtoUint32(value, label) {
286
+ if (!Number.isInteger(value) || value < 0 || value > 0xffffffff) {
287
+ throw new Error(`${label} must be an integer between 0 and 4294967295`);
288
+ }
289
+ }
290
+ /** Assign one oneof arm, clearing whichever sibling was set before. */
291
+ function setInnerMsg(msg, arm, value) {
292
+ for (const other of V1MSG_ONEOF_ARMS) {
293
+ delete msg[other];
294
+ }
295
+ msg[arm] = value;
296
+ }
297
+ function encodeChunk(chunk) {
298
+ const fields = [];
299
+ if (chunk.index !== undefined) {
300
+ fields.push(encodeUint32Field(CHUNK_FIELDS.index, chunk.index));
301
+ }
302
+ if (chunk.data !== undefined) {
303
+ fields.push(encodeBytesField(CHUNK_FIELDS.data, chunk.data));
304
+ }
305
+ return concatFields(...fields);
306
+ }
307
+ function decodeChunk(bytes) {
308
+ const chunk = {};
309
+ const reader = new ProtoReader(bytes);
310
+ while (reader.hasMore()) {
311
+ const { fieldNumber } = reader.readTag();
312
+ switch (fieldNumber) {
313
+ case CHUNK_FIELDS.index:
314
+ chunk.index = reader.readUint32();
315
+ break;
316
+ case CHUNK_FIELDS.data:
317
+ chunk.data = reader.readBytes();
318
+ break;
319
+ default:
320
+ reader.skipField();
321
+ }
322
+ }
323
+ return chunk;
324
+ }
325
+ function encodeVersionCapability(capability) {
326
+ const fields = [];
327
+ if (capability.maxVersion !== undefined) {
328
+ fields.push(encodeEnumField(VERSION_CAPABILITY_FIELDS.maxVersion, capability.maxVersion));
329
+ }
330
+ if (capability.minVersion !== undefined) {
331
+ fields.push(encodeEnumField(VERSION_CAPABILITY_FIELDS.minVersion, capability.minVersion));
332
+ }
333
+ return concatFields(...fields);
334
+ }
335
+ function decodeVersionCapability(bytes) {
336
+ const capability = {};
337
+ const reader = new ProtoReader(bytes);
338
+ while (reader.hasMore()) {
339
+ const { fieldNumber } = reader.readTag();
340
+ switch (fieldNumber) {
341
+ case VERSION_CAPABILITY_FIELDS.maxVersion:
342
+ capability.maxVersion = reader.readEnum();
343
+ break;
344
+ case VERSION_CAPABILITY_FIELDS.minVersion:
345
+ capability.minVersion = reader.readEnum();
346
+ break;
347
+ default:
348
+ reader.skipField();
349
+ }
350
+ }
351
+ return capability;
352
+ }
353
+ function encodeV1Msg(msg) {
354
+ const fields = [];
355
+ if (msg.epoch !== undefined) {
356
+ fields.push(encodeUint64Field(V1MSG_FIELDS.epoch, msg.epoch));
357
+ }
358
+ if (msg.index !== undefined) {
359
+ fields.push(encodeUint32Field(V1MSG_FIELDS.index, msg.index));
360
+ }
361
+ if (msg.hdr !== undefined) {
362
+ fields.push(encodeMessageField(V1MSG_FIELDS.hdr, encodeChunk(msg.hdr)));
363
+ }
364
+ if (msg.ek !== undefined) {
365
+ fields.push(encodeMessageField(V1MSG_FIELDS.ek, encodeChunk(msg.ek)));
366
+ }
367
+ if (msg.ekCt1Ack !== undefined) {
368
+ fields.push(encodeMessageField(V1MSG_FIELDS.ekCt1Ack, encodeChunk(msg.ekCt1Ack)));
369
+ }
370
+ if (msg.ct1Ack !== undefined) {
371
+ fields.push(encodeBoolField(V1MSG_FIELDS.ct1Ack, msg.ct1Ack));
372
+ }
373
+ if (msg.ct1 !== undefined) {
374
+ fields.push(encodeMessageField(V1MSG_FIELDS.ct1, encodeChunk(msg.ct1)));
375
+ }
376
+ if (msg.ct2 !== undefined) {
377
+ fields.push(encodeMessageField(V1MSG_FIELDS.ct2, encodeChunk(msg.ct2)));
378
+ }
379
+ if (msg.versionCapability !== undefined) {
380
+ fields.push(encodeMessageField(V1MSG_FIELDS.versionCapability, encodeVersionCapability(msg.versionCapability)));
381
+ }
382
+ return concatFields(...fields);
383
+ }
384
+ function decodeV1Msg(bytes) {
385
+ const msg = {};
386
+ const reader = new ProtoReader(bytes);
387
+ while (reader.hasMore()) {
388
+ const { fieldNumber } = reader.readTag();
389
+ switch (fieldNumber) {
390
+ case V1MSG_FIELDS.epoch:
391
+ msg.epoch = reader.readUint64();
392
+ break;
393
+ case V1MSG_FIELDS.index:
394
+ msg.index = reader.readUint32();
395
+ break;
396
+ case V1MSG_FIELDS.hdr:
397
+ setInnerMsg(msg, 'hdr', decodeChunk(reader.readMessage()));
398
+ break;
399
+ case V1MSG_FIELDS.ek:
400
+ setInnerMsg(msg, 'ek', decodeChunk(reader.readMessage()));
401
+ break;
402
+ case V1MSG_FIELDS.ekCt1Ack:
403
+ setInnerMsg(msg, 'ekCt1Ack', decodeChunk(reader.readMessage()));
404
+ break;
405
+ case V1MSG_FIELDS.ct1Ack:
406
+ setInnerMsg(msg, 'ct1Ack', reader.readBool());
407
+ break;
408
+ case V1MSG_FIELDS.ct1:
409
+ setInnerMsg(msg, 'ct1', decodeChunk(reader.readMessage()));
410
+ break;
411
+ case V1MSG_FIELDS.ct2:
412
+ setInnerMsg(msg, 'ct2', decodeChunk(reader.readMessage()));
413
+ break;
414
+ case V1MSG_FIELDS.versionCapability:
415
+ msg.versionCapability = decodeVersionCapability(reader.readMessage());
416
+ break;
417
+ default:
418
+ reader.skipField();
419
+ }
420
+ }
421
+ return msg;
422
+ }
423
+ function encodeAuthenticator(auth) {
424
+ const fields = [];
425
+ if (auth.rootKey !== undefined) {
426
+ fields.push(encodeBytesField(AUTHENTICATOR_FIELDS.rootKey, auth.rootKey));
427
+ }
428
+ if (auth.macKey !== undefined) {
429
+ fields.push(encodeBytesField(AUTHENTICATOR_FIELDS.macKey, auth.macKey));
430
+ }
431
+ return concatFields(...fields);
432
+ }
433
+ function decodeAuthenticator(bytes) {
434
+ const auth = {};
435
+ const reader = new ProtoReader(bytes);
436
+ while (reader.hasMore()) {
437
+ const { fieldNumber } = reader.readTag();
438
+ switch (fieldNumber) {
439
+ case AUTHENTICATOR_FIELDS.rootKey:
440
+ auth.rootKey = reader.readBytes();
441
+ break;
442
+ case AUTHENTICATOR_FIELDS.macKey:
443
+ auth.macKey = reader.readBytes();
444
+ break;
445
+ default:
446
+ reader.skipField();
447
+ }
448
+ }
449
+ return auth;
450
+ }
451
+ function encodePolynomialEncoder(state) {
452
+ const fields = [];
453
+ if (state.idx !== undefined) {
454
+ fields.push(encodeUint32Field(POLYNOMIAL_ENCODER_FIELDS.idx, state.idx));
455
+ }
456
+ fields.push(encodeRepeatedBytesField(POLYNOMIAL_ENCODER_FIELDS.pts, state.pts));
457
+ fields.push(encodeRepeatedBytesField(POLYNOMIAL_ENCODER_FIELDS.polys, state.polys));
458
+ if (state.messageSize !== undefined) {
459
+ fields.push(encodeUint32Field(POLYNOMIAL_ENCODER_FIELDS.messageSize, state.messageSize));
460
+ }
461
+ return concatFields(...fields);
462
+ }
463
+ function decodePolynomialEncoder(bytes) {
464
+ const state = { pts: [], polys: [] };
465
+ const reader = new ProtoReader(bytes);
466
+ while (reader.hasMore()) {
467
+ const { fieldNumber } = reader.readTag();
468
+ switch (fieldNumber) {
469
+ case POLYNOMIAL_ENCODER_FIELDS.idx:
470
+ state.idx = reader.readUint32();
471
+ break;
472
+ case POLYNOMIAL_ENCODER_FIELDS.pts:
473
+ state.pts.push(reader.readBytes());
474
+ break;
475
+ case POLYNOMIAL_ENCODER_FIELDS.polys:
476
+ state.polys.push(reader.readBytes());
477
+ break;
478
+ case POLYNOMIAL_ENCODER_FIELDS.messageSize:
479
+ state.messageSize = reader.readUint32();
480
+ break;
481
+ default:
482
+ reader.skipField();
483
+ }
484
+ }
485
+ return state;
486
+ }
487
+ function encodePolynomialDecoder(state) {
488
+ const fields = [];
489
+ if (state.ptsNeeded !== undefined) {
490
+ fields.push(encodeUint32Field(POLYNOMIAL_DECODER_FIELDS.ptsNeeded, state.ptsNeeded));
491
+ }
492
+ if (state.polys !== undefined) {
493
+ fields.push(encodeUint32Field(POLYNOMIAL_DECODER_FIELDS.polys, state.polys));
494
+ }
495
+ fields.push(encodeRepeatedMessageField(POLYNOMIAL_DECODER_FIELDS.chunks, state.chunks.map(encodeChunk)));
496
+ if (state.isComplete !== undefined) {
497
+ fields.push(encodeBoolField(POLYNOMIAL_DECODER_FIELDS.isComplete, state.isComplete));
498
+ }
499
+ if (state.messageSize !== undefined) {
500
+ fields.push(encodeUint32Field(POLYNOMIAL_DECODER_FIELDS.messageSize, state.messageSize));
501
+ }
502
+ return concatFields(...fields);
503
+ }
504
+ function decodePolynomialDecoder(bytes) {
505
+ const state = { chunks: [] };
506
+ const reader = new ProtoReader(bytes);
507
+ while (reader.hasMore()) {
508
+ const { fieldNumber } = reader.readTag();
509
+ switch (fieldNumber) {
510
+ case POLYNOMIAL_DECODER_FIELDS.ptsNeeded:
511
+ state.ptsNeeded = reader.readUint32();
512
+ break;
513
+ case POLYNOMIAL_DECODER_FIELDS.polys:
514
+ state.polys = reader.readUint32();
515
+ break;
516
+ case POLYNOMIAL_DECODER_FIELDS.chunks:
517
+ state.chunks.push(decodeChunk(reader.readMessage()));
518
+ break;
519
+ case POLYNOMIAL_DECODER_FIELDS.isComplete:
520
+ state.isComplete = reader.readBool();
521
+ break;
522
+ case POLYNOMIAL_DECODER_FIELDS.messageSize:
523
+ state.messageSize = reader.readUint32();
524
+ break;
525
+ default:
526
+ reader.skipField();
527
+ }
528
+ }
529
+ return state;
319
530
  }
320
531
  /**
321
532
  * Serialize a message with the ML-KEM Braid protobuf schema.
322
533
  */
323
534
  export async function serializeMessageProto(msg) {
324
535
  validateMessage(msg);
325
- await initProto();
326
- // Protobuf uses Number for uint64 (safe up to 2^53-1)
327
- // For larger values, we'd need to use protobufjs's Long type
328
- let epochValue = Number(msg.epoch);
329
- if (msg.epoch > BigInt(Number.MAX_SAFE_INTEGER)) {
330
- // Use Long from protobufjs for large values
331
- const Long = protobuf.util.Long;
332
- if (Long) {
333
- const high = Number(msg.epoch >> 32n);
334
- const low = Number(msg.epoch & 0xffffffffn);
335
- epochValue = new Long(low, high, true);
336
- }
337
- }
536
+ // Both scalars are written even at zero: the epoch and the chunk index are
537
+ // always set on the wire, never elided as proto3 defaults.
338
538
  const protoMsg = {
339
- epoch: epochValue,
539
+ epoch: msg.epoch,
340
540
  index: msg.chunkIndex ?? 0,
341
541
  };
342
542
  // Map MessageType to oneof field
@@ -370,29 +570,19 @@ export async function serializeMessageProto(msg) {
370
570
  if (msg.versionCapability) {
371
571
  assertV1VersionCapability(msg.versionCapability);
372
572
  protoMsg.versionCapability = {
373
- maxVersion: 1,
374
- minVersion: 1,
573
+ maxVersion: VERSION_V1,
574
+ minVersion: VERSION_V1,
375
575
  };
376
576
  }
377
- const errMsg = V1MsgType.verify(protoMsg);
378
- if (errMsg) {
379
- throw new Error(`Invalid message: ${errMsg}`);
380
- }
381
- const message = V1MsgType.create(protoMsg);
382
- return V1MsgType.encode(message).finish();
577
+ return encodeV1Msg(protoMsg);
383
578
  }
384
579
  /**
385
580
  * Deserialize protobuf message
386
581
  */
387
582
  export async function deserializeMessageProto(bytes) {
388
583
  assertWireInput(bytes, 'ML-KEM Braid protobuf message');
389
- await initProto();
390
- const decoded = V1MsgType.decode(bytes);
391
- const obj = V1MsgType.toObject(decoded, {
392
- longs: String, // bigint support
393
- bytes: Uint8Array,
394
- });
395
- const epoch = typeof obj.epoch === 'string' ? BigInt(obj.epoch) : BigInt(obj.epoch || 0);
584
+ const obj = decodeV1Msg(bytes);
585
+ const epoch = obj.epoch ?? 0n;
396
586
  let type = MessageType.None;
397
587
  let chunkIndex;
398
588
  let data;
@@ -447,34 +637,26 @@ export async function deserializeMessageProto(bytes) {
447
637
  * Serialize authenticator state to protobuf
448
638
  */
449
639
  export async function serializeAuthenticatorProto(auth) {
450
- await initProto();
451
- const protoMsg = {
640
+ assertProtoBytes(auth.root_key, 'Authenticator root key');
641
+ assertProtoBytes(auth.mac_key, 'Authenticator MAC key');
642
+ return encodeAuthenticator({
452
643
  rootKey: auth.root_key,
453
644
  macKey: auth.mac_key,
454
- };
455
- const errMsg = AuthenticatorType.verify(protoMsg);
456
- if (errMsg) {
457
- throw new Error(`Invalid authenticator: ${errMsg}`);
458
- }
459
- const message = AuthenticatorType.create(protoMsg);
460
- return AuthenticatorType.encode(message).finish();
645
+ });
461
646
  }
462
647
  /**
463
648
  * Deserialize protobuf authenticator state
464
649
  */
465
650
  export async function deserializeAuthenticatorProto(bytes) {
466
651
  assertWireInput(bytes, 'ML-KEM Braid authenticator protobuf');
467
- await initProto();
468
- const decoded = AuthenticatorType.decode(bytes);
469
- const obj = AuthenticatorType.toObject(decoded, { bytes: Uint8Array });
470
- const result = {
471
- root_key: obj.rootKey,
472
- mac_key: obj.macKey,
473
- };
474
- if (result.root_key?.length !== 32 || result.mac_key?.length !== 32) {
652
+ const { rootKey, macKey } = decodeAuthenticator(bytes);
653
+ if (rootKey?.length !== 32 || macKey?.length !== 32) {
475
654
  throw new Error('Authenticator keys must each contain exactly 32 bytes');
476
655
  }
477
- return result;
656
+ return {
657
+ root_key: rootKey,
658
+ mac_key: macKey,
659
+ };
478
660
  }
479
661
  // =============================================================================
480
662
  // JSON Format Serialization
@@ -626,30 +808,25 @@ export function deserializeDecoderJSON(jsonStr) {
626
808
  */
627
809
  export async function serializeEncoderProto(state) {
628
810
  assertBraidEncoderCursor(state.currentChunkIndex, 'Encoder state index');
629
- await initProto();
630
- const protoMsg = {
811
+ assertProtoUint32(state.originalDataSize, 'Encoder state message size');
812
+ for (const [position, chunk] of state.dataChunks.entries()) {
813
+ assertProtoBytes(chunk, `Encoder state evaluation point ${position}`);
814
+ }
815
+ return encodePolynomialEncoder({
631
816
  idx: state.currentChunkIndex,
632
817
  pts: state.dataChunks,
633
818
  polys: state.polynomials.map((p) => new Uint8Array(p.coefficients.flatMap((c) => [(c >> 8) & 0xff, c & 0xff]))),
634
819
  messageSize: state.originalDataSize,
635
- };
636
- const errMsg = PolynomialEncoderType.verify(protoMsg);
637
- if (errMsg) {
638
- throw new Error(`Invalid encoder state: ${errMsg}`);
639
- }
640
- const message = PolynomialEncoderType.create(protoMsg);
641
- return PolynomialEncoderType.encode(message).finish();
820
+ });
642
821
  }
643
822
  /**
644
823
  * Deserialize protobuf encoder state
645
824
  */
646
825
  export async function deserializeEncoderProto(bytes) {
647
826
  assertWireInput(bytes, 'ML-KEM Braid encoder protobuf state');
648
- await initProto();
649
- const decoded = PolynomialEncoderType.decode(bytes);
650
- const obj = PolynomialEncoderType.toObject(decoded, { bytes: Uint8Array });
827
+ const obj = decodePolynomialEncoder(bytes);
651
828
  // Convert polys back to coefficient arrays
652
- const polys = (obj.polys || []).map((polyBytes) => {
829
+ const polys = obj.polys.map((polyBytes) => {
653
830
  const coeffs = [];
654
831
  for (let i = 0; i < polyBytes.length; i += 2) {
655
832
  coeffs.push((polyBytes[i] << 8) | polyBytes[i + 1]);
@@ -669,40 +846,40 @@ export async function deserializeEncoderProto(bytes) {
669
846
  * Serialize decoder state to protobuf
670
847
  */
671
848
  export async function serializeDecoderProto(state) {
672
- await initProto();
673
849
  const chunks = [];
674
850
  for (const [index, data] of state.receivedChunks) {
675
851
  assertBraidChunkIndex(index, 'Decoder chunk index');
852
+ assertProtoBytes(data, `Decoder chunk ${index} data`);
676
853
  chunks.push({ index, data });
677
854
  }
678
- const protoMsg = {
855
+ assertProtoUint32(state.config.dataChunks, 'Decoder state points needed');
856
+ assertProtoUint32(state.messageSize, 'Decoder state message size');
857
+ return encodePolynomialDecoder({
679
858
  ptsNeeded: state.config.dataChunks,
680
859
  polys: 16,
681
860
  chunks,
682
861
  isComplete: state.receivedChunks.size >= state.config.dataChunks,
683
862
  messageSize: state.messageSize,
684
- };
685
- const errMsg = PolynomialDecoderType.verify(protoMsg);
686
- if (errMsg) {
687
- throw new Error(`Invalid decoder state: ${errMsg}`);
688
- }
689
- const message = PolynomialDecoderType.create(protoMsg);
690
- return PolynomialDecoderType.encode(message).finish();
863
+ });
691
864
  }
692
865
  /**
693
866
  * Deserialize protobuf decoder state
694
867
  */
695
868
  export async function deserializeDecoderProto(bytes) {
696
869
  assertWireInput(bytes, 'ML-KEM Braid decoder protobuf state');
697
- await initProto();
698
- const decoded = PolynomialDecoderType.decode(bytes);
699
- const obj = PolynomialDecoderType.toObject(decoded, { bytes: Uint8Array });
870
+ const obj = decodePolynomialDecoder(bytes);
700
871
  const chunks = new Map();
701
- for (const chunk of obj.chunks || []) {
872
+ for (const chunk of obj.chunks) {
702
873
  const index = assertBraidChunkIndex(chunk.index, 'Decoder chunk index');
703
874
  if (chunks.has(index)) {
704
875
  throw new Error(`Decoder state contains duplicate chunk index ${index}`);
705
876
  }
877
+ // A chunk entry with no data field at all is malformed state. The
878
+ // reflection codec used to admit it and put `undefined` in the map, which
879
+ // surfaced as a failure inside the Reed-Solomon decoder instead of here.
880
+ if (chunk.data === undefined) {
881
+ throw new Error(`Decoder state chunk ${index} is missing its data`);
882
+ }
706
883
  chunks.set(index, chunk.data);
707
884
  }
708
885
  return {
@@ -717,15 +894,21 @@ export async function deserializeDecoderProto(bytes) {
717
894
  // Initialization
718
895
  // =============================================================================
719
896
  /**
720
- * Initialize serialization module (loads protobuf)
897
+ * Initialize serialization module.
898
+ *
899
+ * Nothing is loaded any more — the codecs above are static functions, so there
900
+ * is no schema to build at runtime and no first-call latency to pay. Kept, and
901
+ * kept async, because callers await it before serializing.
721
902
  */
722
903
  export async function initSerialization() {
723
- await initProto();
904
+ return Promise.resolve();
724
905
  }
725
906
  /**
726
907
  * Check if serialization is ready
908
+ *
909
+ * Always true: with static codecs there is no state that could be missing.
727
910
  */
728
911
  export function isSerializationReady() {
729
- return protoRoot !== null;
912
+ return true;
730
913
  }
731
914
  //# sourceMappingURL=serialize.js.map