@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,291 @@
1
+ /**
2
+ * High-level encrypt/decrypt API for the AES-256-GCM v1 suite.
3
+ *
4
+ * This is what most callers will import. It glues together:
5
+ * - header construction
6
+ * - chunk encryption/decryption with full AAD binding
7
+ * - the v1 wire format
8
+ *
9
+ * Suites 0x02 (XChaCha20-Poly1305) and 0x03 (PQ hybrid) provide identical
10
+ * APIs in their own modules.
11
+ */
12
+
13
+ import {
14
+ buildAuthenticatedHeader,
15
+ parseHeader,
16
+ verifyHeaderMac,
17
+ HeaderError,
18
+ } from '../../format/header.js'
19
+ import {
20
+ AES_GCM_V1_SUITE_PAYLOAD_LENGTH,
21
+ AES_GCM_V1_TAG_BYTES,
22
+ createChunkContext,
23
+ decryptChunk,
24
+ encryptChunk,
25
+ generateContentMaterial,
26
+ parseAesGcmV1SuitePayload,
27
+ } from './index.js'
28
+ import {
29
+ DEFAULT_CHUNK_SIZE,
30
+ type EncryptedFile,
31
+ HEADER_SIZES,
32
+ MAX_TOTAL_CHUNKS,
33
+ type ProgressCallback,
34
+ SUITE,
35
+ } from '../../internal/types.js'
36
+ import {
37
+ asBlobPart,
38
+ concatBytes,
39
+ readUint32BE,
40
+ uint32BE,
41
+ } from '../../internal/encoding.js'
42
+
43
+ const LENGTH_PREFIX_BYTES = 4
44
+
45
+ export interface EncryptOptions {
46
+ blob: Blob
47
+ /** Optional pre-existing content key (32 bytes). If omitted, generated. */
48
+ contentKey?: Uint8Array
49
+ /** Optional pre-existing file_id (16 bytes). If omitted, generated. */
50
+ fileId?: Uint8Array
51
+ /** Optional embedded wrapped key + IV (60 + 12 bytes). Defaults to zeros. */
52
+ suitePayloadOverride?: Uint8Array
53
+ /** Plaintext bytes per chunk. Defaults to 4 MiB. */
54
+ chunkSize?: number
55
+ /** Progress callback (0..1). Called once per chunk and once at completion. */
56
+ onProgress?: ProgressCallback
57
+ }
58
+
59
+ /**
60
+ * Encrypt a Blob/File with the AES-256-GCM v1 suite.
61
+ * Returns the encrypted blob (header + chunks), plus the content key and
62
+ * file id so the caller can wrap/store them externally.
63
+ */
64
+ export async function encryptBlob(
65
+ options: EncryptOptions,
66
+ ): Promise<EncryptedFile & { contentKey: Uint8Array }> {
67
+ const { blob, onProgress } = options
68
+ if (!(blob instanceof Blob)) {
69
+ throw new TypeError('encryptBlob: blob must be a Blob or File')
70
+ }
71
+
72
+ const chunkSize = options.chunkSize ?? DEFAULT_CHUNK_SIZE
73
+ if (!Number.isSafeInteger(chunkSize) || chunkSize <= 0) {
74
+ throw new RangeError('encryptBlob: chunkSize must be a positive integer')
75
+ }
76
+
77
+ const plaintextSize = blob.size
78
+ const totalChunks =
79
+ plaintextSize === 0 ? 0 : Math.ceil(plaintextSize / chunkSize)
80
+ if (totalChunks > MAX_TOTAL_CHUNKS) {
81
+ throw new RangeError('encryptBlob: file would exceed total_chunks limit')
82
+ }
83
+
84
+ // Resolve key material
85
+ const generated = generateContentMaterial()
86
+ const contentKey = options.contentKey ?? generated.contentKey
87
+ const fileId = options.fileId ?? generated.fileId
88
+ if (contentKey.length !== 32) {
89
+ throw new RangeError('encryptBlob: contentKey must be 32 bytes')
90
+ }
91
+ if (fileId.length !== HEADER_SIZES.FILE_ID) {
92
+ throw new RangeError('encryptBlob: fileId must be 16 bytes')
93
+ }
94
+
95
+ // Suite payload (caller-supplied or zero-filled placeholder)
96
+ const suitePayload =
97
+ options.suitePayloadOverride ??
98
+ new Uint8Array(AES_GCM_V1_SUITE_PAYLOAD_LENGTH)
99
+ if (suitePayload.length !== AES_GCM_V1_SUITE_PAYLOAD_LENGTH) {
100
+ throw new RangeError(
101
+ `encryptBlob: suitePayloadOverride must be ${AES_GCM_V1_SUITE_PAYLOAD_LENGTH} bytes`,
102
+ )
103
+ }
104
+
105
+ const header = await buildAuthenticatedHeader(
106
+ {
107
+ suite: SUITE.AES_256_GCM_V1,
108
+ fileId,
109
+ chunkSize,
110
+ totalChunks,
111
+ plaintextSize,
112
+ suitePayload,
113
+ },
114
+ contentKey,
115
+ )
116
+
117
+ const ctx = await createChunkContext(contentKey, fileId, totalChunks)
118
+
119
+ const parts: BlobPart[] = [asBlobPart(header)]
120
+
121
+ for (let i = 0; i < totalChunks; i += 1) {
122
+ const start = i * chunkSize
123
+ const end = Math.min(start + chunkSize, plaintextSize)
124
+ const plaintextBytes = new Uint8Array(
125
+ await blob.slice(start, end).arrayBuffer(),
126
+ )
127
+ const ciphertext = await encryptChunk(ctx, i, plaintextBytes)
128
+ parts.push(asBlobPart(uint32BE(ciphertext.length)))
129
+ parts.push(asBlobPart(ciphertext))
130
+ onProgress?.((i + 1) / Math.max(totalChunks, 1))
131
+ }
132
+
133
+ if (totalChunks === 0) onProgress?.(1)
134
+
135
+ return {
136
+ blob: new Blob(parts, { type: 'application/octet-stream' }),
137
+ suite: SUITE.AES_256_GCM_V1,
138
+ fileId,
139
+ chunkSize,
140
+ totalChunks,
141
+ plaintextSize,
142
+ contentKey,
143
+ }
144
+ }
145
+
146
+ export interface DecryptOptions {
147
+ blob: Blob
148
+ contentKey: Uint8Array
149
+ onProgress?: ProgressCallback
150
+ /**
151
+ * If provided, the parser checks the suite matches before any AEAD
152
+ * operation. Callers who want to refuse, e.g., legacy suites can pass
153
+ * an explicit allowlist.
154
+ */
155
+ allowedSuites?: ReadonlyArray<number>
156
+ }
157
+
158
+ /**
159
+ * Decrypt a v1 blob produced by `encryptBlob`. Reads the entire blob into
160
+ * memory in chunked passes; for streaming decryption see `streams/`.
161
+ */
162
+ export async function decryptBlob(options: DecryptOptions): Promise<Blob> {
163
+ const { blob, contentKey, onProgress } = options
164
+ if (!(blob instanceof Blob)) {
165
+ throw new TypeError('decryptBlob: blob must be a Blob or File')
166
+ }
167
+ if (contentKey.length !== 32) {
168
+ throw new RangeError('decryptBlob: contentKey must be 32 bytes')
169
+ }
170
+
171
+ // Read enough to parse the header. The header is fixed-length plus a
172
+ // bounded suite_payload (max 65535 bytes). We read up to 4 KiB and
173
+ // fall back to streaming if the suite_payload is unusually large.
174
+ const headerProbeBytes = new Uint8Array(
175
+ await blob.slice(0, Math.min(blob.size, 4096)).arrayBuffer(),
176
+ )
177
+
178
+ let parsed: ReturnType<typeof parseHeader>
179
+ try {
180
+ parsed = parseHeader(headerProbeBytes)
181
+ } catch (err) {
182
+ if (err instanceof HeaderError && err.code === 'header_too_short') {
183
+ // The probe might have been too small. Read the whole blob.
184
+ const allHeaderBytes = new Uint8Array(
185
+ await blob
186
+ .slice(0, Math.min(blob.size, 4 + 0xffff + 1024))
187
+ .arrayBuffer(),
188
+ )
189
+ parsed = parseHeader(allHeaderBytes)
190
+ } else {
191
+ throw err
192
+ }
193
+ }
194
+
195
+ if (
196
+ options.allowedSuites &&
197
+ !options.allowedSuites.includes(parsed.suite)
198
+ ) {
199
+ throw new HeaderError('suite_not_allowed')
200
+ }
201
+
202
+ if (parsed.suite !== SUITE.AES_256_GCM_V1) {
203
+ throw new HeaderError(
204
+ `decryptBlob: this entry point only supports aes-256-gcm-v1; got suite 0x${parsed.suite.toString(16)}`,
205
+ )
206
+ }
207
+
208
+ // Validate the suite payload structure (length etc).
209
+ parseAesGcmV1SuitePayload(parsed.suitePayload)
210
+
211
+ // Verify header MAC before processing chunks.
212
+ await verifyHeaderMac(parsed, contentKey)
213
+
214
+ const ctx = await createChunkContext(
215
+ contentKey,
216
+ parsed.fileId,
217
+ parsed.totalChunks,
218
+ )
219
+
220
+ const plaintextParts: BlobPart[] = []
221
+ let cursor = parsed.headerLength
222
+ let bytesEmitted = 0
223
+
224
+ for (let i = 0; i < parsed.totalChunks; i += 1) {
225
+ if (cursor + LENGTH_PREFIX_BYTES > blob.size) {
226
+ throw new HeaderError('chunk_length_truncated')
227
+ }
228
+ const lenBytes = new Uint8Array(
229
+ await blob.slice(cursor, cursor + LENGTH_PREFIX_BYTES).arrayBuffer(),
230
+ )
231
+ cursor += LENGTH_PREFIX_BYTES
232
+ const cipherLen = readUint32BE(lenBytes)
233
+
234
+ // Sanity check: ciphertext for AES-GCM-v1 is exactly chunkSize+tag
235
+ // for non-final chunks. Final chunk is between 1+tag and chunkSize+tag.
236
+ const isFinal = i === parsed.totalChunks - 1
237
+ const minCipher = 1 + AES_GCM_V1_TAG_BYTES
238
+ const maxCipher = parsed.chunkSize + AES_GCM_V1_TAG_BYTES
239
+ if (cipherLen < minCipher || cipherLen > maxCipher) {
240
+ throw new HeaderError('chunk_length_out_of_range')
241
+ }
242
+ if (!isFinal && cipherLen !== maxCipher) {
243
+ throw new HeaderError('non_final_chunk_wrong_size')
244
+ }
245
+
246
+ if (cursor + cipherLen > blob.size) {
247
+ throw new HeaderError('chunk_truncated')
248
+ }
249
+
250
+ const cipherBytes = new Uint8Array(
251
+ await blob.slice(cursor, cursor + cipherLen).arrayBuffer(),
252
+ )
253
+ cursor += cipherLen
254
+
255
+ const plaintext = await decryptChunk(ctx, i, cipherBytes)
256
+ bytesEmitted += plaintext.length
257
+ plaintextParts.push(asBlobPart(plaintext))
258
+
259
+ onProgress?.((i + 1) / Math.max(parsed.totalChunks, 1))
260
+ }
261
+
262
+ // Final consistency: total bytes emitted must equal plaintextSize, and
263
+ // the file must have no trailing garbage past the last chunk.
264
+ if (bytesEmitted !== parsed.plaintextSize) {
265
+ throw new HeaderError('plaintext_size_mismatch')
266
+ }
267
+ if (cursor !== blob.size) {
268
+ throw new HeaderError('trailing_bytes_after_last_chunk')
269
+ }
270
+
271
+ if (parsed.totalChunks === 0) onProgress?.(1)
272
+
273
+ return new Blob(plaintextParts, { type: 'application/octet-stream' })
274
+ }
275
+
276
+ export async function encryptBytes(
277
+ bytes: Uint8Array | ArrayBuffer,
278
+ options: Omit<EncryptOptions, 'blob'>,
279
+ ): Promise<EncryptedFile & { contentKey: Uint8Array }> {
280
+ const part: BlobPart =
281
+ bytes instanceof ArrayBuffer ? bytes : asBlobPart(bytes)
282
+ const blob = new Blob([part])
283
+ return encryptBlob({ blob, ...options })
284
+ }
285
+
286
+ export async function decryptToBytes(
287
+ options: DecryptOptions,
288
+ ): Promise<Uint8Array> {
289
+ const blob = await decryptBlob(options)
290
+ return new Uint8Array(await blob.arrayBuffer())
291
+ }
@@ -0,0 +1,266 @@
1
+ /**
2
+ * Cipher suite 0x01: AES-256-GCM v1.
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 a 4-byte file-derived prefix and an 8-byte
7
+ * big-endian counter.
8
+ */
9
+
10
+ import { buildChunkAad } from '../../format/header.js'
11
+ import {
12
+ HKDF_INFO,
13
+ HEADER_SIZES,
14
+ type ParsedHeader,
15
+ } from '../../internal/types.js'
16
+ import { concatBytes, uint64BE } from '../../internal/encoding.js'
17
+ import { hkdfSha256 } from '../../internal/hkdf.js'
18
+ import { getSubtle, randomBytes } from '../../internal/runtime.js'
19
+
20
+ export const AES_GCM_V1_TAG_BYTES = 16
21
+ export const AES_GCM_V1_IV_BYTES = 12
22
+ export const AES_GCM_V1_KEY_BYTES = 32
23
+
24
+ /** Suite payload layout: 60-byte wrapped key + 12-byte wrap IV = 72 bytes. */
25
+ export const AES_GCM_V1_SUITE_PAYLOAD_LENGTH = 72
26
+
27
+ export interface AesGcmV1SuitePayload {
28
+ wrappedKey: Uint8Array // 60 bytes (32-byte key + 16-byte tag + 12-byte AAD-padded reserved zeros)
29
+ wrapIv: Uint8Array // 12 bytes
30
+ }
31
+
32
+ export function buildAesGcmV1SuitePayload(
33
+ payload: AesGcmV1SuitePayload,
34
+ ): Uint8Array {
35
+ if (payload.wrappedKey.length !== 60) {
36
+ throw new RangeError('aes-gcm-v1: wrappedKey must be 60 bytes')
37
+ }
38
+ if (payload.wrapIv.length !== AES_GCM_V1_IV_BYTES) {
39
+ throw new RangeError('aes-gcm-v1: wrapIv must be 12 bytes')
40
+ }
41
+ return concatBytes([payload.wrappedKey, payload.wrapIv])
42
+ }
43
+
44
+ export function parseAesGcmV1SuitePayload(
45
+ bytes: Uint8Array,
46
+ ): AesGcmV1SuitePayload {
47
+ if (bytes.length !== AES_GCM_V1_SUITE_PAYLOAD_LENGTH) {
48
+ throw new RangeError(
49
+ 'aes-gcm-v1: suite payload must be 72 bytes',
50
+ )
51
+ }
52
+ return {
53
+ wrappedKey: bytes.slice(0, 60),
54
+ wrapIv: bytes.slice(60, 72),
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Derive the per-file chunk key from the content key.
60
+ * Even though the content key is fresh per file, we run it through HKDF
61
+ * so that any future bug that recycles a content key cannot also recycle
62
+ * the chunk key under the same file_id.
63
+ */
64
+ async function deriveChunkKey(
65
+ contentKey: Uint8Array,
66
+ fileId: Uint8Array,
67
+ ): Promise<Uint8Array> {
68
+ return hkdfSha256({
69
+ ikm: contentKey,
70
+ salt: fileId,
71
+ info: HKDF_INFO.AES_GCM_CHUNK_KEY,
72
+ length: AES_GCM_V1_KEY_BYTES,
73
+ })
74
+ }
75
+
76
+ /**
77
+ * Derive the 4-byte nonce prefix from file_id. Stable per file.
78
+ */
79
+ async function deriveNoncePrefix(fileId: Uint8Array): Promise<Uint8Array> {
80
+ const out = await hkdfSha256({
81
+ ikm: fileId,
82
+ info: HKDF_INFO.AES_GCM_NONCE_PREFIX,
83
+ length: 4,
84
+ })
85
+ return out
86
+ }
87
+
88
+ function buildIv(noncePrefix: Uint8Array, chunkIndex: number): Uint8Array {
89
+ const iv = new Uint8Array(AES_GCM_V1_IV_BYTES)
90
+ iv.set(noncePrefix, 0)
91
+ iv.set(uint64BE(chunkIndex), 4)
92
+ return iv
93
+ }
94
+
95
+ async function importAesGcmKey(
96
+ keyBytes: Uint8Array,
97
+ usages: KeyUsage[],
98
+ ): Promise<CryptoKey> {
99
+ if (keyBytes.length !== AES_GCM_V1_KEY_BYTES) {
100
+ throw new RangeError('aes-gcm-v1: key must be 32 bytes')
101
+ }
102
+ return getSubtle().importKey(
103
+ 'raw',
104
+ keyBytes as Uint8Array<ArrayBuffer>,
105
+ { name: 'AES-GCM' },
106
+ false,
107
+ usages,
108
+ )
109
+ }
110
+
111
+ /** Generate a fresh per-file content key and file_id. */
112
+ export function generateContentMaterial(): {
113
+ contentKey: Uint8Array
114
+ fileId: Uint8Array
115
+ } {
116
+ return {
117
+ contentKey: randomBytes(AES_GCM_V1_KEY_BYTES),
118
+ fileId: randomBytes(HEADER_SIZES.FILE_ID),
119
+ }
120
+ }
121
+
122
+ export interface AesGcmV1ChunkContext {
123
+ cryptoKey: CryptoKey
124
+ noncePrefix: Uint8Array
125
+ totalChunks: number
126
+ }
127
+
128
+ export async function createChunkContext(
129
+ contentKey: Uint8Array,
130
+ fileId: Uint8Array,
131
+ totalChunks: number,
132
+ ): Promise<AesGcmV1ChunkContext> {
133
+ const chunkKeyBytes = await deriveChunkKey(contentKey, fileId)
134
+ const noncePrefix = await deriveNoncePrefix(fileId)
135
+ const cryptoKey = await importAesGcmKey(chunkKeyBytes, ['encrypt', 'decrypt'])
136
+ return { cryptoKey, noncePrefix, totalChunks }
137
+ }
138
+
139
+ export async function encryptChunk(
140
+ ctx: AesGcmV1ChunkContext,
141
+ chunkIndex: number,
142
+ plaintext: Uint8Array,
143
+ ): Promise<Uint8Array> {
144
+ const isFinal = chunkIndex === ctx.totalChunks - 1
145
+ const aad = buildChunkAad(chunkIndex, ctx.totalChunks, isFinal)
146
+ const iv = buildIv(ctx.noncePrefix, chunkIndex)
147
+ const ct = await getSubtle().encrypt(
148
+ {
149
+ name: 'AES-GCM',
150
+ iv: iv as Uint8Array<ArrayBuffer>,
151
+ additionalData: aad as Uint8Array<ArrayBuffer>,
152
+ tagLength: 128,
153
+ },
154
+ ctx.cryptoKey,
155
+ plaintext as Uint8Array<ArrayBuffer>,
156
+ )
157
+ return new Uint8Array(ct)
158
+ }
159
+
160
+ export async function decryptChunk(
161
+ ctx: AesGcmV1ChunkContext,
162
+ chunkIndex: number,
163
+ ciphertext: Uint8Array,
164
+ ): Promise<Uint8Array> {
165
+ const isFinal = chunkIndex === ctx.totalChunks - 1
166
+ const aad = buildChunkAad(chunkIndex, ctx.totalChunks, isFinal)
167
+ const iv = buildIv(ctx.noncePrefix, chunkIndex)
168
+ const pt = await getSubtle().decrypt(
169
+ {
170
+ name: 'AES-GCM',
171
+ iv: iv as Uint8Array<ArrayBuffer>,
172
+ additionalData: aad as Uint8Array<ArrayBuffer>,
173
+ tagLength: 128,
174
+ },
175
+ ctx.cryptoKey,
176
+ ciphertext as Uint8Array<ArrayBuffer>,
177
+ )
178
+ return new Uint8Array(pt)
179
+ }
180
+
181
+ /**
182
+ * Wrap (encrypt) a content key under an envelope key (folder/vault key).
183
+ * This is what the suite_payload's wrappedKey field carries when the
184
+ * caller chooses to embed the wrapped key in the file rather than store
185
+ * it in a database.
186
+ */
187
+ export async function wrapContentKey(options: {
188
+ contentKey: Uint8Array
189
+ envelopeKey: Uint8Array
190
+ envelopeAad?: Uint8Array
191
+ }): Promise<{ wrapped: Uint8Array; wrapIv: Uint8Array }> {
192
+ const { contentKey, envelopeKey } = options
193
+ if (contentKey.length !== AES_GCM_V1_KEY_BYTES) {
194
+ throw new RangeError('wrapContentKey: contentKey must be 32 bytes')
195
+ }
196
+ if (envelopeKey.length !== AES_GCM_V1_KEY_BYTES) {
197
+ throw new RangeError('wrapContentKey: envelopeKey must be 32 bytes')
198
+ }
199
+ const wrapIv = randomBytes(AES_GCM_V1_IV_BYTES)
200
+ const wrapKey = await importAesGcmKey(envelopeKey, ['encrypt'])
201
+ const wrapped = await getSubtle().encrypt(
202
+ {
203
+ name: 'AES-GCM',
204
+ iv: wrapIv as Uint8Array<ArrayBuffer>,
205
+ additionalData:
206
+ (options.envelopeAad ?? new Uint8Array(0)) as Uint8Array<ArrayBuffer>,
207
+ tagLength: 128,
208
+ },
209
+ wrapKey,
210
+ contentKey as Uint8Array<ArrayBuffer>,
211
+ )
212
+ // wrapped = 32-byte key + 16-byte tag = 48 bytes; pad to 60 with zeros
213
+ // so the suite_payload size is fixed regardless of whether the file
214
+ // embeds an inline wrapped key or zero-fills the field.
215
+ const wrappedBytes = new Uint8Array(wrapped)
216
+ if (wrappedBytes.length !== 48) {
217
+ throw new Error('wrapContentKey: unexpected wrapped length')
218
+ }
219
+ const padded = new Uint8Array(60)
220
+ padded.set(wrappedBytes, 0)
221
+ return { wrapped: padded, wrapIv }
222
+ }
223
+
224
+ export async function unwrapContentKey(options: {
225
+ envelopeKey: Uint8Array
226
+ wrappedField: Uint8Array
227
+ wrapIv: Uint8Array
228
+ envelopeAad?: Uint8Array
229
+ }): Promise<Uint8Array> {
230
+ const { envelopeKey, wrappedField, wrapIv } = options
231
+ if (envelopeKey.length !== AES_GCM_V1_KEY_BYTES) {
232
+ throw new RangeError('unwrapContentKey: envelopeKey must be 32 bytes')
233
+ }
234
+ if (wrappedField.length !== 60) {
235
+ throw new RangeError('unwrapContentKey: wrappedField must be 60 bytes')
236
+ }
237
+ if (wrapIv.length !== AES_GCM_V1_IV_BYTES) {
238
+ throw new RangeError('unwrapContentKey: wrapIv must be 12 bytes')
239
+ }
240
+ // The first 48 bytes are key+tag; the last 12 are reserved zeros.
241
+ const wrapped = wrappedField.slice(0, 48)
242
+ const wrapKey = await importAesGcmKey(envelopeKey, ['decrypt'])
243
+ const pt = await getSubtle().decrypt(
244
+ {
245
+ name: 'AES-GCM',
246
+ iv: wrapIv as Uint8Array<ArrayBuffer>,
247
+ additionalData:
248
+ (options.envelopeAad ?? new Uint8Array(0)) as Uint8Array<ArrayBuffer>,
249
+ tagLength: 128,
250
+ },
251
+ wrapKey,
252
+ wrapped as Uint8Array<ArrayBuffer>,
253
+ )
254
+ const ptBytes = new Uint8Array(pt)
255
+ if (ptBytes.length !== AES_GCM_V1_KEY_BYTES) {
256
+ throw new Error('unwrapContentKey: bad plaintext length')
257
+ }
258
+ return ptBytes
259
+ }
260
+
261
+ /** Header parser hook — exposes ParsedHeader convenience for suite consumers. */
262
+ export function getSuitePayloadFromHeader(
263
+ header: ParsedHeader,
264
+ ): AesGcmV1SuitePayload {
265
+ return parseAesGcmV1SuitePayload(header.suitePayload)
266
+ }