@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,254 @@
1
+ /**
2
+ * High-level encrypt/decrypt API for the XChaCha20-Poly1305 v1 suite.
3
+ * Mirrors the shape of the AES-GCM v1 API; behavior is identical at the
4
+ * format layer.
5
+ */
6
+
7
+ import {
8
+ buildAuthenticatedHeader,
9
+ parseHeader,
10
+ verifyHeaderMac,
11
+ HeaderError,
12
+ } from '../../format/header.js'
13
+ import {
14
+ XCHACHA_V1_SUITE_PAYLOAD_LENGTH,
15
+ XCHACHA_V1_TAG_BYTES,
16
+ createChunkContext,
17
+ decryptChunk,
18
+ encryptChunk,
19
+ generateContentMaterial,
20
+ parseXChaChaV1SuitePayload,
21
+ } from './index.js'
22
+ import {
23
+ DEFAULT_CHUNK_SIZE,
24
+ type EncryptedFile,
25
+ HEADER_SIZES,
26
+ MAX_TOTAL_CHUNKS,
27
+ type ProgressCallback,
28
+ SUITE,
29
+ } from '../../internal/types.js'
30
+ import {
31
+ asBlobPart,
32
+ readUint32BE,
33
+ uint32BE,
34
+ } from '../../internal/encoding.js'
35
+
36
+ const LENGTH_PREFIX_BYTES = 4
37
+
38
+ export interface XChaChaEncryptOptions {
39
+ blob: Blob
40
+ contentKey?: Uint8Array
41
+ fileId?: Uint8Array
42
+ suitePayloadOverride?: Uint8Array
43
+ chunkSize?: number
44
+ onProgress?: ProgressCallback
45
+ }
46
+
47
+ export async function encryptBlob(
48
+ options: XChaChaEncryptOptions,
49
+ ): Promise<EncryptedFile & { contentKey: Uint8Array }> {
50
+ const { blob, onProgress } = options
51
+ if (!(blob instanceof Blob)) {
52
+ throw new TypeError('encryptBlob: blob must be a Blob or File')
53
+ }
54
+
55
+ const chunkSize = options.chunkSize ?? DEFAULT_CHUNK_SIZE
56
+ if (!Number.isSafeInteger(chunkSize) || chunkSize <= 0) {
57
+ throw new RangeError('encryptBlob: chunkSize must be a positive integer')
58
+ }
59
+
60
+ const plaintextSize = blob.size
61
+ const totalChunks =
62
+ plaintextSize === 0 ? 0 : Math.ceil(plaintextSize / chunkSize)
63
+ if (totalChunks > MAX_TOTAL_CHUNKS) {
64
+ throw new RangeError('encryptBlob: file would exceed total_chunks limit')
65
+ }
66
+
67
+ const generated = generateContentMaterial()
68
+ const contentKey = options.contentKey ?? generated.contentKey
69
+ const fileId = options.fileId ?? generated.fileId
70
+ if (contentKey.length !== 32) {
71
+ throw new RangeError('encryptBlob: contentKey must be 32 bytes')
72
+ }
73
+ if (fileId.length !== HEADER_SIZES.FILE_ID) {
74
+ throw new RangeError('encryptBlob: fileId must be 16 bytes')
75
+ }
76
+
77
+ const suitePayload =
78
+ options.suitePayloadOverride ??
79
+ new Uint8Array(XCHACHA_V1_SUITE_PAYLOAD_LENGTH)
80
+ if (suitePayload.length !== XCHACHA_V1_SUITE_PAYLOAD_LENGTH) {
81
+ throw new RangeError(
82
+ `encryptBlob: suitePayloadOverride must be ${XCHACHA_V1_SUITE_PAYLOAD_LENGTH} bytes`,
83
+ )
84
+ }
85
+
86
+ const header = await buildAuthenticatedHeader(
87
+ {
88
+ suite: SUITE.XCHACHA20_POLY1305_V1,
89
+ fileId,
90
+ chunkSize,
91
+ totalChunks,
92
+ plaintextSize,
93
+ suitePayload,
94
+ },
95
+ contentKey,
96
+ )
97
+
98
+ const ctx = await createChunkContext(contentKey, fileId, totalChunks)
99
+
100
+ const parts: BlobPart[] = [asBlobPart(header)]
101
+ for (let i = 0; i < totalChunks; i += 1) {
102
+ const start = i * chunkSize
103
+ const end = Math.min(start + chunkSize, plaintextSize)
104
+ const plaintextBytes = new Uint8Array(
105
+ await blob.slice(start, end).arrayBuffer(),
106
+ )
107
+ const ciphertext = await encryptChunk(ctx, i, plaintextBytes)
108
+ parts.push(asBlobPart(uint32BE(ciphertext.length)))
109
+ parts.push(asBlobPart(ciphertext))
110
+ onProgress?.((i + 1) / Math.max(totalChunks, 1))
111
+ }
112
+
113
+ if (totalChunks === 0) onProgress?.(1)
114
+
115
+ return {
116
+ blob: new Blob(parts, { type: 'application/octet-stream' }),
117
+ suite: SUITE.XCHACHA20_POLY1305_V1,
118
+ fileId,
119
+ chunkSize,
120
+ totalChunks,
121
+ plaintextSize,
122
+ contentKey,
123
+ }
124
+ }
125
+
126
+ export interface XChaChaDecryptOptions {
127
+ blob: Blob
128
+ contentKey: Uint8Array
129
+ onProgress?: ProgressCallback
130
+ allowedSuites?: ReadonlyArray<number>
131
+ }
132
+
133
+ export async function decryptBlob(
134
+ options: XChaChaDecryptOptions,
135
+ ): Promise<Blob> {
136
+ const { blob, contentKey, onProgress } = options
137
+ if (!(blob instanceof Blob)) {
138
+ throw new TypeError('decryptBlob: blob must be a Blob or File')
139
+ }
140
+ if (contentKey.length !== 32) {
141
+ throw new RangeError('decryptBlob: contentKey must be 32 bytes')
142
+ }
143
+
144
+ const headerProbeBytes = new Uint8Array(
145
+ await blob.slice(0, Math.min(blob.size, 4096)).arrayBuffer(),
146
+ )
147
+
148
+ let parsed: ReturnType<typeof parseHeader>
149
+ try {
150
+ parsed = parseHeader(headerProbeBytes)
151
+ } catch (err) {
152
+ if (err instanceof HeaderError && err.code === 'header_too_short') {
153
+ const allHeaderBytes = new Uint8Array(
154
+ await blob
155
+ .slice(0, Math.min(blob.size, 4 + 0xffff + 1024))
156
+ .arrayBuffer(),
157
+ )
158
+ parsed = parseHeader(allHeaderBytes)
159
+ } else {
160
+ throw err
161
+ }
162
+ }
163
+
164
+ if (
165
+ options.allowedSuites &&
166
+ !options.allowedSuites.includes(parsed.suite)
167
+ ) {
168
+ throw new HeaderError('suite_not_allowed')
169
+ }
170
+
171
+ if (parsed.suite !== SUITE.XCHACHA20_POLY1305_V1) {
172
+ throw new HeaderError(
173
+ `decryptBlob: this entry point only supports xchacha20-poly1305-v1; got suite 0x${parsed.suite.toString(16)}`,
174
+ )
175
+ }
176
+
177
+ // MUST verify the header MAC before reading or interpreting any
178
+ // suite_payload bytes — see parseHeader docstring and
179
+ // spec/format-v1.md § "verification order".
180
+ await verifyHeaderMac(parsed, contentKey)
181
+ parseXChaChaV1SuitePayload(parsed.suitePayload)
182
+
183
+ const ctx = await createChunkContext(
184
+ contentKey,
185
+ parsed.fileId,
186
+ parsed.totalChunks,
187
+ )
188
+
189
+ const plaintextParts: BlobPart[] = []
190
+ let cursor = parsed.headerLength
191
+ let bytesEmitted = 0
192
+
193
+ for (let i = 0; i < parsed.totalChunks; i += 1) {
194
+ if (cursor + LENGTH_PREFIX_BYTES > blob.size) {
195
+ throw new HeaderError('chunk_length_truncated')
196
+ }
197
+ const lenBytes = new Uint8Array(
198
+ await blob.slice(cursor, cursor + LENGTH_PREFIX_BYTES).arrayBuffer(),
199
+ )
200
+ cursor += LENGTH_PREFIX_BYTES
201
+ const cipherLen = readUint32BE(lenBytes)
202
+
203
+ const isFinal = i === parsed.totalChunks - 1
204
+ const minCipher = 1 + XCHACHA_V1_TAG_BYTES
205
+ const maxCipher = parsed.chunkSize + XCHACHA_V1_TAG_BYTES
206
+ if (cipherLen < minCipher || cipherLen > maxCipher) {
207
+ throw new HeaderError('chunk_length_out_of_range')
208
+ }
209
+ if (!isFinal && cipherLen !== maxCipher) {
210
+ throw new HeaderError('non_final_chunk_wrong_size')
211
+ }
212
+
213
+ if (cursor + cipherLen > blob.size) {
214
+ throw new HeaderError('chunk_truncated')
215
+ }
216
+
217
+ const cipherBytes = new Uint8Array(
218
+ await blob.slice(cursor, cursor + cipherLen).arrayBuffer(),
219
+ )
220
+ cursor += cipherLen
221
+
222
+ const plaintext = await decryptChunk(ctx, i, cipherBytes)
223
+ bytesEmitted += plaintext.length
224
+ plaintextParts.push(asBlobPart(plaintext))
225
+
226
+ onProgress?.((i + 1) / Math.max(parsed.totalChunks, 1))
227
+ }
228
+
229
+ if (bytesEmitted !== parsed.plaintextSize) {
230
+ throw new HeaderError('plaintext_size_mismatch')
231
+ }
232
+ if (cursor !== blob.size) {
233
+ throw new HeaderError('trailing_bytes_after_last_chunk')
234
+ }
235
+
236
+ if (parsed.totalChunks === 0) onProgress?.(1)
237
+
238
+ return new Blob(plaintextParts, { type: 'application/octet-stream' })
239
+ }
240
+
241
+ export async function encryptBytes(
242
+ bytes: Uint8Array,
243
+ options: Omit<XChaChaEncryptOptions, 'blob'>,
244
+ ): Promise<EncryptedFile & { contentKey: Uint8Array }> {
245
+ const blob = new Blob([asBlobPart(bytes)])
246
+ return encryptBlob({ blob, ...options })
247
+ }
248
+
249
+ export async function decryptToBytes(
250
+ options: XChaChaDecryptOptions,
251
+ ): Promise<Uint8Array> {
252
+ const blob = await decryptBlob(options)
253
+ return new Uint8Array(await blob.arrayBuffer())
254
+ }
@@ -0,0 +1,213 @@
1
+ /**
2
+ * Cipher suite 0x02: XChaCha20-Poly1305 v1.
3
+ *
4
+ * 256-bit key, 192-bit nonce. Fresh per-file content key. Per-chunk AEAD
5
+ * with the same file_id-bound AAD as the AES-GCM suite. Implementation via
6
+ * libsodium-wrappers-sumo's `crypto_aead_xchacha20poly1305_ietf_*`.
7
+ *
8
+ * Why not secretstream? secretstream is a higher-level construction that
9
+ * embeds its own state machine and chunk count. We want chunk-level random
10
+ * access (for streaming downloads with range requests), so we use the AEAD
11
+ * primitive directly with our own AAD-bound chunk indexing.
12
+ */
13
+
14
+ import { buildChunkAad } from '../../format/header.js'
15
+ import {
16
+ HKDF_INFO,
17
+ HEADER_SIZES,
18
+ type ParsedHeader,
19
+ } from '../../internal/types.js'
20
+ import { concatBytes, uint64BE } from '../../internal/encoding.js'
21
+ import { hkdfSha256 } from '../../internal/hkdf.js'
22
+ import { randomBytes } from '../../internal/runtime.js'
23
+ import { getSodium } from '../../internal/sodium.js'
24
+
25
+ export const XCHACHA_V1_KEY_BYTES = 32
26
+ export const XCHACHA_V1_NONCE_BYTES = 24
27
+ export const XCHACHA_V1_TAG_BYTES = 16
28
+
29
+ /** Suite payload layout: 72-byte secretbox-wrapped key + 24-byte nonce = 96 bytes. */
30
+ export const XCHACHA_V1_SUITE_PAYLOAD_LENGTH = 96
31
+
32
+ export interface XChaChaV1SuitePayload {
33
+ wrappedKey: Uint8Array // 32-byte key + 16-byte secretbox tag = 48 bytes; padded to 72
34
+ wrapNonce: Uint8Array // 24 bytes
35
+ }
36
+
37
+ export function buildXChaChaV1SuitePayload(
38
+ payload: XChaChaV1SuitePayload,
39
+ ): Uint8Array {
40
+ if (payload.wrappedKey.length !== 72) {
41
+ throw new RangeError('xchacha-v1: wrappedKey must be 72 bytes')
42
+ }
43
+ if (payload.wrapNonce.length !== XCHACHA_V1_NONCE_BYTES) {
44
+ throw new RangeError('xchacha-v1: wrapNonce must be 24 bytes')
45
+ }
46
+ return concatBytes([payload.wrappedKey, payload.wrapNonce])
47
+ }
48
+
49
+ export function parseXChaChaV1SuitePayload(
50
+ bytes: Uint8Array,
51
+ ): XChaChaV1SuitePayload {
52
+ if (bytes.length !== XCHACHA_V1_SUITE_PAYLOAD_LENGTH) {
53
+ throw new RangeError('xchacha-v1: suite payload must be 96 bytes')
54
+ }
55
+ return {
56
+ wrappedKey: bytes.slice(0, 72),
57
+ wrapNonce: bytes.slice(72, 96),
58
+ }
59
+ }
60
+
61
+ async function deriveChunkKey(
62
+ contentKey: Uint8Array,
63
+ fileId: Uint8Array,
64
+ ): Promise<Uint8Array> {
65
+ return hkdfSha256({
66
+ ikm: contentKey,
67
+ salt: fileId,
68
+ info: HKDF_INFO.XCHACHA_CHUNK_KEY,
69
+ length: XCHACHA_V1_KEY_BYTES,
70
+ })
71
+ }
72
+
73
+ async function deriveNoncePrefix(fileId: Uint8Array): Promise<Uint8Array> {
74
+ // XChaCha's 24-byte nonce: 16-byte file-derived prefix + 8-byte counter.
75
+ return hkdfSha256({
76
+ ikm: fileId,
77
+ info: HKDF_INFO.XCHACHA_NONCE_PREFIX,
78
+ length: 16,
79
+ })
80
+ }
81
+
82
+ function buildNonce(noncePrefix: Uint8Array, chunkIndex: number): Uint8Array {
83
+ const nonce = new Uint8Array(XCHACHA_V1_NONCE_BYTES)
84
+ nonce.set(noncePrefix, 0)
85
+ nonce.set(uint64BE(chunkIndex), 16)
86
+ return nonce
87
+ }
88
+
89
+ export function generateContentMaterial(): {
90
+ contentKey: Uint8Array
91
+ fileId: Uint8Array
92
+ } {
93
+ return {
94
+ contentKey: randomBytes(XCHACHA_V1_KEY_BYTES),
95
+ fileId: randomBytes(HEADER_SIZES.FILE_ID),
96
+ }
97
+ }
98
+
99
+ export interface XChaChaV1ChunkContext {
100
+ chunkKey: Uint8Array
101
+ noncePrefix: Uint8Array
102
+ totalChunks: number
103
+ }
104
+
105
+ export async function createChunkContext(
106
+ contentKey: Uint8Array,
107
+ fileId: Uint8Array,
108
+ totalChunks: number,
109
+ ): Promise<XChaChaV1ChunkContext> {
110
+ const chunkKey = await deriveChunkKey(contentKey, fileId)
111
+ const noncePrefix = await deriveNoncePrefix(fileId)
112
+ return { chunkKey, noncePrefix, totalChunks }
113
+ }
114
+
115
+ export async function encryptChunk(
116
+ ctx: XChaChaV1ChunkContext,
117
+ chunkIndex: number,
118
+ plaintext: Uint8Array,
119
+ ): Promise<Uint8Array> {
120
+ const sodium = await getSodium()
121
+ const isFinal = chunkIndex === ctx.totalChunks - 1
122
+ const aad = buildChunkAad(chunkIndex, ctx.totalChunks, isFinal)
123
+ const nonce = buildNonce(ctx.noncePrefix, chunkIndex)
124
+ return sodium.crypto_aead_xchacha20poly1305_ietf_encrypt(
125
+ plaintext,
126
+ aad,
127
+ null,
128
+ nonce,
129
+ ctx.chunkKey,
130
+ )
131
+ }
132
+
133
+ export async function decryptChunk(
134
+ ctx: XChaChaV1ChunkContext,
135
+ chunkIndex: number,
136
+ ciphertext: Uint8Array,
137
+ ): Promise<Uint8Array> {
138
+ const sodium = await getSodium()
139
+ const isFinal = chunkIndex === ctx.totalChunks - 1
140
+ const aad = buildChunkAad(chunkIndex, ctx.totalChunks, isFinal)
141
+ const nonce = buildNonce(ctx.noncePrefix, chunkIndex)
142
+ const result = sodium.crypto_aead_xchacha20poly1305_ietf_decrypt(
143
+ null,
144
+ ciphertext,
145
+ aad,
146
+ nonce,
147
+ ctx.chunkKey,
148
+ )
149
+ return result
150
+ }
151
+
152
+ export async function wrapContentKey(options: {
153
+ contentKey: Uint8Array
154
+ envelopeKey: Uint8Array
155
+ }): Promise<{ wrapped: Uint8Array; wrapNonce: Uint8Array }> {
156
+ const sodium = await getSodium()
157
+ const { contentKey, envelopeKey } = options
158
+ if (contentKey.length !== XCHACHA_V1_KEY_BYTES) {
159
+ throw new RangeError('wrapContentKey: contentKey must be 32 bytes')
160
+ }
161
+ if (envelopeKey.length !== XCHACHA_V1_KEY_BYTES) {
162
+ throw new RangeError('wrapContentKey: envelopeKey must be 32 bytes')
163
+ }
164
+ const wrapNonce = randomBytes(XCHACHA_V1_NONCE_BYTES)
165
+ // crypto_secretbox_easy: outputs 16-byte poly1305 tag + ciphertext = 48 bytes
166
+ const wrapped = sodium.crypto_secretbox_easy(
167
+ contentKey,
168
+ wrapNonce,
169
+ envelopeKey,
170
+ )
171
+ if (wrapped.length !== 48) {
172
+ throw new Error('wrapContentKey: unexpected wrapped length')
173
+ }
174
+ // Pad to 72 bytes for fixed suite_payload size
175
+ const padded = new Uint8Array(72)
176
+ padded.set(wrapped, 0)
177
+ return { wrapped: padded, wrapNonce }
178
+ }
179
+
180
+ export async function unwrapContentKey(options: {
181
+ envelopeKey: Uint8Array
182
+ wrappedField: Uint8Array
183
+ wrapNonce: Uint8Array
184
+ }): Promise<Uint8Array> {
185
+ const sodium = await getSodium()
186
+ const { envelopeKey, wrappedField, wrapNonce } = options
187
+ if (envelopeKey.length !== XCHACHA_V1_KEY_BYTES) {
188
+ throw new RangeError('unwrapContentKey: envelopeKey must be 32 bytes')
189
+ }
190
+ if (wrappedField.length !== 72) {
191
+ throw new RangeError('unwrapContentKey: wrappedField must be 72 bytes')
192
+ }
193
+ if (wrapNonce.length !== XCHACHA_V1_NONCE_BYTES) {
194
+ throw new RangeError('unwrapContentKey: wrapNonce must be 24 bytes')
195
+ }
196
+ // First 48 bytes are tag+key, the rest is reserved zeros.
197
+ const wrapped = wrappedField.slice(0, 48)
198
+ const unwrapped = sodium.crypto_secretbox_open_easy(
199
+ wrapped,
200
+ wrapNonce,
201
+ envelopeKey,
202
+ )
203
+ if (!unwrapped) {
204
+ throw new Error('unwrapContentKey: unwrap failed (wrong envelope key?)')
205
+ }
206
+ return unwrapped
207
+ }
208
+
209
+ export function getSuitePayloadFromHeader(
210
+ header: ParsedHeader,
211
+ ): XChaChaV1SuitePayload {
212
+ return parseXChaChaV1SuitePayload(header.suitePayload)
213
+ }