@shieldfive/crypto 1.0.0-alpha.9 → 1.0.0-beta.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 (65) hide show
  1. package/CHANGELOG.md +157 -0
  2. package/README.md +32 -15
  3. package/SECURITY.md +1 -1
  4. package/dist/identity/index.d.ts +16 -0
  5. package/dist/identity/index.d.ts.map +1 -1
  6. package/dist/identity/index.js +84 -22
  7. package/dist/identity/index.js.map +1 -1
  8. package/dist/identity/sign.d.ts +92 -0
  9. package/dist/identity/sign.d.ts.map +1 -0
  10. package/dist/identity/sign.js +182 -0
  11. package/dist/identity/sign.js.map +1 -0
  12. package/dist/index.d.ts +10 -4
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +26 -4
  15. package/dist/index.js.map +1 -1
  16. package/dist/internal/encoding.d.ts.map +1 -1
  17. package/dist/internal/encoding.js +0 -1
  18. package/dist/internal/encoding.js.map +1 -1
  19. package/dist/internal/types.d.ts +4 -1
  20. package/dist/internal/types.d.ts.map +1 -1
  21. package/dist/internal/types.js +8 -0
  22. package/dist/internal/types.js.map +1 -1
  23. package/dist/streams/aes-gcm-v1.d.ts +71 -3
  24. package/dist/streams/aes-gcm-v1.d.ts.map +1 -1
  25. package/dist/streams/aes-gcm-v1.js +192 -50
  26. package/dist/streams/aes-gcm-v1.js.map +1 -1
  27. package/dist/streams/pq-hybrid-v1.d.ts +34 -3
  28. package/dist/streams/pq-hybrid-v1.d.ts.map +1 -1
  29. package/dist/streams/pq-hybrid-v1.js +126 -50
  30. package/dist/streams/pq-hybrid-v1.js.map +1 -1
  31. package/dist/suites/aes-gcm-v1/api.d.ts.map +1 -1
  32. package/dist/suites/aes-gcm-v1/api.js +1 -1
  33. package/dist/suites/aes-gcm-v1/api.js.map +1 -1
  34. package/dist/suites/aes-gcm-v1/index.d.ts +3 -0
  35. package/dist/suites/aes-gcm-v1/index.d.ts.map +1 -1
  36. package/dist/suites/aes-gcm-v1/index.js +3 -0
  37. package/dist/suites/aes-gcm-v1/index.js.map +1 -1
  38. package/dist/suites/aes-gcm-v2/api.d.ts +44 -0
  39. package/dist/suites/aes-gcm-v2/api.d.ts.map +1 -0
  40. package/dist/suites/aes-gcm-v2/api.js +162 -0
  41. package/dist/suites/aes-gcm-v2/api.js.map +1 -0
  42. package/dist/suites/aes-gcm-v2/index.d.ts +63 -0
  43. package/dist/suites/aes-gcm-v2/index.d.ts.map +1 -0
  44. package/dist/suites/aes-gcm-v2/index.js +193 -0
  45. package/dist/suites/aes-gcm-v2/index.js.map +1 -0
  46. package/dist/suites/pq-hybrid-v1/index.d.ts +4 -0
  47. package/dist/suites/pq-hybrid-v1/index.d.ts.map +1 -1
  48. package/dist/suites/pq-hybrid-v1/index.js +15 -1
  49. package/dist/suites/pq-hybrid-v1/index.js.map +1 -1
  50. package/package.json +12 -2
  51. package/spec/format-v1.md +200 -7
  52. package/spec/key-derivation.md +18 -2
  53. package/spec/threat-model.md +36 -21
  54. package/src/identity/index.ts +107 -28
  55. package/src/identity/sign.ts +221 -0
  56. package/src/index.ts +32 -5
  57. package/src/internal/encoding.ts +0 -1
  58. package/src/internal/types.ts +9 -0
  59. package/src/streams/aes-gcm-v1.ts +275 -59
  60. package/src/streams/pq-hybrid-v1.ts +182 -59
  61. package/src/suites/aes-gcm-v1/api.ts +0 -1
  62. package/src/suites/aes-gcm-v1/index.ts +3 -0
  63. package/src/suites/aes-gcm-v2/api.ts +268 -0
  64. package/src/suites/aes-gcm-v2/index.ts +289 -0
  65. package/src/suites/pq-hybrid-v1/index.ts +25 -4
