@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,647 @@
1
+ /**
2
+ * Streaming encrypt/decrypt for the v1 wire format.
3
+ *
4
+ * The whole-blob APIs in `suites/<name>/api.ts` materialize entire files in
5
+ * memory. That's fine for small files; for multi-gigabyte files on a
6
+ * mobile device it isn't.
7
+ *
8
+ * This module exposes a WHATWG TransformStream factory that ingests
9
+ * plaintext (or ciphertext) chunks from any ReadableStream and emits the
10
+ * other side, without ever holding more than one chunk-plus-header in
11
+ * memory at once.
12
+ *
13
+ * Currently implemented:
14
+ * - Suite 0x01 (aes-256-gcm-v1) encrypt
15
+ * - Suite 0x01 (aes-256-gcm-v1) decrypt
16
+ *
17
+ * The XChaCha and PQ-hybrid suites use the same chunk format and AAD;
18
+ * adding them is a copy of the AES module with the suite primitive
19
+ * swapped, but we ship one suite first to lock the streaming contract.
20
+ */
21
+
22
+ import {
23
+ buildHeaderUnauthenticated,
24
+ deriveHeaderMacKey,
25
+ HeaderError,
26
+ parseHeader,
27
+ } from '../format/header.js'
28
+ import {
29
+ AES_GCM_V1_SUITE_PAYLOAD_LENGTH,
30
+ AES_GCM_V1_TAG_BYTES,
31
+ createChunkContext,
32
+ decryptChunk,
33
+ encryptChunk,
34
+ generateContentMaterial,
35
+ } from '../suites/aes-gcm-v1/index.js'
36
+ import {
37
+ DEFAULT_CHUNK_SIZE,
38
+ HEADER_SIZES,
39
+ MAX_TOTAL_CHUNKS,
40
+ SUITE,
41
+ } from '../internal/types.js'
42
+ import { concatBytes, readUint32BE, uint32BE } from '../internal/encoding.js'
43
+ import { hmacSha256 } from '../internal/hmac.js'
44
+ import {
45
+ buildSignatureBlock,
46
+ deriveEd25519PublicKey,
47
+ ED25519_SECRET_KEY_LENGTH,
48
+ parseSignatureBlock,
49
+ SIGNATURE_ALGO_ED25519,
50
+ signHeaderAndMacs,
51
+ type SignatureBlock,
52
+ SignatureError,
53
+ verifyHeaderAndMacs,
54
+ } from '../identity/sign.js'
55
+
56
+ const LENGTH_PREFIX_BYTES = 4
57
+
58
+ // ─────────────────────────────────────────────────────────────────────
59
+ // Encrypting transform
60
+ // ─────────────────────────────────────────────────────────────────────
61
+
62
+ export interface AesGcmV1EncryptStreamOptions {
63
+ /** Total plaintext byte count. Required because the header carries it. */
64
+ plaintextSize: number
65
+ /** Plaintext bytes per chunk. Default 4 MiB. */
66
+ chunkSize?: number
67
+ /** Pre-existing 32-byte content key, or generated if omitted. */
68
+ contentKey?: Uint8Array
69
+ /** Pre-existing 16-byte file_id, or generated if omitted. */
70
+ fileId?: Uint8Array
71
+ /** Optional embedded suite payload (60-byte wrapped key + 12-byte IV). */
72
+ suitePayloadOverride?: Uint8Array
73
+ /**
74
+ * Optional 32-byte Ed25519 secret seed. When provided, the stream
75
+ * appends a signature block over `header_unauthenticated_bytes ||
76
+ * concat(chunk_macs)` after the final chunk. When omitted, no block
77
+ * is emitted and the file decrypts as unsigned (legacy behavior).
78
+ */
79
+ ed25519SecretKey?: Uint8Array
80
+ }
81
+
82
+ export interface AesGcmV1EncryptStreamResult {
83
+ /** TransformStream<Uint8Array, Uint8Array> emitting the v1 wire format. */
84
+ stream: TransformStream<Uint8Array, Uint8Array>
85
+ /** The content key used (for envelope wrapping by the caller). */
86
+ contentKey: Uint8Array
87
+ /** The file_id used (for application-level metadata storage). */
88
+ fileId: Uint8Array
89
+ }
90
+
91
+ /**
92
+ * Build a TransformStream that encrypts plaintext into v1 wire-format
93
+ * ciphertext on the fly. The stream emits the header first, then each
94
+ * chunk as it arrives.
95
+ *
96
+ * The caller MUST pass `plaintextSize` because the header records it.
97
+ * If the caller doesn't know the size up front, they must accumulate
98
+ * the plaintext into a buffer first — there is no way to write a
99
+ * self-describing header otherwise.
100
+ */
101
+ export function createAesGcmV1EncryptStream(
102
+ options: AesGcmV1EncryptStreamOptions,
103
+ ): AesGcmV1EncryptStreamResult {
104
+ const chunkSize = options.chunkSize ?? DEFAULT_CHUNK_SIZE
105
+ if (!Number.isSafeInteger(chunkSize) || chunkSize <= 0) {
106
+ throw new RangeError('encrypt stream: chunkSize must be positive integer')
107
+ }
108
+ if (
109
+ !Number.isSafeInteger(options.plaintextSize) ||
110
+ options.plaintextSize < 0
111
+ ) {
112
+ throw new RangeError('encrypt stream: plaintextSize must be a non-negative integer')
113
+ }
114
+
115
+ const totalChunks =
116
+ options.plaintextSize === 0
117
+ ? 0
118
+ : Math.ceil(options.plaintextSize / chunkSize)
119
+ if (totalChunks > MAX_TOTAL_CHUNKS) {
120
+ throw new RangeError('encrypt stream: file would exceed total_chunks limit')
121
+ }
122
+
123
+ const generated = generateContentMaterial()
124
+ const contentKey = options.contentKey ?? generated.contentKey
125
+ const fileId = options.fileId ?? generated.fileId
126
+ if (contentKey.length !== 32) {
127
+ throw new RangeError('encrypt stream: contentKey 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
+
133
+ const suitePayload =
134
+ options.suitePayloadOverride ??
135
+ new Uint8Array(AES_GCM_V1_SUITE_PAYLOAD_LENGTH)
136
+
137
+ const ed25519SecretKey = options.ed25519SecretKey
138
+ if (ed25519SecretKey && ed25519SecretKey.length !== ED25519_SECRET_KEY_LENGTH) {
139
+ throw new RangeError(
140
+ `encrypt stream: ed25519SecretKey must be ${ED25519_SECRET_KEY_LENGTH} bytes`,
141
+ )
142
+ }
143
+
144
+ // State held across the lifetime of the stream:
145
+ // - pending plaintext buffer (collects until we have a full chunk)
146
+ // - chunk index counter
147
+ // - bytes consumed counter (for sanity check vs plaintextSize)
148
+ // - context (lazily initialized)
149
+ // - unauthenticated header bytes (kept for signing)
150
+ // - per-chunk MAC tags (last 16 bytes of each chunk ciphertext)
151
+ let pending = new Uint8Array(0)
152
+ let chunkIndex = 0
153
+ let bytesConsumed = 0
154
+ let contextPromise: ReturnType<typeof createChunkContext> | null = null
155
+ let headerEmitted = false
156
+ let unauthenticatedHeader: Uint8Array | null = null
157
+ const chunkMacs: Uint8Array[] = []
158
+
159
+ async function ensureHeader(
160
+ controller: TransformStreamDefaultController<Uint8Array>,
161
+ ): Promise<void> {
162
+ if (headerEmitted) return
163
+ const unauth = buildHeaderUnauthenticated({
164
+ suite: SUITE.AES_256_GCM_V1,
165
+ fileId,
166
+ chunkSize,
167
+ totalChunks,
168
+ plaintextSize: options.plaintextSize,
169
+ suitePayload,
170
+ })
171
+ const macKey = await deriveHeaderMacKey(contentKey, fileId)
172
+ const mac = await hmacSha256(macKey, unauth)
173
+ unauthenticatedHeader = unauth
174
+ controller.enqueue(concatBytes([unauth, mac]))
175
+ headerEmitted = true
176
+ }
177
+
178
+ async function emitChunk(
179
+ plaintext: Uint8Array,
180
+ controller: TransformStreamDefaultController<Uint8Array>,
181
+ ): Promise<void> {
182
+ if (!contextPromise) {
183
+ contextPromise = createChunkContext(contentKey, fileId, totalChunks)
184
+ }
185
+ const ctx = await contextPromise
186
+ const ct = await encryptChunk(ctx, chunkIndex, plaintext)
187
+ controller.enqueue(uint32BE(ct.length))
188
+ controller.enqueue(ct)
189
+ if (ed25519SecretKey) {
190
+ // AEAD tag is the trailing AES_GCM_V1_TAG_BYTES of the chunk ct.
191
+ chunkMacs.push(ct.slice(ct.length - AES_GCM_V1_TAG_BYTES))
192
+ }
193
+ chunkIndex += 1
194
+ }
195
+
196
+ const transformer: Transformer<Uint8Array, Uint8Array> = {
197
+ async transform(chunk, controller) {
198
+ await ensureHeader(controller)
199
+ bytesConsumed += chunk.length
200
+ if (bytesConsumed > options.plaintextSize) {
201
+ controller.error(
202
+ new RangeError('encrypt stream: input exceeded declared plaintextSize'),
203
+ )
204
+ return
205
+ }
206
+ // Append to pending buffer
207
+ const merged = new Uint8Array(pending.length + chunk.length)
208
+ merged.set(pending, 0)
209
+ merged.set(chunk, pending.length)
210
+ pending = merged
211
+
212
+ // Drain whole chunks
213
+ while (pending.length >= chunkSize && chunkIndex < totalChunks - 1) {
214
+ const slice = pending.subarray(0, chunkSize)
215
+ await emitChunk(slice, controller)
216
+ pending = pending.subarray(chunkSize)
217
+ // Subarray shares the buffer; copy out so we can drop the rest.
218
+ pending = pending.slice(0)
219
+ }
220
+ },
221
+ async flush(controller) {
222
+ await ensureHeader(controller)
223
+ if (bytesConsumed !== options.plaintextSize) {
224
+ controller.error(
225
+ new RangeError(
226
+ `encrypt stream: input was ${bytesConsumed} bytes, declared ${options.plaintextSize}`,
227
+ ),
228
+ )
229
+ return
230
+ }
231
+ // Emit any remaining whole chunks plus the final partial chunk.
232
+ while (chunkIndex < totalChunks) {
233
+ const isLastIteration = chunkIndex === totalChunks - 1
234
+ const sliceSize = isLastIteration
235
+ ? pending.length // final chunk: whatever's left
236
+ : chunkSize
237
+ const slice = pending.subarray(0, sliceSize)
238
+ await emitChunk(slice, controller)
239
+ pending = pending.subarray(sliceSize).slice(0)
240
+ }
241
+ if (pending.length !== 0) {
242
+ controller.error(
243
+ new RangeError('encrypt stream: residual bytes after final chunk'),
244
+ )
245
+ return
246
+ }
247
+ if (ed25519SecretKey) {
248
+ if (!unauthenticatedHeader) {
249
+ controller.error(
250
+ new Error('encrypt stream: header not finalized before signing'),
251
+ )
252
+ return
253
+ }
254
+ const signature = signHeaderAndMacs({
255
+ ed25519SecretKey,
256
+ header: unauthenticatedHeader,
257
+ chunkMacs,
258
+ })
259
+ const publicKey = deriveEd25519PublicKey(ed25519SecretKey)
260
+ controller.enqueue(
261
+ buildSignatureBlock({
262
+ algorithm: SIGNATURE_ALGO_ED25519,
263
+ publicKey,
264
+ signature,
265
+ }),
266
+ )
267
+ }
268
+ },
269
+ }
270
+
271
+ return {
272
+ stream: new TransformStream(transformer),
273
+ contentKey,
274
+ fileId,
275
+ }
276
+ }
277
+
278
+ // ─────────────────────────────────────────────────────────────────────
279
+ // Decrypting transform
280
+ // ─────────────────────────────────────────────────────────────────────
281
+
282
+ export interface AesGcmV1DecryptStreamOptions {
283
+ contentKey: Uint8Array
284
+ /**
285
+ * If provided, a trailing signature block (if present) is verified
286
+ * against this Ed25519 public key, and the resolved metadata's
287
+ * `signature.verified` reflects the outcome. If omitted, a present
288
+ * block is parsed and surfaced but not verified; `verified` is null.
289
+ */
290
+ expectedSignerPublicKey?: Uint8Array
291
+ }
292
+
293
+ /**
294
+ * Verified signature metadata surfaced by the decrypt stream.
295
+ *
296
+ * - `algorithm`, `publicKey`, `signature` come from the parsed block.
297
+ * - `verified` is `true` if the caller passed `expectedSignerPublicKey`
298
+ * AND it matched the embedded pubkey AND the signature verifies; it
299
+ * is `false` if the check ran and failed; it is `null` if the caller
300
+ * passed no `expectedSignerPublicKey` (the application policy layer
301
+ * is expected to do its own verification using the surfaced bytes).
302
+ */
303
+ export interface VerifiedSignature {
304
+ algorithm: number
305
+ publicKey: Uint8Array
306
+ signature: Uint8Array
307
+ verified: boolean | null
308
+ }
309
+
310
+ export interface DecryptionMetadata {
311
+ /** Null when the file has no signature block (legacy / unsigned). */
312
+ signature: VerifiedSignature | null
313
+ }
314
+
315
+ export interface AesGcmV1DecryptStreamResult {
316
+ stream: TransformStream<Uint8Array, Uint8Array>
317
+ /**
318
+ * Resolves once the stream finishes flushing. Rejects if the stream
319
+ * errored — callers awaiting metadata MUST handle rejection (or await
320
+ * the plaintext drain first, which surfaces the same error).
321
+ */
322
+ metadata: Promise<DecryptionMetadata>
323
+ }
324
+
325
+ /**
326
+ * Build a TransformStream that decrypts a v1 ciphertext stream into
327
+ * plaintext. Unlike the whole-blob decryptor, this version processes
328
+ * input incrementally — useful for very large files or when ciphertext
329
+ * arrives chunked over the network.
330
+ *
331
+ * Files written by an older library version (no signature block) decrypt
332
+ * unchanged: `metadata.signature` resolves to `null`. Files with a
333
+ * trailing signature block are parsed; if `expectedSignerPublicKey` is
334
+ * supplied, the signature is verified and `metadata.signature.verified`
335
+ * reflects the outcome.
336
+ */
337
+ export function createAesGcmV1DecryptStream(
338
+ options: AesGcmV1DecryptStreamOptions,
339
+ ): AesGcmV1DecryptStreamResult {
340
+ const { contentKey } = options
341
+ if (contentKey.length !== 32) {
342
+ throw new RangeError('decrypt stream: contentKey must be 32 bytes')
343
+ }
344
+ const expectedSignerPublicKey = options.expectedSignerPublicKey
345
+
346
+ let resolveMetadata!: (m: DecryptionMetadata) => void
347
+ let rejectMetadata!: (err: unknown) => void
348
+ const metadata = new Promise<DecryptionMetadata>((resolve, reject) => {
349
+ resolveMetadata = resolve
350
+ rejectMetadata = reject
351
+ })
352
+ // Pre-attach a no-op handler so the user-facing promise doesn't trigger
353
+ // an unhandledRejection if the caller never awaits metadata (they
354
+ // typically await the plaintext drain, which surfaces the same error).
355
+ // This does NOT swallow the error for callers who DO await metadata —
356
+ // .catch() returns a new promise; the original `metadata` still rejects.
357
+ metadata.catch(() => {})
358
+
359
+ // Phases:
360
+ // 0 = waiting for header bytes
361
+ // 1 = streaming chunks: alternating length-prefix + ciphertext
362
+ let phase: 0 | 1 = 0
363
+ let buffer = new Uint8Array(0)
364
+ let parsedHeader: ReturnType<typeof parseHeader> | null = null
365
+ let chunkIndex = 0
366
+ let bytesEmitted = 0
367
+ let nextCipherLen = -1
368
+ let contextPromise: ReturnType<typeof createChunkContext> | null = null
369
+ const chunkMacs: Uint8Array[] = []
370
+
371
+ function append(input: Uint8Array): void {
372
+ const merged = new Uint8Array(buffer.length + input.length)
373
+ merged.set(buffer, 0)
374
+ merged.set(input, buffer.length)
375
+ buffer = merged
376
+ }
377
+
378
+ function consume(n: number): Uint8Array {
379
+ const out = buffer.subarray(0, n).slice(0)
380
+ buffer = buffer.subarray(n).slice(0)
381
+ return out
382
+ }
383
+
384
+ async function tryParseHeader(): Promise<boolean> {
385
+ // Need at least the fixed prefix + MAC (no suite_payload).
386
+ if (
387
+ buffer.length <
388
+ HEADER_SIZES.MAGIC +
389
+ HEADER_SIZES.SUITE +
390
+ HEADER_SIZES.FLAGS +
391
+ HEADER_SIZES.FILE_ID +
392
+ HEADER_SIZES.CHUNK_SIZE +
393
+ HEADER_SIZES.TOTAL_CHUNKS +
394
+ HEADER_SIZES.PLAINTEXT_SIZE +
395
+ HEADER_SIZES.SUITE_PAYLOAD_LEN
396
+ ) {
397
+ return false
398
+ }
399
+ // Read suite_payload_len so we know how much more to wait for.
400
+ const suitePayloadLenOffset =
401
+ HEADER_SIZES.MAGIC +
402
+ HEADER_SIZES.SUITE +
403
+ HEADER_SIZES.FLAGS +
404
+ HEADER_SIZES.FILE_ID +
405
+ HEADER_SIZES.CHUNK_SIZE +
406
+ HEADER_SIZES.TOTAL_CHUNKS +
407
+ HEADER_SIZES.PLAINTEXT_SIZE
408
+ const suitePayloadLen =
409
+ (buffer[suitePayloadLenOffset]! << 8) |
410
+ buffer[suitePayloadLenOffset + 1]!
411
+ const fullHeaderLen =
412
+ suitePayloadLenOffset +
413
+ HEADER_SIZES.SUITE_PAYLOAD_LEN +
414
+ suitePayloadLen +
415
+ HEADER_SIZES.HEADER_MAC
416
+ if (buffer.length < fullHeaderLen) return false
417
+
418
+ const headerBytes = consume(fullHeaderLen)
419
+ parsedHeader = parseHeader(headerBytes)
420
+
421
+ if (parsedHeader.suite !== SUITE.AES_256_GCM_V1) {
422
+ throw new HeaderError(
423
+ `decrypt stream: this stream only supports aes-256-gcm-v1; got suite 0x${parsedHeader.suite.toString(16)}`,
424
+ )
425
+ }
426
+ // Verify header MAC using parseHeader's exposed unauthenticated bytes
427
+ // and mac fields.
428
+ const { verifyHeaderMac } = await import('../format/header.js')
429
+ await verifyHeaderMac(parsedHeader, contentKey)
430
+
431
+ contextPromise = createChunkContext(
432
+ contentKey,
433
+ parsedHeader.fileId,
434
+ parsedHeader.totalChunks,
435
+ )
436
+
437
+ phase = 1
438
+ return true
439
+ }
440
+
441
+ async function tryEmitChunk(
442
+ controller: TransformStreamDefaultController<Uint8Array>,
443
+ ): Promise<boolean> {
444
+ if (!parsedHeader) return false
445
+
446
+ if (chunkIndex >= parsedHeader.totalChunks) {
447
+ // Already consumed all expected chunks; anything remaining is trailing
448
+ // garbage and must be flagged at flush time.
449
+ return false
450
+ }
451
+
452
+ if (nextCipherLen < 0) {
453
+ if (buffer.length < LENGTH_PREFIX_BYTES) return false
454
+ const lenBytes = consume(LENGTH_PREFIX_BYTES)
455
+ nextCipherLen = readUint32BE(lenBytes)
456
+
457
+ const isFinal = chunkIndex === parsedHeader.totalChunks - 1
458
+ const minCipher = 1 + AES_GCM_V1_TAG_BYTES
459
+ const maxCipher = parsedHeader.chunkSize + AES_GCM_V1_TAG_BYTES
460
+ if (nextCipherLen < minCipher || nextCipherLen > maxCipher) {
461
+ throw new HeaderError('chunk_length_out_of_range')
462
+ }
463
+ if (!isFinal && nextCipherLen !== maxCipher) {
464
+ throw new HeaderError('non_final_chunk_wrong_size')
465
+ }
466
+ }
467
+
468
+ if (buffer.length < nextCipherLen) return false
469
+
470
+ const ctBytes = consume(nextCipherLen)
471
+ nextCipherLen = -1
472
+
473
+ const ctx = await contextPromise!
474
+ const pt = await decryptChunk(ctx, chunkIndex, ctBytes)
475
+ bytesEmitted += pt.length
476
+ controller.enqueue(pt)
477
+ // AEAD tag is the trailing AES_GCM_V1_TAG_BYTES of ctBytes. Kept
478
+ // for optional signature verification at flush time.
479
+ chunkMacs.push(ctBytes.slice(ctBytes.length - AES_GCM_V1_TAG_BYTES))
480
+ chunkIndex += 1
481
+ return true
482
+ }
483
+
484
+ return {
485
+ stream: new TransformStream<Uint8Array, Uint8Array>({
486
+ async transform(chunk, controller) {
487
+ append(chunk)
488
+ try {
489
+ if (phase === 0) {
490
+ const ok = await tryParseHeader()
491
+ if (!ok) return
492
+ }
493
+ // Drain as many chunks as we have data for.
494
+ while (await tryEmitChunk(controller)) {
495
+ /* loop */
496
+ }
497
+ } catch (err) {
498
+ controller.error(err as Error)
499
+ rejectMetadata(err)
500
+ }
501
+ },
502
+ async flush(controller) {
503
+ try {
504
+ if (phase === 0) {
505
+ throw new HeaderError('header_too_short')
506
+ }
507
+ // No header yet means truncated input.
508
+ if (!parsedHeader) {
509
+ throw new HeaderError('header_too_short')
510
+ }
511
+ // Try once more in case flush is called with everything queued.
512
+ while (await tryEmitChunk(controller)) {
513
+ /* loop */
514
+ }
515
+ if (chunkIndex !== parsedHeader.totalChunks) {
516
+ throw new HeaderError('chunk_truncated')
517
+ }
518
+ if (bytesEmitted !== parsedHeader.plaintextSize) {
519
+ throw new HeaderError('plaintext_size_mismatch')
520
+ }
521
+ const signatureResult = finalizeSignatureMetadata({
522
+ trailingBytes: buffer,
523
+ header: parsedHeader.unauthenticatedBytes,
524
+ chunkMacs,
525
+ expectedSignerPublicKey,
526
+ })
527
+ buffer = new Uint8Array(0)
528
+ resolveMetadata({ signature: signatureResult })
529
+ } catch (err) {
530
+ controller.error(err as Error)
531
+ rejectMetadata(err)
532
+ }
533
+ },
534
+ }),
535
+ metadata,
536
+ }
537
+ }
538
+
539
+ // ─────────────────────────────────────────────────────────────────────
540
+ // Helpers for ergonomics
541
+ // ─────────────────────────────────────────────────────────────────────
542
+
543
+ /**
544
+ * Pipe a ReadableStream<Uint8Array> through the AES-GCM-v1 encrypt
545
+ * transform and return the resulting ReadableStream + key material.
546
+ */
547
+ export function encryptStreamAesGcmV1(
548
+ source: ReadableStream<Uint8Array>,
549
+ options: AesGcmV1EncryptStreamOptions,
550
+ ): {
551
+ ciphertext: ReadableStream<Uint8Array>
552
+ contentKey: Uint8Array
553
+ fileId: Uint8Array
554
+ } {
555
+ const { stream, contentKey, fileId } =
556
+ createAesGcmV1EncryptStream(options)
557
+ return {
558
+ ciphertext: source.pipeThrough(stream),
559
+ contentKey,
560
+ fileId,
561
+ }
562
+ }
563
+
564
+ /**
565
+ * Pipe a ReadableStream<Uint8Array> through the AES-GCM-v1 decrypt
566
+ * transform and return the resulting plaintext ReadableStream alongside
567
+ * a `metadata` Promise that resolves at end-of-stream with the parsed
568
+ * signature block (or `signature: null` for unsigned / legacy files).
569
+ */
570
+ export function decryptStreamAesGcmV1(
571
+ source: ReadableStream<Uint8Array>,
572
+ options: AesGcmV1DecryptStreamOptions,
573
+ ): {
574
+ plaintext: ReadableStream<Uint8Array>
575
+ metadata: Promise<DecryptionMetadata>
576
+ } {
577
+ const { stream, metadata } = createAesGcmV1DecryptStream(options)
578
+ return {
579
+ plaintext: source.pipeThrough(stream),
580
+ metadata,
581
+ }
582
+ }
583
+
584
+ /**
585
+ * Parse a trailing signature block (if any) from the decrypt stream's
586
+ * residual buffer, optionally verifying it against the caller's
587
+ * trusted public key.
588
+ *
589
+ * Shared between the AES-GCM and PQ-hybrid stream decoders so the
590
+ * signature semantics live in one place.
591
+ */
592
+ export function finalizeSignatureMetadata(input: {
593
+ trailingBytes: Uint8Array
594
+ header: Uint8Array
595
+ chunkMacs: ReadonlyArray<Uint8Array>
596
+ expectedSignerPublicKey: Uint8Array | undefined
597
+ }): VerifiedSignature | null {
598
+ if (input.trailingBytes.length === 0) {
599
+ return null
600
+ }
601
+ let parsed: { block: SignatureBlock; consumed: number }
602
+ try {
603
+ parsed = parseSignatureBlock(input.trailingBytes, 0)
604
+ } catch (err) {
605
+ if (err instanceof SignatureError) {
606
+ throw new HeaderError(`signature_block_${err.code}`)
607
+ }
608
+ throw err
609
+ }
610
+ if (parsed.consumed !== input.trailingBytes.length) {
611
+ throw new HeaderError('trailing_bytes_after_signature_block')
612
+ }
613
+ const { algorithm, publicKey, signature } = parsed.block
614
+
615
+ let verified: boolean | null = null
616
+ if (input.expectedSignerPublicKey) {
617
+ if (algorithm !== SIGNATURE_ALGO_ED25519) {
618
+ // Unknown / unsupported algorithm: cannot verify with our
619
+ // Ed25519-only verifier; treat as a verification failure under
620
+ // the caller's policy (they asked us to verify, we couldn't).
621
+ verified = false
622
+ } else {
623
+ // Pubkey-pinning: if the embedded pubkey doesn't match the caller's
624
+ // expected one, fail without doing the (still-honest) Ed25519
625
+ // math. This keeps the "verified=true" contract tight: it means
626
+ // the file was signed by the key the caller expected.
627
+ verified =
628
+ bytesEqualConstantTime(publicKey, input.expectedSignerPublicKey) &&
629
+ verifyHeaderAndMacs({
630
+ ed25519PublicKey: input.expectedSignerPublicKey,
631
+ header: input.header,
632
+ chunkMacs: input.chunkMacs,
633
+ signature,
634
+ })
635
+ }
636
+ }
637
+ return { algorithm, publicKey, signature, verified }
638
+ }
639
+
640
+ function bytesEqualConstantTime(a: Uint8Array, b: Uint8Array): boolean {
641
+ if (a.length !== b.length) return false
642
+ let diff = 0
643
+ for (let i = 0; i < a.length; i += 1) {
644
+ diff |= a[i]! ^ b[i]!
645
+ }
646
+ return diff === 0
647
+ }