@shieldfive/crypto 1.0.0-alpha.3 → 1.0.0-alpha.6

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 (43) hide show
  1. package/CHANGELOG.md +56 -2
  2. package/dist/format/header.d.ts +13 -0
  3. package/dist/format/header.d.ts.map +1 -1
  4. package/dist/format/header.js +38 -11
  5. package/dist/format/header.js.map +1 -1
  6. package/dist/index.d.ts +1 -1
  7. package/dist/index.js +1 -1
  8. package/dist/internal/types.d.ts +2 -0
  9. package/dist/internal/types.d.ts.map +1 -1
  10. package/dist/internal/types.js +2 -0
  11. package/dist/internal/types.js.map +1 -1
  12. package/dist/kdf/argon2id.d.ts.map +1 -1
  13. package/dist/kdf/argon2id.js +2 -1
  14. package/dist/kdf/argon2id.js.map +1 -1
  15. package/dist/streams/pq-hybrid-v1.d.ts +151 -0
  16. package/dist/streams/pq-hybrid-v1.d.ts.map +1 -0
  17. package/dist/streams/pq-hybrid-v1.js +397 -0
  18. package/dist/streams/pq-hybrid-v1.js.map +1 -0
  19. package/dist/suites/aes-gcm-v1/api.d.ts.map +1 -1
  20. package/dist/suites/aes-gcm-v1/api.js +4 -2
  21. package/dist/suites/aes-gcm-v1/api.js.map +1 -1
  22. package/dist/suites/pq-hybrid-v1/api.d.ts +1 -0
  23. package/dist/suites/pq-hybrid-v1/api.d.ts.map +1 -1
  24. package/dist/suites/pq-hybrid-v1/api.js +7 -0
  25. package/dist/suites/pq-hybrid-v1/api.js.map +1 -1
  26. package/dist/suites/pq-hybrid-v1/index.js +1 -1
  27. package/dist/suites/pq-hybrid-v1/index.js.map +1 -1
  28. package/dist/suites/xchacha-v1/api.d.ts.map +1 -1
  29. package/dist/suites/xchacha-v1/api.js +4 -1
  30. package/dist/suites/xchacha-v1/api.js.map +1 -1
  31. package/package.json +5 -1
  32. package/spec/format-v1.md +102 -13
  33. package/spec/key-derivation.md +49 -4
  34. package/spec/threat-model.md +99 -13
  35. package/src/format/header.ts +43 -11
  36. package/src/index.ts +1 -1
  37. package/src/internal/types.ts +2 -0
  38. package/src/kdf/argon2id.ts +2 -1
  39. package/src/streams/pq-hybrid-v1.ts +575 -0
  40. package/src/suites/aes-gcm-v1/api.ts +5 -3
  41. package/src/suites/pq-hybrid-v1/api.ts +12 -0
  42. package/src/suites/pq-hybrid-v1/index.ts +1 -1
  43. package/src/suites/xchacha-v1/api.ts +4 -1