@@ -27,7 +27,8 @@
27
27
  */
28
28
 
29
29
  import {
30
- buildAuthenticatedHeader,
30
+ buildHeaderUnauthenticated,
31
+ deriveHeaderMacKey,
31
32
  HeaderError,
32
33
  parseHeader,
33
34
  } from '../format/header.js'
@@ -39,6 +40,7 @@ import {
39
40
  decryptChunk,
40
41
  encapsulateForRecipient,
41
42
  encryptChunk,
43
+ parsePqHybridV1SuitePayload,
42
44
  } from '../suites/pq-hybrid-v1/index.js'
43
45
  import {
44
46
  DEFAULT_CHUNK_SIZE,
@@ -46,8 +48,22 @@ import {
46
48
  MAX_TOTAL_CHUNKS,
47
49
  SUITE,
48
50
  } from '../internal/types.js'
49
- import { readUint32BE, uint32BE } from '../internal/encoding.js'
51
+ import { concatBytes, readUint32BE, uint32BE } from '../internal/encoding.js'
52
+ import { hmacSha256 } from '../internal/hmac.js'
50
53
  import { randomBytes } from '../internal/runtime.js'
54
+ import {
55
+ buildSignatureBlock,
56
+ deriveEd25519PublicKey,
57
+ ED25519_SECRET_KEY_LENGTH,
58
+ SIGNATURE_ALGO_ED25519,
59
+ signHeaderAndMacs,
60
+ } from '../identity/sign.js'
61
+ import {
62
+ type DecryptionMetadata,
63
+ finalizeSignatureMetadata,
64
+ } from './aes-gcm-v1.js'
65
+
66
+ export type { DecryptionMetadata, VerifiedSignature } from './aes-gcm-v1.js'
51
67
 
52
68
  const LENGTH_PREFIX_BYTES = 4
53
69
 
@@ -81,6 +97,13 @@ export interface PqHybridV1EncryptStreamOptions {
81
97
  * classical nonce).
82
98
  */
83
99
  suitePayload: Uint8Array
100
+ /**
101
+ * Optional 32-byte Ed25519 secret seed. When provided, the stream
102
+ * appends a signature block over `header_unauthenticated_bytes ||
103
+ * concat(chunk_macs)` after the final chunk. When omitted, no block
104
+ * is emitted and the file decrypts as unsigned (legacy behavior).
105
+ */
106
+ ed25519SecretKey?: Uint8Array
84
107
  }
85
108
 
86
109
  export interface PqHybridV1EncryptStreamResult {
@@ -152,34 +175,49 @@ export function createPqHybridV1EncryptStream(
152
175
  `encrypt stream: suitePayload must be ${PQ_HYBRID_V1_SUITE_PAYLOAD_LENGTH} bytes`,
153
176
  )
154
177
  }
178
+ // Reject a structurally-invalid payload (e.g. a non-zero reserved
179
+ // classical_wrapped pad, M6) at encode time too, so the stream never emits
180
+ // a file its own readers would refuse.
181
+ parsePqHybridV1SuitePayload(suitePayload)
182
+
183
+ const ed25519SecretKey = options.ed25519SecretKey
184
+ if (ed25519SecretKey && ed25519SecretKey.length !== ED25519_SECRET_KEY_LENGTH) {
185
+ throw new RangeError(
186
+ `encrypt stream: ed25519SecretKey must be ${ED25519_SECRET_KEY_LENGTH} bytes`,
187
+ )
188
+ }
155
189
 
156
190
  // State held across the lifetime of the stream:
157
191
  // - pending plaintext buffer (collects until we have a full chunk)
158
192
  // - chunk index counter
159
193
  // - bytes consumed counter (for sanity check vs plaintextSize)
160
194
  // - context (lazily initialized)
195
+ // - unauthenticated header bytes (kept for signing)
196
+ // - per-chunk MAC tags (last 16 bytes of each chunk ciphertext)
161
197
  let pending = new Uint8Array(0)
162
198
  let chunkIndex = 0
163
199
  let bytesConsumed = 0
164
200
  let contextPromise: ReturnType<typeof createChunkContext> | null = null
165
201
  let headerEmitted = false
