space-data-module-sdk 0.13.1 → 0.14.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 (72) hide show
  1. package/bin/space-data-module.js +2 -1
  2. package/docs/_shell/consumer-assets.html +1 -1
  3. package/docs/assets/sdn-chrome/sdn-chrome.js +7 -3
  4. package/docs/assets/vendor/sdn-stack-nav/{1.2.0/sdn-stack-nav.ba268c55a1551bcacc390ac01347c319335a1660787b55b4b239df00fc3c1a4c.js → 1.3.0/sdn-stack-nav.2e5d4efc654388c85b79e53b1b148268e4083d9252f2a367ea257ccb50d270cd.js} +5 -0
  5. package/docs/browser-wasmedge-isomorphic.html +1 -1
  6. package/docs/byo-wasm-quickstart.html +1 -1
  7. package/docs/conformance.html +1 -1
  8. package/docs/events-abi.html +1 -1
  9. package/docs/families/analytics.html +1 -1
  10. package/docs/families/attitude.html +1 -1
  11. package/docs/families/behavior.html +1 -1
  12. package/docs/families/breakup.html +1 -1
  13. package/docs/families/conjunction.html +1 -1
  14. package/docs/families/data-source.html +2 -2
  15. package/docs/families/effects.html +1 -1
  16. package/docs/families/environment.html +1 -1
  17. package/docs/families/estimation.html +1 -1
  18. package/docs/families/gnc.html +1 -1
  19. package/docs/families/maneuver.html +1 -1
  20. package/docs/families/obstruction.html +1 -1
  21. package/docs/families/propagator.html +1 -1
  22. package/docs/families/propulsion.html +1 -1
  23. package/docs/families/reentry.html +1 -1
  24. package/docs/families/rf.html +1 -1
  25. package/docs/families/scheduler.html +1 -1
  26. package/docs/families/sensor.html +1 -1
  27. package/docs/families/signature.html +1 -1
  28. package/docs/flatsql-host-contract.html +1 -1
  29. package/docs/flatsql-streaming-standard.html +1 -1
  30. package/docs/gpu-module-abi.html +1 -1
  31. package/docs/index.html +1 -1
  32. package/docs/isomorphic-pthreads.html +1 -1
  33. package/docs/isomorphic-sdn-runtime-plan.html +1 -1
  34. package/docs/language-runtime-matrix.html +1 -1
  35. package/docs/module-bundle-runtime-plan.html +1 -1
  36. package/docs/module-publication-standard.html +10 -7
  37. package/docs/module-publication-standard.md +25 -11
  38. package/docs/node-red-default-node-parity.html +1 -1
  39. package/docs/protect-and-sign.html +9 -7
  40. package/docs/protect-and-sign.md +39 -9
  41. package/docs/protocol-installation.html +1 -1
  42. package/docs/provider-access-abi.md +7 -1
  43. package/docs/publication-submission.html +1 -1
  44. package/docs/secrets-capability.html +1 -1
  45. package/docs/testing-harness.html +1 -1
  46. package/docs/tri-runtime-parity-gate.html +1 -1
  47. package/docs/tri-runtime-parity.html +1 -1
  48. package/package.json +4 -4
  49. package/src/bundle/sdkTestSigner.js +41 -0
  50. package/src/bundle/sigdomain.js +2 -2
  51. package/src/bundle/signing.js +214 -36
  52. package/src/compiler/compileModule.js +4 -2
  53. package/src/flow/flowCompiler.js +7 -4
  54. package/src/generated/spacedatastandards/plg/PLG.d.ts +15 -3
  55. package/src/generated/spacedatastandards/plg/PLG.d.ts.map +1 -1
  56. package/src/generated/spacedatastandards/plg/PLG.js +18 -6
  57. package/src/generated/spacedatastandards/plg/PLG.ts +31 -6
  58. package/src/host/browserHost.js +56 -6
  59. package/src/host/hostWorkerBundleSources.js +3 -3
  60. package/src/host/nodeHost.js +60 -3
  61. package/src/host/providerAccessAbi.js +17 -3
  62. package/src/host/providerAccessFixtureAdapter.js +14 -4
  63. package/src/host/providerAccessTileStoreAdapter.js +5 -1
  64. package/src/index.d.ts +61 -12
  65. package/src/licensing/records.js +18 -0
  66. package/src/manifest/plgCodec.js +22 -0
  67. package/src/transport/index.js +7 -0
  68. package/src/transport/pki.js +331 -172
  69. package/src/transport/records.js +98 -24
  70. package/src/utils/encoding.js +57 -2
  71. package/src/utils/wasmCrypto.js +187 -0
  72. /package/docs/assets/vendor/sdn-stack-nav/{1.2.0 → 1.3.0}/sdn-stack-nav.36a36359ce18322185e9ff179f88175bab67d5ad84a14d9c08a54f2ff27267e7.css +0 -0
