@shieldfive/crypto 1.0.0-alpha.9 → 1.0.0-beta.1

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 +129 -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 +183 -49
  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 +114 -49
  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 +263 -59
  60. package/src/streams/pq-hybrid-v1.ts +169 -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'
@@ -46,8 +47,22 @@ import {
46
47
  MAX_TOTAL_CHUNKS,
47
48
  SUITE,
48
49
  } from '../internal/types.js'
49
- import { readUint32BE, uint32BE } from '../internal/encoding.js'
50
+ import { concatBytes, readUint32BE, uint32BE } from '../internal/encoding.js'
51
+ import { hmacSha256 } from '../internal/hmac.js'
50
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'
51
66
 
52
67
  const LENGTH_PREFIX_BYTES = 4
53
68
 
@@ -81,6 +96,13 @@ export interface PqHybridV1EncryptStreamOptions {
81
96
  * classical nonce).
82
97
  */
83
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
84
106
  }
85
107
 
86
108
  export interface PqHybridV1EncryptStreamResult {
@@ -153,33 +175,44 @@ export function createPqHybridV1EncryptStream(
153
175
  )
154
176
  }
155
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
+
156
185
  // State held across the lifetime of the stream:
157
186
  // - pending plaintext buffer (collects until we have a full chunk)
158
187
  // - chunk index counter
159
188
  // - bytes consumed counter (for sanity check vs plaintextSize)
160
189
  // - context (lazily initialized)
190
+ // - unauthenticated header bytes (kept for signing)
191
+ // - per-chunk MAC tags (last 16 bytes of each chunk ciphertext)
161
192
  let pending = new Uint8Array(0)
162
193
  let chunkIndex = 0
163
194
  let bytesConsumed = 0
164
195
  let contextPromise: ReturnType<typeof createChunkContext> | null = null
165
196
  let headerEmitted = false
197
+ let unauthenticatedHeader: Uint8Array | null = null
198
+ const chunkMacs: Uint8Array[] = []
166
199
 
167
200
  async function ensureHeader(
168
201
  controller: TransformStreamDefaultController<Uint8Array>,
169
202
  ): Promise<void> {
170
203
  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)
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]))
183
216
  headerEmitted = true
184
217
  }
185
218
 
@@ -194,6 +227,9 @@ export function createPqHybridV1EncryptStream(
194
227
  const ct = await encryptChunk(ctx, chunkIndex, plaintext)
195
228
  controller.enqueue(uint32BE(ct.length))
196
229
  controller.enqueue(ct)
230
+ if (ed25519SecretKey) {
231
+ chunkMacs.push(ct.slice(ct.length - PQ_HYBRID_V1_TAG_BYTES))
232
+ }
197
233
  chunkIndex += 1
198
234
  }
199
235
 
@@ -246,6 +282,28 @@ export function createPqHybridV1EncryptStream(
246
282
  controller.error(
247
283
  new RangeError('encrypt stream: residual bytes after final chunk'),
248
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
+ )
249
307
  }
250
308
  },
251
309
  }
@@ -279,6 +337,12 @@ export type PqHybridV1DecryptStreamOptions =
279
337
  /** Classical envelope key (32 bytes). */
280
338
  envelopeKey: Uint8Array
281
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
282
346
  }
283
347
  | {
284
348
  /**
@@ -299,8 +363,15 @@ export type PqHybridV1DecryptStreamOptions =
299
363
  combinedKey: Uint8Array
300
364
  recipientSecretKey?: undefined
301
365
  envelopeKey?: undefined
366
+ /** See sibling variant. */
367
+ expectedSignerPublicKey?: Uint8Array
302
368
  }
303
369
 
370
+ export interface PqHybridV1DecryptStreamResult {
371
+ stream: TransformStream<Uint8Array, Uint8Array>
372
+ metadata: Promise<DecryptionMetadata>
373
+ }
374
+
304
375
  /**
305
376
  * Build a TransformStream that decrypts a v1 ciphertext stream produced
306
377
  * under suite 0x03 into plaintext. Unlike the whole-blob decryptor, this
@@ -319,10 +390,20 @@ export type PqHybridV1DecryptStreamOptions =
319
390
  */
320
391
  export function createPqHybridV1DecryptStream(
321
392
  options: PqHybridV1DecryptStreamOptions,
322
- ): TransformStream<Uint8Array, Uint8Array> {
393
+ ): PqHybridV1DecryptStreamResult {
323
394
  const combinedKeyOverride = options.combinedKey
324
395
  const recipientSecretKey = options.recipientSecretKey
325
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(() => {})
326
407
 
327
408
  if (combinedKeyOverride) {
328
409
  if (combinedKeyOverride.length !== 32) {
@@ -350,6 +431,7 @@ export function createPqHybridV1DecryptStream(
350
431
  let bytesEmitted = 0
351
432
  let nextCipherLen = -1
352
433
  let contextPromise: ReturnType<typeof createChunkContext> | null = null
434
+ const chunkMacs: Uint8Array[] = []
353
435
 
354
436
  function append(input: Uint8Array): void {
355
437
  const merged = new Uint8Array(buffer.length + input.length)
@@ -473,53 +555,64 @@ export function createPqHybridV1DecryptStream(
473
555
  const pt = await decryptChunk(ctx, chunkIndex, ctBytes)
474
556
  bytesEmitted += pt.length
475
557
  controller.enqueue(pt)
558
+ chunkMacs.push(ctBytes.slice(ctBytes.length - PQ_HYBRID_V1_TAG_BYTES))
476
559
  chunkIndex += 1
477
560
  return true
478
561
  }
479
562
 
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')
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)
514
579
  }
515
- if (buffer.length !== 0) {
516
- throw new HeaderError('trailing_bytes_after_last_chunk')
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)
517
611
  }
518
- } catch (err) {
519
- controller.error(err as Error)
520
- }
521
- },
522
- })
612
+ },
613
+ }),
614
+ metadata,
615
+ }
523
616
  }
524
617
 
525
618
  // ─────────────────────────────────────────────────────────────────────
@@ -537,6 +630,11 @@ export interface EncryptStreamPqHybridV1Options {
537
630
  chunkSize?: number
538
631
  /** Pre-existing 16-byte file_id, or generated if omitted. */
539
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
540
638
  }
541
639
 
542
640
  /**
@@ -588,6 +686,9 @@ export async function encryptStreamPqHybridV1(
588
686
  if (options.chunkSize !== undefined) {
589
687
  streamOptions.chunkSize = options.chunkSize
590
688
  }
689
+ if (options.ed25519SecretKey !== undefined) {
690
+ streamOptions.ed25519SecretKey = options.ed25519SecretKey
691
+ }
591
692
  const { stream } = createPqHybridV1EncryptStream(streamOptions)
592
693
 
593
694
  return {
@@ -600,13 +701,22 @@ export async function encryptStreamPqHybridV1(
600
701
 
601
702
  /**
602
703
  * Pipe a ReadableStream<Uint8Array> through the PQ-hybrid-v1 decrypt
603
- * transform and return the resulting plaintext ReadableStream. See
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
604
707
  * {@link PqHybridV1DecryptStreamOptions} for the two key-input modes
605
708
  * (KEM secret + envelope vs. pre-derived combined key K).
606
709
  */
607
710
  export function decryptStreamPqHybridV1(
608
711
  source: ReadableStream<Uint8Array>,
609
712
  options: PqHybridV1DecryptStreamOptions,
610
- ): ReadableStream<Uint8Array> {
611
- return source.pipeThrough(createPqHybridV1DecryptStream(options))
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
+ }
612
722
  }
@@ -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
+ }