@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,299 @@
1
+ /**
2
+ * High-level encrypt/decrypt API for the PQ-hybrid v1 suite.
3
+ *
4
+ * Differs from aes-gcm-v1 / xchacha-v1 because content key derivation is
5
+ * not a single random 32-byte buffer — instead, the combined key is
6
+ * recovered from the on-disk suite payload (PQ ciphertext + wrapped
7
+ * classical share) and the recipient's PQ secret key + envelope key.
8
+ *
9
+ * The header MAC is keyed by the *combined* key, so a successful header
10
+ * MAC verification proves both the PQ KEM and the classical wrap were
11
+ * recovered correctly.
12
+ */
13
+
14
+ import {
15
+ buildAuthenticatedHeader,
16
+ parseHeader,
17
+ verifyHeaderMac,
18
+ HeaderError,
19
+ } from '../../format/header.js'
20
+ import {
21
+ PQ_HYBRID_V1_SUITE_PAYLOAD_LENGTH,
22
+ PQ_HYBRID_V1_TAG_BYTES,
23
+ createChunkContext,
24
+ decapsulateFromHeader,
25
+ decryptChunk,
26
+ encapsulateForRecipient,
27
+ encryptChunk,
28
+ } from './index.js'
29
+ import {
30
+ DEFAULT_CHUNK_SIZE,
31
+ type EncryptedFile,
32
+ HEADER_SIZES,
33
+ MAX_TOTAL_CHUNKS,
34
+ type ProgressCallback,
35
+ SUITE,
36
+ } from '../../internal/types.js'
37
+ import {
38
+ asBlobPart,
39
+ readUint32BE,
40
+ uint32BE,
41
+ } from '../../internal/encoding.js'
42
+ import { randomBytes } from '../../internal/runtime.js'
43
+
44
+ // Re-exports of suite primitives that are useful to callers outside the
45
+ // streaming/whole-blob API surfaces. `decapsulateFromHeader` lets a
46
+ // caller that already has the parsed suite_payload + KEM material
47
+ // recover the combined key K out-of-band (e.g., a share-link generator
48
+ // that wraps K under a separate password for recipients who never see
49
+ // ML-KEM secrets).
50
+ export {
51
+ decapsulateFromHeader,
52
+ deriveMlKemKeypair,
53
+ encapsulateForRecipient,
54
+ generateMlKemKeypair,
55
+ PQ_HYBRID_V1_SUITE_PAYLOAD_LENGTH,
56
+ } from './index.js'
57
+
58
+ const LENGTH_PREFIX_BYTES = 4
59
+
60
+ export interface PqHybridEncryptOptions {
61
+ blob: Blob
62
+ /** Recipient's ML-KEM-1024 public key (1568 bytes) */
63
+ recipientPublicKey: Uint8Array
64
+ /** Classical envelope key under which the classical share is wrapped */
65
+ envelopeKey: Uint8Array
66
+ fileId?: Uint8Array
67
+ chunkSize?: number
68
+ onProgress?: ProgressCallback
69
+ }
70
+
71
+ /**
72
+ * Encrypt a Blob under suite 0x03 (PQ-hybrid XChaCha20-Poly1305 +
73
+ * ML-KEM-1024). Returns the encrypted file alongside the combined
74
+ * content key used to produce it.
75
+ *
76
+ * SECURITY: The returned `combinedKey` grants permanent decryption
77
+ * capability for any file whose header was produced with it. Treat
78
+ * as cryptographic secret material: hold only in memory for the
79
+ * duration of the operation, do not persist to disk or storage, do
80
+ * not log, do not transmit. The only safe way to reproduce it on
81
+ * another machine is to re-encapsulate via the recipient's ML-KEM
82
+ * public key.
83
+ */
84
+ export async function encryptBlob(
85
+ options: PqHybridEncryptOptions,
86
+ ): Promise<EncryptedFile & { combinedKey: Uint8Array }> {
87
+ const { blob, recipientPublicKey, envelopeKey, onProgress } = options
88
+ if (!(blob instanceof Blob)) {
89
+ throw new TypeError('encryptBlob: blob must be a Blob or File')
90
+ }
91
+
92
+ const chunkSize = options.chunkSize ?? DEFAULT_CHUNK_SIZE
93
+ if (!Number.isSafeInteger(chunkSize) || chunkSize <= 0) {
94
+ throw new RangeError('encryptBlob: chunkSize must be a positive integer')
95
+ }
96
+
97
+ const plaintextSize = blob.size
98
+ const totalChunks =
99
+ plaintextSize === 0 ? 0 : Math.ceil(plaintextSize / chunkSize)
100
+ if (totalChunks > MAX_TOTAL_CHUNKS) {
101
+ throw new RangeError('encryptBlob: file would exceed total_chunks limit')
102
+ }
103
+
104
+ const fileId = options.fileId ?? randomBytes(HEADER_SIZES.FILE_ID)
105
+ if (fileId.length !== HEADER_SIZES.FILE_ID) {
106
+ throw new RangeError('encryptBlob: fileId must be 16 bytes')
107
+ }
108
+
109
+ // PQ + classical encapsulation produces the suite payload AND the
110
+ // combined key in one step. The combined key is what authenticates the
111
+ // header and encrypts every chunk.
112
+ const { suitePayload, combinedKey } = await encapsulateForRecipient({
113
+ recipientPublicKey,
114
+ envelopeKey,
115
+ fileId,
116
+ })
117
+
118
+ const header = await buildAuthenticatedHeader(
119
+ {
120
+ suite: SUITE.PQ_HYBRID_XCHACHA_MLKEM1024_V1,
121
+ fileId,
122
+ chunkSize,
123
+ totalChunks,
124
+ plaintextSize,
125
+ suitePayload,
126
+ },
127
+ combinedKey,
128
+ )
129
+
130
+ const ctx = await createChunkContext(combinedKey, fileId, totalChunks)
131
+
132
+ const parts: BlobPart[] = [asBlobPart(header)]
133
+ for (let i = 0; i < totalChunks; i += 1) {
134
+ const start = i * chunkSize
135
+ const end = Math.min(start + chunkSize, plaintextSize)
136
+ const plaintextBytes = new Uint8Array(
137
+ await blob.slice(start, end).arrayBuffer(),
138
+ )
139
+ const ciphertext = await encryptChunk(ctx, i, plaintextBytes)
140
+ parts.push(asBlobPart(uint32BE(ciphertext.length)))
141
+ parts.push(asBlobPart(ciphertext))
142
+ onProgress?.((i + 1) / Math.max(totalChunks, 1))
143
+ }
144
+
145
+ if (totalChunks === 0) onProgress?.(1)
146
+
147
+ return {
148
+ blob: new Blob(parts, { type: 'application/octet-stream' }),
149
+ suite: SUITE.PQ_HYBRID_XCHACHA_MLKEM1024_V1,
150
+ fileId,
151
+ chunkSize,
152
+ totalChunks,
153
+ plaintextSize,
154
+ combinedKey,
155
+ }
156
+ }
157
+
158
+ export interface PqHybridDecryptOptions {
159
+ blob: Blob
160
+ /** Recipient's ML-KEM-1024 secret key (3168 bytes) */
161
+ recipientSecretKey: Uint8Array
162
+ /** Classical envelope key */
163
+ envelopeKey: Uint8Array
164
+ onProgress?: ProgressCallback
165
+ }
166
+
167
+ export async function decryptBlob(
168
+ options: PqHybridDecryptOptions,
169
+ ): Promise<Blob> {
170
+ const { blob, recipientSecretKey, envelopeKey, onProgress } = options
171
+ if (!(blob instanceof Blob)) {
172
+ throw new TypeError('decryptBlob: blob must be a Blob or File')
173
+ }
174
+
175
+ // The header for this suite is large because suite_payload is 1664 bytes.
176
+ // Probe enough bytes to capture it.
177
+ const headerProbeSize = Math.min(
178
+ blob.size,
179
+ HEADER_SIZES.MAGIC +
180
+ HEADER_SIZES.SUITE +
181
+ HEADER_SIZES.FLAGS +
182
+ HEADER_SIZES.FILE_ID +
183
+ HEADER_SIZES.CHUNK_SIZE +
184
+ HEADER_SIZES.TOTAL_CHUNKS +
185
+ HEADER_SIZES.PLAINTEXT_SIZE +
186
+ HEADER_SIZES.SUITE_PAYLOAD_LEN +
187
+ PQ_HYBRID_V1_SUITE_PAYLOAD_LENGTH +
188
+ HEADER_SIZES.HEADER_MAC +
189
+ 32, // padding
190
+ )
191
+ const headerProbeBytes = new Uint8Array(
192
+ await blob.slice(0, headerProbeSize).arrayBuffer(),
193
+ )
194
+
195
+ const parsed = parseHeader(headerProbeBytes)
196
+
197
+ if (parsed.suite !== SUITE.PQ_HYBRID_XCHACHA_MLKEM1024_V1) {
198
+ throw new HeaderError(
199
+ `decryptBlob: this entry point only supports pq-hybrid-xchacha-mlkem1024-v1; got suite 0x${parsed.suite.toString(16)}`,
200
+ )
201
+ }
202
+
203
+ // Recover the combined key — this is where PQ decapsulation happens.
204
+ const { combinedKey } = await decapsulateFromHeader({
205
+ suitePayload: parsed.suitePayload,
206
+ recipientSecretKey,
207
+ envelopeKey,
208
+ fileId: parsed.fileId,
209
+ })
210
+
211
+ // The header MAC implicitly verifies that the right combined key was
212
+ // recovered (i.e., the PQ secret + envelope key match the file).
213
+ await verifyHeaderMac(parsed, combinedKey)
214
+
215
+ const ctx = await createChunkContext(
216
+ combinedKey,
217
+ parsed.fileId,
218
+ parsed.totalChunks,
219
+ )
220
+
221
+ const plaintextParts: BlobPart[] = []
222
+ let cursor = parsed.headerLength
223
+ let bytesEmitted = 0
224
+
225
+ for (let i = 0; i < parsed.totalChunks; i += 1) {
226
+ if (cursor + LENGTH_PREFIX_BYTES > blob.size) {
227
+ throw new HeaderError('chunk_length_truncated')
228
+ }
229
+ const lenBytes = new Uint8Array(
230
+ await blob.slice(cursor, cursor + LENGTH_PREFIX_BYTES).arrayBuffer(),
231
+ )
232
+ cursor += LENGTH_PREFIX_BYTES
233
+ const cipherLen = readUint32BE(lenBytes)
234
+
235
+ const isFinal = i === parsed.totalChunks - 1
236
+ const minCipher = 1 + PQ_HYBRID_V1_TAG_BYTES
237
+ const maxCipher = parsed.chunkSize + PQ_HYBRID_V1_TAG_BYTES
238
+ if (cipherLen < minCipher || cipherLen > maxCipher) {
239
+ throw new HeaderError('chunk_length_out_of_range')
240
+ }
241
+ if (!isFinal && cipherLen !== maxCipher) {
242
+ throw new HeaderError('non_final_chunk_wrong_size')
243
+ }
244
+
245
+ if (cursor + cipherLen > blob.size) {
246
+ throw new HeaderError('chunk_truncated')
247
+ }
248
+
249
+ const cipherBytes = new Uint8Array(
250
+ await blob.slice(cursor, cursor + cipherLen).arrayBuffer(),
251
+ )
252
+ cursor += cipherLen
253
+
254
+ const plaintext = await decryptChunk(ctx, i, cipherBytes)
255
+ bytesEmitted += plaintext.length
256
+ plaintextParts.push(asBlobPart(plaintext))
257
+
258
+ onProgress?.((i + 1) / Math.max(parsed.totalChunks, 1))
259
+ }
260
+
261
+ if (bytesEmitted !== parsed.plaintextSize) {
262
+ throw new HeaderError('plaintext_size_mismatch')
263
+ }
264
+ if (cursor !== blob.size) {
265
+ throw new HeaderError('trailing_bytes_after_last_chunk')
266
+ }
267
+
268
+ if (parsed.totalChunks === 0) onProgress?.(1)
269
+
270
+ return new Blob(plaintextParts, { type: 'application/octet-stream' })
271
+ }
272
+
273
+ /**
274
+ * Encrypt a Uint8Array under suite 0x03 (PQ-hybrid XChaCha20-Poly1305 +
275
+ * ML-KEM-1024). Returns the encrypted file alongside the combined
276
+ * content key used to produce it.
277
+ *
278
+ * SECURITY: The returned `combinedKey` grants permanent decryption
279
+ * capability for any file whose header was produced with it. Treat
280
+ * as cryptographic secret material: hold only in memory for the
281
+ * duration of the operation, do not persist to disk or storage, do
282
+ * not log, do not transmit. The only safe way to reproduce it on
283
+ * another machine is to re-encapsulate via the recipient's ML-KEM
284
+ * public key.
285
+ */
286
+ export async function encryptBytes(
287
+ bytes: Uint8Array,
288
+ options: Omit<PqHybridEncryptOptions, 'blob'>,
289
+ ): Promise<EncryptedFile & { combinedKey: Uint8Array }> {
290
+ const blob = new Blob([asBlobPart(bytes)])
291
+ return encryptBlob({ blob, ...options })
292
+ }
293
+
294
+ export async function decryptToBytes(
295
+ options: PqHybridDecryptOptions,
296
+ ): Promise<Uint8Array> {
297
+ const blob = await decryptBlob(options)
298
+ return new Uint8Array(await blob.arrayBuffer())
299
+ }
@@ -0,0 +1,343 @@
1
+ /**
2
+ * Cipher suite 0x03: PQ-hybrid XChaCha20-Poly1305 + ML-KEM-1024 v1.
3
+ *
4
+ * The default suite for new files. Combines a classical 32-byte secret with
5
+ * an ML-KEM-1024 encapsulated 32-byte shared secret. The combined key is
6
+ * derived via HKDF-SHA-256 with the file_id as salt.
7
+ *
8
+ * Security: an adversary must break BOTH ML-KEM-1024 AND the classical
9
+ * KDF/wrap to recover plaintext. ML-KEM-1024 is FIPS 203, security level
10
+ * 5 (≈AES-256 against quantum search).
11
+ *
12
+ * Implementation:
13
+ * - Classical share encrypted under envelope key with XSalsa20-Poly1305
14
+ * secretbox (libsodium).
15
+ * - PQ encapsulation via @noble/post-quantum's ML-KEM-1024.
16
+ * - Chunk AEAD identical to xchacha-v1 once the combined key is derived.
17
+ */
18
+
19
+ import { ml_kem1024 } from '@noble/post-quantum/ml-kem.js'
20
+
21
+ import { buildChunkAad } from '../../format/header.js'
22
+ import {
23
+ HKDF_INFO,
24
+ HEADER_SIZES,
25
+ type ParsedHeader,
26
+ } from '../../internal/types.js'
27
+ import { concatBytes, uint64BE } from '../../internal/encoding.js'
28
+ import { hkdfSha256 } from '../../internal/hkdf.js'
29
+ import { randomBytes } from '../../internal/runtime.js'
30
+ import { getSodium } from '../../internal/sodium.js'
31
+
32
+ export const PQ_HYBRID_V1_KEY_BYTES = 32
33
+ export const PQ_HYBRID_V1_NONCE_BYTES = 24
34
+ export const PQ_HYBRID_V1_TAG_BYTES = 16
35
+
36
+ /** ML-KEM-1024 ciphertext length per FIPS 203. */
37
+ export const ML_KEM_1024_CIPHERTEXT_BYTES = 1568
38
+ /** ML-KEM-1024 public key length per FIPS 203. */
39
+ export const ML_KEM_1024_PUBLIC_KEY_BYTES = 1568
40
+ /** ML-KEM-1024 secret key length per FIPS 203. */
41
+ export const ML_KEM_1024_SECRET_KEY_BYTES = 3168
42
+
43
+ /**
44
+ * Suite payload layout:
45
+ * mlkem_ciphertext (1568 bytes)
46
+ * classical_wrapped (72 bytes — 48 bytes secretbox + 24 bytes reserved zero pad)
47
+ * classical_nonce (24 bytes)
48
+ * Total: 1664 bytes
49
+ */
50
+ export const PQ_HYBRID_V1_SUITE_PAYLOAD_LENGTH =
51
+ ML_KEM_1024_CIPHERTEXT_BYTES + 72 + 24
52
+
53
+ export interface PqHybridV1SuitePayload {
54
+ mlkemCiphertext: Uint8Array // 1568 bytes
55
+ classicalWrapped: Uint8Array // 72 bytes
56
+ classicalNonce: Uint8Array // 24 bytes
57
+ }
58
+
59
+ export function buildPqHybridV1SuitePayload(
60
+ payload: PqHybridV1SuitePayload,
61
+ ): Uint8Array {
62
+ if (payload.mlkemCiphertext.length !== ML_KEM_1024_CIPHERTEXT_BYTES) {
63
+ throw new RangeError('pq-hybrid-v1: mlkemCiphertext must be 1568 bytes')
64
+ }
65
+ if (payload.classicalWrapped.length !== 72) {
66
+ throw new RangeError('pq-hybrid-v1: classicalWrapped must be 72 bytes')
67
+ }
68
+ if (payload.classicalNonce.length !== 24) {
69
+ throw new RangeError('pq-hybrid-v1: classicalNonce must be 24 bytes')
70
+ }
71
+ return concatBytes([
72
+ payload.mlkemCiphertext,
73
+ payload.classicalWrapped,
74
+ payload.classicalNonce,
75
+ ])
76
+ }
77
+
78
+ export function parsePqHybridV1SuitePayload(
79
+ bytes: Uint8Array,
80
+ ): PqHybridV1SuitePayload {
81
+ if (bytes.length !== PQ_HYBRID_V1_SUITE_PAYLOAD_LENGTH) {
82
+ throw new RangeError(
83
+ `pq-hybrid-v1: suite payload must be ${PQ_HYBRID_V1_SUITE_PAYLOAD_LENGTH} bytes`,
84
+ )
85
+ }
86
+ return {
87
+ mlkemCiphertext: bytes.slice(0, ML_KEM_1024_CIPHERTEXT_BYTES),
88
+ classicalWrapped: bytes.slice(
89
+ ML_KEM_1024_CIPHERTEXT_BYTES,
90
+ ML_KEM_1024_CIPHERTEXT_BYTES + 72,
91
+ ),
92
+ classicalNonce: bytes.slice(
93
+ ML_KEM_1024_CIPHERTEXT_BYTES + 72,
94
+ PQ_HYBRID_V1_SUITE_PAYLOAD_LENGTH,
95
+ ),
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Generate an ML-KEM-1024 keypair. In production the keypair is derived
101
+ * deterministically from the user's master secret via HKDF; this function
102
+ * is exposed for testing and advanced callers.
103
+ */
104
+ export function generateMlKemKeypair(): {
105
+ publicKey: Uint8Array
106
+ secretKey: Uint8Array
107
+ } {
108
+ const seed = randomBytes(64)
109
+ return ml_kem1024.keygen(seed)
110
+ }
111
+
112
+ /**
113
+ * Derive an ML-KEM-1024 keypair deterministically from a master secret.
114
+ * The seed input is 64 bytes; we derive it via HKDF so the same master
115
+ * secret always yields the same keypair across sessions and devices.
116
+ */
117
+ export async function deriveMlKemKeypair(
118
+ masterSecret: Uint8Array,
119
+ ): Promise<{ publicKey: Uint8Array; secretKey: Uint8Array }> {
120
+ const seed = await hkdfSha256({
121
+ ikm: masterSecret,
122
+ info: HKDF_INFO.ML_KEM_1024_SEED,
123
+ length: 64,
124
+ })
125
+ return ml_kem1024.keygen(seed)
126
+ }
127
+
128
+ /**
129
+ * Compute the combined content key from classical and PQ shares.
130
+ *
131
+ * K = HKDF-SHA-256(
132
+ * ikm = classical_share || pq_share,
133
+ * salt = file_id,
134
+ * info = "shieldfive/v1/pq-hybrid/combine",
135
+ * L = 32
136
+ * )
137
+ */
138
+ async function combineKeys(
139
+ classicalShare: Uint8Array,
140
+ pqShare: Uint8Array,
141
+ fileId: Uint8Array,
142
+ ): Promise<Uint8Array> {
143
+ if (classicalShare.length !== 32 || pqShare.length !== 32) {
144
+ throw new RangeError('combineKeys: both shares must be 32 bytes')
145
+ }
146
+ return hkdfSha256({
147
+ ikm: concatBytes([classicalShare, pqShare]),
148
+ salt: fileId,
149
+ info: HKDF_INFO.PQ_HYBRID_COMBINE,
150
+ length: 32,
151
+ })
152
+ }
153
+
154
+ export interface PqHybridV1ChunkContext {
155
+ combinedKey: Uint8Array
156
+ noncePrefix: Uint8Array
157
+ totalChunks: number
158
+ }
159
+
160
+ async function deriveChunkContext(
161
+ combinedKey: Uint8Array,
162
+ fileId: Uint8Array,
163
+ totalChunks: number,
164
+ ): Promise<PqHybridV1ChunkContext> {
165
+ // Reuse the xchacha derivation domain — semantically the same chunk-key role.
166
+ const chunkKey = await hkdfSha256({
167
+ ikm: combinedKey,
168
+ salt: fileId,
169
+ info: HKDF_INFO.XCHACHA_CHUNK_KEY,
170
+ length: 32,
171
+ })
172
+ const noncePrefix = await hkdfSha256({
173
+ ikm: fileId,
174
+ info: HKDF_INFO.XCHACHA_NONCE_PREFIX,
175
+ length: 16,
176
+ })
177
+ return { combinedKey: chunkKey, noncePrefix, totalChunks }
178
+ }
179
+
180
+ function buildNonce(noncePrefix: Uint8Array, chunkIndex: number): Uint8Array {
181
+ const nonce = new Uint8Array(PQ_HYBRID_V1_NONCE_BYTES)
182
+ nonce.set(noncePrefix, 0)
183
+ nonce.set(uint64BE(chunkIndex), 16)
184
+ return nonce
185
+ }
186
+
187
+ export async function encryptChunk(
188
+ ctx: PqHybridV1ChunkContext,
189
+ chunkIndex: number,
190
+ plaintext: Uint8Array,
191
+ ): Promise<Uint8Array> {
192
+ const sodium = await getSodium()
193
+ const isFinal = chunkIndex === ctx.totalChunks - 1
194
+ const aad = buildChunkAad(chunkIndex, ctx.totalChunks, isFinal)
195
+ const nonce = buildNonce(ctx.noncePrefix, chunkIndex)
196
+ return sodium.crypto_aead_xchacha20poly1305_ietf_encrypt(
197
+ plaintext,
198
+ aad,
199
+ null,
200
+ nonce,
201
+ ctx.combinedKey,
202
+ )
203
+ }
204
+
205
+ export async function decryptChunk(
206
+ ctx: PqHybridV1ChunkContext,
207
+ chunkIndex: number,
208
+ ciphertext: Uint8Array,
209
+ ): Promise<Uint8Array> {
210
+ const sodium = await getSodium()
211
+ const isFinal = chunkIndex === ctx.totalChunks - 1
212
+ const aad = buildChunkAad(chunkIndex, ctx.totalChunks, isFinal)
213
+ const nonce = buildNonce(ctx.noncePrefix, chunkIndex)
214
+ return sodium.crypto_aead_xchacha20poly1305_ietf_decrypt(
215
+ null,
216
+ ciphertext,
217
+ aad,
218
+ nonce,
219
+ ctx.combinedKey,
220
+ )
221
+ }
222
+
223
+ /**
224
+ * Sender side: produce the suite payload and the combined key.
225
+ *
226
+ * Inputs:
227
+ * - recipient's ML-KEM public key
228
+ * - envelopeKey: classical key under which the classical share is wrapped
229
+ * - fileId: per-file ID used as HKDF salt
230
+ *
231
+ * Outputs:
232
+ * - the suite payload bytes
233
+ * - the combined content key (used for header MAC and chunk AEAD)
234
+ */
235
+ export async function encapsulateForRecipient(options: {
236
+ recipientPublicKey: Uint8Array
237
+ envelopeKey: Uint8Array
238
+ fileId: Uint8Array
239
+ }): Promise<{ suitePayload: Uint8Array; combinedKey: Uint8Array }> {
240
+ const sodium = await getSodium()
241
+ const { recipientPublicKey, envelopeKey, fileId } = options
242
+
243
+ if (recipientPublicKey.length !== ML_KEM_1024_PUBLIC_KEY_BYTES) {
244
+ throw new RangeError('encapsulate: public key must be 1568 bytes')
245
+ }
246
+ if (envelopeKey.length !== 32) {
247
+ throw new RangeError('encapsulate: envelopeKey must be 32 bytes')
248
+ }
249
+ if (fileId.length !== HEADER_SIZES.FILE_ID) {
250
+ throw new RangeError('encapsulate: fileId must be 16 bytes')
251
+ }
252
+
253
+ // 1) ML-KEM encapsulation: produces (mlkem_ciphertext, S_pq).
254
+ const { cipherText: mlkemCiphertext, sharedSecret: pqShare } =
255
+ ml_kem1024.encapsulate(recipientPublicKey)
256
+
257
+ // 2) Generate classical share and wrap it under the envelope key.
258
+ const classicalShare = randomBytes(32)
259
+ const classicalNonce = randomBytes(24)
260
+ const classicalWrappedShort = sodium.crypto_secretbox_easy(
261
+ classicalShare,
262
+ classicalNonce,
263
+ envelopeKey,
264
+ )
265
+ if (classicalWrappedShort.length !== 48) {
266
+ throw new Error('encapsulate: unexpected secretbox length')
267
+ }
268
+ const classicalWrapped = new Uint8Array(72)
269
+ classicalWrapped.set(classicalWrappedShort, 0)
270
+
271
+ // 3) Combine.
272
+ const combinedKey = await combineKeys(classicalShare, pqShare, fileId)
273
+
274
+ // 4) Pack suite_payload.
275
+ const suitePayload = buildPqHybridV1SuitePayload({
276
+ mlkemCiphertext,
277
+ classicalWrapped,
278
+ classicalNonce,
279
+ })
280
+
281
+ return { suitePayload, combinedKey }
282
+ }
283
+
284
+ /**
285
+ * Recipient side: recover the combined content key from the suite payload.
286
+ */
287
+ export async function decapsulateFromHeader(options: {
288
+ suitePayload: Uint8Array
289
+ recipientSecretKey: Uint8Array
290
+ envelopeKey: Uint8Array
291
+ fileId: Uint8Array
292
+ }): Promise<{ combinedKey: Uint8Array }> {
293
+ const sodium = await getSodium()
294
+ const { suitePayload, recipientSecretKey, envelopeKey, fileId } = options
295
+
296
+ if (recipientSecretKey.length !== ML_KEM_1024_SECRET_KEY_BYTES) {
297
+ throw new RangeError('decapsulate: secret key must be 3168 bytes')
298
+ }
299
+ if (envelopeKey.length !== 32) {
300
+ throw new RangeError('decapsulate: envelopeKey must be 32 bytes')
301
+ }
302
+ if (fileId.length !== HEADER_SIZES.FILE_ID) {
303
+ throw new RangeError('decapsulate: fileId must be 16 bytes')
304
+ }
305
+
306
+ const parsed = parsePqHybridV1SuitePayload(suitePayload)
307
+
308
+ // 1) PQ decapsulation.
309
+ const pqShare = ml_kem1024.decapsulate(
310
+ parsed.mlkemCiphertext,
311
+ recipientSecretKey,
312
+ )
313
+
314
+ // 2) Classical unwrap.
315
+ const wrapped48 = parsed.classicalWrapped.slice(0, 48)
316
+ const classicalShare = sodium.crypto_secretbox_open_easy(
317
+ wrapped48,
318
+ parsed.classicalNonce,
319
+ envelopeKey,
320
+ )
321
+ if (!classicalShare) {
322
+ throw new Error('decapsulate: classical unwrap failed')
323
+ }
324
+
325
+ // 3) Combine.
326
+ const combinedKey = await combineKeys(classicalShare, pqShare, fileId)
327
+
328
+ return { combinedKey }
329
+ }
330
+
331
+ export async function createChunkContext(
332
+ combinedKey: Uint8Array,
333
+ fileId: Uint8Array,
334
+ totalChunks: number,
335
+ ): Promise<PqHybridV1ChunkContext> {
336
+ return deriveChunkContext(combinedKey, fileId, totalChunks)
337
+ }
338
+
339
+ export function getSuitePayloadFromHeader(
340
+ header: ParsedHeader,
341
+ ): PqHybridV1SuitePayload {
342
+ return parsePqHybridV1SuitePayload(header.suitePayload)
343
+ }