202
+ let unauthenticatedHeader: Uint8Array | null = null
203
+ const chunkMacs: Uint8Array[] = []
166
204
 
167
205
  async function ensureHeader(
168
206
  controller: TransformStreamDefaultController<Uint8Array>,
169
207
  ): Promise<void> {
170
208
  if (headerEmitted) return
171
- const header = await buildAuthenticatedHeader(
172
- {
173
- suite: SUITE.PQ_HYBRID_XCHACHA_MLKEM1024_V1,
174
- fileId,
175
- chunkSize,
176
- totalChunks,
177
- plaintextSize: options.plaintextSize,
178
- suitePayload,
179
- },
180
- combinedKey,
181
- )
182
- controller.enqueue(header)
209
+ const unauth = buildHeaderUnauthenticated({
210
+ suite: SUITE.PQ_HYBRID_XCHACHA_MLKEM1024_V1,
211
+ fileId,
212
+ chunkSize,
213
+ totalChunks,
214
+ plaintextSize: options.plaintextSize,
215
+ suitePayload,
216
+ })
217
+ const macKey = await deriveHeaderMacKey(combinedKey, fileId)
218
+ const mac = await hmacSha256(macKey, unauth)
219
+ unauthenticatedHeader = unauth
220
+ controller.enqueue(concatBytes([unauth, mac]))
183
221
  headerEmitted = true
184
222
  }
185
223
 
@@ -194,6 +232,9 @@ export function createPqHybridV1EncryptStream(
194
232
  const ct = await encryptChunk(ctx, chunkIndex, plaintext)
195
233
  controller.enqueue(uint32BE(ct.length))
196
234
  controller.enqueue(ct)
235
+ if (ed25519SecretKey) {
236
+ chunkMacs.push(ct.slice(ct.length - PQ_HYBRID_V1_TAG_BYTES))
237
+ }
197
238
  chunkIndex += 1
198
239
  }
199
240
 
@@ -246,6 +287,28 @@ export function createPqHybridV1EncryptStream(
246
287
  controller.error(
247
288
  new RangeError('encrypt stream: residual bytes after final chunk'),
248
289
  )
290
+ return
291
+ }
292
+ if (ed25519SecretKey) {
293
+ if (!unauthenticatedHeader) {
294
+ controller.error(
295
+ new Error('encrypt stream: header not finalized before signing'),
296
+ )
297
+ return
298
+ }
299
+ const signature = signHeaderAndMacs({
300
+ ed25519SecretKey,
301
+ header: unauthenticatedHeader,
302
+ chunkMacs,
303
+ })
304
+ const publicKey = deriveEd25519PublicKey(ed25519SecretKey)
305
+ controller.enqueue(
306
+ buildSignatureBlock({
307
+ algorithm: SIGNATURE_ALGO_ED25519,
308
+ publicKey,
309
+ signature,
310
+ }),
311
+ )
249
312
  }
250
313
  },
251
314
  }
@@ -279,6 +342,12 @@ export type PqHybridV1DecryptStreamOptions =
279
342
  /** Classical envelope key (32 bytes). */
280
343
  envelopeKey: Uint8Array
281
344
  combinedKey?: undefined
345
+ /**
346
+ * If provided, a trailing signature block (if present) is verified
347
+ * against this Ed25519 public key. See `AesGcmV1DecryptStreamOptions`
348
+ * for the verification semantics — they are identical here.
349
+ */
350
+ expectedSignerPublicKey?: Uint8Array
282
351
  }
283
352
  | {
284
353
  /**
@@ -299,8 +368,15 @@ export type PqHybridV1DecryptStreamOptions =
299
368
  combinedKey: Uint8Array
300
369
  recipientSecretKey?: undefined
301
370
  envelopeKey?: undefined
371
+ /** See sibling variant. */
372
+ expectedSignerPublicKey?: Uint8Array
302
373
  }
303
374
 
375
+ export interface PqHybridV1DecryptStreamResult {
376
+ stream: TransformStream<Uint8Array, Uint8Array>
377
+ metadata: Promise<DecryptionMetadata>
378
+ }
379
+
304
380
  /**
305
381
  * Build a TransformStream that decrypts a v1 ciphertext stream produced
306
382
  * under suite 0x03 into plaintext. Unlike the whole-blob decryptor, this
@@ -319,10 +395,20 @@ export type PqHybridV1DecryptStreamOptions =
319
395
  */