@@ -11,10 +11,17 @@ import {
11
11
  import {
12
12
  aesGcmDecrypt,
13
13
  aesGcmEncrypt,
14
+ generateX25519Mlkem768Keypair as generateHybridKeypair,
14
15
  hkdfBytes,
16
+ MLKEM768_CIPHERTEXT_SIZE,
15
17
  randomBytes,
18
+ X25519_MLKEM768_PUBLIC_KEY_SIZE,
19
+ X25519_MLKEM768_SEED_SIZE,
20
+ X25519_MLKEM768_SHARED_SECRET_SIZE,
21
+ X25519_MLKEM768_X25519_SIZE,
22
+ x25519Mlkem768Decapsulate,
23
+ x25519Mlkem768Encapsulate,
16
24
  x25519PublicKey,
17
- x25519SharedSecret,
18
25
  } from "../utils/wasmCrypto.js";
19
26
  import {
20
27
  appendPublicationRecordCollection,
@@ -23,100 +30,178 @@ import {
23
30
  encodeEncRecord,
24
31
  encodePublicationRecordCollection,
25
32
  extractPublicationRecordCollection,
33
+ PROTECTED_DELIVERY_SCHEME,
34
+ REMOVED_PROTECTED_DELIVERY_SCHEMES,
26
35
  } from "./records.js";
27
36
 
37
+ /**
38
+ * Protected module delivery is post-quantum hybrid only
39
+ * (DigitalArsenal/spacedatanetwork-stack#1628, zero backward compatibility):
40
+ *
41
+ * X-Wing(X25519 + ML-KEM-768) -> HKDF-SHA256(ss, salt = "", info = context)
42
+ * -> AES-256-GCM(nonce = NONCE_START,
43
+ * aad = $ENC without AUTH_TAG)
44
+ *
45
+ * The $ENC 1.0.3 record carries KEY_EXCHANGE X25519_MLKEM768,
46
+ * EPHEMERAL_PUBLIC_KEY (32 B X25519), KEM_CIPHERTEXT (1088 B ML-KEM-768),
47
+ * SYMMETRIC AES_256_GCM, KEY_DERIVATION HKDF_SHA256 and AUTH_TAG (16 B). The
48
+ * payload before the $REC trailer is the GCM ciphertext alone.
49
+ *
50
+ * A classical X25519-only envelope (KEY_EXCHANGE X25519, or the removed
51
+ * "x25519-hkdf-aes-256-gcm[-rec]" schemes) is REFUSED by name
52
+ * (`classical_delivery_refused`), never decrypted.
53
+ */
54
+ export const MARKETPLACE_KEY_WRAP_ALGORITHM =
55
+ "X25519-MLKEM768-HKDF-SHA256-AES-256-GCM-KMF";
56
+ const REMOVED_MARKETPLACE_KEY_WRAP_ALGORITHMS = Object.freeze([
57
+ "X25519-HKDF-SHA256-AES-256-GCM-KMF",
58
+ ]);
28
59
  const GCM_TAG_LENGTH = 16;
29
60
 
30
- // The authenticated payload layout is ciphertext || 16-byte GCM tag. The ENC
31
- // FlatBuffer schema has no dedicated tag field, so the tag travels appended to
32
- // the ciphertext, mirroring the packed layout already used by the legacy
33
- // salt-based envelope format.
34
- function splitGcmPayload(payloadBytes) {
35
- const payload = toUint8Array(payloadBytes);
36
- if (payload.length < GCM_TAG_LENGTH) {
37
- throw new Error("AES-256-GCM protected payload is truncated.");
61
+ export class ProtectedDeliveryError extends Error {
62
+ constructor(code, message) {
63
+ super(message);
64
+ this.name = "ProtectedDeliveryError";
65
+ this.code = code;
38
66
  }
39
- return {
40
- ciphertext: payload.subarray(0, payload.length - GCM_TAG_LENGTH),
41
- tag: payload.subarray(payload.length - GCM_TAG_LENGTH),
42
- };
43
67
  }
44
68
 
45
- function assertGcmEncRecord(enc) {
46
- if (enc?.symmetric !== "AES_256_GCM") {
47
- throw new Error(
48
- `Unsupported ENC symmetric algorithm "${enc?.symmetric}"; only AES_256_GCM is supported.`,
69
+ function refuseClassical(label, what) {
70
+ return new ProtectedDeliveryError(
71
+ "classical_delivery_refused",
72
+ `${label}: ${what} is classical X25519-only; space-data-module-sdk 0.14.0 delivers protected modules only under ${PROTECTED_DELIVERY_SCHEME} (hybrid X25519 + ML-KEM-768). Re-encrypt to the recipient's 1216-byte hybrid public key.`,
73
+ );
74
+ }
75
+
76
+ // The ENC record is the GCM AAD, minus the AUTH_TAG it will carry: every
77
+ // delivery parameter (key exchange, X25519 ephemeral key, ML-KEM ciphertext,
78
+ // nonce, context, recipient key id, schema hash, root type, timestamp) is
79
+ // authenticated alongside the ciphertext. encodeEncRecord() is deterministic
80
+ // for a normalized record, so the decrypt path recomputes identical bytes.
81
+ function encRecordAad(enc) {
82
+ return encodeEncRecord({ ...enc, authTag: null });
83
+ }
84
+
85
+ function assertHybridEncRecord(label, enc) {
86
+ if (!enc) {
87
+ throw new ProtectedDeliveryError("missing_enc_record", `${label}: no $ENC record.`);
88
+ }
89
+ if (enc.keyExchange === "X25519") {
90
+ throw refuseClassical(label, "the $ENC record's KEY_EXCHANGE (X25519)");
91
+ }
92
+ if (enc.keyExchange !== "X25519_MLKEM768") {
93
+ throw new ProtectedDeliveryError(
94
+ "unsupported_key_exchange",
95
+ `${label}: unsupported $ENC KEY_EXCHANGE "${enc.keyExchange}"; protected modules use X25519_MLKEM768.`,
96
+ );
97
+ }
98
+ if (enc.symmetric !== "AES_256_GCM") {
99
+ throw new ProtectedDeliveryError(
100
+ "unsupported_symmetric_algorithm",
101
+ `${label}: unsupported $ENC SYMMETRIC "${enc.symmetric}"; only AES_256_GCM is supported.`,
102
+ );
103
+ }
104
+ if (enc.keyDerivation !== "HKDF_SHA256") {
105
+ throw new ProtectedDeliveryError(
106
+ "unsupported_key_derivation",
107
+ `${label}: unsupported $ENC KEY_DERIVATION "${enc.keyDerivation}"; this SDK derives with HKDF_SHA256.`,
49
108
  );
50
109
  }
110
+ if (enc.ephemeralPublicKey?.length !== X25519_MLKEM768_X25519_SIZE) {
111
+ throw new ProtectedDeliveryError("invalid_enc_record", `${label}: X25519 ephemeral public key must be 32 bytes.`);
112
+ }
113
+ if (enc.kemCiphertext?.length !== MLKEM768_CIPHERTEXT_SIZE) {
114
+ throw new ProtectedDeliveryError("invalid_enc_record", `${label}: ML-KEM-768 ciphertext must be ${MLKEM768_CIPHERTEXT_SIZE} bytes.`);
115
+ }
116
+ if (enc.authTag?.length !== GCM_TAG_LENGTH) {
117
+ throw new ProtectedDeliveryError("invalid_enc_record", `${label}: AES-256-GCM AUTH_TAG must be ${GCM_TAG_LENGTH} bytes.`);
118
+ }
119
+ if (enc.nonceStart?.length !== 12) {
120
+ throw new ProtectedDeliveryError("invalid_enc_record", `${label}: NONCE_START must be 12 bytes.`);
121
+ }
51
122
  }
52
123
 
53
- function normalizePublicKey(value) {
124
+ function normalizeKeyBytes(value) {
54
125
  if (typeof value === "string") {
55
126
  return hexToBytes(value);
56
127
  }
57
128
  return toUint8Array(value);
58
129
  }
59
130
 
60
- function normalizePrivateKey(value) {
61
- if (typeof value === "string") {
62
- return hexToBytes(value);
131
+ function normalizeRecipientPublicKey(label, value) {
132
+ const publicKey = normalizeKeyBytes(value);
133
+ if (publicKey.length === X25519_MLKEM768_X25519_SIZE) {
134
+ throw refuseClassical(label, "the 32-byte recipient public key");
63
135
  }
64
- return toUint8Array(value);
136
+ if (publicKey.length !== X25519_MLKEM768_PUBLIC_KEY_SIZE) {
137
+ throw new ProtectedDeliveryError(
138
+ "invalid_recipient_public_key",
139
+ `${label}: recipient public key must be ${X25519_MLKEM768_PUBLIC_KEY_SIZE} bytes (32 B X25519 || 1184 B ML-KEM-768), got ${publicKey.length}.`,
140
+ );
141
+ }
142
+ return publicKey;
65
143
  }
66
144
 
67
- async function deriveSharedSecret(privateKey, publicKey) {
68
- return x25519SharedSecret(
69
- normalizePrivateKey(privateKey),
70
- normalizePublicKey(publicKey),
71
- );
145
+ function normalizeRecipientSeed(label, value) {
146
+ const seed = normalizeKeyBytes(value);
147
+ if (seed.length === X25519_MLKEM768_X25519_SIZE) {
148
+ throw refuseClassical(label, "the 32-byte recipient private key");
149
+ }
150
+ if (seed.length !== X25519_MLKEM768_SEED_SIZE) {
151
+ throw new ProtectedDeliveryError(
152
+ "invalid_recipient_private_key",
153
+ `${label}: recipient private key must be the ${X25519_MLKEM768_SEED_SIZE}-byte hybrid seed (X25519 sk || ML-KEM-768 d || z), got ${seed.length}.`,
154
+ );
155
+ }
156
+ return seed;
72
157
  }
73
158
 
74
- async function deriveAesKey(sharedSecret, salt, context) {
159
+ async function deriveAesKey(sharedSecret, context) {
75
160
  return hkdfBytes(
76
161
  sharedSecret,
77
- salt,
162
+ new Uint8Array(0),
78
163
  new TextEncoder().encode(context),
79
164
  32,
80
165
  );
81
166
  }
82
167
 
83
- // SAW-M3: the recipient's raw private scalar never has to enter this module.
84
- // A caller (e.g. a browser session backed by hd-wallet-wasm) may supply a
85
- // `keyAgreement` provider that performs step 1 (the X25519 ECDH, the ONLY
86
- // step that needs the scalar) behind its own custody boundary and resolves
87
- // the 32-byte shared secret. Steps 2-3 (HKDF derive, AES-GCM) stay here —
88
- // public math, curve-agnostic, not duplicated into the wallet.
89
- function keyExchangeFromAlgorithm(algorithm) {
90
- if (typeof algorithm !== "string" || !algorithm.length) {
91
- return "X25519";
92
- }
93
- return algorithm.split("-")[0] || "X25519";
94
- }
95
-
168
+ // The recipient's hybrid seed never has to enter this module: a caller (a
169
+ // browser session backed by hd-wallet-wasm, a host keyslot) may supply a
170
+ // `keyDecapsulation` provider that performs the X-Wing decapsulation (the
171
+ // ONLY step that needs the seed) behind its own custody boundary and resolves
172
+ // the 32-byte shared secret. HKDF and AES-GCM stay here.
96
173
  async function resolveSharedSecret(
97
174
  label,
98
- { recipientPrivateKey, keyAgreement, ephemeralPublicKey, context, keyExchange },
175
+ { recipientPrivateKey, keyDecapsulation, ephemeralPublicKey, kemCiphertext, context },
99
176
  ) {
100
- if (recipientPrivateKey && keyAgreement) {
177
+ if (recipientPrivateKey && keyDecapsulation) {
101
178
  throw new Error(
102
- `${label} accepts either recipientPrivateKey or keyAgreement, not both.`,
179
+ `${label} accepts either recipientPrivateKey or keyDecapsulation, not both.`,
103
180
  );
104
181
  }
105
- if (keyAgreement) {
182
+ if (keyDecapsulation) {
106
183
  const sharedSecret = toUint8Array(
107
- await keyAgreement({ ephemeralPublicKey, context, keyExchange }),
184
+ await keyDecapsulation({
185
+ keyExchange: "X25519_MLKEM768",
186
+ x25519EphemeralPublicKey: ephemeralPublicKey,
187
+ kemCiphertext,
188
+ context,
189
+ }),
108
190
  );
109
- if (sharedSecret.length !== 32) {
191
+ if (sharedSecret.length !== X25519_MLKEM768_SHARED_SECRET_SIZE) {
110
192
  throw new Error(
111
- `${label} keyAgreement provider must resolve a 32-byte shared secret.`,
193
+ `${label} keyDecapsulation provider must resolve a 32-byte shared secret.`,
112
194
  );
113
195
  }
114
196
  return sharedSecret;
115
197
  }
116
198
  if (!recipientPrivateKey) {
117
- throw new Error(`${label} requires recipientPrivateKey or keyAgreement.`);
199
+ throw new Error(`${label} requires recipientPrivateKey or keyDecapsulation.`);
118
200
  }
119
- return deriveSharedSecret(recipientPrivateKey, ephemeralPublicKey);
201
+ return x25519Mlkem768Decapsulate(
202
+ normalizeRecipientSeed(label, recipientPrivateKey),
203
+ { x25519EphemeralPublicKey: ephemeralPublicKey, kemCiphertext },
204
+ );
120
205
  }
121
206
 
122
207
  function normalizeOptionalBytes(value) {
@@ -243,6 +328,11 @@ function decodeContentKeyMaterial(bytes) {
243
328
  return new Uint8Array(keyBytes);
244
329
  }
245
330
 
331
+ /**
332
+ * A raw X25519 keypair. Classical key agreement for host crypto operations;
333
+ * it is NOT a protected-module delivery key (see
334
+ * {@link generateX25519Mlkem768Keypair}).
335
+ */
246
336
  export async function generateX25519Keypair() {
247
337
  const privateKey = await randomBytes(32);
248
338
  const publicKey = await x25519PublicKey(privateKey);
@@ -252,13 +342,23 @@ export async function generateX25519Keypair() {
252
342
  };
253
343
  }
254
344
 
345
+ /**
346
+ * A protected-delivery recipient keypair: `privateKey` is the 96-byte hybrid
347
+ * seed (X25519 sk || ML-KEM-768 d || z), `publicKey` the 1216-byte hybrid
348
+ * public key (32 B X25519 || 1184 B ML-KEM-768).
349
+ */
350
+ export async function generateX25519Mlkem768Keypair() {
351
+ const { seed, publicKey } = await generateHybridKeypair();
352
+ return { privateKey: seed, publicKey };
353
+ }
354
+
255
355
  export async function protectMarketplaceContent({
256
356
  plaintext,
257
357
  artifact,
258
358
  recipients = [],
259
359
  contentKey = null,
260
360
  contentNonce = null,
261
- providerWrapKeyPair = null,
361
+ encapsulationSeed = null,
262
362
  wrapNonce = null,
263
363
  } = {}) {
264
364
  if (!Array.isArray(recipients) || recipients.length === 0) {
@@ -282,8 +382,10 @@ export async function protectMarketplaceContent({
282
382
  );
283
383
  const wrappedKeys = [];
284
384
  for (const recipient of recipients) {
285
- const sender = providerWrapKeyPair ?? (await generateX25519Keypair());
286
- const recipientPublicKey = normalizePublicKey(recipient.publicKey);
385
+ const recipientPublicKey = normalizeRecipientPublicKey(
386
+ "protectMarketplaceContent",
387
+ recipient.publicKey,
388
+ );
287
389
  const wrapIv = wrapNonce ? toUint8Array(wrapNonce) : await randomBytes(12);
288
390
  if (wrapIv.length !== 12) {
289
391
  throw new Error("AES-256-GCM key wrapping requires a 12-byte nonce.");
@@ -291,14 +393,14 @@ export async function protectMarketplaceContent({
291
393
  const wrapAad = createWrapAad({
292
394
  artifact: binding,
293
395
  recipient,
294
- algorithm: "X25519-HKDF-SHA256-AES-256-GCM-KMF",
396
+ algorithm: MARKETPLACE_KEY_WRAP_ALGORITHM,
295
397
  });
296
- const sharedSecret = await deriveSharedSecret(
297
- sender.privateKey,
398
+ const encapsulation = await x25519Mlkem768Encapsulate(
298
399
  recipientPublicKey,
400
+ encapsulationSeed,
299
401
  );
300
402
  const wrapContext = `marketplace-content-key:${binding.providerId}:${binding.contentKeyId}:${recipient.recipientKeyId}`;
301
- const wrapKey = await deriveAesKey(sharedSecret, new Uint8Array(0), wrapContext);
403
+ const wrapKey = await deriveAesKey(encapsulation.sharedSecret, wrapContext);
302
404
  const keyMaterial = encodeContentKeyMaterial({
303
405
  keyId: binding.contentKeyId,
304
406
  keyBytes,
@@ -306,7 +408,7 @@ export async function protectMarketplaceContent({
306
408
  });
307
409
  const wrapped = await aesGcmEncrypt(wrapKey, keyMaterial, wrapIv, wrapAad);
308
410
  wrappedKeys.push({
309
- algorithm: "X25519-HKDF-SHA256-AES-256-GCM-KMF",
411
+ algorithm: MARKETPLACE_KEY_WRAP_ALGORITHM,
310
412
  contentKeyId: binding.contentKeyId,
311
413
  recipientPeerId: normalizeRequiredString(
312
414
  recipient.recipientPeerId,
@@ -321,7 +423,8 @@ export async function protectMarketplaceContent({
321
423
  grantId: normalizeRequiredString(recipient.grantId, "recipient.grantId"),
322
424
  scope: normalizeRequiredString(recipient.scope, "recipient.scope"),
323
425
  expiresAtMs: Number(recipient.expiresAtMs ?? 0),
324
- providerEphemeralPublicKey: sender.publicKey,
426
+ providerEphemeralPublicKey: encapsulation.x25519EphemeralPublicKey,
427
+ kemCiphertext: encapsulation.kemCiphertext,
325
428
  nonce: wrapIv,
326
429
  aad: wrapAad,
327
430
  ciphertext: wrapped.ciphertext,
@@ -347,23 +450,35 @@ export async function protectMarketplaceContent({
347
450
  export async function decryptMarketplaceContentKeyWrap({
348
451
  wrap,
349
452
  recipientPrivateKey,
350
- keyAgreement,
453
+ keyDecapsulation,
351
454
  } = {}) {
352
455
  if (!wrap) {
353
456
  throw new Error("decryptMarketplaceContentKeyWrap requires wrap.");
354
457
  }
458
+ if (REMOVED_MARKETPLACE_KEY_WRAP_ALGORITHMS.includes(wrap.algorithm)) {
459
+ throw refuseClassical(
460
+ "decryptMarketplaceContentKeyWrap",
461
+ `the key wrap algorithm "${wrap.algorithm}"`,
462
+ );
463
+ }
464
+ if (wrap.algorithm !== MARKETPLACE_KEY_WRAP_ALGORITHM) {
465
+ throw new ProtectedDeliveryError(
466
+ "unsupported_key_wrap_algorithm",
467
+ `decryptMarketplaceContentKeyWrap: unsupported key wrap algorithm "${wrap.algorithm}"; expected ${MARKETPLACE_KEY_WRAP_ALGORITHM}.`,
468
+ );
469
+ }
355
470
  const wrapContext = `marketplace-content-key:${wrap.providerId}:${wrap.contentKeyId}:${wrap.recipientKeyId}`;
356
471
  const sharedSecret = await resolveSharedSecret(
357
472
  "decryptMarketplaceContentKeyWrap",
358
473
  {
359
474
  recipientPrivateKey,
360
- keyAgreement,
361
- ephemeralPublicKey: wrap.providerEphemeralPublicKey,
475
+ keyDecapsulation,
476
+ ephemeralPublicKey: toUint8Array(wrap.providerEphemeralPublicKey),
477
+ kemCiphertext: toUint8Array(wrap.kemCiphertext ?? []),
362
478
  context: wrapContext,
363
- keyExchange: keyExchangeFromAlgorithm(wrap.algorithm),
364
479
  },
365
480
  );
366
- const wrapKey = await deriveAesKey(sharedSecret, new Uint8Array(0), wrapContext);
481
+ const wrapKey = await deriveAesKey(sharedSecret, wrapContext);
367
482
  const keyMaterial = await aesGcmDecrypt(
368
483
  wrapKey,
369
484
  wrap.ciphertext,
@@ -374,117 +489,95 @@ export async function decryptMarketplaceContentKeyWrap({
374
489
  return decodeContentKeyMaterial(keyMaterial);
375
490
  }
376
491
 
377
- async function encryptBytesLegacy({
378
- plaintext,
379
- recipientPublicKey,
380
- context = "space-data-module-sdk/package",
381
- senderKeyPair = null,
382
- } = {}) {
383
- const sender = senderKeyPair ?? (await generateX25519Keypair());
384
- const salt = await randomBytes(32);
385
- const iv = await randomBytes(12);
386
- const sharedSecret = await deriveSharedSecret(
387
- sender.privateKey,
388
- recipientPublicKey,
389
- );
390
- const aesKey = await deriveAesKey(sharedSecret, salt, context);
391
- const { ciphertext, tag } = await aesGcmEncrypt(
492
+ async function decryptWithEncRecord(label, { enc, ciphertext, recipientPrivateKey, keyDecapsulation }) {
493
+ assertHybridEncRecord(label, enc);
494
+ const sharedSecret = await resolveSharedSecret(label, {
495
+ recipientPrivateKey,
496
+ keyDecapsulation,
497
+ ephemeralPublicKey: enc.ephemeralPublicKey,
498
+ kemCiphertext: enc.kemCiphertext,
499
+ context: enc.context ?? "",
500
+ });
501
+ const aesKey = await deriveAesKey(sharedSecret, enc.context ?? "");
502
+ return aesGcmDecrypt(
392
503
  aesKey,
393
- toUint8Array(plaintext),
394
- iv,
504
+ toUint8Array(ciphertext),
505
+ enc.authTag,
506
+ enc.nonceStart,
507
+ encRecordAad(enc),
395
508
  );
396
- const packedCiphertext = new Uint8Array(ciphertext.length + tag.length);
397
- packedCiphertext.set(ciphertext, 0);
398
- packedCiphertext.set(tag, ciphertext.length);
399
- return {
400
- version: 1,
401
- scheme: "x25519-hkdf-aes-256-gcm",
402
- context,
403
- senderPublicKeyBase64: bytesToBase64(sender.publicKey),
404
- saltBase64: bytesToBase64(salt),
405
- ivBase64: bytesToBase64(iv),
406
- ciphertextBase64: bytesToBase64(packedCiphertext),
407
- };
408
509
  }
409
510
 
410
511
  export async function decryptProtectedBytes({
411
512
  protectedBytes,
412
513
  recipientPrivateKey,
413
- keyAgreement,
514
+ keyDecapsulation,
414
515
  } = {}) {
415
516
  const parsed = extractPublicationRecordCollection(protectedBytes);
416
517
  if (!parsed?.enc) {
417
518
  return toUint8Array(protectedBytes);
418
519
  }
419
- assertGcmEncRecord(parsed.enc);
420
- const sharedSecret = await resolveSharedSecret("decryptProtectedBytes", {
520
+ return decryptWithEncRecord("decryptProtectedBytes", {
521
+ enc: parsed.enc,
522
+ ciphertext: parsed.payloadBytes,
421
523
  recipientPrivateKey,
422
- keyAgreement,
423
- ephemeralPublicKey: parsed.enc.ephemeralPublicKey,
424
- context: parsed.enc.context ?? "",
425
- keyExchange: parsed.enc.keyExchange,
524
+ keyDecapsulation,
426
525
  });
427
- const aesKey = await deriveAesKey(
428
- sharedSecret,
429
- new Uint8Array(0),
430
- parsed.enc.context ?? "",
431
- );
432
- const { ciphertext, tag } = splitGcmPayload(parsed.payloadBytes);
433
- return aesGcmDecrypt(
434
- aesKey,
435
- ciphertext,
436
- tag,
437
- parsed.enc.nonceStart,
438
- encodeEncRecord(parsed.enc),
439
- );
440
526
  }
441
527
 
528
+ /**
529
+ * Encrypt bytes to a recipient's 1216-byte hybrid X25519+ML-KEM-768 public
530
+ * key under {@link PROTECTED_DELIVERY_SCHEME}. `encapsulationSeed` (64 B) and
531
+ * `nonceStart` (12 B) make the output deterministic, for known-answer tests
532
+ * only; production leaves them unset.
533
+ */
442
534
  export async function encryptBytesForRecipient({
443
535
  plaintext,
444
536
  recipientPublicKey,
445
537
  context = "space-data-module-sdk/package",
446
- senderKeyPair = null,
447
538
  recipientKeyId = null,
448
539
  schemaHash = null,
449
540
  rootType = null,
541
+ encapsulationSeed = null,
542
+ nonceStart = null,
543
+ timestamp = null,
450
544
  } = {}) {
451
545
  if (!recipientPublicKey) {
452
546
  throw new Error("encryptBytesForRecipient requires recipientPublicKey.");
453
547
  }
454
- const sender = senderKeyPair ?? (await generateX25519Keypair());
455
- const nonceStart = await randomBytes(12);
456
- const sharedSecret = await deriveSharedSecret(
457
- sender.privateKey,
548
+ const publicKey = normalizeRecipientPublicKey(
549
+ "encryptBytesForRecipient",
458
550
  recipientPublicKey,
459
551
  );
460
- const aesKey = await deriveAesKey(sharedSecret, new Uint8Array(0), context);
552
+ const nonce = nonceStart ? toUint8Array(nonceStart) : await randomBytes(12);
553
+ if (nonce.length !== 12) {
554
+ throw new Error("encryptBytesForRecipient nonceStart must be 12 bytes.");
555
+ }
556
+ const encapsulation = await x25519Mlkem768Encapsulate(publicKey, encapsulationSeed);
557
+ const aesKey = await deriveAesKey(encapsulation.sharedSecret, context);
461
558
  const enc = {
462
559
  version: 1,
463
- keyExchange: "X25519",
560
+ keyExchange: "X25519_MLKEM768",
464
561
  symmetric: "AES_256_GCM",
465
562
  keyDerivation: "HKDF_SHA256",
466
- ephemeralPublicKey: sender.publicKey,
467
- nonceStart,
563
+ ephemeralPublicKey: encapsulation.x25519EphemeralPublicKey,
564
+ kemCiphertext: encapsulation.kemCiphertext,
565
+ nonceStart: nonce,
468
566
  recipientKeyId,
469
567
  context,
470
568
  schemaHash,
471
569
  rootType,
472
- timestamp: Date.now(),
570
+ timestamp: timestamp ?? Date.now(),
571
+ authTag: null,
473
572
  };
474
- // The encoded ENC record doubles as the GCM AAD so every delivery parameter
475
- // (context, schema hash, root type, recipient key id, nonce, ephemeral key)
476
- // is authenticated alongside the ciphertext. encodeEncRecord() is
477
- // deterministic for a normalized record, so decrypt paths recompute the
478
- // identical bytes from the parsed ENC record.
479
573
  const { ciphertext, tag } = await aesGcmEncrypt(
480
574
  aesKey,
481
575
  toUint8Array(plaintext),
482
- nonceStart,
483
- encodeEncRecord(enc),
576
+ nonce,
577
+ encRecordAad(enc),
484
578
  );
485
- const payloadBytes = new Uint8Array(ciphertext.length + tag.length);
486
- payloadBytes.set(ciphertext, 0);
487
- payloadBytes.set(tag, ciphertext.length);
579
+ enc.authTag = toUint8Array(tag);
580
+ const payloadBytes = toUint8Array(ciphertext);
488
581
  const recordCollectionBytes = encodePublicationRecordCollection({ enc });
489
582
  const protectedBlobBytes = appendPublicationRecordCollection(
490
583
  payloadBytes,
@@ -500,62 +593,48 @@ export async function encryptBytesForRecipient({
500
593
  },
501
594
  enc,
502
595
  context,
596
+ scheme: PROTECTED_DELIVERY_SCHEME,
503
597
  });
504
598
  }
505
599
 
506
600
  export async function decryptBytesFromEnvelope({
507
601
  envelope,
508
602
  recipientPrivateKey,
603
+ keyDecapsulation,
509
604
  } = {}) {
510
- if (!envelope || !recipientPrivateKey) {
605
+ if (!envelope || (!recipientPrivateKey && !keyDecapsulation)) {
511
606
  throw new Error(
512
- "decryptBytesFromEnvelope requires envelope and recipientPrivateKey.",
607
+ "decryptBytesFromEnvelope requires envelope and recipientPrivateKey (or keyDecapsulation).",
608
+ );
609
+ }
610
+ const scheme = String(envelope.scheme ?? "").trim();
611
+ if (REMOVED_PROTECTED_DELIVERY_SCHEMES.includes(scheme)) {
612
+ throw refuseClassical("decryptBytesFromEnvelope", `the envelope scheme "${scheme}"`);
613
+ }
614
+ if (scheme !== PROTECTED_DELIVERY_SCHEME) {
615
+ throw new ProtectedDeliveryError(
616
+ "unsupported_delivery_scheme",
617
+ `decryptBytesFromEnvelope: unsupported envelope scheme "${scheme}"; expected ${PROTECTED_DELIVERY_SCHEME}.`,
513
618
  );
514
619
  }
515
620
  if (envelope.protectedBlobBase64) {
516
621
  return decryptProtectedBytes({
517
622
  protectedBytes: base64ToBytes(envelope.protectedBlobBase64),
518
623
  recipientPrivateKey,
624
+ keyDecapsulation,
519
625
  });
520
626
  }
521
627
  if (envelope.ciphertextBase64 && envelope.encRecordBase64) {
522
- const encRecordBytes = base64ToBytes(envelope.encRecordBase64);
523
- const enc = decodeEncRecord(encRecordBytes);
524
- assertGcmEncRecord(enc);
525
- const sharedSecret = await deriveSharedSecret(
628
+ return decryptWithEncRecord("decryptBytesFromEnvelope", {
629
+ enc: decodeEncRecord(base64ToBytes(envelope.encRecordBase64)),
630
+ ciphertext: base64ToBytes(envelope.ciphertextBase64),
526
631
  recipientPrivateKey,
527
- enc.ephemeralPublicKey,
528
- );
529
- const aesKey = await deriveAesKey(
530
- sharedSecret,
531
- new Uint8Array(0),
532
- enc.context ?? envelope.context ?? "",
533
- );
534
- const { ciphertext, tag } = splitGcmPayload(
535
- base64ToBytes(envelope.ciphertextBase64),
536
- );
537
- return aesGcmDecrypt(aesKey, ciphertext, tag, enc.nonceStart, encRecordBytes);
538
- }
539
- const sharedSecret = await deriveSharedSecret(
540
- recipientPrivateKey,
541
- base64ToBytes(envelope.senderPublicKeyBase64),
542
- );
543
- const aesKey = await deriveAesKey(
544
- sharedSecret,
545
- base64ToBytes(envelope.saltBase64),
546
- envelope.context,
547
- );
548
- const packedCiphertext = base64ToBytes(envelope.ciphertextBase64);
549
- if (packedCiphertext.length < 16) {
550
- throw new Error("Encrypted envelope payload is truncated.");
632
+ keyDecapsulation,
633
+ });
551
634
  }
552
- const ciphertext = packedCiphertext.slice(0, packedCiphertext.length - 16);
553
- const tag = packedCiphertext.slice(packedCiphertext.length - 16);
554
- return aesGcmDecrypt(
555
- aesKey,
556
- ciphertext,
557
- tag,
558
- base64ToBytes(envelope.ivBase64),
635
+ throw new ProtectedDeliveryError(
636
+ "invalid_envelope",
637
+ "decryptBytesFromEnvelope: the envelope carries neither protectedBlobBase64 nor ciphertextBase64 + encRecordBase64.",
559
638
  );
560
639
  }
561
640
 
@@ -574,6 +653,7 @@ export async function decryptJsonFromEnvelope(options = {}) {
574
653
  export async function decryptPublicationRecordCollection({
575
654
  protectedBytes,
576
655
  recipientPrivateKey,
656
+ keyDecapsulation,
577
657
  } = {}) {
578
658
  const parsed = extractPublicationRecordCollection(protectedBytes);
579
659
  if (!parsed) {
@@ -584,7 +664,7 @@ export async function decryptPublicationRecordCollection({
584
664
  };
585
665
  }
586
666
  const decryptedBytes = parsed.enc
587
- ? await decryptProtectedBytes({ protectedBytes, recipientPrivateKey })
667
+ ? await decryptProtectedBytes({ protectedBytes, recipientPrivateKey, keyDecapsulation })
588
668
  : parsed.payloadBytes;
589
669
  return {
590
670
  payloadBytes: parsed.payloadBytes,
@@ -592,3 +672,82 @@ export async function decryptPublicationRecordCollection({
592
672
  publication: parsed,
593
673
  };
594
674
  }
675
+
676
+ // ---- $KMF 1.82.3 public key material -------------------------------------
677
+
678
+ const PUBLIC_KEY_MATERIAL = Object.freeze({
679
+ "x25519-ml-kem-768": {
680
+ algorithm: keyMaterialAlgorithm.HybridX25519MlKem768Public,
681
+ encoding: keyMaterialEncoding.HybridPublic,
682
+ role: keyMaterialRole.DecryptKey,
683
+ size: X25519_MLKEM768_PUBLIC_KEY_SIZE,
684
+ },
685
+ "ml-dsa-65": {
686
+ algorithm: keyMaterialAlgorithm.MlDsa65Public,
687
+ encoding: keyMaterialEncoding.MlDsaPublic,
688
+ role: keyMaterialRole.VerificationKey,
689
+ size: 1952,
690
+ },
691
+ });
692
+
693
+ /**
694
+ * Encode a public key as a $KMF 1.82.3 record: a protected-delivery recipient
695
+ * key (`kind: "x25519-ml-kem-768"`, HybridX25519MlKem768Public / HybridPublic,
696
+ * 1216 B) or a module signer key (`kind: "ml-dsa-65"`, MlDsa65Public /
697
+ * MlDsaPublic, 1952 B).
698
+ */
699
+ export function encodePublicKeyMaterial({ kind, keyId = "", publicKey, expiresAtMs = 0 } = {}) {
700
+ const spec = PUBLIC_KEY_MATERIAL[kind];
701
+ if (!spec) {
702
+ throw new Error(`encodePublicKeyMaterial: unsupported kind "${kind}".`);
703
+ }
704
+ const keyBytes = normalizeKeyBytes(publicKey);
705
+ if (keyBytes.length !== spec.size) {
706
+ throw new Error(`encodePublicKeyMaterial: a ${kind} public key is ${spec.size} bytes, got ${keyBytes.length}.`);
707
+ }
708
+ const builder = new flatbuffers.Builder(keyBytes.length + 128);
709
+ const keyIdOffset = builder.createString(String(keyId ?? ""));
710
+ const keyBytesOffset = KMF.createKeyBytesVector(builder, keyBytes);
711
+ const root = KMF.createKMF(
712
+ builder,
713
+ keyIdOffset,
714
+ spec.role,
715
+ spec.algorithm,
716
+ spec.encoding,
717
+ keyBytesOffset,
718
+ 1,
719
+ BigInt(Number(expiresAtMs ?? 0)),
720
+ );
721
+ KMF.finishKMFBuffer(builder, root);
722
+ return builder.asUint8Array();
723
+ }
724
+
725
+ /** Decode a $KMF public key record written by {@link encodePublicKeyMaterial}. */
726
+ export function decodePublicKeyMaterial(bytes) {
727
+ const bb = new flatbuffers.ByteBuffer(toUint8Array(bytes));
728
+ if (!KMF.bufferHasIdentifier(bb)) {
729
+ throw new Error("decodePublicKeyMaterial: not a $KMF record.");
730
+ }
731
+ const kmf = KMF.getRootAsKMF(bb);
732
+ const kind = Object.keys(PUBLIC_KEY_MATERIAL).find(
733
+ (name) =>
734
+ PUBLIC_KEY_MATERIAL[name].algorithm === kmf.ALGORITHM() &&
735
+ PUBLIC_KEY_MATERIAL[name].encoding === kmf.ENCODING(),
736
+ );
737
+ if (!kind) {
738
+ if (kmf.ALGORITHM() === keyMaterialAlgorithm.X25519Public) {
739
+ throw refuseClassical("decodePublicKeyMaterial", "the $KMF X25519Public key");
740
+ }
741
+ throw new Error(`decodePublicKeyMaterial: unsupported $KMF algorithm ${kmf.ALGORITHM()} / encoding ${kmf.ENCODING()}.`);
742
+ }
743
+ const publicKey = new Uint8Array(kmf.keyBytesArray() ?? []);
744
+ if (publicKey.length !== PUBLIC_KEY_MATERIAL[kind].size) {
745
+ throw new Error(`decodePublicKeyMaterial: ${kind} key is ${publicKey.length} bytes.`);
746
+ }
747
+ return {
748
+ kind,
749
+ keyId: kmf.KEY_ID() ?? "",
750
+ publicKey,
751
+ expiresAtMs: Number(kmf.EXPIRES_AT()),
752
+ };
753
+ }