@shieldfive/crypto 1.0.0-alpha.11

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 (124) hide show
  1. package/CHANGELOG.md +228 -0
  2. package/LICENSE +201 -0
  3. package/README.md +275 -0
  4. package/SECURITY.md +130 -0
  5. package/dist/format/header.d.ts +73 -0
  6. package/dist/format/header.d.ts.map +1 -0
  7. package/dist/format/header.js +230 -0
  8. package/dist/format/header.js.map +1 -0
  9. package/dist/identity/index.d.ts +119 -0
  10. package/dist/identity/index.d.ts.map +1 -0
  11. package/dist/identity/index.js +217 -0
  12. package/dist/identity/index.js.map +1 -0
  13. package/dist/identity/sign.d.ts +92 -0
  14. package/dist/identity/sign.d.ts.map +1 -0
  15. package/dist/identity/sign.js +182 -0
  16. package/dist/identity/sign.js.map +1 -0
  17. package/dist/index.d.ts +58 -0
  18. package/dist/index.d.ts.map +1 -0
  19. package/dist/index.js +146 -0
  20. package/dist/index.js.map +1 -0
  21. package/dist/internal/encoding.d.ts +33 -0
  22. package/dist/internal/encoding.d.ts.map +1 -0
  23. package/dist/internal/encoding.js +135 -0
  24. package/dist/internal/encoding.js.map +1 -0
  25. package/dist/internal/hkdf.d.ts +14 -0
  26. package/dist/internal/hkdf.d.ts.map +1 -0
  27. package/dist/internal/hkdf.js +27 -0
  28. package/dist/internal/hkdf.js.map +1 -0
  29. package/dist/internal/hmac.d.ts +9 -0
  30. package/dist/internal/hmac.d.ts.map +1 -0
  31. package/dist/internal/hmac.js +18 -0
  32. package/dist/internal/hmac.js.map +1 -0
  33. package/dist/internal/runtime.d.ts +29 -0
  34. package/dist/internal/runtime.d.ts.map +1 -0
  35. package/dist/internal/runtime.js +67 -0
  36. package/dist/internal/runtime.js.map +1 -0
  37. package/dist/internal/sodium.d.ts +12 -0
  38. package/dist/internal/sodium.d.ts.map +1 -0
  39. package/dist/internal/sodium.js +34 -0
  40. package/dist/internal/sodium.js.map +1 -0
  41. package/dist/internal/types.d.ts +98 -0
  42. package/dist/internal/types.d.ts.map +1 -0
  43. package/dist/internal/types.js +70 -0
  44. package/dist/internal/types.js.map +1 -0
  45. package/dist/kdf/argon2id.d.ts +72 -0
  46. package/dist/kdf/argon2id.d.ts.map +1 -0
  47. package/dist/kdf/argon2id.js +98 -0
  48. package/dist/kdf/argon2id.js.map +1 -0
  49. package/dist/migration/v0-bridge.d.ts +94 -0
  50. package/dist/migration/v0-bridge.d.ts.map +1 -0
  51. package/dist/migration/v0-bridge.js +203 -0
  52. package/dist/migration/v0-bridge.js.map +1 -0
  53. package/dist/streams/aes-gcm-v1.d.ts +144 -0
  54. package/dist/streams/aes-gcm-v1.d.ts.map +1 -0
  55. package/dist/streams/aes-gcm-v1.js +456 -0
  56. package/dist/streams/aes-gcm-v1.js.map +1 -0
  57. package/dist/streams/pq-hybrid-v1.d.ts +219 -0
  58. package/dist/streams/pq-hybrid-v1.d.ts.map +1 -0
  59. package/dist/streams/pq-hybrid-v1.js +473 -0
  60. package/dist/streams/pq-hybrid-v1.js.map +1 -0
  61. package/dist/suites/aes-gcm-v0/api.d.ts +48 -0
  62. package/dist/suites/aes-gcm-v0/api.d.ts.map +1 -0
  63. package/dist/suites/aes-gcm-v0/api.js +110 -0
  64. package/dist/suites/aes-gcm-v0/api.js.map +1 -0
  65. package/dist/suites/aes-gcm-v1/api.d.ts +54 -0
  66. package/dist/suites/aes-gcm-v1/api.d.ts.map +1 -0
  67. package/dist/suites/aes-gcm-v1/api.js +181 -0
  68. package/dist/suites/aes-gcm-v1/api.js.map +1 -0
  69. package/dist/suites/aes-gcm-v1/index.d.ts +59 -0
  70. package/dist/suites/aes-gcm-v1/index.d.ts.map +1 -0
  71. package/dist/suites/aes-gcm-v1/index.js +177 -0
  72. package/dist/suites/aes-gcm-v1/index.js.map +1 -0
  73. package/dist/suites/aes-gcm-v2/api.d.ts +44 -0
  74. package/dist/suites/aes-gcm-v2/api.d.ts.map +1 -0
  75. package/dist/suites/aes-gcm-v2/api.js +162 -0
  76. package/dist/suites/aes-gcm-v2/api.js.map +1 -0
  77. package/dist/suites/aes-gcm-v2/index.d.ts +63 -0
  78. package/dist/suites/aes-gcm-v2/index.d.ts.map +1 -0
  79. package/dist/suites/aes-gcm-v2/index.js +193 -0
  80. package/dist/suites/aes-gcm-v2/index.js.map +1 -0
  81. package/dist/suites/pq-hybrid-v1/api.d.ts +67 -0
  82. package/dist/suites/pq-hybrid-v1/api.d.ts.map +1 -0
  83. package/dist/suites/pq-hybrid-v1/api.js +190 -0
  84. package/dist/suites/pq-hybrid-v1/api.js.map +1 -0
  85. package/dist/suites/pq-hybrid-v1/index.d.ts +101 -0
  86. package/dist/suites/pq-hybrid-v1/index.d.ts.map +1 -0
  87. package/dist/suites/pq-hybrid-v1/index.js +225 -0
  88. package/dist/suites/pq-hybrid-v1/index.js.map +1 -0
  89. package/dist/suites/xchacha-v1/api.d.ts +29 -0
  90. package/dist/suites/xchacha-v1/api.d.ts.map +1 -0
  91. package/dist/suites/xchacha-v1/api.js +154 -0
  92. package/dist/suites/xchacha-v1/api.js.map +1 -0
  93. package/dist/suites/xchacha-v1/index.d.ts +50 -0
  94. package/dist/suites/xchacha-v1/index.d.ts.map +1 -0
  95. package/dist/suites/xchacha-v1/index.js +133 -0
  96. package/dist/suites/xchacha-v1/index.js.map +1 -0
  97. package/package.json +124 -0
  98. package/spec/format-v0.md +81 -0
  99. package/spec/format-v1.md +400 -0
  100. package/spec/key-derivation.md +167 -0
  101. package/spec/threat-model.md +242 -0
  102. package/src/format/header.ts +316 -0
  103. package/src/identity/index.ts +371 -0
  104. package/src/identity/sign.ts +221 -0
  105. package/src/index.ts +224 -0
  106. package/src/internal/encoding.ts +152 -0
  107. package/src/internal/hkdf.ts +47 -0
  108. package/src/internal/hmac.ts +33 -0
  109. package/src/internal/runtime.ts +80 -0
  110. package/src/internal/sodium.ts +38 -0
  111. package/src/internal/types.ts +134 -0
  112. package/src/kdf/argon2id.ts +165 -0
  113. package/src/migration/v0-bridge.ts +347 -0
  114. package/src/streams/aes-gcm-v1.ts +647 -0
  115. package/src/streams/pq-hybrid-v1.ts +722 -0
  116. package/src/suites/aes-gcm-v0/api.ts +155 -0
  117. package/src/suites/aes-gcm-v1/api.ts +292 -0
  118. package/src/suites/aes-gcm-v1/index.ts +269 -0
  119. package/src/suites/aes-gcm-v2/api.ts +268 -0
  120. package/src/suites/aes-gcm-v2/index.ts +289 -0
  121. package/src/suites/pq-hybrid-v1/api.ts +299 -0
  122. package/src/suites/pq-hybrid-v1/index.ts +343 -0
  123. package/src/suites/xchacha-v1/api.ts +254 -0
  124. package/src/suites/xchacha-v1/index.ts +213 -0