320
396
  export function createPqHybridV1DecryptStream(
321
397
  options: PqHybridV1DecryptStreamOptions,
322
- ): TransformStream<Uint8Array, Uint8Array> {
398
+ ): PqHybridV1DecryptStreamResult {
323
399
  const combinedKeyOverride = options.combinedKey
324
400
  const recipientSecretKey = options.recipientSecretKey
325
401
  const envelopeKey = options.envelopeKey
402
+ const expectedSignerPublicKey = options.expectedSignerPublicKey
403
+
404
+ let resolveMetadata!: (m: DecryptionMetadata) => void
405
+ let rejectMetadata!: (err: unknown) => void
406
+ const metadata = new Promise<DecryptionMetadata>((resolve, reject) => {
407
+ resolveMetadata = resolve
408
+ rejectMetadata = reject
409
+ })
410
+ // See aes-gcm-v1.ts createAesGcmV1DecryptStream for rationale.
411
+ metadata.catch(() => {})
326
412
 
327
413
  if (combinedKeyOverride) {
328
414
  if (combinedKeyOverride.length !== 32) {
@@ -350,6 +436,7 @@ export function createPqHybridV1DecryptStream(
350
436
  let bytesEmitted = 0
351
437
  let nextCipherLen = -1
352
438
  let contextPromise: ReturnType<typeof createChunkContext> | null = null
439
+ const chunkMacs: Uint8Array[] = []
353
440
 
354
441
  function append(input: Uint8Array): void {
355
442
  const merged = new Uint8Array(buffer.length + input.length)
@@ -427,6 +514,14 @@ export function createPqHybridV1DecryptStream(
427
514
  const { verifyHeaderMac } = await import('../format/header.js')
428
515
  await verifyHeaderMac(parsedHeader, combinedKey)
429
516
 
517
+ // Combined-key mode skips decapsulateFromHeader, so it must run the same
518
+ // structural check the KEM path gets there: suite_payload length + the
519
+ // all-zero reserved classical_wrapped pad (M6, spec/format-v1.md § 0x03).
520
+ // Validated after the MAC so it only interprets authenticated bytes.
521
+ if (combinedKeyOverride) {
522
+ parsePqHybridV1SuitePayload(parsedHeader.suitePayload)
523
+ }
524
+
430
525
  contextPromise = createChunkContext(
431
526
  combinedKey,
432
527
  parsedHeader.fileId,
@@ -473,53 +568,64 @@ export function createPqHybridV1DecryptStream(
473
568
  const pt = await decryptChunk(ctx, chunkIndex, ctBytes)
474
569
  bytesEmitted += pt.length
475
570
  controller.enqueue(pt)
571
+ chunkMacs.push(ctBytes.slice(ctBytes.length - PQ_HYBRID_V1_TAG_BYTES))
476
572
  chunkIndex += 1
477
573
  return true
478
574
  }
479
575
 
480
- return new TransformStream<Uint8Array, Uint8Array>({
481
- async transform(chunk, controller) {
482
- append(chunk)
483
- try {
484
- if (phase === 0) {
485
- const ok = await tryParseHeader()
486
- if (!ok) return
487
- }
488
- // Drain as many chunks as we have data for.
489
- while (await tryEmitChunk(controller)) {
490
- /* loop */
491
- }
492
- } catch (err) {
493
- controller.error(err as Error)
494
- }
495
- },
496
- async flush(controller) {
497
- try {
498
- if (phase === 0) {
499
- throw new HeaderError('header_too_short')
500
- }
501
- // No header yet means truncated input.
502
- if (!parsedHeader) {
503
- throw new HeaderError('header_too_short')
504
- }
505
- // Try once more in case flush is called with everything queued.
506
- while (await tryEmitChunk(controller)) {
507
- /* loop */
508
- }
509
- if (chunkIndex !== parsedHeader.totalChunks) {
510
- throw new HeaderError('chunk_truncated')
511
- }
512
- if (bytesEmitted !== parsedHeader.plaintextSize) {
513
- throw new HeaderError('plaintext_size_mismatch')
576
+ return {
577
+ stream: new TransformStream<Uint8Array, Uint8Array>({
578
+ async transform(chunk, controller) {
579
+ append(chunk)
580
+ try {
581
+ if (phase === 0) {
582
+ const ok = await tryParseHeader()
583
+ if (!ok) return
584
+ }
585
+ // Drain as many chunks as we have data for.
586
+ while (await tryEmitChunk(controller)) {
587
+ /* loop */
588
+ }
589
+ } catch (err) {
590
+ controller.error(err as Error)
591
+ rejectMetadata(err)
514
592
  }
515
- if (buffer.length !== 0) {
516
- throw new HeaderError('trailing_bytes_after_last_chunk')
593
+ },
594
+ async flush(controller) {
595
+ try {
596
+ if (phase === 0) {
597
+ throw new HeaderError('header_too_short')
598
+ }
599
+ // No header yet means truncated input.
600
+ if (!parsedHeader) {
601
+ throw new HeaderError('header_too_short')
602
+ }
603
+ // Try once more in case flush is called with everything queued.
604
+ while (await tryEmitChunk(controller)) {
605
+ /* loop */
606
+ }
607
+ if (chunkIndex !== parsedHeader.totalChunks) {
608
+ throw new HeaderError('chunk_truncated')
609
+ }
610
+ if (bytesEmitted !== parsedHeader.plaintextSize) {
611
+ throw new HeaderError('plaintext_size_mismatch')
612
+ }
613
+ const signatureResult = finalizeSignatureMetadata({
614
+ trailingBytes: buffer,
615
+ header: parsedHeader.unauthenticatedBytes,
616
+ chunkMacs,
617
+ expectedSignerPublicKey,
618
+ })
619
+ buffer = new Uint8Array(0)
620
+ resolveMetadata({ signature: signatureResult })
621
+ } catch (err) {
622
+ controller.error(err as Error)
623
+ rejectMetadata(err)
517
624
  }
518
- } catch (err) {
519
- controller.error(err as Error)
520
- }
521
- },
522
- })
625
+ },
626
+ }),
627
+ metadata,
628
+ }
523
629
  }
524
630
 
525
631
  // ─────────────────────────────────────────────────────────────────────
@@ -537,6 +643,11 @@ export interface EncryptStreamPqHybridV1Options {
537
643
  chunkSize?: number
538
644
  /** Pre-existing 16-byte file_id, or generated if omitted. */
539
645
  fileId?: Uint8Array
646
+ /**
647
+ * Optional 32-byte Ed25519 secret seed for sender attribution. When
648
+ * provided, a signature block is appended after the final chunk.
649
+ */
650
+ ed25519SecretKey?: Uint8Array
540
651
  }
541
652
 
542
653
  /**
@@ -588,6 +699,9 @@ export async function encryptStreamPqHybridV1(
588
699
  if (options.chunkSize !== undefined) {
589
700
  streamOptions.chunkSize = options.chunkSize
590
701
  }
702
+ if (options.ed25519SecretKey !== undefined) {
703
+ streamOptions.ed25519SecretKey = options.ed25519SecretKey
704
+ }
591
705
  const { stream } = createPqHybridV1EncryptStream(streamOptions)
592
706
 
593
707
  return {
@@ -600,13 +714,22 @@ export async function encryptStreamPqHybridV1(
600
714
 
601
715
  /**
602
716
  * Pipe a ReadableStream<Uint8Array> through the PQ-hybrid-v1 decrypt
603
- * transform and return the resulting plaintext ReadableStream. See
717
+ * transform and return the resulting plaintext ReadableStream + a
718
+ * `metadata` Promise carrying the parsed signature block (or
719
+ * `signature: null` for unsigned / legacy files). See
604
720
  * {@link PqHybridV1DecryptStreamOptions} for the two key-input modes
605
721
  * (KEM secret + envelope vs. pre-derived combined key K).
606
722
  */
607
723
  export function decryptStreamPqHybridV1(
608
724
  source: ReadableStream<Uint8Array>,
609
725
  options: PqHybridV1DecryptStreamOptions,
610
- ): ReadableStream<Uint8Array> {
611
- return source.pipeThrough(createPqHybridV1DecryptStream(options))
726
+ ): {
727
+ plaintext: ReadableStream<Uint8Array>
728
+ metadata: Promise<DecryptionMetadata>
729
+ } {
730
+ const { stream, metadata } = createPqHybridV1DecryptStream(options)
731
+ return {
732
+ plaintext: source.pipeThrough(stream),
733
+ metadata,
734
+ }
612
735
  }
@@ -35,7 +35,6 @@ import {
35
35
  } from '../../internal/types.js'
36
36
  import {
37
37
  asBlobPart,
38
- concatBytes,
39
38
  readUint32BE,
40
39
  uint32BE,
41
40
  } from '../../internal/encoding.js'
@@ -1,6 +1,9 @@
1
1
  /**
2
2
  * Cipher suite 0x01: AES-256-GCM v1.
3
3
  *
4
+ * Decrypt-only for legacy files created before 2026-05-21; new encrypts
5
+ * use 0x04 aes-gcm-v2, which widens the file-derived nonce prefix.
6
+ *
4
7
  * Per-file content key. Per-chunk AEAD with file_id-bound AAD that
5
8
  * authenticates chunk index, total chunks, and the is-final flag. The
6
9
  * 12-byte GCM IV is split into a 4-byte file-derived prefix and an 8-byte
@@ -0,0 +1,268 @@
1
+ /**
2
+ * High-level encrypt/decrypt API for the AES-256-GCM v2 suite.
3
+ *
4
+ * Identical glue to the v1 API (header construction + chunked AEAD); the
5
+ * difference is the suite ID and the underlying nonce-prefix width — see
6
+ * `./index.ts` for the v2 rationale.
7
+ */
8
+
9
+ import {
10
+ buildAuthenticatedHeader,
11
+ parseHeader,
12
+ verifyHeaderMac,
13
+ HeaderError,
14
+ } from '../../format/header.js'
15
+ import {
16
+ AES_GCM_V2_SUITE_PAYLOAD_LENGTH,
17
+ AES_GCM_V2_TAG_BYTES,
18
+ createChunkContext,
19
+ decryptChunk,
20
+ encryptChunk,
21
+ generateContentMaterial,
22
+ parseAesGcmV2SuitePayload,
23
+ } from './index.js'
24
+ import {
25
+ DEFAULT_CHUNK_SIZE,
26
+ type EncryptedFile,
27
+ HEADER_SIZES,
28
+ MAX_TOTAL_CHUNKS,
29
+ type ProgressCallback,
30
+ SUITE,
31
+ } from '../../internal/types.js'
32
+ import {
33
+ asBlobPart,
34
+ readUint32BE,
35
+ uint32BE,
36
+ } from '../../internal/encoding.js'
37
+
38
+ const LENGTH_PREFIX_BYTES = 4
39
+
40
+ export interface EncryptOptions {
41
+ blob: Blob
42
+ /** Optional pre-existing content key (32 bytes). If omitted, generated. */
43
+ contentKey?: Uint8Array
44
+ /** Optional pre-existing file_id (16 bytes). If omitted, generated. */
45
+ fileId?: Uint8Array
46
+ /** Optional embedded wrapped key + IV (60 + 12 bytes). Defaults to zeros. */
47
+ suitePayloadOverride?: Uint8Array
48
+ /** Plaintext bytes per chunk. Defaults to 4 MiB. */
49
+ chunkSize?: number
50
+ /** Progress callback (0..1). Called once per chunk and once at completion. */
51
+ onProgress?: ProgressCallback
52
+ }
53
+
54
+ /**
55
+ * Encrypt a Blob/File with the AES-256-GCM v2 suite.
56
+ * Returns the encrypted blob (header + chunks), plus the content key and
57
+ * file id so the caller can wrap/store them externally.
58
+ */
59
+ export async function encryptBlob(
60
+ options: EncryptOptions,
61
+ ): Promise<EncryptedFile & { contentKey: Uint8Array }> {
62
+ const { blob, onProgress } = options
63
+ if (!(blob instanceof Blob)) {
64
+ throw new TypeError('encryptBlob: blob must be a Blob or File')
65
+ }
66
+
67
+ const chunkSize = options.chunkSize ?? DEFAULT_CHUNK_SIZE
68
+ if (!Number.isSafeInteger(chunkSize) || chunkSize <= 0) {
69
+ throw new RangeError('encryptBlob: chunkSize must be a positive integer')
70
+ }
71
+
72
+ const plaintextSize = blob.size
73
+ const totalChunks =
74
+ plaintextSize === 0 ? 0 : Math.ceil(plaintextSize / chunkSize)
75
+ if (totalChunks > MAX_TOTAL_CHUNKS) {
76
+ throw new RangeError('encryptBlob: file would exceed total_chunks limit')
77
+ }
78
+
79
+ const generated = generateContentMaterial()
80
+ const contentKey = options.contentKey ?? generated.contentKey
81
+ const fileId = options.fileId ?? generated.fileId
82
+ if (contentKey.length !== 32) {
83
+ throw new RangeError('encryptBlob: contentKey must be 32 bytes')
84
+ }
85
+ if (fileId.length !== HEADER_SIZES.FILE_ID) {
86
+ throw new RangeError('encryptBlob: fileId must be 16 bytes')
87
+ }
88
+
89
+ const suitePayload =
90
+ options.suitePayloadOverride ??
91
+ new Uint8Array(AES_GCM_V2_SUITE_PAYLOAD_LENGTH)
92
+ if (suitePayload.length !== AES_GCM_V2_SUITE_PAYLOAD_LENGTH) {
93
+ throw new RangeError(
94
+ `encryptBlob: suitePayloadOverride must be ${AES_GCM_V2_SUITE_PAYLOAD_LENGTH} bytes`,
95
+ )
96
+ }
97
+
98
+ const header = await buildAuthenticatedHeader(
99
+ {
100
+ suite: SUITE.AES_256_GCM_V2,
101
+ fileId,
102
+ chunkSize,
103
+ totalChunks,
104
+ plaintextSize,
105
+ suitePayload,
106
+ },
107
+ contentKey,
108
+ )
109
+
110
+ const ctx = await createChunkContext(contentKey, fileId, totalChunks)
111
+
112
+ const parts: BlobPart[] = [asBlobPart(header)]
113
+
114
+ for (let i = 0; i < totalChunks; i += 1) {
115
+ const start = i * chunkSize
116
+ const end = Math.min(start + chunkSize, plaintextSize)
117
+ const plaintextBytes = new Uint8Array(
118
+ await blob.slice(start, end).arrayBuffer(),
119
+ )
120
+ const ciphertext = await encryptChunk(ctx, i, plaintextBytes)
121
+ parts.push(asBlobPart(uint32BE(ciphertext.length)))
122
+ parts.push(asBlobPart(ciphertext))
123
+ onProgress?.((i + 1) / Math.max(totalChunks, 1))
124
+ }
125
+
126
+ if (totalChunks === 0) onProgress?.(1)
127
+
128
+ return {
129
+ blob: new Blob(parts, { type: 'application/octet-stream' }),
130
+ suite: SUITE.AES_256_GCM_V2,
131
+ fileId,
132
+ chunkSize,
133
+ totalChunks,
134
+ plaintextSize,
135
+ contentKey,
136
+ }
137
+ }
138
+
139
+ export interface DecryptOptions {
140
+ blob: Blob
141
+ contentKey: Uint8Array
142
+ onProgress?: ProgressCallback
143
+ allowedSuites?: ReadonlyArray<number>
144
+ }
145
+
146
+ /**
147
+ * Decrypt a v2 blob produced by `encryptBlob`.
148
+ */
149
+ export async function decryptBlob(options: DecryptOptions): Promise<Blob> {
150
+ const { blob, contentKey, onProgress } = options
151
+ if (!(blob instanceof Blob)) {
152
+ throw new TypeError('decryptBlob: blob must be a Blob or File')
153
+ }
154
+ if (contentKey.length !== 32) {
155
+ throw new RangeError('decryptBlob: contentKey must be 32 bytes')
156
+ }
157
+
158
+ const headerProbeBytes = new Uint8Array(
159
+ await blob.slice(0, Math.min(blob.size, 4096)).arrayBuffer(),
160
+ )
161
+
162
+ let parsed: ReturnType<typeof parseHeader>
163
+ try {
164
+ parsed = parseHeader(headerProbeBytes)
165
+ } catch (err) {
166
+ if (err instanceof HeaderError && err.code === 'header_too_short') {
167
+ const allHeaderBytes = new Uint8Array(
168
+ await blob
169
+ .slice(0, Math.min(blob.size, 4 + 0xffff + 1024))
170
+ .arrayBuffer(),
171
+ )
172
+ parsed = parseHeader(allHeaderBytes)
173
+ } else {
174
+ throw err
175
+ }
176
+ }
177
+
178
+ if (
179
+ options.allowedSuites &&
180
+ !options.allowedSuites.includes(parsed.suite)
181
+ ) {
182
+ throw new HeaderError('suite_not_allowed')
183
+ }
184
+
185
+ if (parsed.suite !== SUITE.AES_256_GCM_V2) {
186
+ throw new HeaderError(
187
+ `decryptBlob: this entry point only supports aes-256-gcm-v2; got suite 0x${parsed.suite.toString(16)}`,
188
+ )
189
+ }
190
+
191
+ await verifyHeaderMac(parsed, contentKey)
192
+
193
+ parseAesGcmV2SuitePayload(parsed.suitePayload)
194
+
195
+ const ctx = await createChunkContext(
196
+ contentKey,
197
+ parsed.fileId,
198
+ parsed.totalChunks,
199
+ )
200
+
201
+ const plaintextParts: BlobPart[] = []
202
+ let cursor = parsed.headerLength
203
+ let bytesEmitted = 0
204
+
205
+ for (let i = 0; i < parsed.totalChunks; i += 1) {
206
+ if (cursor + LENGTH_PREFIX_BYTES > blob.size) {
207
+ throw new HeaderError('chunk_length_truncated')
208
+ }
209
+ const lenBytes = new Uint8Array(
210
+ await blob.slice(cursor, cursor + LENGTH_PREFIX_BYTES).arrayBuffer(),
211
+ )
212
+ cursor += LENGTH_PREFIX_BYTES
213
+ const cipherLen = readUint32BE(lenBytes)
214
+
215
+ const isFinal = i === parsed.totalChunks - 1
216
+ const minCipher = 1 + AES_GCM_V2_TAG_BYTES
217
+ const maxCipher = parsed.chunkSize + AES_GCM_V2_TAG_BYTES
218
+ if (cipherLen < minCipher || cipherLen > maxCipher) {
219
+ throw new HeaderError('chunk_length_out_of_range')
220
+ }
221
+ if (!isFinal && cipherLen !== maxCipher) {
222
+ throw new HeaderError('non_final_chunk_wrong_size')
223
+ }
224
+
225
+ if (cursor + cipherLen > blob.size) {
226
+ throw new HeaderError('chunk_truncated')
227
+ }
228
+
229
+ const cipherBytes = new Uint8Array(
230
+ await blob.slice(cursor, cursor + cipherLen).arrayBuffer(),
231
+ )
232
+ cursor += cipherLen
233
+
234
+ const plaintext = await decryptChunk(ctx, i, cipherBytes)
235
+ bytesEmitted += plaintext.length
236
+ plaintextParts.push(asBlobPart(plaintext))
237
+
238
+ onProgress?.((i + 1) / Math.max(parsed.totalChunks, 1))
239
+ }
240
+
241
+ if (bytesEmitted !== parsed.plaintextSize) {
242
+ throw new HeaderError('plaintext_size_mismatch')
243
+ }
244
+ if (cursor !== blob.size) {
245
+ throw new HeaderError('trailing_bytes_after_last_chunk')
246
+ }
247
+
248
+ if (parsed.totalChunks === 0) onProgress?.(1)
249
+
250
+ return new Blob(plaintextParts, { type: 'application/octet-stream' })
251
+ }
252
+
253
+ export async function encryptBytes(
254
+ bytes: Uint8Array | ArrayBuffer,
255
+ options: Omit<EncryptOptions, 'blob'>,
256
+ ): Promise<EncryptedFile & { contentKey: Uint8Array }> {
257
+ const part: BlobPart =
258
+ bytes instanceof ArrayBuffer ? bytes : asBlobPart(bytes)
259
+ const blob = new Blob([part])
260
+ return encryptBlob({ blob, ...options })
261
+ }
262
+
263
+ export async function decryptToBytes(
264
+ options: DecryptOptions,
265
+ ): Promise<Uint8Array> {
266
+ const blob = await decryptBlob(options)
267
+ return new Uint8Array(await blob.arrayBuffer())
268
+ }