@@ -0,0 +1,575 @@
1
+ /**
2
+ * Streaming encrypt/decrypt for the v1 wire format under suite 0x03
3
+ * (PQ-hybrid XChaCha20-Poly1305 + ML-KEM-1024).
4
+ *
5
+ * The whole-blob APIs in `suites/<name>/api.ts` materialize entire files in
6
+ * memory. That's fine for small files; for multi-gigabyte files on a
7
+ * mobile device it isn't.
8
+ *
9
+ * This module exposes a WHATWG TransformStream factory that ingests
10
+ * plaintext (or ciphertext) chunks from any ReadableStream and emits the
11
+ * other side, without ever holding more than one chunk-plus-header in
12
+ * memory at once.
13
+ *
14
+ * Currently implemented:
15
+ * - Suite 0x03 (pq-hybrid-xchacha-mlkem1024-v1) encrypt
16
+ * - Suite 0x03 (pq-hybrid-xchacha-mlkem1024-v1) decrypt
17
+ *
18
+ * Differences from the AES-GCM-v1 streaming module: the encrypt factory
19
+ * requires the caller to pre-run `encapsulateForRecipient` and pass the
20
+ * resulting `{combinedKey, suitePayload, fileId}` — the PQ suite cannot
21
+ * fabricate its own content material the way AES can, because it depends
22
+ * on the recipient's ML-KEM public key. The async helper
23
+ * `encryptStreamPqHybridV1` bundles encapsulation + stream construction.
24
+ * On the decrypt side, the stream itself performs PQ decapsulation as
25
+ * soon as the header has been parsed, then proceeds identically to the
26
+ * AES path.
27
+ */
28
+
29
+ import {
30
+ buildAuthenticatedHeader,
31
+ HeaderError,
32
+ parseHeader,
33
+ } from '../format/header.js'
34
+ import {
35
+ PQ_HYBRID_V1_SUITE_PAYLOAD_LENGTH,
36
+ PQ_HYBRID_V1_TAG_BYTES,
37
+ createChunkContext,
38
+ decapsulateFromHeader,
39
+ decryptChunk,
40
+ encapsulateForRecipient,
41
+ encryptChunk,
42
+ } from '../suites/pq-hybrid-v1/index.js'
43
+ import {
44
+ DEFAULT_CHUNK_SIZE,
45
+ HEADER_SIZES,
46
+ MAX_TOTAL_CHUNKS,
47
+ SUITE,
48
+ } from '../internal/types.js'
49
+ import { readUint32BE, uint32BE } from '../internal/encoding.js'
50
+ import { randomBytes } from '../internal/runtime.js'
51
+
52
+ const LENGTH_PREFIX_BYTES = 4
53
+
54
+ // ─────────────────────────────────────────────────────────────────────
55
+ // Encrypting transform
56
+ // ─────────────────────────────────────────────────────────────────────
57
+
58
+ export interface PqHybridV1EncryptStreamOptions {
59
+ /** Total plaintext byte count. Required because the header carries it. */
60
+ plaintextSize: number
61
+ /** Plaintext bytes per chunk. Default 4 MiB. */
62
+ chunkSize?: number
63
+ /**
64
+ * Combined content key from `encapsulateForRecipient`. 32 bytes. Used
65
+ * both for header MAC and for chunk AEAD.
66
+ */
67
+ combinedKey: Uint8Array
68
+ /** 16-byte file_id used as HKDF salt in encapsulation and key derivation. */
69
+ fileId: Uint8Array
70
+ /**
71
+ * Suite payload produced by `encapsulateForRecipient` (1664 bytes —
72
+ * 1568-byte ML-KEM ciphertext + 72-byte wrapped classical share + 24-byte
73
+ * classical nonce).
74
+ */
75
+ suitePayload: Uint8Array
76
+ }
77
+
78
+ export interface PqHybridV1EncryptStreamResult {
79
+ /** TransformStream<Uint8Array, Uint8Array> emitting the v1 wire format. */
80
+ stream: TransformStream<Uint8Array, Uint8Array>
81
+ /** The combined key used (echoed back for caller convenience). */
82
+ combinedKey: Uint8Array
83
+ /** The file_id used (echoed back for caller convenience). */
84
+ fileId: Uint8Array
85
+ }
86
+
87
+ /**
88
+ * Build a TransformStream that encrypts plaintext into v1 wire-format
89
+ * ciphertext on the fly under suite 0x03. The stream emits the header
90
+ * first, then each chunk as it arrives.
91
+ *
92
+ * The caller MUST pass `plaintextSize` because the header records it.
93
+ * If the caller doesn't know the size up front, they must accumulate
94
+ * the plaintext into a buffer first — there is no way to write a
95
+ * self-describing header otherwise.
96
+ *
97
+ * Unlike the AES-GCM-v1 factory, the PQ-hybrid factory cannot manufacture
98
+ * its own key material — the combined key, file_id, and suite payload
99
+ * are all outputs of `encapsulateForRecipient`. Use the
100
+ * `encryptStreamPqHybridV1` helper when you'd rather pass a recipient
101
+ * public key directly.
102
+ */
103
+ export function createPqHybridV1EncryptStream(
104
+ options: PqHybridV1EncryptStreamOptions,
105
+ ): PqHybridV1EncryptStreamResult {
106
+ const chunkSize = options.chunkSize ?? DEFAULT_CHUNK_SIZE
107
+ if (!Number.isSafeInteger(chunkSize) || chunkSize <= 0) {
108
+ throw new RangeError('encrypt stream: chunkSize must be positive integer')
109
+ }
110
+ if (
111
+ !Number.isSafeInteger(options.plaintextSize) ||
112
+ options.plaintextSize < 0
113
+ ) {
114
+ throw new RangeError('encrypt stream: plaintextSize must be a non-negative integer')
115
+ }
116
+
117
+ const totalChunks =
118
+ options.plaintextSize === 0
119
+ ? 0
120
+ : Math.ceil(options.plaintextSize / chunkSize)
121
+ if (totalChunks > MAX_TOTAL_CHUNKS) {
122
+ throw new RangeError('encrypt stream: file would exceed total_chunks limit')
123
+ }
124
+
125
+ const { combinedKey, fileId, suitePayload } = options
126
+ if (combinedKey.length !== 32) {
127
+ throw new RangeError('encrypt stream: combinedKey must be 32 bytes')
128
+ }
129
+ if (fileId.length !== HEADER_SIZES.FILE_ID) {
130
+ throw new RangeError('encrypt stream: fileId must be 16 bytes')
131
+ }
132
+ if (suitePayload.length !== PQ_HYBRID_V1_SUITE_PAYLOAD_LENGTH) {
133
+ throw new RangeError(
134
+ `encrypt stream: suitePayload must be ${PQ_HYBRID_V1_SUITE_PAYLOAD_LENGTH} bytes`,
135
+ )
136
+ }
137
+
138
+ // State held across the lifetime of the stream:
139
+ // - pending plaintext buffer (collects until we have a full chunk)
140
+ // - chunk index counter
141
+ // - bytes consumed counter (for sanity check vs plaintextSize)
142
+ // - context (lazily initialized)
143
+ let pending = new Uint8Array(0)
144
+ let chunkIndex = 0
145
+ let bytesConsumed = 0
146
+ let contextPromise: ReturnType<typeof createChunkContext> | null = null
147
+ let headerEmitted = false
148
+
149
+ async function ensureHeader(
150
+ controller: TransformStreamDefaultController<Uint8Array>,
151
+ ): Promise<void> {
152
+ if (headerEmitted) return
153
+ const header = await buildAuthenticatedHeader(
154
+ {
155
+ suite: SUITE.PQ_HYBRID_XCHACHA_MLKEM1024_V1,
156
+ fileId,
157
+ chunkSize,
158
+ totalChunks,
159
+ plaintextSize: options.plaintextSize,
160
+ suitePayload,
161
+ },
162
+ combinedKey,
163
+ )
164
+ controller.enqueue(header)
165
+ headerEmitted = true
166
+ }
167
+
168
+ async function emitChunk(
169
+ plaintext: Uint8Array,
170
+ controller: TransformStreamDefaultController<Uint8Array>,
171
+ ): Promise<void> {
172
+ if (!contextPromise) {
173
+ contextPromise = createChunkContext(combinedKey, fileId, totalChunks)
174
+ }
175
+ const ctx = await contextPromise
176
+ const ct = await encryptChunk(ctx, chunkIndex, plaintext)
177
+ controller.enqueue(uint32BE(ct.length))
178
+ controller.enqueue(ct)
179
+ chunkIndex += 1
180
+ }
181
+
182
+ const transformer: Transformer<Uint8Array, Uint8Array> = {
183
+ async transform(chunk, controller) {
184
+ await ensureHeader(controller)
185
+ bytesConsumed += chunk.length
186
+ if (bytesConsumed > options.plaintextSize) {
187
+ controller.error(
188
+ new RangeError('encrypt stream: input exceeded declared plaintextSize'),
189
+ )
190
+ return
191
+ }
192
+ // Append to pending buffer
193
+ const merged = new Uint8Array(pending.length + chunk.length)
194
+ merged.set(pending, 0)
195
+ merged.set(chunk, pending.length)
196
+ pending = merged
197
+
198
+ // Drain whole chunks
199
+ while (pending.length >= chunkSize && chunkIndex < totalChunks - 1) {
200
+ const slice = pending.subarray(0, chunkSize)
201
+ await emitChunk(slice, controller)
202
+ pending = pending.subarray(chunkSize)
203
+ // Subarray shares the buffer; copy out so we can drop the rest.
204
+ pending = pending.slice(0)
205
+ }
206
+ },
207
+ async flush(controller) {
208
+ await ensureHeader(controller)
209
+ if (bytesConsumed !== options.plaintextSize) {
210
+ controller.error(
211
+ new RangeError(
212
+ `encrypt stream: input was ${bytesConsumed} bytes, declared ${options.plaintextSize}`,
213
+ ),
214
+ )
215
+ return
216
+ }
217
+ // Emit any remaining whole chunks plus the final partial chunk.
218
+ while (chunkIndex < totalChunks) {
219
+ const isLastIteration = chunkIndex === totalChunks - 1
220
+ const sliceSize = isLastIteration
221
+ ? pending.length // final chunk: whatever's left
222
+ : chunkSize
223
+ const slice = pending.subarray(0, sliceSize)
224
+ await emitChunk(slice, controller)
225
+ pending = pending.subarray(sliceSize).slice(0)
226
+ }
227
+ if (pending.length !== 0) {
228
+ controller.error(
229
+ new RangeError('encrypt stream: residual bytes after final chunk'),
230
+ )
231
+ }
232
+ },
233
+ }
234
+
235
+ return {
236
+ stream: new TransformStream(transformer),
237
+ combinedKey,
238
+ fileId,
239
+ }
240
+ }
241
+
242
+ // ─────────────────────────────────────────────────────────────────────
243
+ // Decrypting transform
244
+ // ─────────────────────────────────────────────────────────────────────
245
+
246
+ /**
247
+ * Inputs for {@link createPqHybridV1DecryptStream}. Either provide the
248
+ * KEM material (`recipientSecretKey` + `envelopeKey`) so the stream can
249
+ * derive the combined key itself, OR provide the already-derived
250
+ * `combinedKey` directly. The latter is what share-link recipients use:
251
+ * they hold a 32-byte K (wrapped under the share-link password) and
252
+ * never see the ML-KEM secret key.
253
+ *
254
+ * Mixing both modes is not supported — `combinedKey` always wins. The
255
+ * caller is responsible for picking one path.
256
+ */
257
+ export type PqHybridV1DecryptStreamOptions =
258
+ | {
259
+ /** Recipient's ML-KEM-1024 secret key (3168 bytes). */
260
+ recipientSecretKey: Uint8Array
261
+ /** Classical envelope key (32 bytes). */
262
+ envelopeKey: Uint8Array
263
+ combinedKey?: undefined
264
+ }
265
+ | {
266
+ /**
267
+ * Pre-derived 32-byte combined key K. When provided, the stream
268
+ * skips ML-KEM decapsulation entirely and uses K for header MAC
269
+ * verification + per-chunk AEAD. Header MAC validation still
270
+ * cryptographically gates the rest of the stream, so a wrong K
271
+ * fails fast.
272
+ */
273
+ combinedKey: Uint8Array
274
+ recipientSecretKey?: undefined
275
+ envelopeKey?: undefined
276
+ }
277
+
278
+ /**
279
+ * Build a TransformStream that decrypts a v1 ciphertext stream produced
280
+ * under suite 0x03 into plaintext. Unlike the whole-blob decryptor, this
281
+ * version processes input incrementally — useful for very large files or
282
+ * when ciphertext arrives chunked over the network.
283
+ *
284
+ * Two key-input modes:
285
+ * - KEM mode (`recipientSecretKey` + `envelopeKey`): the stream runs
286
+ * ML-KEM decapsulation once, the moment the header has been
287
+ * buffered, then proceeds identically to the AES-GCM-v1 decrypt
288
+ * stream.
289
+ * - Combined-key mode (`combinedKey`): skips decapsulation entirely
290
+ * and uses the supplied K for header MAC verification + chunk AEAD.
291
+ * Intended for share-link recipients who hold a wrapped K but no
292
+ * ML-KEM secret.
293
+ */
294
+ export function createPqHybridV1DecryptStream(
295
+ options: PqHybridV1DecryptStreamOptions,
296
+ ): TransformStream<Uint8Array, Uint8Array> {
297
+ const combinedKeyOverride = options.combinedKey
298
+ const recipientSecretKey = options.recipientSecretKey
299
+ const envelopeKey = options.envelopeKey
300
+
301
+ if (combinedKeyOverride) {
302
+ if (combinedKeyOverride.length !== 32) {
303
+ throw new RangeError('decrypt stream: combinedKey must be 32 bytes')
304
+ }
305
+ } else {
306
+ if (!recipientSecretKey || !envelopeKey) {
307
+ throw new RangeError(
308
+ 'decrypt stream: provide either combinedKey or recipientSecretKey + envelopeKey',
309
+ )
310
+ }
311
+ if (envelopeKey.length !== 32) {
312
+ throw new RangeError('decrypt stream: envelopeKey must be 32 bytes')
313
+ }
314
+ // Length of recipientSecretKey is checked inside decapsulateFromHeader.
315
+ }
316
+
317
+ // Phases:
318
+ // 0 = waiting for header bytes
319
+ // 1 = streaming chunks: alternating length-prefix + ciphertext
320
+ let phase: 0 | 1 = 0
321
+ let buffer = new Uint8Array(0)
322
+ let parsedHeader: ReturnType<typeof parseHeader> | null = null
323
+ let chunkIndex = 0
324
+ let bytesEmitted = 0
325
+ let nextCipherLen = -1
326
+ let contextPromise: ReturnType<typeof createChunkContext> | null = null
327
+
328
+ function append(input: Uint8Array): void {
329
+ const merged = new Uint8Array(buffer.length + input.length)
330
+ merged.set(buffer, 0)
331
+ merged.set(input, buffer.length)
332
+ buffer = merged
333
+ }
334
+
335
+ function consume(n: number): Uint8Array {
336
+ const out = buffer.subarray(0, n).slice(0)
337
+ buffer = buffer.subarray(n).slice(0)
338
+ return out
339
+ }
340
+
341
+ async function tryParseHeader(): Promise<boolean> {
342
+ // Need at least the fixed prefix + MAC (no suite_payload).
343
+ if (
344
+ buffer.length <
345
+ HEADER_SIZES.MAGIC +
346
+ HEADER_SIZES.SUITE +
347
+ HEADER_SIZES.FLAGS +
348
+ HEADER_SIZES.FILE_ID +
349
+ HEADER_SIZES.CHUNK_SIZE +
350
+ HEADER_SIZES.TOTAL_CHUNKS +
351
+ HEADER_SIZES.PLAINTEXT_SIZE +
352
+ HEADER_SIZES.SUITE_PAYLOAD_LEN
353
+ ) {
354
+ return false
355
+ }
356
+ // Read suite_payload_len so we know how much more to wait for.
357
+ const suitePayloadLenOffset =
358
+ HEADER_SIZES.MAGIC +
359
+ HEADER_SIZES.SUITE +
360
+ HEADER_SIZES.FLAGS +
361
+ HEADER_SIZES.FILE_ID +
362
+ HEADER_SIZES.CHUNK_SIZE +
363
+ HEADER_SIZES.TOTAL_CHUNKS +
364
+ HEADER_SIZES.PLAINTEXT_SIZE
365
+ const suitePayloadLen =
366
+ (buffer[suitePayloadLenOffset]! << 8) |
367
+ buffer[suitePayloadLenOffset + 1]!
368
+ const fullHeaderLen =
369
+ suitePayloadLenOffset +
370
+ HEADER_SIZES.SUITE_PAYLOAD_LEN +
371
+ suitePayloadLen +
372
+ HEADER_SIZES.HEADER_MAC
373
+ if (buffer.length < fullHeaderLen) return false
374
+
375
+ const headerBytes = consume(fullHeaderLen)
376
+ parsedHeader = parseHeader(headerBytes)
377
+
378
+ if (parsedHeader.suite !== SUITE.PQ_HYBRID_XCHACHA_MLKEM1024_V1) {
379
+ throw new HeaderError(
380
+ `decrypt stream: this stream only supports pq-hybrid-xchacha-mlkem1024-v1; got suite 0x${parsedHeader.suite.toString(16)}`,
381
+ )
382
+ }
383
+
384
+ // Recover the combined key. Two paths:
385
+ // - KEM mode: run ML-KEM decapsulation now.
386
+ // - Combined-key mode: trust the supplied K. The header MAC check
387
+ // below still cryptographically gates the rest of the stream, so
388
+ // a wrong K fails fast.
389
+ let combinedKey: Uint8Array
390
+ if (combinedKeyOverride) {
391
+ combinedKey = combinedKeyOverride
392
+ } else {
393
+ ;({ combinedKey } = await decapsulateFromHeader({
394
+ suitePayload: parsedHeader.suitePayload,
395
+ recipientSecretKey: recipientSecretKey!,
396
+ envelopeKey: envelopeKey!,
397
+ fileId: parsedHeader.fileId,
398
+ }))
399
+ }
400
+
401
+ const { verifyHeaderMac } = await import('../format/header.js')
402
+ await verifyHeaderMac(parsedHeader, combinedKey)
403
+
404
+ contextPromise = createChunkContext(
405
+ combinedKey,
406
+ parsedHeader.fileId,
407
+ parsedHeader.totalChunks,
408
+ )
409
+
410
+ phase = 1
411
+ return true
412
+ }
413
+
414
+ async function tryEmitChunk(
415
+ controller: TransformStreamDefaultController<Uint8Array>,
416
+ ): Promise<boolean> {
417
+ if (!parsedHeader) return false
418
+
419
+ if (chunkIndex >= parsedHeader.totalChunks) {
420
+ // Already consumed all expected chunks; anything remaining is trailing
421
+ // garbage and must be flagged at flush time.
422
+ return false
423
+ }
424
+
425
+ if (nextCipherLen < 0) {
426
+ if (buffer.length < LENGTH_PREFIX_BYTES) return false
427
+ const lenBytes = consume(LENGTH_PREFIX_BYTES)
428
+ nextCipherLen = readUint32BE(lenBytes)
429
+
430
+ const isFinal = chunkIndex === parsedHeader.totalChunks - 1
431
+ const minCipher = 1 + PQ_HYBRID_V1_TAG_BYTES
432
+ const maxCipher = parsedHeader.chunkSize + PQ_HYBRID_V1_TAG_BYTES
433
+ if (nextCipherLen < minCipher || nextCipherLen > maxCipher) {
434
+ throw new HeaderError('chunk_length_out_of_range')
435
+ }
436
+ if (!isFinal && nextCipherLen !== maxCipher) {
437
+ throw new HeaderError('non_final_chunk_wrong_size')
438
+ }
439
+ }
440
+
441
+ if (buffer.length < nextCipherLen) return false
442
+
443
+ const ctBytes = consume(nextCipherLen)
444
+ nextCipherLen = -1
445
+
446
+ const ctx = await contextPromise!
447
+ const pt = await decryptChunk(ctx, chunkIndex, ctBytes)
448
+ bytesEmitted += pt.length
449
+ controller.enqueue(pt)
450
+ chunkIndex += 1
451
+ return true
452
+ }
453
+
454
+ return new TransformStream<Uint8Array, Uint8Array>({
455
+ async transform(chunk, controller) {
456
+ append(chunk)
457
+ try {
458
+ if (phase === 0) {
459
+ const ok = await tryParseHeader()
460
+ if (!ok) return
461
+ }
462
+ // Drain as many chunks as we have data for.
463
+ while (await tryEmitChunk(controller)) {
464
+ /* loop */
465
+ }
466
+ } catch (err) {
467
+ controller.error(err as Error)
468
+ }
469
+ },
470
+ async flush(controller) {
471
+ try {
472
+ if (phase === 0) {
473
+ throw new HeaderError('header_too_short')
474
+ }
475
+ // No header yet means truncated input.
476
+ if (!parsedHeader) {
477
+ throw new HeaderError('header_too_short')
478
+ }
479
+ // Try once more in case flush is called with everything queued.
480
+ while (await tryEmitChunk(controller)) {
481
+ /* loop */
482
+ }
483
+ if (chunkIndex !== parsedHeader.totalChunks) {
484
+ throw new HeaderError('chunk_truncated')
485
+ }
486
+ if (bytesEmitted !== parsedHeader.plaintextSize) {
487
+ throw new HeaderError('plaintext_size_mismatch')
488
+ }
489
+ if (buffer.length !== 0) {
490
+ throw new HeaderError('trailing_bytes_after_last_chunk')
491
+ }
492
+ } catch (err) {
493
+ controller.error(err as Error)
494
+ }
495
+ },
496
+ })
497
+ }
498
+
499
+ // ─────────────────────────────────────────────────────────────────────
500
+ // Helpers for ergonomics
501
+ // ─────────────────────────────────────────────────────────────────────
502
+
503
+ export interface EncryptStreamPqHybridV1Options {
504
+ /** Recipient's ML-KEM-1024 public key (1568 bytes) */
505
+ recipientPublicKey: Uint8Array
506
+ /** Classical envelope key (32 bytes) */
507
+ envelopeKey: Uint8Array
508
+ /** Total plaintext byte count. Required because the header carries it. */
509
+ plaintextSize: number
510
+ /** Plaintext bytes per chunk. Default 4 MiB. */
511
+ chunkSize?: number
512
+ /** Pre-existing 16-byte file_id, or generated if omitted. */
513
+ fileId?: Uint8Array
514
+ }
515
+
516
+ /**
517
+ * Pipe a ReadableStream<Uint8Array> through the PQ-hybrid-v1 encrypt
518
+ * transform and return the resulting ReadableStream + the materials the
519
+ * caller will need to store alongside the file (file_id) or share back
520
+ * to the sender's records (combined key, suite payload).
521
+ *
522
+ * This helper is async because PQ encapsulation requires libsodium init.
523
+ */
524
+ export async function encryptStreamPqHybridV1(
525
+ source: ReadableStream<Uint8Array>,
526
+ options: EncryptStreamPqHybridV1Options,
527
+ ): Promise<{
528
+ ciphertext: ReadableStream<Uint8Array>
529
+ combinedKey: Uint8Array
530
+ fileId: Uint8Array
531
+ suitePayload: Uint8Array
532
+ }> {
533
+ const { recipientPublicKey, envelopeKey } = options
534
+ const fileId = options.fileId ?? randomBytes(HEADER_SIZES.FILE_ID)
535
+ if (fileId.length !== HEADER_SIZES.FILE_ID) {
536
+ throw new RangeError('encryptStreamPqHybridV1: fileId must be 16 bytes')
537
+ }
538
+
539
+ const { suitePayload, combinedKey } = await encapsulateForRecipient({
540
+ recipientPublicKey,
541
+ envelopeKey,
542
+ fileId,
543
+ })
544
+
545
+ const streamOptions: PqHybridV1EncryptStreamOptions = {
546
+ plaintextSize: options.plaintextSize,
547
+ combinedKey,
548
+ fileId,
549
+ suitePayload,
550
+ }
551
+ if (options.chunkSize !== undefined) {
552
+ streamOptions.chunkSize = options.chunkSize
553
+ }
554
+ const { stream } = createPqHybridV1EncryptStream(streamOptions)
555
+
556
+ return {
557
+ ciphertext: source.pipeThrough(stream),
558
+ combinedKey,
559
+ fileId,
560
+ suitePayload,
561
+ }
562
+ }
563
+
564
+ /**
565
+ * Pipe a ReadableStream<Uint8Array> through the PQ-hybrid-v1 decrypt
566
+ * transform and return the resulting plaintext ReadableStream. See
567
+ * {@link PqHybridV1DecryptStreamOptions} for the two key-input modes
568
+ * (KEM secret + envelope vs. pre-derived combined key K).
569
+ */
570
+ export function decryptStreamPqHybridV1(
571
+ source: ReadableStream<Uint8Array>,
572
+ options: PqHybridV1DecryptStreamOptions,
573
+ ): ReadableStream<Uint8Array> {
574
+ return source.pipeThrough(createPqHybridV1DecryptStream(options))
575
+ }
@@ -205,12 +205,14 @@ export async function decryptBlob(options: DecryptOptions): Promise<Blob> {
205
205
  )
