@shieldfive/crypto 1.0.0-alpha.2

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 (104) hide show
  1. package/CHANGELOG.md +81 -0
  2. package/LICENSE +201 -0
  3. package/README.md +241 -0
  4. package/SECURITY.md +123 -0
  5. package/dist/format/header.d.ts +60 -0
  6. package/dist/format/header.d.ts.map +1 -0
  7. package/dist/format/header.js +203 -0
  8. package/dist/format/header.js.map +1 -0
  9. package/dist/identity/index.d.ts +117 -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/index.d.ts +52 -0
  14. package/dist/index.d.ts.map +1 -0
  15. package/dist/index.js +124 -0
  16. package/dist/index.js.map +1 -0
  17. package/dist/internal/encoding.d.ts +33 -0
  18. package/dist/internal/encoding.d.ts.map +1 -0
  19. package/dist/internal/encoding.js +136 -0
  20. package/dist/internal/encoding.js.map +1 -0
  21. package/dist/internal/hkdf.d.ts +14 -0
  22. package/dist/internal/hkdf.d.ts.map +1 -0
  23. package/dist/internal/hkdf.js +27 -0
  24. package/dist/internal/hkdf.js.map +1 -0
  25. package/dist/internal/hmac.d.ts +9 -0
  26. package/dist/internal/hmac.d.ts.map +1 -0
  27. package/dist/internal/hmac.js +18 -0
  28. package/dist/internal/hmac.js.map +1 -0
  29. package/dist/internal/runtime.d.ts +29 -0
  30. package/dist/internal/runtime.d.ts.map +1 -0
  31. package/dist/internal/runtime.js +67 -0
  32. package/dist/internal/runtime.js.map +1 -0
  33. package/dist/internal/sodium.d.ts +12 -0
  34. package/dist/internal/sodium.d.ts.map +1 -0
  35. package/dist/internal/sodium.js +34 -0
  36. package/dist/internal/sodium.js.map +1 -0
  37. package/dist/internal/types.d.ts +94 -0
  38. package/dist/internal/types.d.ts.map +1 -0
  39. package/dist/internal/types.js +65 -0
  40. package/dist/internal/types.js.map +1 -0
  41. package/dist/kdf/argon2id.d.ts +72 -0
  42. package/dist/kdf/argon2id.d.ts.map +1 -0
  43. package/dist/kdf/argon2id.js +97 -0
  44. package/dist/kdf/argon2id.js.map +1 -0
  45. package/dist/migration/v0-bridge.d.ts +94 -0
  46. package/dist/migration/v0-bridge.d.ts.map +1 -0
  47. package/dist/migration/v0-bridge.js +203 -0
  48. package/dist/migration/v0-bridge.js.map +1 -0
  49. package/dist/streams/aes-gcm-v1.d.ts +76 -0
  50. package/dist/streams/aes-gcm-v1.d.ts.map +1 -0
  51. package/dist/streams/aes-gcm-v1.js +322 -0
  52. package/dist/streams/aes-gcm-v1.js.map +1 -0
  53. package/dist/suites/aes-gcm-v0/api.d.ts +48 -0
  54. package/dist/suites/aes-gcm-v0/api.d.ts.map +1 -0
  55. package/dist/suites/aes-gcm-v0/api.js +110 -0
  56. package/dist/suites/aes-gcm-v0/api.js.map +1 -0
  57. package/dist/suites/aes-gcm-v1/api.d.ts +54 -0
  58. package/dist/suites/aes-gcm-v1/api.d.ts.map +1 -0
  59. package/dist/suites/aes-gcm-v1/api.js +179 -0
  60. package/dist/suites/aes-gcm-v1/api.js.map +1 -0
  61. package/dist/suites/aes-gcm-v1/index.d.ts +56 -0
  62. package/dist/suites/aes-gcm-v1/index.d.ts.map +1 -0
  63. package/dist/suites/aes-gcm-v1/index.js +174 -0
  64. package/dist/suites/aes-gcm-v1/index.js.map +1 -0
  65. package/dist/suites/pq-hybrid-v1/api.d.ts +40 -0
  66. package/dist/suites/pq-hybrid-v1/api.d.ts.map +1 -0
  67. package/dist/suites/pq-hybrid-v1/api.js +157 -0
  68. package/dist/suites/pq-hybrid-v1/api.js.map +1 -0
  69. package/dist/suites/pq-hybrid-v1/index.d.ts +101 -0
  70. package/dist/suites/pq-hybrid-v1/index.d.ts.map +1 -0
  71. package/dist/suites/pq-hybrid-v1/index.js +225 -0
  72. package/dist/suites/pq-hybrid-v1/index.js.map +1 -0
  73. package/dist/suites/xchacha-v1/api.d.ts +29 -0
  74. package/dist/suites/xchacha-v1/api.d.ts.map +1 -0
  75. package/dist/suites/xchacha-v1/api.js +151 -0
  76. package/dist/suites/xchacha-v1/api.js.map +1 -0
  77. package/dist/suites/xchacha-v1/index.d.ts +50 -0
  78. package/dist/suites/xchacha-v1/index.d.ts.map +1 -0
  79. package/dist/suites/xchacha-v1/index.js +133 -0
  80. package/dist/suites/xchacha-v1/index.js.map +1 -0
  81. package/package.json +112 -0
  82. package/spec/format-v0.md +81 -0
  83. package/spec/format-v1.md +245 -0
  84. package/spec/key-derivation.md +122 -0
  85. package/spec/threat-model.md +152 -0
  86. package/src/format/header.ts +284 -0
  87. package/src/identity/index.ts +358 -0
  88. package/src/index.ts +197 -0
  89. package/src/internal/encoding.ts +153 -0
  90. package/src/internal/hkdf.ts +47 -0
  91. package/src/internal/hmac.ts +33 -0
  92. package/src/internal/runtime.ts +80 -0
  93. package/src/internal/sodium.ts +38 -0
  94. package/src/internal/types.ts +128 -0
  95. package/src/kdf/argon2id.ts +164 -0
  96. package/src/migration/v0-bridge.ts +347 -0
  97. package/src/streams/aes-gcm-v1.ts +443 -0
  98. package/src/suites/aes-gcm-v0/api.ts +155 -0
  99. package/src/suites/aes-gcm-v1/api.ts +291 -0
  100. package/src/suites/aes-gcm-v1/index.ts +266 -0
  101. package/src/suites/pq-hybrid-v1/api.ts +259 -0
  102. package/src/suites/pq-hybrid-v1/index.ts +343 -0
  103. package/src/suites/xchacha-v1/api.ts +251 -0
  104. package/src/suites/xchacha-v1/index.ts +213 -0
