@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,134 @@
1
+ /**
2
+ * Public type definitions for the shieldfive-crypto library.
3
+ */
4
+
5
+ export type Crypto = {
6
+ subtle: SubtleCrypto
7
+ getRandomValues<T extends ArrayBufferView>(array: T): T
8
+ }
9
+
10
+ export type SubtleCrypto = globalThis.SubtleCrypto
11
+
12
+ /**
13
+ * Suite identifiers as written to the on-disk format byte.
14
+ * See `spec/format-v1.md` for the canonical assignment.
15
+ */
16
+ export const SUITE = {
17
+ AES_256_GCM_V1: 0x01,
18
+ XCHACHA20_POLY1305_V1: 0x02,
19
+ PQ_HYBRID_XCHACHA_MLKEM1024_V1: 0x03,
20
+ AES_256_GCM_V2: 0x04,
21
+ } as const
22
+
23
+ export type SuiteId = (typeof SUITE)[keyof typeof SUITE]
24
+
25
+ export type SuiteName =
26
+ | 'aes-256-gcm-v1'
27
+ | 'xchacha20-poly1305-v1'
28
+ | 'pq-hybrid-xchacha-mlkem1024-v1'
29
+ | 'aes-256-gcm-v2'
30
+
31
+ export const SUITE_NAMES: Record<SuiteId, SuiteName> = {
32
+ [SUITE.AES_256_GCM_V1]: 'aes-256-gcm-v1',
33
+ [SUITE.XCHACHA20_POLY1305_V1]: 'xchacha20-poly1305-v1',
34
+ [SUITE.PQ_HYBRID_XCHACHA_MLKEM1024_V1]: 'pq-hybrid-xchacha-mlkem1024-v1',
35
+ [SUITE.AES_256_GCM_V2]: 'aes-256-gcm-v2',
36
+ }
37
+
38
+ /**
39
+ * Magic bytes prefixing every v1-format file: "SF5" + major(1) + minor(0).
40
+ * Treat as immutable; do not mutate.
41
+ */
42
+ export const FORMAT_MAGIC: Uint8Array = new Uint8Array([
43
+ 0x53, 0x46, 0x35, 0x01, 0x00,
44
+ ])
45
+
46
+ export const FORMAT_MAGIC_LENGTH = 5
47
+
48
+ /** Header field sizes — see spec/format-v1.md */
49
+ export const HEADER_SIZES = Object.freeze({
50
+ MAGIC: 5,
51
+ SUITE: 1,
52
+ FLAGS: 1,
53
+ FILE_ID: 16,
54
+ CHUNK_SIZE: 4,
55
+ TOTAL_CHUNKS: 8,
56
+ PLAINTEXT_SIZE: 8,
57
+ SUITE_PAYLOAD_LEN: 2,
58
+ HEADER_MAC: 32,
59
+ })
60
+
61
+ /** Fixed bytes preceding the variable-length suite_payload */
62
+ export const HEADER_FIXED_PREFIX_LENGTH =
63
+ HEADER_SIZES.MAGIC +
64
+ HEADER_SIZES.SUITE +
65
+ HEADER_SIZES.FLAGS +
66
+ HEADER_SIZES.FILE_ID +
67
+ HEADER_SIZES.CHUNK_SIZE +
68
+ HEADER_SIZES.TOTAL_CHUNKS +
69
+ HEADER_SIZES.PLAINTEXT_SIZE +
70
+ HEADER_SIZES.SUITE_PAYLOAD_LEN
71
+
72
+ /** Default plaintext bytes per chunk for new uploads (4 MiB) */
73
+ export const DEFAULT_CHUNK_SIZE = 4 * 1024 * 1024
74
+
75
+ /** Maximum permitted chunk_size in the format (uint32 max) */
76
+ export const MAX_CHUNK_SIZE = 0xffff_ffff
77
+
78
+ /** Maximum permitted total_chunks (sane upper bound, well below uint64 max) */
79
+ export const MAX_TOTAL_CHUNKS = 1_000_000_000
80
+
81
+ /** Domain separators for HKDF — never reuse a string here in another context */
82
+ export const HKDF_INFO = Object.freeze({
83
+ HEADER_MAC: 'shieldfive/v1/header-mac',
84
+ AES_GCM_CHUNK_KEY: 'shieldfive/v1/aes-gcm/chunk-key',
85
+ AES_GCM_NONCE_PREFIX: 'shieldfive/v1/aes-gcm/nonce-prefix',
86
+ AES_GCM_V2_NONCE_PREFIX: 'shieldfive/v1/aes-gcm-v2/nonce-prefix',
87
+ XCHACHA_CHUNK_KEY: 'shieldfive/v1/xchacha/chunk-key',
88
+ XCHACHA_NONCE_PREFIX: 'shieldfive/v1/xchacha/nonce-prefix',
89
+ PQ_HYBRID_COMBINE: 'shieldfive/v1/pq-hybrid/combine',
90
+ ML_KEM_1024_SEED: 'shieldfive/v1/pq-hybrid/ml-kem-1024-seed',
91
+ ARGON2ID_SALT_COMPRESSION: 'shieldfive/v1/argon2id/salt-compression',
92
+ })
93
+
94
+ /** AAD domain string mixed into every chunk's authenticator */
95
+ export const CHUNK_AAD_DOMAIN = 'shieldfive/v1/chunk'
96
+ export const CHUNK_AAD_LENGTH = CHUNK_AAD_DOMAIN.length + 8 + 8 + 1
97
+
98
+ /**
99
+ * Header values reflecting how a particular file was encrypted.
100
+ * Returned by header parsers; consumed by chunk encrypt/decrypt loops.
101
+ */
102
+ export interface ParsedHeader {
103
+ suite: SuiteId
104
+ flags: number
105
+ fileId: Uint8Array
106
+ chunkSize: number
107
+ totalChunks: number
108
+ plaintextSize: number
109
+ suitePayload: Uint8Array
110
+ /** Bytes consumed from the input — chunks start at this offset */
111
+ headerLength: number
112
+ }
113
+
114
+ /**
115
+ * Result of encrypting a file. The blob is the on-disk form (header +
116
+ * concatenated chunks). Application metadata (file id, suite, chunk size)
117
+ * is also returned so callers can stash it in their own database if they
118
+ * want to look files up by id.
119
+ */
120
+ export interface EncryptedFile {
121
+ blob: Blob
122
+ suite: SuiteId
123
+ fileId: Uint8Array
124
+ chunkSize: number
125
+ totalChunks: number
126
+ plaintextSize: number
127
+ }
128
+
129
+ /**
130
+ * Progress callback shape, called after each chunk is processed. Progress
131
+ * is reported as a float in [0, 1] inclusive. The final call is always
132
+ * exactly 1.0.
133
+ */
134
+ export type ProgressCallback = (progress: number) => void
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Argon2id-based key derivation for password-derived master secrets.
3
+ *
4
+ * The library does not require its callers to use this module — the host
5
+ * application can produce a 32-byte master secret any way it likes. But
6
+ * for the common case of "stretch a user passphrase into a master key,"
7
+ * this module gives a vetted default with explicit parameter choices.
8
+ *
9
+ * Backed by libsodium-wrappers-sumo (loaded lazily). Requires the
10
+ * optional peer dependency to be installed.
11
+ */
12
+
13
+ import { getSodium } from '../internal/sodium.js'
14
+ import { hkdfSha256 } from '../internal/hkdf.js'
15
+ import { randomBytes } from '../internal/runtime.js'
16
+ import { HKDF_INFO } from '../internal/types.js'
17
+
18
+ /**
19
+ * Argon2id parameter presets.
20
+ *
21
+ * "interactive" is libsodium's MIN; we deliberately do not expose it.
22
+ * "moderate" is the documented default for password storage on
23
+ * contemporary devices (3 ops, 256 MiB).
24
+ * "sensitive" is appropriate for high-value secrets but requires 1 GiB
25
+ * of RAM and is unsuitable for mobile devices.
26
+ *
27
+ * The chosen preset is encoded into the output so a derived secret can be
28
+ * re-derived later without storing the parameters alongside.
29
+ */
30
+ export type Argon2idPreset = 'moderate' | 'sensitive'
31
+
32
+ export const ARGON2ID_SALT_BYTES = 16
33
+ export const MASTER_SECRET_BYTES = 32
34
+
35
+ interface PresetConfig {
36
+ opslimit: number // libsodium ops parameter
37
+ memlimit: number // libsodium memory parameter (bytes)
38
+ }
39
+
40
+ /** Resolve a preset name to (opslimit, memlimit) using libsodium constants. */
41
+ async function resolvePreset(preset: Argon2idPreset): Promise<PresetConfig> {
42
+ const sodium = await getSodium()
43
+ switch (preset) {
44
+ case 'moderate':
45
+ return {
46
+ opslimit: sodium.crypto_pwhash_OPSLIMIT_MODERATE,
47
+ memlimit: sodium.crypto_pwhash_MEMLIMIT_MODERATE,
48
+ }
49
+ case 'sensitive':
50
+ return {
51
+ opslimit: sodium.crypto_pwhash_OPSLIMIT_SENSITIVE,
52
+ memlimit: sodium.crypto_pwhash_MEMLIMIT_SENSITIVE,
53
+ }
54
+ default: {
55
+ const _exhaustive: never = preset
56
+ throw new Error(`unknown Argon2id preset: ${String(_exhaustive)}`)
57
+ }
58
+ }
59
+ }
60
+
61
+ export interface DeriveMasterSecretInput {
62
+ /** User passphrase. UTF-8 encoded internally. */
63
+ passphrase: string
64
+ /** Per-user salt. Must be ≥16 bytes. Generated if not provided. */
65
+ salt?: Uint8Array
66
+ /** Argon2id strength preset. Default: 'moderate'. */
67
+ preset?: Argon2idPreset
68
+ }
69
+
70
+ export interface DeriveMasterSecretOutput {
71
+ /** 32-byte master secret. Treat as the highest-value secret in the system. */
72
+ masterSecret: Uint8Array
73
+ /** Salt used (caller must persist this for re-derivation). */
74
+ salt: Uint8Array
75
+ /** Preset used. Encoded so a future re-derivation produces the same key. */
76
+ preset: Argon2idPreset
77
+ }
78
+
79
+ /**
80
+ * Derive a 32-byte master secret from a passphrase using Argon2id.
81
+ *
82
+ * The host application MUST persist `salt` and `preset` alongside the
83
+ * user's account so that future logins can reproduce the same master
84
+ * secret. The passphrase itself MUST NOT be stored.
85
+ */
86
+ export async function deriveMasterSecret(
87
+ input: DeriveMasterSecretInput,
88
+ ): Promise<DeriveMasterSecretOutput> {
89
+ const sodium = await getSodium()
90
+
91
+ if (typeof input.passphrase !== 'string' || input.passphrase.length === 0) {
92
+ throw new Error('deriveMasterSecret: passphrase must be a non-empty string')
93
+ }
94
+
95
+ const salt = input.salt ?? randomBytes(ARGON2ID_SALT_BYTES)
96
+ if (salt.length < ARGON2ID_SALT_BYTES) {
97
+ throw new RangeError(
98
+ `deriveMasterSecret: salt must be at least ${ARGON2ID_SALT_BYTES} bytes`,
99
+ )
100
+ }
101
+ // libsodium expects exactly SALTBYTES; if a longer salt is supplied,
102
+ // we domain-separate it through HKDF first to land on 16 bytes.
103
+ let usableSalt = salt
104
+ if (salt.length > ARGON2ID_SALT_BYTES) {
105
+ usableSalt = await hkdfSha256({
106
+ ikm: salt,
107
+ info: HKDF_INFO.ARGON2ID_SALT_COMPRESSION,
108
+ length: ARGON2ID_SALT_BYTES,
109
+ })
110
+ }
111
+
112
+ const preset = input.preset ?? 'moderate'
113
+ const { opslimit, memlimit } = await resolvePreset(preset)
114
+
115
+ const passphraseBytes = new TextEncoder().encode(input.passphrase)
116
+
117
+ const derived = sodium.crypto_pwhash(
118
+ MASTER_SECRET_BYTES,
119
+ passphraseBytes,
120
+ usableSalt,
121
+ opslimit,
122
+ memlimit,
123
+ sodium.crypto_pwhash_ALG_ARGON2ID13,
124
+ )
125
+
126
+ return {
127
+ masterSecret: new Uint8Array(derived),
128
+ salt,
129
+ preset,
130
+ }
131
+ }
132
+
133
+ /**
134
+ * Re-derive the same master secret given the previously stored salt and
135
+ * preset. Convenience wrapper; exactly equivalent to deriveMasterSecret
136
+ * called with the saved parameters.
137
+ */
138
+ export async function reDeriveMasterSecret(input: {
139
+ passphrase: string
140
+ salt: Uint8Array
141
+ preset: Argon2idPreset
142
+ }): Promise<Uint8Array> {
143
+ const result = await deriveMasterSecret(input)
144
+ return result.masterSecret
145
+ }
146
+
147
+ /**
148
+ * Verify a passphrase against a previously derived master secret without
149
+ * exposing whether the input was wrong before the constant-time compare.
150
+ * Returns true iff the rederived master secret matches.
151
+ */
152
+ export async function verifyPassphrase(input: {
153
+ passphrase: string
154
+ salt: Uint8Array
155
+ preset: Argon2idPreset
156
+ expectedMasterSecret: Uint8Array
157
+ }): Promise<boolean> {
158
+ const computed = await reDeriveMasterSecret(input)
159
+ if (computed.length !== input.expectedMasterSecret.length) return false
160
+ let diff = 0
161
+ for (let i = 0; i < computed.length; i += 1) {
162
+ diff |= computed[i]! ^ input.expectedMasterSecret[i]!
163
+ }
164
+ return diff === 0
165
+ }
@@ -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
+ }