206
206
  }
207
207
 
208
+ // MUST verify the header MAC before reading or interpreting any
209
+ // suite_payload bytes — see parseHeader docstring and
210
+ // spec/format-v1.md § "verification order".
211
+ await verifyHeaderMac(parsed, contentKey)
212
+
208
213
  // Validate the suite payload structure (length etc).
209
214
  parseAesGcmV1SuitePayload(parsed.suitePayload)
210
215
 
211
- // Verify header MAC before processing chunks.
212
- await verifyHeaderMac(parsed, contentKey)
213
-
214
216
  const ctx = await createChunkContext(
215
217
  contentKey,
216
218
  parsed.fileId,
@@ -41,6 +41,18 @@ import {
41
41
  } from '../../internal/encoding.js'
42
42
  import { randomBytes } from '../../internal/runtime.js'
43
43
 
44
+ // Re-exports of suite primitives that are useful to callers outside the
45
+ // streaming/whole-blob API surfaces. `decapsulateFromHeader` lets a
46
+ // caller that already has the parsed suite_payload + KEM material
47
+ // recover the combined key K out-of-band (e.g., a share-link generator
48
+ // that wraps K under a separate password for recipients who never see
49
+ // ML-KEM secrets).
50
+ export {
51
+ decapsulateFromHeader,
52
+ encapsulateForRecipient,
53
+ PQ_HYBRID_V1_SUITE_PAYLOAD_LENGTH,
54
+ } from './index.js'
55
+
44
56
  const LENGTH_PREFIX_BYTES = 4
45
57
 
46
58
  export interface PqHybridEncryptOptions {
@@ -119,7 +119,7 @@ export async function deriveMlKemKeypair(
119
119
  ): Promise<{ publicKey: Uint8Array; secretKey: Uint8Array }> {
120
120
  const seed = await hkdfSha256({
121
121
  ikm: masterSecret,
122
- info: 'shieldfive/v1/pq-hybrid/ml-kem-1024-seed',
122
+ info: HKDF_INFO.ML_KEM_1024_SEED,
123
123
  length: 64,
124
124
  })
125
125
  return ml_kem1024.keygen(seed)
@@ -174,8 +174,11 @@ export async function decryptBlob(
174
174
  )
175
175
  }
176
176
 
177
- parseXChaChaV1SuitePayload(parsed.suitePayload)
177
+ // MUST verify the header MAC before reading or interpreting any
178
+ // suite_payload bytes — see parseHeader docstring and
179
+ // spec/format-v1.md § "verification order".
178
180
  await verifyHeaderMac(parsed, contentKey)
181
+ parseXChaChaV1SuitePayload(parsed.suitePayload)
179
182
 
180
183
  const ctx = await createChunkContext(
181
184
  contentKey,