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
@@ -48,20 +48,26 @@ const KEY_EXCHANGE_BY_NAME = Object.freeze({
48
48
  X25519: KeyExchange.X25519,
49
49
  SECP256K1: KeyExchange.Secp256k1,
50
50
  P256: KeyExchange.P256,
51
+ X25519_MLKEM768: KeyExchange.X25519_MLKEM768,
52
+ MLKEM768: KeyExchange.MLKEM768,
53
+ MLKEM1024: KeyExchange.MLKEM1024,
51
54
  });
55
+ // ENC 1.0.3 KEM_CIPHERTEXT width per key exchange; absent for the classical
56
+ // exchanges.
57
+ const KEM_CIPHERTEXT_LENGTH_BY_KEY_EXCHANGE = Object.freeze({
58
+ X25519_MLKEM768: 1088,
59
+ MLKEM768: 1088,
60
+ MLKEM1024: 1568,
61
+ });
62
+ const ENC_AUTH_TAG_LENGTH = 16;
52
63
  const KEY_EXCHANGE_NAME_BY_VALUE = Object.freeze(
53
64
  Object.fromEntries(
54
65
  Object.entries(KEY_EXCHANGE_BY_NAME).map(([name, value]) => [value, name]),
55
66
  ),
56
67
  );
57
- // AES_256_GCM is not yet published in the spacedatastandards.org generated
58
- // SymmetricAlgo enum (which only defines AES_256_CTR = 0). The SYMMETRIC field
59
- // is a plain byte on the wire, so value 1 is encoded directly until the schema
60
- // publishes the enum member.
61
- const SYMMETRIC_ALGO_AES_256_GCM = 1;
62
68
  const SYMMETRIC_ALGO_BY_NAME = Object.freeze({
63
69
  AES_256_CTR: SymmetricAlgo.AES_256_CTR,
64
- AES_256_GCM: SYMMETRIC_ALGO_AES_256_GCM,
70
+ AES_256_GCM: SymmetricAlgo.AES_256_GCM,
65
71
  });
