@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,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
+ }
@@ -0,0 +1,289 @@
1
+ /**
2
+ * Cipher suite 0x04: AES-256-GCM v2.
3
+ *
4
+ * Per-file content key. Per-chunk AEAD with file_id-bound AAD that
5
+ * authenticates chunk index, total chunks, and the is-final flag. The
6
+ * 12-byte GCM IV is split into an 8-byte file-derived prefix and a 4-byte
7
+ * big-endian counter — a wider prefix than v1 (0x01) so the per-file
8
+ * `(prefix, counter)` collision space across files sharing a content
9
+ * key shrinks from 2^32 to 2^64. The per-file chunk ceiling drops from
10
+ * 2^64 to 2^32 chunks, which is still well above any practical bound
11
+ * the format permits (`MAX_TOTAL_CHUNKS` is 1e9 and `chunkIndex` is a
12
+ * safe JS integer).
13
+ */
14
+
15
+ import { buildChunkAad } from '../../format/header.js'
16
+ import {
17
+ HKDF_INFO,
18
+ HEADER_SIZES,
19
+ type ParsedHeader,
20
+ } from '../../internal/types.js'
21
+ import { concatBytes, uint32BE } from '../../internal/encoding.js'
22
+ import { hkdfSha256 } from '../../internal/hkdf.js'
23
+ import { getSubtle, randomBytes } from '../../internal/runtime.js'
24
+
25
+ export const AES_GCM_V2_TAG_BYTES = 16
26
+ export const AES_GCM_V2_IV_BYTES = 12
27
+ export const AES_GCM_V2_KEY_BYTES = 32
28
+ export const AES_GCM_V2_NONCE_PREFIX_LENGTH = 8
29
+ export const AES_GCM_V2_MAX_CHUNK_INDEX = 0xffff_ffff
30
+
31
+ /** Suite payload layout: 60-byte wrapped key + 12-byte wrap IV = 72 bytes. */
32
+ export const AES_GCM_V2_SUITE_PAYLOAD_LENGTH = 72
33
+
34
+ export interface AesGcmV2SuitePayload {
35
+ wrappedKey: Uint8Array // 60 bytes (32-byte key + 16-byte tag + 12-byte AAD-padded reserved zeros)
36
+ wrapIv: Uint8Array // 12 bytes
37
+ }
38
+
39
+ export function buildAesGcmV2SuitePayload(
40
+ payload: AesGcmV2SuitePayload,
41
+ ): Uint8Array {
42
+ if (payload.wrappedKey.length !== 60) {
43
+ throw new RangeError('aes-gcm-v2: wrappedKey must be 60 bytes')
44
+ }
45
+ if (payload.wrapIv.length !== AES_GCM_V2_IV_BYTES) {
46
+ throw new RangeError('aes-gcm-v2: wrapIv must be 12 bytes')
47
+ }
48
+ return concatBytes([payload.wrappedKey, payload.wrapIv])
49
+ }
50
+
51
+ export function parseAesGcmV2SuitePayload(
52
+ bytes: Uint8Array,
53
+ ): AesGcmV2SuitePayload {
54
+ if (bytes.length !== AES_GCM_V2_SUITE_PAYLOAD_LENGTH) {
55
+ throw new RangeError('aes-gcm-v2: suite payload must be 72 bytes')
56
+ }
57
+ return {
58
+ wrappedKey: bytes.slice(0, 60),
59
+ wrapIv: bytes.slice(60, 72),
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Derive the per-file chunk key from the content key. The chunk-key HKDF
65
+ * info matches v1 because the chunk-key derivation is unchanged across
66
+ * versions; only the nonce-prefix derivation differs. Files of either
67
+ * suite encrypted with the same content_key + file_id derive identical
68
+ * chunk keys, but their `(prefix, counter)` spaces are disjoint because
69
+ * the prefix info string differs.
70
+ */
71
+ async function deriveChunkKey(
72
+ contentKey: Uint8Array,
73
+ fileId: Uint8Array,
74
+ ): Promise<Uint8Array> {
75
+ return hkdfSha256({
76
+ ikm: contentKey,
77
+ salt: fileId,
78
+ info: HKDF_INFO.AES_GCM_CHUNK_KEY,
79
+ length: AES_GCM_V2_KEY_BYTES,
80
+ })
81
+ }
82
+
83
+ /**
84
+ * Derive the 8-byte nonce prefix from file_id. Stable per file. The wider
85
+ * prefix is the entire point of the v2 suite — see this file's top
86
+ * docstring.
87
+ */
88
+ async function deriveNoncePrefix(fileId: Uint8Array): Promise<Uint8Array> {
89
+ return hkdfSha256({
90
+ ikm: fileId,
91
+ info: HKDF_INFO.AES_GCM_V2_NONCE_PREFIX,
92
+ length: AES_GCM_V2_NONCE_PREFIX_LENGTH,
93
+ })
94
+ }
95
+
96
+ function buildIv(noncePrefix: Uint8Array, chunkIndex: number): Uint8Array {
97
+ if (
98
+ !Number.isSafeInteger(chunkIndex) ||
99
+ chunkIndex < 0 ||
100
+ chunkIndex > AES_GCM_V2_MAX_CHUNK_INDEX
101
+ ) {
102
+ throw new RangeError(
103
+ 'aes-gcm-v2: chunkIndex must be in [0, 2^32)',
104
+ )
105
+ }
106
+ if (noncePrefix.length !== AES_GCM_V2_NONCE_PREFIX_LENGTH) {
107
+ throw new RangeError('aes-gcm-v2: noncePrefix must be 8 bytes')
108
+ }
109
+ const iv = new Uint8Array(AES_GCM_V2_IV_BYTES)
110
+ iv.set(noncePrefix, 0)
111
+ iv.set(uint32BE(chunkIndex), AES_GCM_V2_NONCE_PREFIX_LENGTH)
112
+ return iv
113
+ }
114
+
115
+ async function importAesGcmKey(
116
+ keyBytes: Uint8Array,
117
+ usages: KeyUsage[],
118
+ ): Promise<CryptoKey> {
119
+ if (keyBytes.length !== AES_GCM_V2_KEY_BYTES) {
120
+ throw new RangeError('aes-gcm-v2: key must be 32 bytes')
121
+ }
122
+ return getSubtle().importKey(
123
+ 'raw',
124
+ keyBytes as Uint8Array<ArrayBuffer>,
125
+ { name: 'AES-GCM' },
126
+ false,
127
+ usages,
128
+ )
129
+ }
130
+
131
+ /** Generate a fresh per-file content key and file_id. */
132
+ export function generateContentMaterial(): {
133
+ contentKey: Uint8Array
134
+ fileId: Uint8Array
135
+ } {
136
+ return {
137
+ contentKey: randomBytes(AES_GCM_V2_KEY_BYTES),
138
+ fileId: randomBytes(HEADER_SIZES.FILE_ID),
139
+ }
140
+ }
141
+
142
+ export interface AesGcmV2ChunkContext {
143
+ cryptoKey: CryptoKey
144
+ noncePrefix: Uint8Array
145
+ totalChunks: number
146
+ }
147
+
148
+ export async function createChunkContext(
149
+ contentKey: Uint8Array,
150
+ fileId: Uint8Array,
151
+ totalChunks: number,
152
+ ): Promise<AesGcmV2ChunkContext> {
153
+ if (totalChunks > AES_GCM_V2_MAX_CHUNK_INDEX + 1) {
154
+ // Defense in depth — header-layer MAX_TOTAL_CHUNKS already caps this
155
+ // well below 2^32, but the suite enforces its own ceiling.
156
+ throw new RangeError(
157
+ 'aes-gcm-v2: totalChunks exceeds 2^32 chunk-index space',
158
+ )
159
+ }
160
+ const chunkKeyBytes = await deriveChunkKey(contentKey, fileId)
161
+ const noncePrefix = await deriveNoncePrefix(fileId)
162
+ const cryptoKey = await importAesGcmKey(chunkKeyBytes, ['encrypt', 'decrypt'])
163
+ return { cryptoKey, noncePrefix, totalChunks }
164
+ }
165
+
166
+ export async function encryptChunk(
167
+ ctx: AesGcmV2ChunkContext,
168
+ chunkIndex: number,
169
+ plaintext: Uint8Array,
170
+ ): Promise<Uint8Array> {
171
+ const isFinal = chunkIndex === ctx.totalChunks - 1
172
+ const aad = buildChunkAad(chunkIndex, ctx.totalChunks, isFinal)
173
+ const iv = buildIv(ctx.noncePrefix, chunkIndex)
174
+ const ct = await getSubtle().encrypt(
175
+ {
176
+ name: 'AES-GCM',
177
+ iv: iv as Uint8Array<ArrayBuffer>,
178
+ additionalData: aad as Uint8Array<ArrayBuffer>,
179
+ tagLength: 128,
180
+ },
181
+ ctx.cryptoKey,
182
+ plaintext as Uint8Array<ArrayBuffer>,
183
+ )
184
+ return new Uint8Array(ct)
185
+ }
186
+
187
+ export async function decryptChunk(
188
+ ctx: AesGcmV2ChunkContext,
189
+ chunkIndex: number,
190
+ ciphertext: Uint8Array,
191
+ ): Promise<Uint8Array> {
192
+ const isFinal = chunkIndex === ctx.totalChunks - 1
193
+ const aad = buildChunkAad(chunkIndex, ctx.totalChunks, isFinal)
194
+ const iv = buildIv(ctx.noncePrefix, chunkIndex)
195
+ const pt = await getSubtle().decrypt(
196
+ {
197
+ name: 'AES-GCM',
198
+ iv: iv as Uint8Array<ArrayBuffer>,
199
+ additionalData: aad as Uint8Array<ArrayBuffer>,
200
+ tagLength: 128,
201
+ },
202
+ ctx.cryptoKey,
203
+ ciphertext as Uint8Array<ArrayBuffer>,
204
+ )
205
+ return new Uint8Array(pt)
206
+ }
207
+
208
+ /**
209
+ * Wrap (encrypt) a content key under an envelope key (folder/vault key).
210
+ * The wrap layer is identical to v1: it is a one-shot AES-GCM encryption
211
+ * of a 32-byte key under a fresh 12-byte IV, which has no counter-mode
212
+ * collision concern.
213
+ */
214
+ export async function wrapContentKey(options: {
215
+ contentKey: Uint8Array
216
+ envelopeKey: Uint8Array
217
+ envelopeAad?: Uint8Array
218
+ }): Promise<{ wrapped: Uint8Array; wrapIv: Uint8Array }> {
219
+ const { contentKey, envelopeKey } = options
220
+ if (contentKey.length !== AES_GCM_V2_KEY_BYTES) {
221
+ throw new RangeError('wrapContentKey: contentKey must be 32 bytes')
222
+ }
223
+ if (envelopeKey.length !== AES_GCM_V2_KEY_BYTES) {
224
+ throw new RangeError('wrapContentKey: envelopeKey must be 32 bytes')
225
+ }
226
+ const wrapIv = randomBytes(AES_GCM_V2_IV_BYTES)
227
+ const wrapKey = await importAesGcmKey(envelopeKey, ['encrypt'])
228
+ const wrapped = await getSubtle().encrypt(
229
+ {
230
+ name: 'AES-GCM',
231
+ iv: wrapIv as Uint8Array<ArrayBuffer>,
232
+ additionalData:
233
+ (options.envelopeAad ?? new Uint8Array(0)) as Uint8Array<ArrayBuffer>,
234
+ tagLength: 128,
235
+ },
236
+ wrapKey,
237
+ contentKey as Uint8Array<ArrayBuffer>,
238
+ )
239
+ const wrappedBytes = new Uint8Array(wrapped)
240
+ if (wrappedBytes.length !== 48) {
241
+ throw new Error('wrapContentKey: unexpected wrapped length')
242
+ }
243
+ const padded = new Uint8Array(60)
244
+ padded.set(wrappedBytes, 0)
245
+ return { wrapped: padded, wrapIv }
246
+ }
247
+
248
+ export async function unwrapContentKey(options: {
249
+ envelopeKey: Uint8Array
250
+ wrappedField: Uint8Array
251
+ wrapIv: Uint8Array
252
+ envelopeAad?: Uint8Array
253
+ }): Promise<Uint8Array> {
254
+ const { envelopeKey, wrappedField, wrapIv } = options
255
+ if (envelopeKey.length !== AES_GCM_V2_KEY_BYTES) {
256
+ throw new RangeError('unwrapContentKey: envelopeKey must be 32 bytes')
257
+ }
258
+ if (wrappedField.length !== 60) {
259
+ throw new RangeError('unwrapContentKey: wrappedField must be 60 bytes')
260
+ }
261
+ if (wrapIv.length !== AES_GCM_V2_IV_BYTES) {
262
+ throw new RangeError('unwrapContentKey: wrapIv must be 12 bytes')
263
+ }
264
+ const wrapped = wrappedField.slice(0, 48)
265
+ const wrapKey = await importAesGcmKey(envelopeKey, ['decrypt'])
266
+ const pt = await getSubtle().decrypt(
267
+ {
268
+ name: 'AES-GCM',
269
+ iv: wrapIv as Uint8Array<ArrayBuffer>,
270
+ additionalData:
271
+ (options.envelopeAad ?? new Uint8Array(0)) as Uint8Array<ArrayBuffer>,
272
+ tagLength: 128,
273
+ },
274
+ wrapKey,
275
+ wrapped as Uint8Array<ArrayBuffer>,
276
+ )
277
+ const ptBytes = new Uint8Array(pt)
278
+ if (ptBytes.length !== AES_GCM_V2_KEY_BYTES) {
279
+ throw new Error('unwrapContentKey: bad plaintext length')
280
+ }
281
+ return ptBytes
282
+ }
283
+
284
+ /** Header parser hook — exposes ParsedHeader convenience for suite consumers. */
285
+ export function getSuitePayloadFromHeader(
286
+ header: ParsedHeader,
287
+ ): AesGcmV2SuitePayload {
288
+ return parseAesGcmV2SuitePayload(header.suitePayload)
289
+ }