@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,347 @@
1
+ /**
2
+ * Phase 1 migration bridge: v0 (legacy) format encrypt/decrypt.
3
+ *
4
+ * ⚠️ THIS MODULE EXISTS SOLELY FOR THE PHASE 1 SHIELDFIVE MIGRATION ⚠️
5
+ *
6
+ * The on-disk file format here is the legacy "v0" format documented in
7
+ * `spec/format-v0.md` — concatenated AES-256-GCM chunks, no header, no
8
+ * AAD, IV = 4-byte file-prefix || uint64_be(counter), all metadata stored
9
+ * out-of-band in the application database.
10
+ *
11
+ * v0 has documented structural weaknesses (no truncation detection at
12
+ * the AEAD layer, no chunk-index AAD, etc.) that v1 fixes. We expose a
13
+ * v0 *writer* in this bridge module ONLY so that ShieldFive can swap the
14
+ * inline crypto in the main repository for library calls **without**
15
+ * changing the on-disk format in the same release. Once Phase 2 ships
16
+ * (writers default to suite 0x01 / v1), this module is deprecated; once
17
+ * all v0 files have been migrated to v1, this module is deleted.
18
+ *
19
+ * Outside the ShieldFive main-repo migration, callers SHOULD NOT use
20
+ * `legacyV0Writer.encryptV0`. Use one of the v1 suites instead.
21
+ *
22
+ * The decrypt path delegates straight to `suites/aes-gcm-v0/api.ts`
23
+ * (which is the supported, public legacy reader).
24
+ */
25
+
26
+ import { uint64BE } from '../internal/encoding.js'
27
+ import { getSubtle, randomBytes } from '../internal/runtime.js'
28
+ import {
29
+ decryptV0,
30
+ decryptV0ToBytes,
31
+ V0_IV_BYTES,
32
+ V0_KEY_BYTES,
33
+ V0_NONCE_PREFIX_BYTES,
34
+ V0_TAG_BYTES,
35
+ type V0DecryptOptions,
36
+ } from '../suites/aes-gcm-v0/api.js'
37
+
38
+ export {
39
+ decryptV0,
40
+ decryptV0ToBytes,
41
+ V0_IV_BYTES,
42
+ V0_KEY_BYTES,
43
+ V0_NONCE_PREFIX_BYTES,
44
+ V0_TAG_BYTES,
45
+ type V0DecryptOptions,
46
+ }
47
+
48
+ // ─────────────────────────────────────────────────────────────────────
49
+ // v0 writer (Phase 1 migration only)
50
+ // ─────────────────────────────────────────────────────────────────────
51
+
52
+ export interface V0EncryptOptions {
53
+ /** Plaintext blob. */
54
+ blob: Blob
55
+ /** 32-byte AES-256 content key. Must already be unwrapped. */
56
+ contentKey: Uint8Array
57
+ /** 4-byte per-file random nonce prefix. Generated if omitted. */
58
+ noncePrefix?: Uint8Array
59
+ /** Plaintext bytes per chunk. Production uses 5 MiB or 8 MiB. */
60
+ chunkSize: number
61
+ /** Optional progress callback (0..1). */
62
+ onProgress?: (progress: number) => void
63
+ /**
64
+ * If true, also computes per-chunk SHA-1 hashes for storage-layer
65
+ * integrity checks (matching the production worker's behavior).
66
+ */
67
+ computeChunkHashes?: boolean
68
+ }
69
+
70
+ export interface V0EncryptResult {
71
+ /** Encrypted blob (concatenated chunks, no header). */
72
+ blob: Blob
73
+ /** Number of chunks emitted. */
74
+ totalChunks: number
75
+ /** Plaintext byte count. */
76
+ plaintextSize: number
77
+ /** Nonce prefix used (caller MUST persist this in the database). */
78
+ noncePrefix: Uint8Array
79
+ /** SHA-1 hashes per chunk if requested; otherwise omitted. */
80
+ chunkHashes?: string[]
81
+ }
82
+
83
+ function buildV0Iv(prefix: Uint8Array, counter: number): Uint8Array {
84
+ const iv = new Uint8Array(V0_IV_BYTES)
85
+ iv.set(prefix, 0)
86
+ iv.set(uint64BE(counter), 4)
87
+ return iv
88
+ }
89
+
90
+ async function sha1Hex(bytes: Uint8Array): Promise<string> {
91
+ const subtle = getSubtle()
92
+ const digest = await subtle.digest(
93
+ 'SHA-1',
94
+ bytes as Uint8Array<ArrayBuffer>,
95
+ )
96
+ const arr = new Uint8Array(digest)
97
+ let out = ''
98
+ for (let i = 0; i < arr.length; i += 1) {
99
+ out += arr[i]!.toString(16).padStart(2, '0')
100
+ }
101
+ return out
102
+ }
103
+
104
+ /**
105
+ * Encrypt a blob in the legacy v0 format. Drop-in replacement for the
106
+ * inline AES-GCM calls in `public/workers/sf-crypto-worker.js`.
107
+ *
108
+ * **Wire format:** identical to current production. Bit-for-bit
109
+ * compatible.
110
+ *
111
+ * **Key handling:** the caller must bring their own pre-unwrapped 32-byte
112
+ * content key. This module does not wrap or unwrap keys.
113
+ */
114
+ export async function encryptV0(
115
+ options: V0EncryptOptions,
116
+ ): Promise<V0EncryptResult> {
117
+ const { blob, contentKey, chunkSize, onProgress } = options
118
+
119
+ if (!(blob instanceof Blob)) {
120
+ throw new TypeError('encryptV0: blob must be a Blob or File')
121
+ }
122
+ if (contentKey.length !== V0_KEY_BYTES) {
123
+ throw new RangeError('encryptV0: contentKey must be 32 bytes')
124
+ }
125
+ if (!Number.isSafeInteger(chunkSize) || chunkSize <= 0) {
126
+ throw new RangeError('encryptV0: chunkSize must be a positive integer')
127
+ }
128
+
129
+ const noncePrefix = options.noncePrefix ?? randomBytes(V0_NONCE_PREFIX_BYTES)
130
+ if (noncePrefix.length !== V0_NONCE_PREFIX_BYTES) {
131
+ throw new RangeError('encryptV0: noncePrefix must be 4 bytes')
132
+ }
133
+
134
+ const plaintextSize = blob.size
135
+ if (plaintextSize === 0) {
136
+ return {
137
+ blob: new Blob([], { type: 'application/octet-stream' }),
138
+ totalChunks: 0,
139
+ plaintextSize: 0,
140
+ noncePrefix,
141
+ ...(options.computeChunkHashes ? { chunkHashes: [] } : {}),
142
+ }
143
+ }
144
+
145
+ const totalChunks = Math.ceil(plaintextSize / chunkSize)
146
+
147
+ const subtle = getSubtle()
148
+ const key = await subtle.importKey(
149
+ 'raw',
150
+ contentKey as Uint8Array<ArrayBuffer>,
151
+ { name: 'AES-GCM' },
152
+ false,
153
+ ['encrypt'],
154
+ )
155
+
156
+ const parts: BlobPart[] = []
157
+ const chunkHashes: string[] = []
158
+
159
+ for (let i = 0; i < totalChunks; i += 1) {
160
+ const start = i * chunkSize
161
+ const end = Math.min(start + chunkSize, plaintextSize)
162
+ const slice = new Uint8Array(await blob.slice(start, end).arrayBuffer())
163
+ const iv = buildV0Iv(noncePrefix, i)
164
+
165
+ const ct = new Uint8Array(
166
+ await subtle.encrypt(
167
+ {
168
+ name: 'AES-GCM',
169
+ iv: iv as Uint8Array<ArrayBuffer>,
170
+ tagLength: 128,
171
+ },
172
+ key,
173
+ slice as Uint8Array<ArrayBuffer>,
174
+ ),
175
+ )
176
+
177
+ parts.push(ct as Uint8Array<ArrayBuffer>)
178
+ if (options.computeChunkHashes) {
179
+ chunkHashes.push(await sha1Hex(ct))
180
+ }
181
+
182
+ onProgress?.((i + 1) / totalChunks)
183
+ }
184
+
185
+ const result: V0EncryptResult = {
186
+ blob: new Blob(parts, { type: 'application/octet-stream' }),
187
+ totalChunks,
188
+ plaintextSize,
189
+ noncePrefix,
190
+ }
191
+ if (options.computeChunkHashes) {
192
+ result.chunkHashes = chunkHashes
193
+ }
194
+ return result
195
+ }
196
+
197
+ /**
198
+ * Web Worker message handler shaped to match the existing production
199
+ * worker contract at `public/workers/sf-crypto-worker.js`. Lets the main
200
+ * repo replace the worker file's body with `installV0WorkerHandler(self)`
201
+ * during Phase 1 of the migration — no API changes for callers.
202
+ *
203
+ * Message shape (matches production):
204
+ * { type: 'init', mode: 'encrypt' | 'decrypt', key: ArrayBuffer,
205
+ * noncePrefix: ArrayBuffer, chunkSize: number, blob: Blob }
206
+ * { type: 'process', index: number }
207
+ * (also accepted: { type: 'chunk_request', index: number } — alias)
208
+ * { type: 'clear' }
209
+ *
210
+ * Responses:
211
+ * { type: 'inited', totalChunks: number }
212
+ * { type: 'chunk', mode: 'encrypt', index, data: ArrayBuffer, sha1: string }
213
+ * { type: 'chunk', mode: 'decrypt', index, data: ArrayBuffer }
214
+ * { type: 'cleared' }
215
+ * { type: 'error', error: string }
216
+ */
217
+ export interface WorkerLike {
218
+ onmessage:
219
+ | ((event: { data: unknown }) => void | Promise<void>)
220
+ | null
221
+ postMessage: (msg: unknown) => void
222
+ }
223
+
224
+ interface V0WorkerState {
225
+ mode: 'encrypt' | 'decrypt'
226
+ key: CryptoKey
227
+ noncePrefix: Uint8Array
228
+ chunkSize: number
229
+ blob: Blob
230
+ totalChunks: number
231
+ }
232
+
233
+ export function installV0WorkerHandler(scope: WorkerLike): void {
234
+ let state: V0WorkerState | null = null
235
+
236
+ scope.onmessage = async (event: { data: unknown }) => {
237
+ const msg = (event.data ?? {}) as Record<string, unknown>
238
+ try {
239
+ if (msg.type === 'init') {
240
+ const mode = msg.mode === 'decrypt' ? 'decrypt' : 'encrypt'
241
+ const rawKeyBuf = msg.key as ArrayBuffer | undefined
242
+ const rawPrefixBuf = msg.noncePrefix as ArrayBuffer | undefined
243
+ const blob = msg.blob as Blob | undefined
244
+ const chunkSize = Number(msg.chunkSize ?? 0)
245
+
246
+ if (!rawKeyBuf || !rawPrefixBuf || !blob || !chunkSize || chunkSize <= 0) {
247
+ throw new Error('worker_init_invalid')
248
+ }
249
+ const rawKey = new Uint8Array(rawKeyBuf)
250
+ const noncePrefix = new Uint8Array(rawPrefixBuf)
251
+ if (rawKey.length !== V0_KEY_BYTES) {
252
+ throw new Error('worker_init_key_invalid')
253
+ }
254
+ if (noncePrefix.length !== V0_NONCE_PREFIX_BYTES) {
255
+ throw new Error('worker_init_nonce_prefix_invalid')
256
+ }
257
+
258
+ const key = await getSubtle().importKey(
259
+ 'raw',
260
+ rawKey as Uint8Array<ArrayBuffer>,
261
+ { name: 'AES-GCM' },
262
+ false,
263
+ ['encrypt', 'decrypt'],
264
+ )
265
+
266
+ const ctChunkSize = chunkSize + V0_TAG_BYTES
267
+ const totalChunks =
268
+ mode === 'encrypt'
269
+ ? Math.ceil(blob.size / chunkSize)
270
+ : Math.ceil(blob.size / ctChunkSize)
271
+
272
+ state = {
273
+ mode,
274
+ key,
275
+ noncePrefix,
276
+ chunkSize,
277
+ blob,
278
+ totalChunks,
279
+ }
280
+ scope.postMessage({ type: 'inited', totalChunks })
281
+ return
282
+ }
283
+
284
+ if (msg.type === 'process' || msg.type === 'chunk_request') {
285
+ if (!state) throw new Error('worker_not_inited')
286
+ const index = Number(msg.index ?? -1)
287
+ if (!Number.isInteger(index) || index < 0 || index >= state.totalChunks) {
288
+ throw new Error('worker_chunk_index_invalid')
289
+ }
290
+ const iv = buildV0Iv(state.noncePrefix, index)
291
+ if (state.mode === 'encrypt') {
292
+ const start = index * state.chunkSize
293
+ const end = Math.min(start + state.chunkSize, state.blob.size)
294
+ const slice = new Uint8Array(
295
+ await state.blob.slice(start, end).arrayBuffer(),
296
+ )
297
+ const ciphertext = await getSubtle().encrypt(
298
+ { name: 'AES-GCM', iv: iv as Uint8Array<ArrayBuffer>, tagLength: 128 },
299
+ state.key,
300
+ slice as Uint8Array<ArrayBuffer>,
301
+ )
302
+ const ctBytes = new Uint8Array(ciphertext)
303
+ const sha1 = await sha1Hex(ctBytes)
304
+ scope.postMessage({
305
+ type: 'chunk',
306
+ mode: 'encrypt',
307
+ index,
308
+ data: ciphertext,
309
+ sha1,
310
+ })
311
+ } else {
312
+ const ctChunk = state.chunkSize + V0_TAG_BYTES
313
+ const start = index * ctChunk
314
+ const end = Math.min(start + ctChunk, state.blob.size)
315
+ const slice = new Uint8Array(
316
+ await state.blob.slice(start, end).arrayBuffer(),
317
+ )
318
+ const plaintext = await getSubtle().decrypt(
319
+ { name: 'AES-GCM', iv: iv as Uint8Array<ArrayBuffer>, tagLength: 128 },
320
+ state.key,
321
+ slice as Uint8Array<ArrayBuffer>,
322
+ )
323
+ scope.postMessage({
324
+ type: 'chunk',
325
+ mode: 'decrypt',
326
+ index,
327
+ data: plaintext,
328
+ })
329
+ }
330
+ return
331
+ }
332
+
333
+ if (msg.type === 'clear') {
334
+ state = null
335
+ scope.postMessage({ type: 'cleared' })
336
+ return
337
+ }
338
+
339
+ throw new Error('worker_unknown_message_type')
340
+ } catch (err) {
341
+ scope.postMessage({
342
+ type: 'error',
343
+ error: (err as Error).message ?? 'unknown_error',
344
+ })
345
+ }
346
+ }
347
+ }