66
72
  const SYMMETRIC_ALGO_NAME_BY_VALUE = Object.freeze(
67
73
  Object.fromEntries(
@@ -70,6 +76,8 @@ const SYMMETRIC_ALGO_NAME_BY_VALUE = Object.freeze(
70
76
  );
71
77
  const KDF_BY_NAME = Object.freeze({
72
78
  HKDF_SHA256: KDF.HKDF_SHA256,
79
+ HKDF_SHA384: KDF.HKDF_SHA384,
80
+ SHAKE256: KDF.SHAKE256,
73
81
  });
74
82
  const KDF_NAME_BY_VALUE = Object.freeze(
75
83
  Object.fromEntries(
@@ -305,7 +313,6 @@ function assertUnionTableField(buffer, tableMeta, vtableFieldOffset, label) {
305
313
  function validateEncTable(table, buffer, label) {
306
314
  const tableMeta = assertFlatbufferTable(buffer, table.bb_pos, label);
307
315
  assertOptionalByteVectorField(buffer, tableMeta, 12, `${label} ephemeral public key`, {
308
- minLength: 1,
309
316
  maxLength: 65,
310
317
  });
311
318
  assertOptionalByteVectorField(buffer, tableMeta, 14, `${label} nonce start`, {
@@ -320,6 +327,12 @@ function validateEncTable(table, buffer, label) {
320
327
  maxLength: 32,
321
328
  });
322
329
  assertOptionalStringField(buffer, tableMeta, 22, `${label} root type`);
330
+ assertOptionalByteVectorField(buffer, tableMeta, 26, `${label} KEM ciphertext`, {
331
+ maxLength: 1568,
332
+ });
333
+ assertOptionalByteVectorField(buffer, tableMeta, 28, `${label} auth tag`, {
334
+ maxLength: ENC_AUTH_TAG_LENGTH,
335
+ });
323
336
  const timestamp = table.TIMESTAMP();
324
337
  const record = {
325
338
  version: Number(table.VERSION()),
@@ -340,21 +353,47 @@ function validateEncTable(table, buffer, label) {
340
353
  rootType: normalizeStringField(table.ROOT_TYPE()),
341
354
  timestamp:
342
355
  timestamp === undefined || timestamp === null ? 0 : Number(timestamp),
356
+ kemCiphertext: normalizeByteField(table.kemCiphertextArray()),
357
+ authTag: normalizeByteField(table.authTagArray()),
343
358
  };
344
- if (!record.ephemeralPublicKey?.length) {
359
+ const pureKem =
360
+ record.keyExchange === "MLKEM768" || record.keyExchange === "MLKEM1024";
361
+ if (!pureKem && !record.ephemeralPublicKey?.length) {
345
362
  throw new Error(`${label} is missing the ephemeral public key.`);
346
363
  }
364
+ if (pureKem && record.ephemeralPublicKey?.length) {
365
+ throw new Error(`${label} ${record.keyExchange} ephemeral public key must be empty.`);
366
+ }
367
+ const kemCiphertextLength =
368
+ KEM_CIPHERTEXT_LENGTH_BY_KEY_EXCHANGE[record.keyExchange];
369
+ if (kemCiphertextLength !== undefined) {
370
+ if (record.kemCiphertext?.length !== kemCiphertextLength) {
371
+ throw new Error(
372
+ `${label} ${record.keyExchange} KEM ciphertext must be ${kemCiphertextLength} bytes.`,
373
+ );
374
+ }
375
+ } else if (record.kemCiphertext) {
376
+ throw new Error(
377
+ `${label} ${record.keyExchange} carries a KEM ciphertext; only the ML-KEM exchanges do.`,
378
+ );
379
+ }
380
+ if (record.authTag && record.authTag.length !== ENC_AUTH_TAG_LENGTH) {
381
+ throw new Error(`${label} auth tag must be ${ENC_AUTH_TAG_LENGTH} bytes.`);
382
+ }
347
383
  if (!record.nonceStart || record.nonceStart.length !== 12) {
348
384
  throw new Error(`${label} nonce start must be 12 bytes.`);
349
385
  }
350
386
  if (
351
- record.keyExchange === "X25519" &&
387
+ (record.keyExchange === "X25519" ||
388
+ record.keyExchange === "X25519_MLKEM768") &&
352
389
  record.ephemeralPublicKey.length !== 32
353
390
  ) {
354
391
  throw new Error(`${label} X25519 ephemeral public key must be 32 bytes.`);
355
392
  }
356
393
  if (
394
+ !pureKem &&
357
395
  record.keyExchange !== "X25519" &&
396
+ record.keyExchange !== "X25519_MLKEM768" &&
358
397
  (record.ephemeralPublicKey.length < 32 || record.ephemeralPublicKey.length > 65)
359
398
  ) {
360
399
  throw new Error(`${label} ephemeral public key length is invalid.`);
@@ -437,12 +476,15 @@ function normalizeKeyExchange(value) {
437
476
  if (typeof value === "number") {
438
477
  return value;
439
478
  }
440
- return KEY_EXCHANGE_BY_NAME[
441
- String(value ?? "X25519")
442
- .trim()
443
- .replace(/[^A-Za-z0-9]+/g, "_")
444
- .toUpperCase()
445
- ] ?? KeyExchange.X25519;
479
+ const normalized = String(value ?? "X25519_MLKEM768")
480
+ .trim()
481
+ .replace(/[^A-Za-z0-9]+/g, "_")
482
+ .toUpperCase();
483
+ const resolved = KEY_EXCHANGE_BY_NAME[normalized];
484
+ if (resolved === undefined) {
485
+ throw new Error(`Unsupported ENC key exchange "${value}".`);
486
+ }
487
+ return resolved;
446
488
  }
447
489
 
448
490
  function normalizeSymmetricAlgorithm(value) {
@@ -464,15 +506,30 @@ function normalizeKdf(value) {
464
506
  if (typeof value === "number") {
465
507
  return value;
466
508
  }
467
- return KDF_BY_NAME[
468
- String(value ?? "HKDF_SHA256")
469
- .trim()
470
- .replace(/[^A-Za-z0-9]+/g, "_")
471
- .toUpperCase()
472
- ] ?? KDF.HKDF_SHA256;
509
+ const normalized = String(value ?? "HKDF_SHA256")
510
+ .trim()
511
+ .replace(/[^A-Za-z0-9]+/g, "_")
512
+ .toUpperCase();
513
+ const resolved = KDF_BY_NAME[normalized];
514
+ if (resolved === undefined) {
515
+ throw new Error(`Unsupported ENC key derivation "${value}".`);
516
+ }
517
+ return resolved;
473
518
  }
474
519
 
475
520
  function encTableFromObject(record = {}) {
521
+ const recipientKeyId = normalizeByteField(record.recipientKeyId);
522
+ if (recipientKeyId && recipientKeyId.length > 32) {
523
+ throw new RangeError(
524
+ `ENC recipientKeyId must be at most 32 bytes (got ${recipientKeyId.length}); pass a key hash/fingerprint such as SHA-256(publicKey).`,
525
+ );
526
+ }
527
+ const schemaHash = normalizeByteField(record.schemaHash);
528
+ if (schemaHash && schemaHash.length > 32) {
529
+ throw new RangeError(
530
+ `ENC schemaHash must be at most 32 bytes (got ${schemaHash.length}).`,
531
+ );
532
+ }
476
533
  return new ENCT(
477
534
  Number(record.version ?? 1),
478
535
  normalizeKeyExchange(record.keyExchange),
@@ -480,11 +537,13 @@ function encTableFromObject(record = {}) {
480
537
  normalizeKdf(record.keyDerivation),
481
538
  Array.from(toUint8Array(record.ephemeralPublicKey)),
482
539
  Array.from(toUint8Array(record.nonceStart)),
483
- Array.from(normalizeByteField(record.recipientKeyId) ?? []),
540
+ Array.from(recipientKeyId ?? []),
484
541
  normalizeStringField(record.context),
485
- Array.from(normalizeByteField(record.schemaHash) ?? []),
542
+ Array.from(schemaHash ?? []),
486
543
  normalizeStringField(record.rootType),
487
544
  BigInt(record.timestamp ?? 0),
545
+ Array.from(normalizeByteField(record.kemCiphertext) ?? []),
546
+ Array.from(normalizeByteField(record.authTag) ?? []),
488
547
  );
489
548
  }
490
549
 
@@ -857,7 +916,7 @@ export function createEncryptedEnvelopePayload(options = {}) {
857
916
  const envelope = {
858
917
  version: Number(options.version ?? 2),
859
918
  scheme:
860
- normalizeStringField(options.scheme) ?? "x25519-hkdf-aes-256-gcm-rec",
919
+ normalizeStringField(options.scheme) ?? PROTECTED_DELIVERY_SCHEME,
861
920
  context: normalizeStringField(options.context ?? enc?.context) ?? "",
862
921
  protectedBlobBase64: bytesToBase64(protectedBlob),
863
922
  recordCollectionBase64: parsed
@@ -868,6 +927,9 @@ export function createEncryptedEnvelopePayload(options = {}) {
868
927
  if (enc?.ephemeralPublicKey) {
869
928
  envelope.senderPublicKeyBase64 = bytesToBase64(enc.ephemeralPublicKey);
870
929
  }
930
+ if (enc?.kemCiphertext) {
931
+ envelope.kemCiphertextBase64 = bytesToBase64(enc.kemCiphertext);
932
+ }
871
933
  if (enc?.nonceStart) {
872
934
  envelope.nonceStartBase64 = bytesToBase64(enc.nonceStart);
873
935
  }
@@ -890,6 +952,18 @@ export function decodeProtectedBlobBase64(base64) {
890
952
 
891
953
  export { TRAILER_MAGIC_TEXT, TRAILER_FOOTER_LENGTH };
892
954
 
955
+ /**
956
+ * The one protected-module delivery scheme: hybrid X25519 + ML-KEM-768
957
+ * (X-Wing, Go 1.26 crypto/hpke.MLKEM768X25519()), HKDF-SHA256, AES-256-GCM,
958
+ * carried in an SDS $ENC 1.0.3 record inside the $REC trailer. The classical
959
+ * X25519-only scheme ("x25519-hkdf-aes-256-gcm-rec") is refused.
960
+ */
961
+ export const PROTECTED_DELIVERY_SCHEME = "x25519-mlkem768-hkdf-aes-256-gcm-rec";
962
+ export const REMOVED_PROTECTED_DELIVERY_SCHEMES = Object.freeze([
963
+ "x25519-hkdf-aes-256-gcm-rec",
964
+ "x25519-hkdf-aes-256-gcm",
965
+ ]);
966
+
893
967
  /* ------------------------------------------------------------------------ *
894
968
  * $BPF — Build Profile (SDS ordinal 227, published in
895
969
  * spacedatastandards.org 1.200.0).
@@ -44,8 +44,43 @@ export function hexToBytes(hex) {
44
44
  return bytes;
45
45
  }
46
46
 
47
+ // Base64 in plain JavaScript, ONE implementation for every runtime (Node,
48
+ // browser, WasmEdge): Node's Buffer does not exist in a browser, and a
49
+ // runtime-detected fork would make the browser host a different program.
50
+ const BASE64_ALPHABET =
51
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
52
+ const BASE64_VALUES = (() => {
53
+ const table = new Int16Array(128).fill(-1);
54
+ for (let i = 0; i < BASE64_ALPHABET.length; i += 1) {
55
+ table[BASE64_ALPHABET.charCodeAt(i)] = i;
56
+ }
57
+ // The URL-safe alphabet decodes too, as Node's Buffer decodes it.
58
+ table["-".charCodeAt(0)] = 62;
59
+ table["_".charCodeAt(0)] = 63;
60
+ return table;
61
+ })();
62
+
47
63
  export function bytesToBase64(bytes) {
48
- return Buffer.from(toUint8Array(bytes)).toString("base64");
64
+ const data = toUint8Array(bytes);
65
+ let out = "";
66
+ let i = 0;
67
+ for (; i + 2 < data.length; i += 3) {
68
+ const n = (data[i] << 16) | (data[i + 1] << 8) | data[i + 2];
69
+ out +=
70
+ BASE64_ALPHABET[(n >>> 18) & 63] +
71
+ BASE64_ALPHABET[(n >>> 12) & 63] +
72
+ BASE64_ALPHABET[(n >>> 6) & 63] +
73
+ BASE64_ALPHABET[n & 63];
74
+ }
75
+ const rest = data.length - i;
76
+ if (rest === 1) {
77
+ const n = data[i] << 16;
78
+ out += `${BASE64_ALPHABET[(n >>> 18) & 63]}${BASE64_ALPHABET[(n >>> 12) & 63]}==`;
79
+ } else if (rest === 2) {
80
+ const n = (data[i] << 16) | (data[i + 1] << 8);
81
+ out += `${BASE64_ALPHABET[(n >>> 18) & 63]}${BASE64_ALPHABET[(n >>> 12) & 63]}${BASE64_ALPHABET[(n >>> 6) & 63]}=`;
82
+ }
83
+ return out;
49
84
  }
50
85
 
51
86
  const MAX_BASE64_LENGTH = 256 * 1024 * 1024;
@@ -57,6 +92,26 @@ export function base64ToBytes(base64) {
57
92
  `Base64 input exceeds ${MAX_BASE64_LENGTH} character limit.`,
58
93
  );
59
94
  }
60
- return new Uint8Array(Buffer.from(str, "base64"));
95
+ // Decoded as Node's Buffer.from(str, "base64") decodes: characters outside
96
+ // the alphabet are skipped, decoding stops at the first "=", and trailing
97
+ // bits that do not fill a byte are dropped.
98
+ const out = new Uint8Array(Math.floor((str.length * 3) / 4) + 3);
99
+ let length = 0;
100
+ let accumulator = 0;
101
+ let bits = 0;
102
+ for (let i = 0; i < str.length; i += 1) {
103
+ const code = str.charCodeAt(i);
104
+ if (code === 61) break; // "="
105
+ const value = code < 128 ? BASE64_VALUES[code] : -1;
106
+ if (value < 0) continue;
107
+ accumulator = ((accumulator << 6) | value) & 0xffffff;
108
+ bits += 6;
109
+ if (bits >= 8) {
110
+ bits -= 8;
111
+ out[length] = (accumulator >>> bits) & 0xff;
112
+ length += 1;
113
+ }
114
+ }
115
+ return out.slice(0, length);
61
116
  }
62
117
 
@@ -164,3 +164,190 @@ export async function aesGcmDecrypt(key, ciphertext, tag, iv, aad = null) {
164
164
  aad ? toUint8Array(aad) : undefined,
165
165
  );
166
166
  }
167
+
168
+ // ---------------------------------------------------------------------------
169
+ // Post-quantum primitives (hd-wallet-wasm 2.3.0 `wallet.pqc`, OpenSSL 3.5).
170
+ //
171
+ // Every secret input is a SEED, never an expanded key:
172
+ // ML-DSA-65 / ML-DSA-87 32 B xi (FIPS 204, pure, empty context)
173
+ // SLH-DSA-SHA2-256s 96 B SK.seed || SK.prf || PK.seed (FIPS 205)
174
+ // X25519+ML-KEM-768 hybrid 96 B X25519 sk || ML-KEM d || z
175
+ //
176
+ // The hybrid KEM is X-Wing exactly as Go 1.26 crypto/hpke.MLKEM768X25519()
177
+ // combines it. SDS v1.318.0 orders the public key and the ciphertext X25519
178
+ // FIRST: public key 1216 B = X25519 (32) || ML-KEM-768 (1184); ciphertext
179
+ // 1120 B = X25519 ephemeral (32) || ML-KEM-768 ciphertext (1088). These helpers
180
+ // are the ONE implementation every runtime uses (Node, browser, WasmEdge).
181
+ // ---------------------------------------------------------------------------
182
+
183
+ export const ML_DSA_SEED_SIZE = 32;
184
+ export const SLH_DSA_SEED_SIZE = 96;
185
+ export const X25519_MLKEM768_SEED_SIZE = 96;
186
+ export const X25519_MLKEM768_PUBLIC_KEY_SIZE = 1216;
187
+ export const X25519_MLKEM768_X25519_SIZE = 32;
188
+ export const MLKEM768_CIPHERTEXT_SIZE = 1088;
189
+ export const X25519_MLKEM768_SHARED_SECRET_SIZE = 32;
190
+
191
+ /**
192
+ * Sizes of the signature algorithms the module verifier dispatches on, keyed
193
+ * by the wire name a signature entry or PLG.SIGNATURE_ALGORITHM carries.
194
+ */
195
+ export const PQ_SIGNATURE_ALGORITHMS = Object.freeze({
196
+ "ml-dsa-65": Object.freeze({ publicKeySize: 1952, signatureSize: 3309, seedSize: 32 }),
197
+ "ml-dsa-87": Object.freeze({ publicKeySize: 2592, signatureSize: 4627, seedSize: 32 }),
198
+ "slh-dsa-sha2-256s": Object.freeze({ publicKeySize: 64, signatureSize: 29792, seedSize: 96 }),
199
+ });
200
+
201
+ function exactLength(bytes, size, label) {
202
+ if (bytes.length !== size) {
203
+ throw new RangeError(`${label} must be ${size} bytes, got ${bytes.length}.`);
204
+ }
205
+ return bytes;
206
+ }
207
+
208
+ async function pqc() {
209
+ const wallet = await getWasmWallet();
210
+ if (!wallet?.pqc?.mlDsa || !wallet?.pqc?.hybrid) {
211
+ throw new Error(
212
+ "hd-wallet-wasm does not expose wallet.pqc; space-data-module-sdk requires hd-wallet-wasm 2.3.0 or later.",
213
+ );
214
+ }
215
+ return wallet.pqc;
216
+ }
217
+
218
+ function mlDsa(level) {
219
+ return {
220
+ publicKey: async (seed) =>
221
+ new Uint8Array((await pqc()).mlDsa.keygen(level, exactLength(toUint8Array(seed), ML_DSA_SEED_SIZE, `ML-DSA-${level} seed`))),
222
+ // Deterministic signing (FIPS 204 rnd = 0^32): one seed and one message
223
+ // always give the same bytes in every runtime.
224
+ sign: async (message, seed) =>
225
+ new Uint8Array(
226
+ (await pqc()).mlDsa.sign(
227
+ level,
228
+ exactLength(toUint8Array(seed), ML_DSA_SEED_SIZE, `ML-DSA-${level} seed`),
229
+ toUint8Array(message),
230
+ { deterministic: true },
231
+ ),
232
+ ),
233
+ verify: async (message, signature, publicKey) => {
234
+ try {
235
+ return Boolean(
236
+ (await pqc()).mlDsa.verify(level, toUint8Array(publicKey), toUint8Array(message), toUint8Array(signature)),
237
+ );
238
+ } catch {
239
+ return false;
240
+ }
241
+ },
242
+ };
243
+ }
244
+
245
+ const MLDSA65 = mlDsa(65);
246
+ const MLDSA87 = mlDsa(87);
247
+
248
+ /** ML-DSA-65 verification key (1952 B) from a 32-byte seed. */
249
+ export const mldsa65PublicKey = MLDSA65.publicKey;
250
+ /** Pure ML-DSA-65 signature (3309 B), deterministic, empty context. */
251
+ export const mldsa65Sign = MLDSA65.sign;
252
+ /** Whether `signature` is a pure ML-DSA-65 signature over `message` for `publicKey`. */
253
+ export const mldsa65Verify = MLDSA65.verify;
254
+ /** ML-DSA-87 verification key (2592 B) from a 32-byte seed. */
255
+ export const mldsa87PublicKey = MLDSA87.publicKey;
256
+ /** Pure ML-DSA-87 signature (4627 B), deterministic, empty context. */
257
+ export const mldsa87Sign = MLDSA87.sign;
258
+ export const mldsa87Verify = MLDSA87.verify;
259
+
260
+ /** SLH-DSA-SHA2-256s verification key (64 B) from a 96-byte seed. */
261
+ export async function slhDsaSha2256sPublicKey(seed) {
262
+ return new Uint8Array((await pqc()).slhDsa.keygen(exactLength(toUint8Array(seed), SLH_DSA_SEED_SIZE, "SLH-DSA-SHA2-256s seed")));
263
+ }
264
+
265
+ /** SLH-DSA-SHA2-256s signature (29792 B), deterministic. */
266
+ export async function slhDsaSha2256sSign(message, seed) {
267
+ return new Uint8Array(
268
+ (await pqc()).slhDsa.sign(
269
+ exactLength(toUint8Array(seed), SLH_DSA_SEED_SIZE, "SLH-DSA-SHA2-256s seed"),
270
+ toUint8Array(message),
271
+ { deterministic: true },
272
+ ),
273
+ );
274
+ }
275
+
276
+ export async function slhDsaSha2256sVerify(message, signature, publicKey) {
277
+ try {
278
+ return Boolean((await pqc()).slhDsa.verify(toUint8Array(publicKey), toUint8Array(message), toUint8Array(signature)));
279
+ } catch {
280
+ return false;
281
+ }
282
+ }
283
+
284
+ /**
285
+ * Verify a signature under one of {@link PQ_SIGNATURE_ALGORITHMS}. Unknown
286
+ * algorithms (Ed25519 included) are refused by name: this is the dispatch the
287
+ * module verifier uses, and a classical signature never verifies here.
288
+ */
289
+ export async function pqSignatureVerify(algorithm, message, signature, publicKey) {
290
+ switch (algorithm) {
291
+ case "ml-dsa-65":
292
+ return mldsa65Verify(message, signature, publicKey);
293
+ case "ml-dsa-87":
294
+ return mldsa87Verify(message, signature, publicKey);
295
+ case "slh-dsa-sha2-256s":
296
+ return slhDsaSha2256sVerify(message, signature, publicKey);
297
+ default:
298
+ throw new Error(`unsupported post-quantum signature algorithm: ${algorithm}`);
299
+ }
300
+ }
301
+
302
+ /**
303
+ * Hybrid X25519+ML-KEM-768 keypair from a 96-byte seed (X25519 sk || d || z):
304
+ * `{ seed, publicKey }`, publicKey 1216 B = X25519 (32) || ML-KEM-768 (1184).
305
+ */
306
+ export async function x25519Mlkem768KeypairFromSeed(seed) {
307
+ const seedBytes = exactLength(toUint8Array(seed), X25519_MLKEM768_SEED_SIZE, "X25519+ML-KEM-768 seed");
308
+ const publicKey = new Uint8Array((await pqc()).hybrid.keygen(seedBytes));
309
+ return { seed: new Uint8Array(seedBytes), publicKey };
310
+ }
311
+
312
+ /** A fresh random hybrid keypair. */
313
+ export async function generateX25519Mlkem768Keypair() {
314
+ return x25519Mlkem768KeypairFromSeed(await randomBytes(X25519_MLKEM768_SEED_SIZE));
315
+ }
316
+
317
+ /**
318
+ * Encapsulate to a 1216-byte hybrid public key. Returns the X-Wing shared
319
+ * secret (32 B) and the ciphertext split as SDS $ENC carries it:
320
+ * `x25519EphemeralPublicKey` (EPHEMERAL_PUBLIC_KEY, 32 B) and `kemCiphertext`
321
+ * (KEM_CIPHERTEXT, 1088 B). `eseed` (64 B) makes it deterministic, for tests.
322
+ */
323
+ export async function x25519Mlkem768Encapsulate(publicKey, eseed = null) {
324
+ const pk = exactLength(toUint8Array(publicKey), X25519_MLKEM768_PUBLIC_KEY_SIZE, "X25519+ML-KEM-768 public key");
325
+ const result = (await pqc()).hybrid.encapsulate(pk, eseed ? toUint8Array(eseed) : null);
326
+ const ciphertext = new Uint8Array(result.ciphertext);
327
+ return {
328
+ sharedSecret: new Uint8Array(result.sharedSecret),
329
+ ciphertext,
330
+ x25519EphemeralPublicKey: ciphertext.slice(0, X25519_MLKEM768_X25519_SIZE),
331
+ kemCiphertext: ciphertext.slice(X25519_MLKEM768_X25519_SIZE),
332
+ };
333
+ }
334
+
335
+ /**
336
+ * Decapsulate with the 96-byte hybrid seed. `ciphertext` is either the full
337
+ * 1120-byte hybrid ciphertext or `{ x25519EphemeralPublicKey, kemCiphertext }`
338
+ * as $ENC carries them. Returns the 32-byte X-Wing shared secret.
339
+ */
340
+ export async function x25519Mlkem768Decapsulate(seed, ciphertext) {
341
+ const seedBytes = exactLength(toUint8Array(seed), X25519_MLKEM768_SEED_SIZE, "X25519+ML-KEM-768 seed");
342
+ let full;
343
+ if (ciphertext && !ArrayBuffer.isView(ciphertext) && !(ciphertext instanceof ArrayBuffer) && !Array.isArray(ciphertext)) {
344
+ const eph = exactLength(toUint8Array(ciphertext.x25519EphemeralPublicKey), X25519_MLKEM768_X25519_SIZE, "X25519 ephemeral public key");
345
+ const kem = exactLength(toUint8Array(ciphertext.kemCiphertext), MLKEM768_CIPHERTEXT_SIZE, "ML-KEM-768 ciphertext");
346
+ full = new Uint8Array(eph.length + kem.length);
347
+ full.set(eph, 0);
348
+ full.set(kem, eph.length);
349
+ } else {
350
+ full = exactLength(toUint8Array(ciphertext), X25519_MLKEM768_X25519_SIZE + MLKEM768_CIPHERTEXT_SIZE, "X25519+ML-KEM-768 ciphertext");
351
+ }
352
+ return new Uint8Array((await pqc()).hybrid.decapsulate(seedBytes, full));
353
+ }