@@ -0,0 +1,443 @@
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
+ buildAuthenticatedHeader,
24
+ HeaderError,
25
+ parseHeader,
26
+ } from '../format/header.js'
27
+ import {
28
+ AES_GCM_V1_SUITE_PAYLOAD_LENGTH,
29
+ AES_GCM_V1_TAG_BYTES,
30
+ createChunkContext,
31
+ decryptChunk,
32
+ encryptChunk,
33
+ generateContentMaterial,
34
+ } from '../suites/aes-gcm-v1/index.js'
35
+ import {
36
+ DEFAULT_CHUNK_SIZE,
37
+ HEADER_SIZES,
38
+ MAX_TOTAL_CHUNKS,
39
+ SUITE,
40
+ } from '../internal/types.js'
41
+ import { readUint32BE, uint32BE } from '../internal/encoding.js'
42
+
43
+ const LENGTH_PREFIX_BYTES = 4
44
+
45
+ // ─────────────────────────────────────────────────────────────────────
46
+ // Encrypting transform
47
+ // ─────────────────────────────────────────────────────────────────────
48
+
49
+ export interface AesGcmV1EncryptStreamOptions {
50
+ /** Total plaintext byte count. Required because the header carries it. */
51
+ plaintextSize: number
52
+ /** Plaintext bytes per chunk. Default 4 MiB. */
53
+ chunkSize?: number
54
+ /** Pre-existing 32-byte content key, or generated if omitted. */
55
+ contentKey?: Uint8Array
56
+ /** Pre-existing 16-byte file_id, or generated if omitted. */
57
+ fileId?: Uint8Array
58
+ /** Optional embedded suite payload (60-byte wrapped key + 12-byte IV). */
59
+ suitePayloadOverride?: Uint8Array
60
+ }
61
+
62
+ export interface AesGcmV1EncryptStreamResult {
63
+ /** TransformStream<Uint8Array, Uint8Array> emitting the v1 wire format. */
64
+ stream: TransformStream<Uint8Array, Uint8Array>
65
+ /** The content key used (for envelope wrapping by the caller). */
66
+ contentKey: Uint8Array
67
+ /** The file_id used (for application-level metadata storage). */
68
+ fileId: Uint8Array
69
+ }
70
+
71
+ /**
72
+ * Build a TransformStream that encrypts plaintext into v1 wire-format
73
+ * ciphertext on the fly. The stream emits the header first, then each
74
+ * chunk as it arrives.
75
+ *
76
+ * The caller MUST pass `plaintextSize` because the header records it.
77
+ * If the caller doesn't know the size up front, they must accumulate
78
+ * the plaintext into a buffer first — there is no way to write a
79
+ * self-describing header otherwise.
80
+ */
81
+ export function createAesGcmV1EncryptStream(
82
+ options: AesGcmV1EncryptStreamOptions,
83
+ ): AesGcmV1EncryptStreamResult {
84
+ const chunkSize = options.chunkSize ?? DEFAULT_CHUNK_SIZE
85
+ if (!Number.isSafeInteger(chunkSize) || chunkSize <= 0) {
86
+ throw new RangeError('encrypt stream: chunkSize must be positive integer')
87
+ }
88
+ if (
89
+ !Number.isSafeInteger(options.plaintextSize) ||
90
+ options.plaintextSize < 0
91
+ ) {
92
+ throw new RangeError('encrypt stream: plaintextSize must be a non-negative integer')
93
+ }
94
+
95
+ const totalChunks =
96
+ options.plaintextSize === 0
97
+ ? 0
98
+ : Math.ceil(options.plaintextSize / chunkSize)
99
+ if (totalChunks > MAX_TOTAL_CHUNKS) {
100
+ throw new RangeError('encrypt stream: file would exceed total_chunks limit')
101
+ }
102
+
103
+ const generated = generateContentMaterial()
104
+ const contentKey = options.contentKey ?? generated.contentKey
105
+ const fileId = options.fileId ?? generated.fileId
106
+ if (contentKey.length !== 32) {
107
+ throw new RangeError('encrypt stream: contentKey must be 32 bytes')
108
+ }
109
+ if (fileId.length !== HEADER_SIZES.FILE_ID) {
110
+ throw new RangeError('encrypt stream: fileId must be 16 bytes')
111
+ }
112
+
113
+ const suitePayload =
114
+ options.suitePayloadOverride ??
115
+ new Uint8Array(AES_GCM_V1_SUITE_PAYLOAD_LENGTH)
116
+
117
+ // State held across the lifetime of the stream:
118
+ // - pending plaintext buffer (collects until we have a full chunk)
119
+ // - chunk index counter
120
+ // - bytes consumed counter (for sanity check vs plaintextSize)
121
+ // - context (lazily initialized)
122
+ let pending = new Uint8Array(0)
123
+ let chunkIndex = 0
124
+ let bytesConsumed = 0
125
+ let contextPromise: ReturnType<typeof createChunkContext> | null = null
126
+ let headerEmitted = false
127
+
128
+ async function ensureHeader(
129
+ controller: TransformStreamDefaultController<Uint8Array>,
130
+ ): Promise<void> {
131
+ if (headerEmitted) return
132
+ const header = await buildAuthenticatedHeader(
133
+ {
134
+ suite: SUITE.AES_256_GCM_V1,
135
+ fileId,
136
+ chunkSize,
137
+ totalChunks,
138
+ plaintextSize: options.plaintextSize,
139
+ suitePayload,
140
+ },
141
+ contentKey,
142
+ )
143
+ controller.enqueue(header)
144
+ headerEmitted = true
145
+ }
146
+
147
+ async function emitChunk(
148
+ plaintext: Uint8Array,
149
+ controller: TransformStreamDefaultController<Uint8Array>,
150
+ ): Promise<void> {
151
+ if (!contextPromise) {
152
+ contextPromise = createChunkContext(contentKey, fileId, totalChunks)
153
+ }
154
+ const ctx = await contextPromise
155
+ const ct = await encryptChunk(ctx, chunkIndex, plaintext)
156
+ controller.enqueue(uint32BE(ct.length))
157
+ controller.enqueue(ct)
158
+ chunkIndex += 1
159
+ }
160
+
161
+ const transformer: Transformer<Uint8Array, Uint8Array> = {
162
+ async transform(chunk, controller) {
163
+ await ensureHeader(controller)
164
+ bytesConsumed += chunk.length
165
+ if (bytesConsumed > options.plaintextSize) {
166
+ controller.error(
167
+ new RangeError('encrypt stream: input exceeded declared plaintextSize'),
168
+ )
169
+ return
170
+ }
171
+ // Append to pending buffer
172
+ const merged = new Uint8Array(pending.length + chunk.length)
173
+ merged.set(pending, 0)
174
+ merged.set(chunk, pending.length)
175
+ pending = merged
176
+
177
+ // Drain whole chunks
178
+ while (pending.length >= chunkSize && chunkIndex < totalChunks - 1) {
179
+ const slice = pending.subarray(0, chunkSize)
180
+ await emitChunk(slice, controller)
181
+ pending = pending.subarray(chunkSize)
182
+ // Subarray shares the buffer; copy out so we can drop the rest.
183
+ pending = pending.slice(0)
184
+ }
185
+ },
186
+ async flush(controller) {
187
+ await ensureHeader(controller)
188
+ if (bytesConsumed !== options.plaintextSize) {
189
+ controller.error(
190
+ new RangeError(
191
+ `encrypt stream: input was ${bytesConsumed} bytes, declared ${options.plaintextSize}`,
192
+ ),
193
+ )
194
+ return
195
+ }
196
+ // Emit any remaining whole chunks plus the final partial chunk.
197
+ while (chunkIndex < totalChunks) {
198
+ const isLastIteration = chunkIndex === totalChunks - 1
199
+ const sliceSize = isLastIteration
200
+ ? pending.length // final chunk: whatever's left
201
+ : chunkSize
202
+ const slice = pending.subarray(0, sliceSize)
203
+ await emitChunk(slice, controller)
204
+ pending = pending.subarray(sliceSize).slice(0)
205
+ }
206
+ if (pending.length !== 0) {
207
+ controller.error(
208
+ new RangeError('encrypt stream: residual bytes after final chunk'),
209
+ )
210
+ }
211
+ },
212
+ }
213
+
214
+ return {
215
+ stream: new TransformStream(transformer),
216
+ contentKey,
217
+ fileId,
218
+ }
219
+ }
220
+
221
+ // ─────────────────────────────────────────────────────────────────────
222
+ // Decrypting transform
223
+ // ─────────────────────────────────────────────────────────────────────
224
+
225
+ export interface AesGcmV1DecryptStreamOptions {
226
+ contentKey: Uint8Array
227
+ }
228
+
229
+ /**
230
+ * Build a TransformStream that decrypts a v1 ciphertext stream into
231
+ * plaintext. Unlike the whole-blob decryptor, this version processes
232
+ * input incrementally — useful for very large files or when ciphertext
233
+ * arrives chunked over the network.
234
+ */
235
+ export function createAesGcmV1DecryptStream(
236
+ options: AesGcmV1DecryptStreamOptions,
237
+ ): TransformStream<Uint8Array, Uint8Array> {
238
+ const { contentKey } = options
239
+ if (contentKey.length !== 32) {
240
+ throw new RangeError('decrypt stream: contentKey must be 32 bytes')
241
+ }
242
+
243
+ // Phases:
244
+ // 0 = waiting for header bytes
245
+ // 1 = streaming chunks: alternating length-prefix + ciphertext
246
+ let phase: 0 | 1 = 0
247
+ let buffer = new Uint8Array(0)
248
+ let parsedHeader: ReturnType<typeof parseHeader> | null = null
249
+ let chunkIndex = 0
250
+ let bytesEmitted = 0
251
+ let nextCipherLen = -1
252
+ let contextPromise: ReturnType<typeof createChunkContext> | null = null
253
+
254
+ function append(input: Uint8Array): void {
255
+ const merged = new Uint8Array(buffer.length + input.length)
256
+ merged.set(buffer, 0)
257
+ merged.set(input, buffer.length)
258
+ buffer = merged
259
+ }
260
+
261
+ function consume(n: number): Uint8Array {
262
+ const out = buffer.subarray(0, n).slice(0)
263
+ buffer = buffer.subarray(n).slice(0)
264
+ return out
265
+ }
266
+
267
+ async function tryParseHeader(): Promise<boolean> {
268
+ // Need at least the fixed prefix + MAC (no suite_payload).
269
+ if (
270
+ buffer.length <
271
+ HEADER_SIZES.MAGIC +
272
+ HEADER_SIZES.SUITE +
273
+ HEADER_SIZES.FLAGS +
274
+ HEADER_SIZES.FILE_ID +
275
+ HEADER_SIZES.CHUNK_SIZE +
276
+ HEADER_SIZES.TOTAL_CHUNKS +
277
+ HEADER_SIZES.PLAINTEXT_SIZE +
278
+ HEADER_SIZES.SUITE_PAYLOAD_LEN
279
+ ) {
280
+ return false
281
+ }
282
+ // Read suite_payload_len so we know how much more to wait for.
283
+ const suitePayloadLenOffset =
284
+ HEADER_SIZES.MAGIC +
285
+ HEADER_SIZES.SUITE +
286
+ HEADER_SIZES.FLAGS +
287
+ HEADER_SIZES.FILE_ID +
288
+ HEADER_SIZES.CHUNK_SIZE +
289
+ HEADER_SIZES.TOTAL_CHUNKS +
290
+ HEADER_SIZES.PLAINTEXT_SIZE
291
+ const suitePayloadLen =
292
+ (buffer[suitePayloadLenOffset]! << 8) |
293
+ buffer[suitePayloadLenOffset + 1]!
294
+ const fullHeaderLen =
295
+ suitePayloadLenOffset +
296
+ HEADER_SIZES.SUITE_PAYLOAD_LEN +
297
+ suitePayloadLen +
298
+ HEADER_SIZES.HEADER_MAC
299
+ if (buffer.length < fullHeaderLen) return false
300
+
301
+ const headerBytes = consume(fullHeaderLen)
302
+ parsedHeader = parseHeader(headerBytes)
303
+
304
+ if (parsedHeader.suite !== SUITE.AES_256_GCM_V1) {
305
+ throw new HeaderError(
306
+ `decrypt stream: this stream only supports aes-256-gcm-v1; got suite 0x${parsedHeader.suite.toString(16)}`,
307
+ )
308
+ }
309
+ // Verify header MAC using parseHeader's exposed unauthenticated bytes
310
+ // and mac fields.
311
+ const { verifyHeaderMac } = await import('../format/header.js')
312
+ await verifyHeaderMac(parsedHeader, contentKey)
313
+
314
+ contextPromise = createChunkContext(
315
+ contentKey,
316
+ parsedHeader.fileId,
317
+ parsedHeader.totalChunks,
318
+ )
319
+
320
+ phase = 1
321
+ return true
322
+ }
323
+
324
+ async function tryEmitChunk(
325
+ controller: TransformStreamDefaultController<Uint8Array>,
326
+ ): Promise<boolean> {
327
+ if (!parsedHeader) return false
328
+
329
+ if (chunkIndex >= parsedHeader.totalChunks) {
330
+ // Already consumed all expected chunks; anything remaining is trailing
331
+ // garbage and must be flagged at flush time.
332
+ return false
333
+ }
334
+
335
+ if (nextCipherLen < 0) {
336
+ if (buffer.length < LENGTH_PREFIX_BYTES) return false
337
+ const lenBytes = consume(LENGTH_PREFIX_BYTES)
338
+ nextCipherLen = readUint32BE(lenBytes)
339
+
340
+ const isFinal = chunkIndex === parsedHeader.totalChunks - 1
341
+ const minCipher = 1 + AES_GCM_V1_TAG_BYTES
342
+ const maxCipher = parsedHeader.chunkSize + AES_GCM_V1_TAG_BYTES
343
+ if (nextCipherLen < minCipher || nextCipherLen > maxCipher) {
344
+ throw new HeaderError('chunk_length_out_of_range')
345
+ }
346
+ if (!isFinal && nextCipherLen !== maxCipher) {
347
+ throw new HeaderError('non_final_chunk_wrong_size')
348
+ }
349
+ }
350
+
351
+ if (buffer.length < nextCipherLen) return false
352
+
353
+ const ctBytes = consume(nextCipherLen)
354
+ nextCipherLen = -1
355
+
356
+ const ctx = await contextPromise!
357
+ const pt = await decryptChunk(ctx, chunkIndex, ctBytes)
358
+ bytesEmitted += pt.length
359
+ controller.enqueue(pt)
360
+ chunkIndex += 1
361
+ return true
362
+ }
363
+
364
+ return new TransformStream<Uint8Array, Uint8Array>({
365
+ async transform(chunk, controller) {
366
+ append(chunk)
367
+ try {
368
+ if (phase === 0) {
369
+ const ok = await tryParseHeader()
370
+ if (!ok) return
371
+ }
372
+ // Drain as many chunks as we have data for.
373
+ while (await tryEmitChunk(controller)) {
374
+ /* loop */
375
+ }
376
+ } catch (err) {
377
+ controller.error(err as Error)
378
+ }
379
+ },
380
+ async flush(controller) {
381
+ try {
382
+ if (phase === 0) {
383
+ throw new HeaderError('header_too_short')
384
+ }
385
+ // No header yet means truncated input.
386
+ if (!parsedHeader) {
387
+ throw new HeaderError('header_too_short')
388
+ }
389
+ // Try once more in case flush is called with everything queued.
390
+ while (await tryEmitChunk(controller)) {
391
+ /* loop */
392
+ }
393
+ if (chunkIndex !== parsedHeader.totalChunks) {
394
+ throw new HeaderError('chunk_truncated')
395
+ }
396
+ if (bytesEmitted !== parsedHeader.plaintextSize) {
397
+ throw new HeaderError('plaintext_size_mismatch')
398
+ }
399
+ if (buffer.length !== 0) {
400
+ throw new HeaderError('trailing_bytes_after_last_chunk')
401
+ }
402
+ } catch (err) {
403
+ controller.error(err as Error)
404
+ }
405
+ },
406
+ })
407
+ }
408
+
409
+ // ─────────────────────────────────────────────────────────────────────
410
+ // Helpers for ergonomics
411
+ // ─────────────────────────────────────────────────────────────────────
412
+
413
+ /**
414
+ * Pipe a ReadableStream<Uint8Array> through the AES-GCM-v1 encrypt
415
+ * transform and return the resulting ReadableStream + key material.
416
+ */
417
+ export function encryptStreamAesGcmV1(
418
+ source: ReadableStream<Uint8Array>,
419
+ options: AesGcmV1EncryptStreamOptions,
420
+ ): {
421
+ ciphertext: ReadableStream<Uint8Array>
422
+ contentKey: Uint8Array
423
+ fileId: Uint8Array
424
+ } {
425
+ const { stream, contentKey, fileId } =
426
+ createAesGcmV1EncryptStream(options)
427
+ return {
428
+ ciphertext: source.pipeThrough(stream),
429
+ contentKey,
430
+ fileId,
431
+ }
432
+ }
433
+
434
+ /**
435
+ * Pipe a ReadableStream<Uint8Array> through the AES-GCM-v1 decrypt
436
+ * transform and return the resulting plaintext ReadableStream.
437
+ */
438
+ export function decryptStreamAesGcmV1(
439
+ source: ReadableStream<Uint8Array>,
440
+ options: AesGcmV1DecryptStreamOptions,
441
+ ): ReadableStream<Uint8Array> {
442
+ return source.pipeThrough(createAesGcmV1DecryptStream(options))
443
+ }
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Cipher suite "0x00" / v0: legacy AES-256-GCM, READ-ONLY.
3
+ *
4
+ * This module decrypts files written by the pre-v1 ShieldFive client.
5
+ * It is intentionally read-only: there is no `encryptV0` exported symbol,
6
+ * and applications MUST NOT write new files in this format.
7
+ *
8
+ * v0 wire format (described in `spec/format-v0.md`):
9
+ *
10
+ * v0_file := chunk_0 || chunk_1 || ... || chunk_n
11
+ * chunk_i := AES-GCM(key=content_key, iv=prefix(4)||counter_be(8), aad=∅, pt=plain_i)
12
+ *
13
+ * No on-disk header. The reader must be told the chunk size and nonce
14
+ * prefix out of band (from the application database).
15
+ */
16
+
17
+ import { uint64BE } from '../../internal/encoding.js'
18
+ import { getSubtle } from '../../internal/runtime.js'
19
+
20
+ export const V0_TAG_BYTES = 16
21
+ export const V0_IV_BYTES = 12
22
+ export const V0_KEY_BYTES = 32
23
+ export const V0_NONCE_PREFIX_BYTES = 4
24
+
25
+ export interface V0DecryptOptions {
26
+ /** Encrypted file bytes (concatenated chunks; no header) */
27
+ blob: Blob
28
+ /** 32-byte AES-256 content key, already unwrapped from the envelope */
29
+ contentKey: Uint8Array
30
+ /** 4-byte per-file random prefix, stored in the database */
31
+ noncePrefix: Uint8Array
32
+ /** Plaintext bytes per chunk (5 MiB or 8 MiB in production) */
33
+ chunkSize: number
34
+ /** Optional progress callback (0..1) */
35
+ onProgress?: (progress: number) => void
36
+ }
37
+
38
+ function buildIv(prefix: Uint8Array, counter: number): Uint8Array {
39
+ const iv = new Uint8Array(V0_IV_BYTES)
40
+ iv.set(prefix, 0)
41
+ iv.set(uint64BE(counter), 4)
42
+ return iv
43
+ }
44
+
45
+ /**
46
+ * Decrypt a v0 file. Throws if any chunk fails to authenticate, if the
47
+ * blob size is inconsistent with the chunk size (no clean chunk boundary),
48
+ * or if the inputs have wrong sizes.
49
+ */
50
+ export async function decryptV0(options: V0DecryptOptions): Promise<Blob> {
51
+ const { blob, contentKey, noncePrefix, chunkSize, onProgress } = options
52
+
53
+ if (!(blob instanceof Blob)) {
54
+ throw new TypeError('decryptV0: blob must be a Blob or File')
55
+ }
56
+ if (contentKey.length !== V0_KEY_BYTES) {
57
+ throw new RangeError('decryptV0: contentKey must be 32 bytes')
58
+ }
59
+ if (noncePrefix.length !== V0_NONCE_PREFIX_BYTES) {
60
+ throw new RangeError('decryptV0: noncePrefix must be 4 bytes')
61
+ }
62
+ if (!Number.isSafeInteger(chunkSize) || chunkSize <= 0) {
63
+ throw new RangeError('decryptV0: chunkSize must be a positive integer')
64
+ }
65
+
66
+ // Compute chunk layout from blob size.
67
+ const fullCipherLen = chunkSize + V0_TAG_BYTES
68
+ const totalSize = blob.size
69
+
70
+ if (totalSize === 0) {
71
+ return new Blob([], { type: 'application/octet-stream' })
72
+ }
73
+
74
+ const fullChunkCount = Math.floor(totalSize / fullCipherLen)
75
+ const trailingBytes = totalSize - fullChunkCount * fullCipherLen
76
+
77
+ let totalChunks: number
78
+ if (trailingBytes === 0) {
79
+ totalChunks = fullChunkCount
80
+ } else if (trailingBytes <= V0_TAG_BYTES) {
81
+ throw new Error(
82
+ `decryptV0: trailing bytes (${trailingBytes}) too small for an AEAD tag — file truncated`,
83
+ )
84
+ } else {
85
+ totalChunks = fullChunkCount + 1
86
+ }
87
+
88
+ // Import the AES-GCM key once.
89
+ const key = await getSubtle().importKey(
90
+ 'raw',
91
+ contentKey as Uint8Array<ArrayBuffer>,
92
+ { name: 'AES-GCM' },
93
+ false,
94
+ ['decrypt'],
95
+ )
96
+
97
+ const plaintextParts: BlobPart[] = []
98
+ let cursor = 0
99
+ for (let i = 0; i < totalChunks; i += 1) {
100
+ const isFinal = i === totalChunks - 1
101
+ const cipherLen = isFinal && trailingBytes > 0 ? trailingBytes : fullCipherLen
102
+ const cipherBytes = new Uint8Array(
103
+ await blob.slice(cursor, cursor + cipherLen).arrayBuffer(),
104
+ )
105
+ cursor += cipherLen
106
+
107
+ const iv = buildIv(noncePrefix, i)
108
+ let pt: ArrayBuffer
109
+ try {
110
+ pt = await getSubtle().decrypt(
111
+ { name: 'AES-GCM', iv: iv as Uint8Array<ArrayBuffer>, tagLength: 128 },
112
+ key,
113
+ cipherBytes as Uint8Array<ArrayBuffer>,
114
+ )
115
+ } catch (err) {
116
+ throw new Error(
117
+ `decryptV0: chunk ${i} failed authentication`,
118
+ { cause: err as Error },
119
+ )
120
+ }
121
+ plaintextParts.push(pt)
122
+
123
+ onProgress?.((i + 1) / totalChunks)
124
+ }
125
+
126
+ return new Blob(plaintextParts, { type: 'application/octet-stream' })
127
+ }
128
+
129
+ /**
130
+ * Convenience wrapper that returns plaintext bytes directly.
131
+ */
132
+ export async function decryptV0ToBytes(
133
+ options: V0DecryptOptions,
134
+ ): Promise<Uint8Array> {
135
+ const blob = await decryptV0(options)
136
+ return new Uint8Array(await blob.arrayBuffer())
137
+ }
138
+
139
+ /**
140
+ * Detect whether a blob is v0 (legacy) by checking the absence of the v1
141
+ * magic prefix. Use only when out-of-band metadata is unavailable. For
142
+ * normal application use, the database flag `cipher_version` is canonical.
143
+ */
144
+ export async function looksLikeV0(blob: Blob): Promise<boolean> {
145
+ if (blob.size < 5) return true // too small to be v1
146
+ const head = new Uint8Array(await blob.slice(0, 5).arrayBuffer())
147
+ // v1 magic is "SF5\x01\x00" = 0x53 0x46 0x35 0x01 0x00
148
+ return !(
149
+ head[0] === 0x53 &&
150
+ head[1] === 0x46 &&
151
+ head[2] === 0x35 &&
152
+ head[3] === 0x01 &&
153
+ head[4] === 0x00
154
+ )
155
+ }