@@ -0,0 +1,722 @@
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
+ buildHeaderUnauthenticated,
31
+ deriveHeaderMacKey,
32
+ HeaderError,
33
+ parseHeader,
34
+ } from '../format/header.js'
35
+ import {
36
+ PQ_HYBRID_V1_SUITE_PAYLOAD_LENGTH,
37
+ PQ_HYBRID_V1_TAG_BYTES,
38
+ createChunkContext,
39
+ decapsulateFromHeader,
40
+ decryptChunk,
41
+ encapsulateForRecipient,
42
+ encryptChunk,
43
+ } from '../suites/pq-hybrid-v1/index.js'
44
+ import {
45
+ DEFAULT_CHUNK_SIZE,
46
+ HEADER_SIZES,
47
+ MAX_TOTAL_CHUNKS,
48
+ SUITE,
49
+ } from '../internal/types.js'
50
+ import { concatBytes, readUint32BE, uint32BE } from '../internal/encoding.js'
51
+ import { hmacSha256 } from '../internal/hmac.js'
52
+ import { randomBytes } from '../internal/runtime.js'
53
+ import {
54
+ buildSignatureBlock,
55
+ deriveEd25519PublicKey,
56
+ ED25519_SECRET_KEY_LENGTH,
57
+ SIGNATURE_ALGO_ED25519,
58
+ signHeaderAndMacs,
59
+ } from '../identity/sign.js'
60
+ import {
61
+ type DecryptionMetadata,
62
+ finalizeSignatureMetadata,
63
+ } from './aes-gcm-v1.js'
64
+
65
+ export type { DecryptionMetadata, VerifiedSignature } from './aes-gcm-v1.js'
66
+
67
+ const LENGTH_PREFIX_BYTES = 4
68
+
69
+ // ─────────────────────────────────────────────────────────────────────
70
+ // Encrypting transform
71
+ // ─────────────────────────────────────────────────────────────────────
72
+
73
+ export interface PqHybridV1EncryptStreamOptions {
74
+ /** Total plaintext byte count. Required because the header carries it. */
75
+ plaintextSize: number
76
+ /** Plaintext bytes per chunk. Default 4 MiB. */
77
+ chunkSize?: number
78
+ /**
79
+ * Combined content key from `encapsulateForRecipient`. 32 bytes. Used
80
+ * both for header MAC and for chunk AEAD.
81
+ *
82
+ * SECURITY: Possession of `combinedKey` grants permanent decryption
83
+ * capability for any file whose header was produced with it. Treat
84
+ * as cryptographic secret material: hold only in memory for the
85
+ * duration of the operation, do not persist to disk or storage, do
86
+ * not log, do not transmit. The only safe way to reproduce it on
87
+ * another machine is to re-encapsulate via the recipient's ML-KEM
88
+ * public key.
89
+ */
90
+ combinedKey: Uint8Array
91
+ /** 16-byte file_id used as HKDF salt in encapsulation and key derivation. */
92
+ fileId: Uint8Array
93
+ /**
94
+ * Suite payload produced by `encapsulateForRecipient` (1664 bytes —
95
+ * 1568-byte ML-KEM ciphertext + 72-byte wrapped classical share + 24-byte
96
+ * classical nonce).
97
+ */
98
+ suitePayload: Uint8Array
99
+ /**
100
+ * Optional 32-byte Ed25519 secret seed. When provided, the stream
101
+ * appends a signature block over `header_unauthenticated_bytes ||
102
+ * concat(chunk_macs)` after the final chunk. When omitted, no block
103
+ * is emitted and the file decrypts as unsigned (legacy behavior).
104
+ */
105
+ ed25519SecretKey?: Uint8Array
106
+ }
107
+
108
+ export interface PqHybridV1EncryptStreamResult {
109
+ /** TransformStream<Uint8Array, Uint8Array> emitting the v1 wire format. */
110
+ stream: TransformStream<Uint8Array, Uint8Array>
111
+ /**
112
+ * SECURITY: Possession of `combinedKey` grants permanent decryption
113
+ * capability for any file whose header was produced with it. Treat
114
+ * as cryptographic secret material: hold only in memory for the
115
+ * duration of the operation, do not persist to disk or storage, do
116
+ * not log, do not transmit. The only safe way to reproduce it on
117
+ * another machine is to re-encapsulate via the recipient's ML-KEM
118
+ * public key.
119
+ *
120
+ * Echoed back for caller convenience.
121
+ */
122
+ combinedKey: Uint8Array
123
+ /** The file_id used (echoed back for caller convenience). */
124
+ fileId: Uint8Array
125
+ }
126
+
127
+ /**
128
+ * Build a TransformStream that encrypts plaintext into v1 wire-format
129
+ * ciphertext on the fly under suite 0x03. The stream emits the header
130
+ * first, then each chunk as it arrives.
131
+ *
132
+ * The caller MUST pass `plaintextSize` because the header records it.
133
+ * If the caller doesn't know the size up front, they must accumulate
134
+ * the plaintext into a buffer first — there is no way to write a
135
+ * self-describing header otherwise.
136
+ *
137
+ * Unlike the AES-GCM-v1 factory, the PQ-hybrid factory cannot manufacture
138
+ * its own key material — the combined key, file_id, and suite payload
139
+ * are all outputs of `encapsulateForRecipient`. Use the
140
+ * `encryptStreamPqHybridV1` helper when you'd rather pass a recipient
141
+ * public key directly.
142
+ */
143
+ export function createPqHybridV1EncryptStream(
144
+ options: PqHybridV1EncryptStreamOptions,
145
+ ): PqHybridV1EncryptStreamResult {
146
+ const chunkSize = options.chunkSize ?? DEFAULT_CHUNK_SIZE
147
+ if (!Number.isSafeInteger(chunkSize) || chunkSize <= 0) {
148
+ throw new RangeError('encrypt stream: chunkSize must be positive integer')
149
+ }
150
+ if (
151
+ !Number.isSafeInteger(options.plaintextSize) ||
152
+ options.plaintextSize < 0
153
+ ) {
154
+ throw new RangeError('encrypt stream: plaintextSize must be a non-negative integer')
155
+ }
156
+
157
+ const totalChunks =
158
+ options.plaintextSize === 0
159
+ ? 0
160
+ : Math.ceil(options.plaintextSize / chunkSize)
161
+ if (totalChunks > MAX_TOTAL_CHUNKS) {
162
+ throw new RangeError('encrypt stream: file would exceed total_chunks limit')
163
+ }
164
+
165
+ const { combinedKey, fileId, suitePayload } = options
166
+ if (combinedKey.length !== 32) {
167
+ throw new RangeError('encrypt stream: combinedKey must be 32 bytes')
168
+ }
169
+ if (fileId.length !== HEADER_SIZES.FILE_ID) {
170
+ throw new RangeError('encrypt stream: fileId must be 16 bytes')
171
+ }
172
+ if (suitePayload.length !== PQ_HYBRID_V1_SUITE_PAYLOAD_LENGTH) {
173
+ throw new RangeError(
174
+ `encrypt stream: suitePayload must be ${PQ_HYBRID_V1_SUITE_PAYLOAD_LENGTH} bytes`,
175
+ )
176
+ }
177
+
178
+ const ed25519SecretKey = options.ed25519SecretKey
179
+ if (ed25519SecretKey && ed25519SecretKey.length !== ED25519_SECRET_KEY_LENGTH) {
180
+ throw new RangeError(
181
+ `encrypt stream: ed25519SecretKey must be ${ED25519_SECRET_KEY_LENGTH} bytes`,
182
+ )
183
+ }
184
+
185
+ // State held across the lifetime of the stream:
186
+ // - pending plaintext buffer (collects until we have a full chunk)
187
+ // - chunk index counter
188
+ // - bytes consumed counter (for sanity check vs plaintextSize)
189
+ // - context (lazily initialized)
190
+ // - unauthenticated header bytes (kept for signing)
191
+ // - per-chunk MAC tags (last 16 bytes of each chunk ciphertext)
192
+ let pending = new Uint8Array(0)
193
+ let chunkIndex = 0
194
+ let bytesConsumed = 0
195
+ let contextPromise: ReturnType<typeof createChunkContext> | null = null
196
+ let headerEmitted = false
197
+ let unauthenticatedHeader: Uint8Array | null = null
198
+ const chunkMacs: Uint8Array[] = []
199
+
200
+ async function ensureHeader(
201
+ controller: TransformStreamDefaultController<Uint8Array>,
202
+ ): Promise<void> {
203
+ if (headerEmitted) return
204
+ const unauth = buildHeaderUnauthenticated({
205
+ suite: SUITE.PQ_HYBRID_XCHACHA_MLKEM1024_V1,
206
+ fileId,
207
+ chunkSize,
208
+ totalChunks,
209
+ plaintextSize: options.plaintextSize,
210
+ suitePayload,
211
+ })
212
+ const macKey = await deriveHeaderMacKey(combinedKey, fileId)
213
+ const mac = await hmacSha256(macKey, unauth)
214
+ unauthenticatedHeader = unauth
215
+ controller.enqueue(concatBytes([unauth, mac]))
216
+ headerEmitted = true
217
+ }
218
+
219
+ async function emitChunk(
220
+ plaintext: Uint8Array,
221
+ controller: TransformStreamDefaultController<Uint8Array>,
222
+ ): Promise<void> {
223
+ if (!contextPromise) {
224
+ contextPromise = createChunkContext(combinedKey, fileId, totalChunks)
225
+ }
226
+ const ctx = await contextPromise
227
+ const ct = await encryptChunk(ctx, chunkIndex, plaintext)
228
+ controller.enqueue(uint32BE(ct.length))
229
+ controller.enqueue(ct)
230
+ if (ed25519SecretKey) {
231
+ chunkMacs.push(ct.slice(ct.length - PQ_HYBRID_V1_TAG_BYTES))
232
+ }
233
+ chunkIndex += 1
234
+ }
235
+
236
+ const transformer: Transformer<Uint8Array, Uint8Array> = {
237
+ async transform(chunk, controller) {
238
+ await ensureHeader(controller)
239
+ bytesConsumed += chunk.length
240
+ if (bytesConsumed > options.plaintextSize) {
241
+ controller.error(
242
+ new RangeError('encrypt stream: input exceeded declared plaintextSize'),
243
+ )
244
+ return
245
+ }
246
+ // Append to pending buffer
247
+ const merged = new Uint8Array(pending.length + chunk.length)
248
+ merged.set(pending, 0)
249
+ merged.set(chunk, pending.length)
250
+ pending = merged
251
+
252
+ // Drain whole chunks
253
+ while (pending.length >= chunkSize && chunkIndex < totalChunks - 1) {
254
+ const slice = pending.subarray(0, chunkSize)
255
+ await emitChunk(slice, controller)
256
+ pending = pending.subarray(chunkSize)
257
+ // Subarray shares the buffer; copy out so we can drop the rest.
258
+ pending = pending.slice(0)
259
+ }
260
+ },
261
+ async flush(controller) {
262
+ await ensureHeader(controller)
263
+ if (bytesConsumed !== options.plaintextSize) {
264
+ controller.error(
265
+ new RangeError(
266
+ `encrypt stream: input was ${bytesConsumed} bytes, declared ${options.plaintextSize}`,
267
+ ),
268
+ )
269
+ return
270
+ }
271
+ // Emit any remaining whole chunks plus the final partial chunk.
272
+ while (chunkIndex < totalChunks) {
273
+ const isLastIteration = chunkIndex === totalChunks - 1
274
+ const sliceSize = isLastIteration
275
+ ? pending.length // final chunk: whatever's left
276
+ : chunkSize
277
+ const slice = pending.subarray(0, sliceSize)
278
+ await emitChunk(slice, controller)
279
+ pending = pending.subarray(sliceSize).slice(0)
280
+ }
281
+ if (pending.length !== 0) {
282
+ controller.error(
283
+ new RangeError('encrypt stream: residual bytes after final chunk'),
284
+ )
285
+ return
286
+ }
287
+ if (ed25519SecretKey) {
288
+ if (!unauthenticatedHeader) {
289
+ controller.error(
290
+ new Error('encrypt stream: header not finalized before signing'),
291
+ )
292
+ return
293
+ }
294
+ const signature = signHeaderAndMacs({
295
+ ed25519SecretKey,
296
+ header: unauthenticatedHeader,
297
+ chunkMacs,
298
+ })
299
+ const publicKey = deriveEd25519PublicKey(ed25519SecretKey)
300
+ controller.enqueue(
301
+ buildSignatureBlock({
302
+ algorithm: SIGNATURE_ALGO_ED25519,
303
+ publicKey,
304
+ signature,
305
+ }),
306
+ )
307
+ }
308
+ },
309
+ }
310
+
311
+ return {
312
+ stream: new TransformStream(transformer),
313
+ combinedKey,
314
+ fileId,
315
+ }
316
+ }
317
+
318
+ // ─────────────────────────────────────────────────────────────────────
319
+ // Decrypting transform
320
+ // ─────────────────────────────────────────────────────────────────────
321
+
322
+ /**
323
+ * Inputs for {@link createPqHybridV1DecryptStream}. Either provide the
324
+ * KEM material (`recipientSecretKey` + `envelopeKey`) so the stream can
325
+ * derive the combined key itself, OR provide the already-derived
326
+ * `combinedKey` directly. The latter is what share-link recipients use:
327
+ * they hold a 32-byte K (wrapped under the share-link password) and
328
+ * never see the ML-KEM secret key.
329
+ *
330
+ * Mixing both modes is not supported — `combinedKey` always wins. The
331
+ * caller is responsible for picking one path.
332
+ */
333
+ export type PqHybridV1DecryptStreamOptions =
334
+ | {
335
+ /** Recipient's ML-KEM-1024 secret key (3168 bytes). */
336
+ recipientSecretKey: Uint8Array
337
+ /** Classical envelope key (32 bytes). */
338
+ envelopeKey: Uint8Array
339
+ combinedKey?: undefined
340
+ /**
341
+ * If provided, a trailing signature block (if present) is verified
342
+ * against this Ed25519 public key. See `AesGcmV1DecryptStreamOptions`
343
+ * for the verification semantics — they are identical here.
344
+ */
345
+ expectedSignerPublicKey?: Uint8Array
346
+ }
347
+ | {
348
+ /**
349
+ * Pre-derived 32-byte combined key K. When provided, the stream
350
+ * skips ML-KEM decapsulation entirely and uses K for header MAC
351
+ * verification + per-chunk AEAD. Header MAC validation still
352
+ * cryptographically gates the rest of the stream, so a wrong K
353
+ * fails fast.
354
+ *
355
+ * SECURITY: Possession of `combinedKey` grants permanent decryption
356
+ * capability for any file whose header was produced with it. Treat
357
+ * as cryptographic secret material: hold only in memory for the
358
+ * duration of the operation, do not persist to disk or storage, do
359
+ * not log, do not transmit. The only safe way to reproduce it on
360
+ * another machine is to re-encapsulate via the recipient's ML-KEM
361
+ * public key.
362
+ */
363
+ combinedKey: Uint8Array
364
+ recipientSecretKey?: undefined
365
+ envelopeKey?: undefined
366
+ /** See sibling variant. */
367
+ expectedSignerPublicKey?: Uint8Array
368
+ }
369
+
370
+ export interface PqHybridV1DecryptStreamResult {
371
+ stream: TransformStream<Uint8Array, Uint8Array>
372
+ metadata: Promise<DecryptionMetadata>
373
+ }
374
+
375
+ /**
376
+ * Build a TransformStream that decrypts a v1 ciphertext stream produced
377
+ * under suite 0x03 into plaintext. Unlike the whole-blob decryptor, this
378
+ * version processes input incrementally — useful for very large files or
379
+ * when ciphertext arrives chunked over the network.
380
+ *
381
+ * Two key-input modes:
382
+ * - KEM mode (`recipientSecretKey` + `envelopeKey`): the stream runs
383
+ * ML-KEM decapsulation once, the moment the header has been
384
+ * buffered, then proceeds identically to the AES-GCM-v1 decrypt
385
+ * stream.
386
+ * - Combined-key mode (`combinedKey`): skips decapsulation entirely
387
+ * and uses the supplied K for header MAC verification + chunk AEAD.
388
+ * Intended for share-link recipients who hold a wrapped K but no
389
+ * ML-KEM secret.
390
+ */
391
+ export function createPqHybridV1DecryptStream(
392
+ options: PqHybridV1DecryptStreamOptions,
393
+ ): PqHybridV1DecryptStreamResult {
394
+ const combinedKeyOverride = options.combinedKey
395
+ const recipientSecretKey = options.recipientSecretKey
396
+ const envelopeKey = options.envelopeKey
397
+ const expectedSignerPublicKey = options.expectedSignerPublicKey
398
+
399
+ let resolveMetadata!: (m: DecryptionMetadata) => void
400
+ let rejectMetadata!: (err: unknown) => void
401
+ const metadata = new Promise<DecryptionMetadata>((resolve, reject) => {
402
+ resolveMetadata = resolve
403
+ rejectMetadata = reject
404
+ })
405
+ // See aes-gcm-v1.ts createAesGcmV1DecryptStream for rationale.
406
+ metadata.catch(() => {})
407
+
408
+ if (combinedKeyOverride) {
409
+ if (combinedKeyOverride.length !== 32) {
410
+ throw new RangeError('decrypt stream: combinedKey must be 32 bytes')
411
+ }
412
+ } else {
413
+ if (!recipientSecretKey || !envelopeKey) {
414
+ throw new RangeError(
415
+ 'decrypt stream: provide either combinedKey or recipientSecretKey + envelopeKey',
416
+ )
417
+ }
418
+ if (envelopeKey.length !== 32) {
419
+ throw new RangeError('decrypt stream: envelopeKey must be 32 bytes')
420
+ }
421
+ // Length of recipientSecretKey is checked inside decapsulateFromHeader.
422
+ }
423
+
424
+ // Phases:
425
+ // 0 = waiting for header bytes
426
+ // 1 = streaming chunks: alternating length-prefix + ciphertext
427
+ let phase: 0 | 1 = 0
428
+ let buffer = new Uint8Array(0)
429
+ let parsedHeader: ReturnType<typeof parseHeader> | null = null
430
+ let chunkIndex = 0
431
+ let bytesEmitted = 0
432
+ let nextCipherLen = -1
433
+ let contextPromise: ReturnType<typeof createChunkContext> | null = null
434
+ const chunkMacs: Uint8Array[] = []
435
+
436
+ function append(input: Uint8Array): void {
437
+ const merged = new Uint8Array(buffer.length + input.length)
438
+ merged.set(buffer, 0)
439
+ merged.set(input, buffer.length)
440
+ buffer = merged
441
+ }
442
+
443
+ function consume(n: number): Uint8Array {
444
+ const out = buffer.subarray(0, n).slice(0)
445
+ buffer = buffer.subarray(n).slice(0)
446
+ return out
447
+ }
448
+
449
+ async function tryParseHeader(): Promise<boolean> {
450
+ // Need at least the fixed prefix + MAC (no suite_payload).
451
+ if (
452
+ buffer.length <
453
+ HEADER_SIZES.MAGIC +
454
+ HEADER_SIZES.SUITE +
455
+ HEADER_SIZES.FLAGS +
456
+ HEADER_SIZES.FILE_ID +
457
+ HEADER_SIZES.CHUNK_SIZE +
458
+ HEADER_SIZES.TOTAL_CHUNKS +
459
+ HEADER_SIZES.PLAINTEXT_SIZE +
460
+ HEADER_SIZES.SUITE_PAYLOAD_LEN
461
+ ) {
462
+ return false
463
+ }
464
+ // Read suite_payload_len so we know how much more to wait for.
465
+ const suitePayloadLenOffset =
466
+ HEADER_SIZES.MAGIC +
467
+ HEADER_SIZES.SUITE +
468
+ HEADER_SIZES.FLAGS +
469
+ HEADER_SIZES.FILE_ID +
470
+ HEADER_SIZES.CHUNK_SIZE +
471
+ HEADER_SIZES.TOTAL_CHUNKS +
472
+ HEADER_SIZES.PLAINTEXT_SIZE
473
+ const suitePayloadLen =
474
+ (buffer[suitePayloadLenOffset]! << 8) |
475
+ buffer[suitePayloadLenOffset + 1]!
476
+ const fullHeaderLen =
477
+ suitePayloadLenOffset +
478
+ HEADER_SIZES.SUITE_PAYLOAD_LEN +
479
+ suitePayloadLen +
480
+ HEADER_SIZES.HEADER_MAC
481
+ if (buffer.length < fullHeaderLen) return false
482
+
483
+ const headerBytes = consume(fullHeaderLen)
484
+ parsedHeader = parseHeader(headerBytes)
485
+
486
+ if (parsedHeader.suite !== SUITE.PQ_HYBRID_XCHACHA_MLKEM1024_V1) {
487
+ throw new HeaderError(
488
+ `decrypt stream: this stream only supports pq-hybrid-xchacha-mlkem1024-v1; got suite 0x${parsedHeader.suite.toString(16)}`,
489
+ )
490
+ }
491
+
492
+ // Recover the combined key. Two paths:
493
+ // - KEM mode: run ML-KEM decapsulation now.
494
+ // - Combined-key mode: trust the supplied K. The header MAC check
495
+ // below still cryptographically gates the rest of the stream, so
496
+ // a wrong K fails fast.
497
+ let combinedKey: Uint8Array
498
+ if (combinedKeyOverride) {
499
+ combinedKey = combinedKeyOverride
500
+ } else {
501
+ ;({ combinedKey } = await decapsulateFromHeader({
502
+ suitePayload: parsedHeader.suitePayload,
503
+ recipientSecretKey: recipientSecretKey!,
504
+ envelopeKey: envelopeKey!,
505
+ fileId: parsedHeader.fileId,
506
+ }))
507
+ }
508
+
509
+ const { verifyHeaderMac } = await import('../format/header.js')
510
+ await verifyHeaderMac(parsedHeader, combinedKey)
511
+
512
+ contextPromise = createChunkContext(
513
+ combinedKey,
514
+ parsedHeader.fileId,
515
+ parsedHeader.totalChunks,
516
+ )
517
+
518
+ phase = 1
519
+ return true
520
+ }
521
+
522
+ async function tryEmitChunk(
523
+ controller: TransformStreamDefaultController<Uint8Array>,
524
+ ): Promise<boolean> {
525
+ if (!parsedHeader) return false
526
+
527
+ if (chunkIndex >= parsedHeader.totalChunks) {
528
+ // Already consumed all expected chunks; anything remaining is trailing
529
+ // garbage and must be flagged at flush time.
530
+ return false
531
+ }
532
+
533
+ if (nextCipherLen < 0) {
534
+ if (buffer.length < LENGTH_PREFIX_BYTES) return false
535
+ const lenBytes = consume(LENGTH_PREFIX_BYTES)
536
+ nextCipherLen = readUint32BE(lenBytes)
537
+
538
+ const isFinal = chunkIndex === parsedHeader.totalChunks - 1
539
+ const minCipher = 1 + PQ_HYBRID_V1_TAG_BYTES
540
+ const maxCipher = parsedHeader.chunkSize + PQ_HYBRID_V1_TAG_BYTES
541
+ if (nextCipherLen < minCipher || nextCipherLen > maxCipher) {
542
+ throw new HeaderError('chunk_length_out_of_range')
543
+ }
544
+ if (!isFinal && nextCipherLen !== maxCipher) {
545
+ throw new HeaderError('non_final_chunk_wrong_size')
546
+ }
547
+ }
548
+
549
+ if (buffer.length < nextCipherLen) return false
550
+
551
+ const ctBytes = consume(nextCipherLen)
552
+ nextCipherLen = -1
553
+
554
+ const ctx = await contextPromise!
555
+ const pt = await decryptChunk(ctx, chunkIndex, ctBytes)
556
+ bytesEmitted += pt.length
557
+ controller.enqueue(pt)
558
+ chunkMacs.push(ctBytes.slice(ctBytes.length - PQ_HYBRID_V1_TAG_BYTES))
559
+ chunkIndex += 1
560
+ return true
561
+ }
562
+
563
+ return {
564
+ stream: new TransformStream<Uint8Array, Uint8Array>({
565
+ async transform(chunk, controller) {
566
+ append(chunk)
567
+ try {
568
+ if (phase === 0) {
569
+ const ok = await tryParseHeader()
570
+ if (!ok) return
571
+ }
572
+ // Drain as many chunks as we have data for.
573
+ while (await tryEmitChunk(controller)) {
574
+ /* loop */
575
+ }
576
+ } catch (err) {
577
+ controller.error(err as Error)
578
+ rejectMetadata(err)
579
+ }
580
+ },
581
+ async flush(controller) {
582
+ try {
583
+ if (phase === 0) {
584
+ throw new HeaderError('header_too_short')
585
+ }
586
+ // No header yet means truncated input.
587
+ if (!parsedHeader) {
588
+ throw new HeaderError('header_too_short')
589
+ }
590
+ // Try once more in case flush is called with everything queued.
591
+ while (await tryEmitChunk(controller)) {
592
+ /* loop */
593
+ }
594
+ if (chunkIndex !== parsedHeader.totalChunks) {
595
+ throw new HeaderError('chunk_truncated')
596
+ }
597
+ if (bytesEmitted !== parsedHeader.plaintextSize) {
598
+ throw new HeaderError('plaintext_size_mismatch')
599
+ }
600
+ const signatureResult = finalizeSignatureMetadata({
601
+ trailingBytes: buffer,
602
+ header: parsedHeader.unauthenticatedBytes,
603
+ chunkMacs,
604
+ expectedSignerPublicKey,
605
+ })
606
+ buffer = new Uint8Array(0)
607
+ resolveMetadata({ signature: signatureResult })
608
+ } catch (err) {
609
+ controller.error(err as Error)
610
+ rejectMetadata(err)
611
+ }
612
+ },
613
+ }),
614
+ metadata,
615
+ }
616
+ }
617
+
618
+ // ─────────────────────────────────────────────────────────────────────
619
+ // Helpers for ergonomics
620
+ // ─────────────────────────────────────────────────────────────────────
621
+
622
+ export interface EncryptStreamPqHybridV1Options {
623
+ /** Recipient's ML-KEM-1024 public key (1568 bytes) */
624
+ recipientPublicKey: Uint8Array
625
+ /** Classical envelope key (32 bytes) */
626
+ envelopeKey: Uint8Array
627
+ /** Total plaintext byte count. Required because the header carries it. */
628
+ plaintextSize: number
629
+ /** Plaintext bytes per chunk. Default 4 MiB. */
630
+ chunkSize?: number
631
+ /** Pre-existing 16-byte file_id, or generated if omitted. */
632
+ fileId?: Uint8Array
633
+ /**
634
+ * Optional 32-byte Ed25519 secret seed for sender attribution. When
635
+ * provided, a signature block is appended after the final chunk.
636
+ */
637
+ ed25519SecretKey?: Uint8Array
638
+ }
639
+
640
+ /**
641
+ * Pipe a ReadableStream<Uint8Array> through the PQ-hybrid-v1 encrypt
642
+ * transform and return the resulting ReadableStream alongside the
643
+ * derived material the caller will need: the 16-byte file_id (safe
644
+ * to persist with the ciphertext), the suite payload (safe to
645
+ * persist with the ciphertext; required for later decapsulation),
646
+ * and the 32-byte combined key.
647
+ *
648
+ * SECURITY: The returned `combinedKey` grants permanent decryption
649
+ * capability for any file whose header was produced with it. Treat
650
+ * as cryptographic secret material: hold only in memory for the
651
+ * duration of the operation, do not persist to disk or storage, do
652
+ * not log, do not transmit. The only safe way to reproduce it on
653
+ * another machine is to re-encapsulate via the recipient's ML-KEM
654
+ * public key.
655
+ *
656
+ * This helper is async because PQ encapsulation requires libsodium
657
+ * init.
658
+ */
659
+ export async function encryptStreamPqHybridV1(
660
+ source: ReadableStream<Uint8Array>,
661
+ options: EncryptStreamPqHybridV1Options,
662
+ ): Promise<{
663
+ ciphertext: ReadableStream<Uint8Array>
664
+ combinedKey: Uint8Array
665
+ fileId: Uint8Array
666
+ suitePayload: Uint8Array
667
+ }> {
668
+ const { recipientPublicKey, envelopeKey } = options
669
+ const fileId = options.fileId ?? randomBytes(HEADER_SIZES.FILE_ID)
670
+ if (fileId.length !== HEADER_SIZES.FILE_ID) {
671
+ throw new RangeError('encryptStreamPqHybridV1: fileId must be 16 bytes')
672
+ }
673
+
674
+ const { suitePayload, combinedKey } = await encapsulateForRecipient({
675
+ recipientPublicKey,
676
+ envelopeKey,
677
+ fileId,
678
+ })
679
+
680
+ const streamOptions: PqHybridV1EncryptStreamOptions = {
681
+ plaintextSize: options.plaintextSize,
682
+ combinedKey,
683
+ fileId,
684
+ suitePayload,
685
+ }
686
+ if (options.chunkSize !== undefined) {
687
+ streamOptions.chunkSize = options.chunkSize
688
+ }
689
+ if (options.ed25519SecretKey !== undefined) {
690
+ streamOptions.ed25519SecretKey = options.ed25519SecretKey
691
+ }
692
+ const { stream } = createPqHybridV1EncryptStream(streamOptions)
693
+
694
+ return {
695
+ ciphertext: source.pipeThrough(stream),
696
+ combinedKey,
697
+ fileId,
698
+ suitePayload,
699
+ }
700
+ }
701
+
702
+ /**
703
+ * Pipe a ReadableStream<Uint8Array> through the PQ-hybrid-v1 decrypt
704
+ * transform and return the resulting plaintext ReadableStream + a
705
+ * `metadata` Promise carrying the parsed signature block (or
706
+ * `signature: null` for unsigned / legacy files). See
707
+ * {@link PqHybridV1DecryptStreamOptions} for the two key-input modes
708
+ * (KEM secret + envelope vs. pre-derived combined key K).
709
+ */
710
+ export function decryptStreamPqHybridV1(
711
+ source: ReadableStream<Uint8Array>,
712
+ options: PqHybridV1DecryptStreamOptions,
713
+ ): {
714
+ plaintext: ReadableStream<Uint8Array>
715
+ metadata: Promise<DecryptionMetadata>
716
+ } {
717
+ const { stream, metadata } = createPqHybridV1DecryptStream(options)
718
+ return {
719
+ plaintext: source.pipeThrough(stream),
720
+ metadata,
721
+ }
722
+ }