@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,358 @@
1
+ /**
2
+ * User identity & public-key directory helpers.
3
+ *
4
+ * In a multi-user system, the PQ-hybrid suite needs the recipient's public
5
+ * key to encrypt to. This module provides:
6
+ *
7
+ * - A canonical wire format for publishing a user's public-key bundle
8
+ * (ML-KEM-1024 public key + a self-signed-by-application identity tag).
9
+ * - Helpers for creating, parsing, and verifying public-key bundles.
10
+ * - Helpers for re-encrypting a file's content key to additional
11
+ * recipients (sharing) without re-uploading the file.
12
+ *
13
+ * Cryptographic identity beyond the application's own auth layer is
14
+ * deliberately NOT in scope. The bundle format does not sign the public
15
+ * key with any user-controlled key — the trust anchor is the application's
16
+ * authenticated channel for publishing keys (TLS + auth token). If callers
17
+ * want stronger identity (e.g. SAS verification, gossiped signatures),
18
+ * they wrap this module rather than modify it.
19
+ */
20
+
21
+ import {
22
+ ML_KEM_1024_PUBLIC_KEY_BYTES,
23
+ ML_KEM_1024_SECRET_KEY_BYTES,
24
+ deriveMlKemKeypair,
25
+ generateMlKemKeypair,
26
+ encapsulateForRecipient,
27
+ decapsulateFromHeader,
28
+ parsePqHybridV1SuitePayload,
29
+ buildPqHybridV1SuitePayload,
30
+ } from '../suites/pq-hybrid-v1/index.js'
31
+ import {
32
+ bytesToBase64,
33
+ base64ToBytes,
34
+ concatBytes,
35
+ uint16BE,
36
+ uint32BE,
37
+ readUint16BE,
38
+ readUint32BE,
39
+ } from '../internal/encoding.js'
40
+ import { randomBytes } from '../internal/runtime.js'
41
+ import { getSodium } from '../internal/sodium.js'
42
+
43
+ const IDENTITY_BUNDLE_MAGIC = new Uint8Array([0x53, 0x46, 0x35, 0x49, 0x01]) // "SF5I" + version
44
+ const IDENTITY_BUNDLE_VERSION = 0x01
45
+
46
+ export interface PublicIdentityBundle {
47
+ /** ML-KEM-1024 public key (1568 bytes) */
48
+ mlKemPublicKey: Uint8Array
49
+ /** Application-assigned user ID (UTF-8 string, ≤255 bytes) */
50
+ userId: string
51
+ /** Optional metadata blob (≤4 KiB), e.g. a profile JSON */
52
+ metadata?: Uint8Array
53
+ /** Issuance timestamp (UNIX seconds, uint32) */
54
+ issuedAt: number
55
+ }
56
+
57
+ /**
58
+ * Wire format for an identity bundle:
59
+ *
60
+ * magic 5 bytes "SF5I" + version
61
+ * issued_at 4 bytes uint32 BE (UNIX seconds)
62
+ * user_id_len 1 byte
63
+ * user_id variable UTF-8
64
+ * ml_kem_pk 1568 bytes
65
+ * metadata_len 2 bytes uint16 BE
66
+ * metadata variable opaque
67
+ *
68
+ * Unsigned. Trust comes from the channel that publishes it.
69
+ */
70
+
71
+ export function encodeIdentityBundle(bundle: PublicIdentityBundle): Uint8Array {
72
+ if (bundle.mlKemPublicKey.length !== ML_KEM_1024_PUBLIC_KEY_BYTES) {
73
+ throw new RangeError(
74
+ `encodeIdentityBundle: mlKemPublicKey must be ${ML_KEM_1024_PUBLIC_KEY_BYTES} bytes`,
75
+ )
76
+ }
77
+ const userIdBytes = new TextEncoder().encode(bundle.userId)
78
+ if (userIdBytes.length === 0 || userIdBytes.length > 255) {
79
+ throw new RangeError(
80
+ 'encodeIdentityBundle: userId must be 1..255 UTF-8 bytes',
81
+ )
82
+ }
83
+ if (
84
+ !Number.isSafeInteger(bundle.issuedAt) ||
85
+ bundle.issuedAt < 0 ||
86
+ bundle.issuedAt > 0xffff_ffff
87
+ ) {
88
+ throw new RangeError('encodeIdentityBundle: issuedAt must fit in uint32')
89
+ }
90
+ const metadata = bundle.metadata ?? new Uint8Array(0)
91
+ if (metadata.length > 4096) {
92
+ throw new RangeError(
93
+ 'encodeIdentityBundle: metadata must be at most 4096 bytes',
94
+ )
95
+ }
96
+ return concatBytes([
97
+ IDENTITY_BUNDLE_MAGIC,
98
+ uint32BE(bundle.issuedAt),
99
+ new Uint8Array([userIdBytes.length]),
100
+ userIdBytes,
101
+ bundle.mlKemPublicKey,
102
+ uint16BE(metadata.length),
103
+ metadata,
104
+ ])
105
+ }
106
+
107
+ export function decodeIdentityBundle(bytes: Uint8Array): PublicIdentityBundle {
108
+ if (bytes.length < IDENTITY_BUNDLE_MAGIC.length + 4 + 1) {
109
+ throw new RangeError('decodeIdentityBundle: input too short')
110
+ }
111
+ for (let i = 0; i < IDENTITY_BUNDLE_MAGIC.length; i += 1) {
112
+ if (bytes[i] !== IDENTITY_BUNDLE_MAGIC[i]) {
113
+ throw new Error('decodeIdentityBundle: bad magic / unknown bundle version')
114
+ }
115
+ }
116
+
117
+ let offset = IDENTITY_BUNDLE_MAGIC.length
118
+ const issuedAt = readUint32BE(bytes, offset)
119
+ offset += 4
120
+
121
+ const userIdLen = bytes[offset]!
122
+ offset += 1
123
+ if (userIdLen === 0) {
124
+ throw new Error('decodeIdentityBundle: empty user_id')
125
+ }
126
+ if (offset + userIdLen + ML_KEM_1024_PUBLIC_KEY_BYTES + 2 > bytes.length) {
127
+ throw new Error('decodeIdentityBundle: truncated')
128
+ }
129
+
130
+ const userId = new TextDecoder('utf-8', { fatal: true }).decode(
131
+ bytes.slice(offset, offset + userIdLen),
132
+ )
133
+ offset += userIdLen
134
+
135
+ const mlKemPublicKey = bytes.slice(
136
+ offset,
137
+ offset + ML_KEM_1024_PUBLIC_KEY_BYTES,
138
+ )
139
+ offset += ML_KEM_1024_PUBLIC_KEY_BYTES
140
+
141
+ const metadataLen = readUint16BE(bytes, offset)
142
+ offset += 2
143
+ if (offset + metadataLen !== bytes.length) {
144
+ throw new Error('decodeIdentityBundle: trailing bytes or wrong metadata_len')
145
+ }
146
+ const metadata = bytes.slice(offset, offset + metadataLen)
147
+
148
+ const result: PublicIdentityBundle = {
149
+ mlKemPublicKey,
150
+ userId,
151
+ issuedAt,
152
+ }
153
+ if (metadata.length > 0) result.metadata = metadata
154
+ return result
155
+ }
156
+
157
+ /**
158
+ * Serialize a bundle as a base64 string suitable for storing in a database
159
+ * column or transmitting over a JSON API.
160
+ */
161
+ export function bundleToBase64(bundle: PublicIdentityBundle): string {
162
+ return bytesToBase64(encodeIdentityBundle(bundle))
163
+ }
164
+
165
+ export function bundleFromBase64(b64: string): PublicIdentityBundle {
166
+ return decodeIdentityBundle(base64ToBytes(b64))
167
+ }
168
+
169
+ // ──────────────────────────────────────────────────────────────────────
170
+ // Identity creation
171
+ // ──────────────────────────────────────────────────────────────────────
172
+
173
+ export interface CreateIdentityOptions {
174
+ userId: string
175
+ metadata?: Uint8Array
176
+ /**
177
+ * If provided, the ML-KEM keypair is derived deterministically from
178
+ * this master secret. Otherwise a fresh keypair is generated. Most
179
+ * applications should pass the user's master secret here so that
180
+ * loss of an ML-KEM secret key does not lock the user out.
181
+ */
182
+ masterSecret?: Uint8Array
183
+ /** Defaults to current time. */
184
+ issuedAt?: number
185
+ }
186
+
187
+ export interface IdentityKeypair {
188
+ publicBundle: PublicIdentityBundle
189
+ /** Encoded form of the public bundle for direct publishing. */
190
+ publicBundleBytes: Uint8Array
191
+ /** ML-KEM-1024 secret key. Treat as highly sensitive. */
192
+ mlKemSecretKey: Uint8Array
193
+ }
194
+
195
+ export async function createIdentity(
196
+ options: CreateIdentityOptions,
197
+ ): Promise<IdentityKeypair> {
198
+ const keypair = options.masterSecret
199
+ ? await deriveMlKemKeypair(options.masterSecret)
200
+ : generateMlKemKeypair()
201
+
202
+ const bundle: PublicIdentityBundle = {
203
+ mlKemPublicKey: keypair.publicKey,
204
+ userId: options.userId,
205
+ issuedAt: options.issuedAt ?? Math.floor(Date.now() / 1000),
206
+ }
207
+ if (options.metadata) bundle.metadata = options.metadata
208
+
209
+ if (keypair.secretKey.length !== ML_KEM_1024_SECRET_KEY_BYTES) {
210
+ throw new Error(
211
+ `createIdentity: unexpected secret key length ${keypair.secretKey.length}`,
212
+ )
213
+ }
214
+
215
+ return {
216
+ publicBundle: bundle,
217
+ publicBundleBytes: encodeIdentityBundle(bundle),
218
+ mlKemSecretKey: keypair.secretKey,
219
+ }
220
+ }
221
+
222
+ // ──────────────────────────────────────────────────────────────────────
223
+ // Sharing: re-encrypt a file's content key to additional recipients
224
+ // ──────────────────────────────────────────────────────────────────────
225
+
226
+ /**
227
+ * The PQ-hybrid suite encrypts each file's combined key for exactly one
228
+ * recipient (whoever owns the ML-KEM public key the encryptor used).
229
+ * Sharing a file with N additional recipients means: recover the
230
+ * original combined key (only the owner can do this), then produce N new
231
+ * suite_payloads — one per recipient — that decrypt to the SAME combined
232
+ * key. The chunks themselves are not re-encrypted.
233
+ *
234
+ * Each per-recipient suite_payload is stored alongside the file's chunks
235
+ * in the application's database (one row per recipient). The on-disk
236
+ * blob remains unchanged.
237
+ */
238
+
239
+ export interface ShareFileInput {
240
+ /** The file's combined key, recovered by the owner. */
241
+ combinedKey: Uint8Array
242
+ /** The file's 16-byte file_id. */
243
+ fileId: Uint8Array
244
+ /** The recipient's identity bundle (provides their ML-KEM public key). */
245
+ recipient: PublicIdentityBundle
246
+ /** Classical envelope key the recipient holds. */
247
+ recipientEnvelopeKey: Uint8Array
248
+ }
249
+
250
+ /**
251
+ * Build a new suite_payload that decrypts to `combinedKey` for the given
252
+ * recipient. Stored alongside the file as a per-recipient share record.
253
+ *
254
+ * NOTE: the standard `encapsulateForRecipient` produces a NEW combined
255
+ * key. To make sharing work, we use a different construction: we wrap
256
+ * the existing combined key under (recipient PQ KEM ⊕ recipient
257
+ * envelope) and emit only the wrapped form.
258
+ */
259
+ export async function buildShareForRecipient(
260
+ input: ShareFileInput,
261
+ ): Promise<{ shareBundle: Uint8Array }> {
262
+ const sodium = await getSodium()
263
+
264
+ // Generate a fresh transport key for this share.
265
+ // ML-KEM encapsulation gives us the PQ-half of the transport secret.
266
+ const { suitePayload: pqPayload, combinedKey: transportKey } =
267
+ await encapsulateForRecipient({
268
+ recipientPublicKey: input.recipient.mlKemPublicKey,
269
+ envelopeKey: input.recipientEnvelopeKey,
270
+ fileId: input.fileId,
271
+ })
272
+
273
+ // Now wrap the original combined key under the transport key using
274
+ // XSalsa20-Poly1305 secretbox.
275
+ if (transportKey.length !== 32) {
276
+ throw new Error('buildShareForRecipient: transport key length wrong')
277
+ }
278
+ const wrapNonce = randomBytes(24)
279
+ const wrappedCombinedKey = sodium.crypto_secretbox_easy(
280
+ input.combinedKey,
281
+ wrapNonce,
282
+ transportKey,
283
+ )
284
+ if (wrappedCombinedKey.length !== 32 + 16) {
285
+ throw new Error('buildShareForRecipient: secretbox produced unexpected length')
286
+ }
287
+
288
+ // Share record format:
289
+ // [4 bytes BE length of pqPayload][pqPayload][24-byte wrap nonce][48-byte wrapped combined key]
290
+ return {
291
+ shareBundle: concatBytes([
292
+ uint32BE(pqPayload.length),
293
+ pqPayload,
294
+ wrapNonce,
295
+ wrappedCombinedKey,
296
+ ]),
297
+ }
298
+ }
299
+
300
+ /**
301
+ * Recipient side: open a share bundle to recover the file's combined key.
302
+ * The recipient then uses that combined key with the standard PQ-hybrid
303
+ * decrypt path (via the original on-disk file).
304
+ */
305
+ export async function openShareAsRecipient(input: {
306
+ shareBundle: Uint8Array
307
+ fileId: Uint8Array
308
+ recipientSecretKey: Uint8Array
309
+ recipientEnvelopeKey: Uint8Array
310
+ }): Promise<Uint8Array> {
311
+ const sodium = await getSodium()
312
+ if (input.shareBundle.length < 4) {
313
+ throw new Error('openShareAsRecipient: share too short')
314
+ }
315
+ let offset = 0
316
+ const pqLen = readUint32BE(input.shareBundle, offset)
317
+ offset += 4
318
+ if (offset + pqLen + 24 + 48 !== input.shareBundle.length) {
319
+ throw new Error('openShareAsRecipient: malformed share')
320
+ }
321
+ const pqPayload = input.shareBundle.slice(offset, offset + pqLen)
322
+ offset += pqLen
323
+ const wrapNonce = input.shareBundle.slice(offset, offset + 24)
324
+ offset += 24
325
+ const wrappedCombinedKey = input.shareBundle.slice(offset, offset + 48)
326
+
327
+ // Sanity-check the suite payload structure (this throws if malformed).
328
+ parsePqHybridV1SuitePayload(pqPayload)
329
+ // Round-trip through builder to ensure we got back the same bytes.
330
+ const checkBytes = buildPqHybridV1SuitePayload(
331
+ parsePqHybridV1SuitePayload(pqPayload),
332
+ )
333
+ if (checkBytes.length !== pqPayload.length) {
334
+ throw new Error('openShareAsRecipient: pq payload self-check failed')
335
+ }
336
+
337
+ const { combinedKey: transportKey } = await decapsulateFromHeader({
338
+ suitePayload: pqPayload,
339
+ recipientSecretKey: input.recipientSecretKey,
340
+ envelopeKey: input.recipientEnvelopeKey,
341
+ fileId: input.fileId,
342
+ })
343
+
344
+ const unwrapped = sodium.crypto_secretbox_open_easy(
345
+ wrappedCombinedKey,
346
+ wrapNonce,
347
+ transportKey,
348
+ )
349
+ if (!unwrapped) {
350
+ throw new Error(
351
+ 'openShareAsRecipient: secretbox unwrap failed — wrong recipient or tampered share',
352
+ )
353
+ }
354
+ if (unwrapped.length !== 32) {
355
+ throw new Error('openShareAsRecipient: bad combined key length')
356
+ }
357
+ return new Uint8Array(unwrapped)
358
+ }
package/src/index.ts ADDED
@@ -0,0 +1,197 @@
1
+ /**
2
+ * @shieldfive/crypto — open-source, post-quantum-hybrid client-side
3
+ * encryption for cloud storage.
4
+ *
5
+ * Public entry point. Most callers should import from a specific suite
6
+ * subpath instead of the bare module name:
7
+ *
8
+ * import { encryptBlob, decryptBlob } from '@shieldfive/crypto/pq-hybrid-v1'
9
+ * import { encryptBlob, decryptBlob } from '@shieldfive/crypto/aes-gcm-v1'
10
+ * import { encryptBlob, decryptBlob } from '@shieldfive/crypto/xchacha-v1'
11
+ * import { decryptV0 } from '@shieldfive/crypto/legacy-v0'
12
+ *
13
+ * The umbrella `import { ... } from '@shieldfive/crypto'` exposes shared
14
+ * format primitives, type definitions, and an auto-routing decryptor that
15
+ * dispatches by suite ID.
16
+ */
17
+
18
+ // ──────────────────────────────────────────────────────────────────────
19
+ // Format primitives
20
+ // ──────────────────────────────────────────────────────────────────────
21
+ export {
22
+ buildAuthenticatedHeader,
23
+ buildChunkAad,
24
+ buildHeaderUnauthenticated,
25
+ deriveHeaderMacKey,
26
+ HeaderError,
27
+ parseHeader,
28
+ verifyHeaderMac,
29
+ } from './format/header.js'
30
+
31
+ // ──────────────────────────────────────────────────────────────────────
32
+ // Type definitions and constants
33
+ // ──────────────────────────────────────────────────────────────────────
34
+ export {
35
+ CHUNK_AAD_DOMAIN,
36
+ CHUNK_AAD_LENGTH,
37
+ DEFAULT_CHUNK_SIZE,
38
+ FORMAT_MAGIC,
39
+ FORMAT_MAGIC_LENGTH,
40
+ HEADER_FIXED_PREFIX_LENGTH,
41
+ HEADER_SIZES,
42
+ HKDF_INFO,
43
+ MAX_CHUNK_SIZE,
44
+ MAX_TOTAL_CHUNKS,
45
+ SUITE,
46
+ SUITE_NAMES,
47
+ } from './internal/types.js'
48
+ export type {
49
+ EncryptedFile,
50
+ ParsedHeader,
51
+ ProgressCallback,
52
+ SuiteId,
53
+ SuiteName,
54
+ } from './internal/types.js'
55
+
56
+ // ──────────────────────────────────────────────────────────────────────
57
+ // Encoding utilities (base64, hex, uint codecs)
58
+ // ──────────────────────────────────────────────────────────────────────
59
+ export {
60
+ base64ToBytes,
61
+ bytesToBase64,
62
+ bytesToHex,
63
+ hexToBytes,
64
+ concatBytes,
65
+ } from './internal/encoding.js'
66
+
67
+ // ──────────────────────────────────────────────────────────────────────
68
+ // Runtime helpers
69
+ // ──────────────────────────────────────────────────────────────────────
70
+ export {
71
+ constantTimeEqual,
72
+ randomBytes,
73
+ zeroize,
74
+ } from './internal/runtime.js'
75
+
76
+ // ──────────────────────────────────────────────────────────────────────
77
+ // Re-export suite namespaces for direct consumption
78
+ // ──────────────────────────────────────────────────────────────────────
79
+ export * as aesGcmV1 from './suites/aes-gcm-v1/api.js'
80
+ export * as xchachaV1 from './suites/xchacha-v1/api.js'
81
+ export * as pqHybridV1 from './suites/pq-hybrid-v1/api.js'
82
+ export * as legacyV0 from './suites/aes-gcm-v0/api.js'
83
+ export * as streamsAesGcmV1 from './streams/aes-gcm-v1.js'
84
+ export * as kdfArgon2id from './kdf/argon2id.js'
85
+ export * as identity from './identity/index.js'
86
+ export * as migrationV0 from './migration/v0-bridge.js'
87
+
88
+ // ──────────────────────────────────────────────────────────────────────
89
+ // Auto-routing decryptor
90
+ // ──────────────────────────────────────────────────────────────────────
91
+ import { parseHeader, HeaderError } from './format/header.js'
92
+ import { SUITE, type SuiteId } from './internal/types.js'
93
+ import * as aes from './suites/aes-gcm-v1/api.js'
94
+ import * as xchacha from './suites/xchacha-v1/api.js'
95
+ import * as pqHybrid from './suites/pq-hybrid-v1/api.js'
96
+
97
+ export interface AutoDecryptOptions {
98
+ blob: Blob
99
+ /** Used for AES-GCM-v1 and XChaCha-v1 (32-byte raw content key) */
100
+ contentKey?: Uint8Array
101
+ /** Required for PQ-hybrid: ML-KEM-1024 secret key (3168 bytes) */
102
+ recipientSecretKey?: Uint8Array
103
+ /** Required for PQ-hybrid: classical 32-byte envelope key */
104
+ envelopeKey?: Uint8Array
105
+ /** Optional progress callback (0..1) */
106
+ onProgress?: (progress: number) => void
107
+ }
108
+
109
+ /**
110
+ * Decrypt a v1-format blob, automatically dispatching to the correct suite
111
+ * based on the header's suite byte. Throws if the suite requires inputs the
112
+ * caller didn't provide. For v0 (legacy) files, use `legacyV0.decryptV0`
113
+ * directly — v0 has no header, so the dispatcher cannot route to it.
114
+ */
115
+ export async function autoDecryptBlob(
116
+ options: AutoDecryptOptions,
117
+ ): Promise<Blob> {
118
+ const { blob } = options
119
+ if (!(blob instanceof Blob)) {
120
+ throw new TypeError('autoDecryptBlob: blob must be a Blob or File')
121
+ }
122
+
123
+ const headerProbe = new Uint8Array(
124
+ await blob.slice(0, Math.min(blob.size, 4096)).arrayBuffer(),
125
+ )
126
+
127
+ let suite: SuiteId
128
+ try {
129
+ const parsed = parseHeader(headerProbe)
130
+ suite = parsed.suite
131
+ } catch (err) {
132
+ // If parse fails because of a too-short probe, escalate. Suites with
133
+ // larger suite_payloads (notably PQ hybrid at 1664 bytes) need more.
134
+ if (err instanceof HeaderError && err.code === 'header_too_short') {
135
+ const bigger = new Uint8Array(
136
+ await blob
137
+ .slice(0, Math.min(blob.size, 4 + 0xffff + 64))
138
+ .arrayBuffer(),
139
+ )
140
+ const parsed = parseHeader(bigger)
141
+ suite = parsed.suite
142
+ } else {
143
+ throw err
144
+ }
145
+ }
146
+
147
+ switch (suite) {
148
+ case SUITE.AES_256_GCM_V1: {
149
+ if (!options.contentKey) {
150
+ throw new Error(
151
+ 'autoDecryptBlob: contentKey required for aes-256-gcm-v1',
152
+ )
153
+ }
154
+ return aes.decryptBlob({
155
+ blob,
156
+ contentKey: options.contentKey,
157
+ ...(options.onProgress ? { onProgress: options.onProgress } : {}),
158
+ })
159
+ }
160
+ case SUITE.XCHACHA20_POLY1305_V1: {
161
+ if (!options.contentKey) {
162
+ throw new Error(
163
+ 'autoDecryptBlob: contentKey required for xchacha20-poly1305-v1',
164
+ )
165
+ }
166
+ return xchacha.decryptBlob({
167
+ blob,
168
+ contentKey: options.contentKey,
169
+ ...(options.onProgress ? { onProgress: options.onProgress } : {}),
170
+ })
171
+ }
172
+ case SUITE.PQ_HYBRID_XCHACHA_MLKEM1024_V1: {
173
+ if (!options.recipientSecretKey || !options.envelopeKey) {
174
+ throw new Error(
175
+ 'autoDecryptBlob: recipientSecretKey and envelopeKey required for pq-hybrid-v1',
176
+ )
177
+ }
178
+ return pqHybrid.decryptBlob({
179
+ blob,
180
+ recipientSecretKey: options.recipientSecretKey,
181
+ envelopeKey: options.envelopeKey,
182
+ ...(options.onProgress ? { onProgress: options.onProgress } : {}),
183
+ })
184
+ }
185
+ default: {
186
+ throw new HeaderError(
187
+ `autoDecryptBlob: unknown suite 0x${(suite as number).toString(16)}`,
188
+ )
189
+ }
190
+ }
191
+ }
192
+
193
+ /** Library version, also written into format documentation. */
194
+ export const SHIELDFIVE_CRYPTO_VERSION = '1.0.0-alpha.2'
195
+
196
+ /** Default cipher suite for new files when not specified by the caller. */
197
+ export const DEFAULT_SUITE = SUITE.PQ_HYBRID_XCHACHA_MLKEM1024_V1