@shieldfive/crypto 1.0.0-alpha.2 → 1.0.0-alpha.5

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 (39) hide show
  1. package/CHANGELOG.md +42 -4
  2. package/README.md +2 -2
  3. package/dist/format/header.d.ts +13 -0
  4. package/dist/format/header.d.ts.map +1 -1
  5. package/dist/format/header.js +38 -11
  6. package/dist/format/header.js.map +1 -1
  7. package/dist/index.d.ts +1 -1
  8. package/dist/index.js +1 -1
  9. package/dist/internal/types.d.ts +2 -0
  10. package/dist/internal/types.d.ts.map +1 -1
  11. package/dist/internal/types.js +2 -0
  12. package/dist/internal/types.js.map +1 -1
  13. package/dist/kdf/argon2id.d.ts.map +1 -1
  14. package/dist/kdf/argon2id.js +2 -1
  15. package/dist/kdf/argon2id.js.map +1 -1
  16. package/dist/streams/pq-hybrid-v1.d.ts +120 -0
  17. package/dist/streams/pq-hybrid-v1.d.ts.map +1 -0
  18. package/dist/streams/pq-hybrid-v1.js +368 -0
  19. package/dist/streams/pq-hybrid-v1.js.map +1 -0
  20. package/dist/suites/aes-gcm-v1/api.d.ts.map +1 -1
  21. package/dist/suites/aes-gcm-v1/api.js +4 -2
  22. package/dist/suites/aes-gcm-v1/api.js.map +1 -1
  23. package/dist/suites/pq-hybrid-v1/index.js +1 -1
  24. package/dist/suites/pq-hybrid-v1/index.js.map +1 -1
  25. package/dist/suites/xchacha-v1/api.d.ts.map +1 -1
  26. package/dist/suites/xchacha-v1/api.js +4 -1
  27. package/dist/suites/xchacha-v1/api.js.map +1 -1
  28. package/package.json +8 -4
  29. package/spec/format-v1.md +102 -13
  30. package/spec/key-derivation.md +49 -4
  31. package/spec/threat-model.md +99 -13
  32. package/src/format/header.ts +43 -11
  33. package/src/index.ts +1 -1
  34. package/src/internal/types.ts +2 -0
  35. package/src/kdf/argon2id.ts +2 -1
  36. package/src/streams/pq-hybrid-v1.ts +521 -0
  37. package/src/suites/aes-gcm-v1/api.ts +5 -3
  38. package/src/suites/pq-hybrid-v1/index.ts +1 -1
  39. package/src/suites/xchacha-v1/api.ts +4 -1
package/spec/format-v1.md CHANGED
@@ -66,9 +66,12 @@ byte. Future versions may introduce flags such as
66
66
  `0x01 = compressed-plaintext` or `0x02 = sparse-file-encoding`.
67
67
 
68
68
  `file_id` is 16 cryptographically random bytes generated per file. It is
69
- mixed into every chunk's AAD to bind ciphertext to its file. This prevents
70
- chunk-mixing attacks where chunks from one file are spliced into another
71
- file with the same content key.
69
+ mixed into every chunk's key and nonce derivation (see the per-suite
70
+ definitions below) to bind ciphertext to its file. `file_id` is NOT
71
+ present in the AAD itself; the cross-file splice resistance is
72
+ structural, via the suite-specific HKDF salt. Future implementers MUST
73
+ NOT add `file_id` to the AAD bytes — doing so would break wire
74
+ compatibility with already-shipped v1 files.
72
75
 
73
76
  `plaintext_size` is the exact number of plaintext bytes. It allows a reader
74
77
  to detect truncation of the final chunk before AEAD verification, and to
@@ -88,9 +91,14 @@ header_mac_key := HKDF-SHA-256(
88
91
  )
89
92
  ```
90
93
 
91
- Readers MUST verify `header_mac` before parsing `suite_payload` or any
92
- chunk. A header_mac failure means the wrong content key was supplied or the
93
- header has been tampered with.
94
+ For suites whose header MAC key is not derived from `suite_payload`
95
+ (currently `0x01` aes-gcm-v1, `0x02` xchacha-v1), readers MUST verify
96
+ `header_mac` before parsing `suite_payload` or any chunk. KEM suites
97
+ (currently `0x03` pq-hybrid-v1) verify `header_mac` after decapsulation
98
+ per their suite-specific decryption flow; see § "`0x03` — pq-hybrid"
99
+ below for the required ordering and security argument. A header_mac
100
+ failure means the wrong content key was supplied or the header has been
101
+ tampered with.
94
102
 
95
103
  ### Chunks
96
104
 
@@ -114,6 +122,11 @@ where:
114
122
  - `chunk_nonce` and `chunk_key` are defined per suite.
115
123
  - `aad` is a fixed-length 36 bytes (19 bytes domain string + 8 + 8 + 1).
116
124
 
125
+ Note: the AAD is exactly the 36 bytes defined above. Do not extend it.
126
+ Cross-file splice resistance is provided by the suite-specific
127
+ chunk-key and nonce-prefix derivations, which use `file_id` as HKDF
128
+ salt and IKM respectively.
129
+
117
130
  The plaintext input is:
118
131
 
119
132
  - For all chunks except the final: exactly `chunk_size` plaintext bytes.
@@ -144,9 +157,14 @@ suite_payload := wrapped_key (60 bytes) = AES-GCM-wrapped 32-byte content key
144
157
  - `chunk_key(content_key, file_id)` =
145
158
  `HKDF-SHA-256(ikm=content_key, salt=file_id, info="shieldfive/v1/aes-gcm/chunk-key", L=32)`
146
159
  - `chunk_nonce(file_id, i)` =
147
- `truncate12(HKDF-SHA-256(ikm=file_id, salt="", info="shieldfive/v1/aes-gcm/nonce-prefix", L=12))[0..3]`
160
+ `HKDF-SHA-256(ikm=file_id, salt=zeros(32), info="shieldfive/v1/aes-gcm/nonce-prefix", L=4)`
148
161
  `|| uint64_be(i)`
149
162
 
163
+ The salt is the RFC 5869 "absent salt" convention: a 32-byte all-zero
164
+ string (the SHA-256 output length). Implementations MUST use this
165
+ canonical form, even though HMAC-SHA-256 happens to produce an
166
+ identical HKDF-Extract output for any salt that zero-pads to 64 bytes.
167
+
150
168
  The nonce prefix is derived from `file_id` so that two files encrypted with
151
169
  the same content key (which never happens under correct use, but defense in
152
170
  depth) cannot collide on a `(prefix, counter)` pair.
@@ -154,11 +172,14 @@ depth) cannot collide on a `(prefix, counter)` pair.
154
172
  The wrapped content key is wrapped with the *parent envelope key* (folder
155
173
  key, vault key, etc.) using AES-256-GCM. This wrapping is OUT OF SCOPE for
156
174
  the on-disk file format and is the responsibility of the application's
157
- keyring module. The 60-byte field above is for files that choose to embed
158
- the wrapped key inline (e.g. exported files); files stored in the
159
- ShieldFive vault store the wrapped key in the database and set this field
160
- to 60 bytes of zero. Whether the field is inline or zero-filled is a deploy
161
- decision; either way the field length is fixed.
175
+ keyring module. The fields above are for files that choose to embed the
176
+ wrapped key inline (e.g. exported files). When the wrapped key is stored
177
+ out-of-band (e.g. in the ShieldFive vault database), all 72 bytes of
178
+ `suite_payload` (60-byte `wrapped_key` + 12-byte `wrap_iv`) are set to
179
+ zero. Readers MUST accept all-zero `suite_payload` bytes in this case
180
+ and obtain the wrapped key from the out-of-band channel. Whether the
181
+ field is inline or zero-filled is a deploy decision; either way the
182
+ field length is fixed at 72 bytes.
162
183
 
163
184
  ### `0x02` — `xchacha20-poly1305-v1`
164
185
 
@@ -170,12 +191,22 @@ suite_payload := wrapped_key (72 bytes) = secretbox-wrapped 32-byte content ke
170
191
  - `chunk_key(content_key, file_id)` =
171
192
  `HKDF-SHA-256(ikm=content_key, salt=file_id, info="shieldfive/v1/xchacha/chunk-key", L=32)`
172
193
  - `chunk_nonce(file_id, i)` =
173
- `truncate24(HKDF-SHA-256(ikm=file_id, salt="", info="shieldfive/v1/xchacha/nonce-prefix", L=24))[0..15]`
194
+ `HKDF-SHA-256(ikm=file_id, salt=zeros(32), info="shieldfive/v1/xchacha/nonce-prefix", L=16)`
174
195
  `|| uint64_be(i)`
175
196
 
197
+ Salt convention is the RFC 5869 absent-salt zero-fill (32 zero bytes),
198
+ identical to the AES-GCM suite above.
199
+
176
200
  XChaCha20's 24-byte nonce gives us a 16-byte random prefix and an 8-byte
177
201
  counter, which is structurally safer than AES-GCM's 4+8 split.
178
202
 
203
+ As with the AES-GCM suite, when the wrapped key is stored out-of-band
204
+ (e.g. in the ShieldFive vault database), all 96 bytes of `suite_payload`
205
+ (72-byte `wrapped_key` + 24-byte `wrap_nonce`) are set to zero. Readers
206
+ MUST accept all-zero `suite_payload` bytes in this case and obtain the
207
+ wrapped key from the out-of-band channel. The field length is fixed at
208
+ 96 bytes whether inline or zero-filled.
209
+
179
210
  ### `0x03` — `pq-hybrid-xchacha-mlkem1024-v1` (default)
180
211
 
181
212
  ```
@@ -212,11 +243,61 @@ Decryption:
212
243
  4. Reader verifies `header_mac` (which uses `K`).
213
244
  5. Reader processes chunks.
214
245
 
246
+ #### Security argument for pre-MAC decapsulation
247
+
248
+ The decapsulation in step 1 operates on unauthenticated
249
+ `mlkem_ciphertext` bytes — the header MAC cannot yet be verified at
250
+ that point, because the MAC key is the combined key K, which requires
251
+ both decapsulation and classical unwrap to compute. Safety of this
252
+ construction rests on three properties:
253
+
254
+ 1. **ML-KEM-1024 is IND-CCA2-secure** (FIPS 203). Decapsulation of
255
+ malformed or adversarial ciphertext does not leak the encapsulated
256
+ secret `S_pq` and does not leak the secret key `sk_pq`. An attacker
257
+ who modifies `mlkem_ciphertext` bytes obtains a different `S_pq`
258
+ (computationally indistinguishable from random under IND-CCA2), but
259
+ learns nothing about the underlying key material.
260
+
261
+ 2. **The classical share is wrapped with XSalsa20-Poly1305 secretbox.**
262
+ The unwrap in step 2 is an AEAD operation over attacker-influenced
263
+ `classical_wrapped` bytes. Any modification of those bytes causes
264
+ the secretbox tag check to fail, raising before plaintext is
265
+ produced. An attacker who modifies the classical share cannot
266
+ silently substitute a different `S_c`.
267
+
268
+ 3. **The recombined key K is verified via `header_mac`.** The
269
+ encryptor's `header_mac` is a valid HMAC-SHA-256 tag under the
270
+ encryptor's K over the encryptor's header bytes. An attacker who
271
+ modifies any bytes covered by the MAC (header fields,
272
+ `suite_payload`, or both) and whose modified inputs cause
273
+ decapsulation and classical unwrap to yield some K' would then
274
+ need to forge an HMAC-SHA-256 tag under K' over the modified
275
+ bytes — which contradicts HMAC's EUF-CMA security. Equivalently:
276
+ the only way to pass MAC verification under any K' is to leave
277
+ the MAC-covered bytes unchanged, in which case the encryption
278
+ succeeds against the unmodified ciphertext (not an attack).
279
+
280
+ An attacker modifying `suite_payload` bytes therefore either (a) gets a
281
+ different combined key K and fails `header_mac` verification, or (b)
282
+ fails at secretbox tag check during classical unwrap, or (c) learns
283
+ nothing under ML-KEM IND-CCA2. In no case is plaintext revealed.
284
+ Implementations MAY surface a distinct error for case (b) (secretbox
285
+ failure) versus case (a) (MAC failure) since case (b) is reachable with
286
+ smaller attacker effort and may be useful for telemetry; they MUST NOT
287
+ leak the value of K, S_c, or S_pq in any error path.
288
+
215
289
  This construction is IND-CCA2 against an adversary who breaks *either* the
216
290
  classical wrap *or* the PQ KEM, but not both. As long as one primitive
217
291
  remains secure, the file is secure. Under correct use, both must be broken
218
292
  to recover the plaintext.
219
293
 
294
+ Unlike the AES-GCM and XChaCha suites, the all-zero `suite_payload`
295
+ convention does NOT apply to PQ-hybrid: `mlkem_ciphertext` is part of
296
+ decryption (the PQ shared secret is recovered from it via
297
+ decapsulation) and therefore cannot be stored out-of-band. The full
298
+ 1664-byte `suite_payload` MUST be present inline in every PQ-hybrid
299
+ file.
300
+
220
301
  ## Versioning policy
221
302
 
222
303
  - **Format major version (4th byte of magic)** changes when the parser
@@ -238,6 +319,14 @@ by the absence of magic and by the presence of the database-stored
238
319
  `cipher_version = 1` flag. ShieldFive applications MUST be able to read
239
320
  v0 indefinitely; v0 writes are deprecated and SHOULD be migrated to v1.
240
321
 
322
+ v0 and v1 cannot be silently confused in either direction. A v1 blob fed
323
+ to the v0 reader fails AES-GCM authentication on chunk 0 (the v1
324
+ magic/suite/file_id bytes do not form a valid GCM tag). A v0 blob fed to
325
+ `parseHeader` fails the magic-byte check with probability `1 - 2^-40`
326
+ per file. Application dispatchers MUST route by an explicit version
327
+ field (e.g. a database column) and MUST NOT auto-detect across formats.
328
+ The library does not expose cross-format auto-detection.
329
+
241
330
  ## Test vectors
242
331
 
243
332
  Implementations MUST produce identical bit-for-bit output for the test
@@ -22,8 +22,16 @@ Everything below is a deterministic function of this secret.
22
22
  ## Derivation tree
23
23
 
24
24
  All derivations are HKDF-SHA-256. The `info` string is a printable
25
- domain separator. Salt is empty unless otherwise stated. Keys are 32 bytes
26
- unless otherwise stated.
25
+ domain separator. When the salt is omitted in the definitions below,
26
+ its canonical form is `zeros(32)` per RFC 5869's "absent salt"
27
+ convention (a string of `HashLen` zero octets, where `HashLen = 32` for
28
+ SHA-256). Implementations MUST use this form; under HMAC-SHA-256 a
29
+ zero-length salt yields the same HKDF-Extract output because HMAC
30
+ zero-pads short keys to its 64-byte block size, but the canonical form
31
+ is required so that cross-implementation test vectors pin a single
32
+ shape. Keys are 32 bytes unless otherwise stated. Test vectors for the
33
+ nonce-prefix absent-salt derivation are at `tests/vectors/vectors.json`
34
+ (group `09_nonce_prefix_absent_salt`).
27
35
 
28
36
  ```
29
37
  master_secret
@@ -36,6 +44,17 @@ master_secret
36
44
  └── (ml_kem_pk, ml_kem_sk) = ML-KEM-1024.KeyGen(ml_kem_seed)
37
45
  ```
38
46
 
47
+ The 64-byte `ml_kem_seed` is split into `d = ml_kem_seed[0..32]` and
48
+ `z = ml_kem_seed[32..64]`, with `d` consumed as ML-KEM-1024.KeyGen's
49
+ random-coins input (FIPS 203 § Algorithm 16, parameter `d`) and `z`
50
+ stored as the implicit-rejection seed (FIPS 203 § Algorithm 17,
51
+ parameter `z`). Implementers using a library whose API exposes a
52
+ combined-seed form `KeyGen(seed)` (e.g., @noble/post-quantum) typically
53
+ follow this same convention, but MUST verify against the deterministic
54
+ test vectors below. Implementers using a library that exposes
55
+ `KeyGen(d, z)` separately MUST split the seed exactly as specified
56
+ here.
57
+
39
58
  The function `deriveMlKemKeypair(masterSecret)` exported from
40
59
  `@shieldfive/crypto/pq-hybrid-v1` performs the seed derivation and the
41
60
  ML-KEM keygen step in one call.
@@ -79,11 +98,20 @@ iv / nonce_i = nonce_prefix || uint64_be(chunk_index)
79
98
 
80
99
  For the PQ-hybrid suite, `content_key` is replaced by the combined key
81
100
  `K = HKDF(classical_share || pq_share, salt=file_id,
82
- info="shieldfive/v1/pq-hybrid/combine")`.
101
+ info="shieldfive/v1/pq-hybrid/combine", L=32)`. The chunk-key and
102
+ nonce-prefix derivations are then identical to the XChaCha suite's,
103
+ with `K` in the role of `content_key` and the same info strings
104
+ (`shieldfive/v1/xchacha/chunk-key` and
105
+ `shieldfive/v1/xchacha/nonce-prefix`). Reuse of those info strings
106
+ across the two suites is safe because the IKM space is partitioned:
107
+ XChaCha uses a fresh random `content_key` per file, PQ-hybrid uses the
108
+ file-bound HKDF output `K`. Both are 32 bytes of uniformly random or
109
+ pseudorandom material per file; cross-suite output collision
110
+ probability is `2^-256`.
83
111
 
84
112
  ## Forbidden cross-context usage
85
113
 
86
- These domain strings are consumed *only* by the crypto layer. The host
114
+ These domain strings are consumed by the crypto layer. The host
87
115
  application MUST NOT reuse any of them for unrelated purposes:
88
116
 
89
117
  ```
@@ -94,10 +122,27 @@ shieldfive/v1/xchacha/chunk-key
94
122
  shieldfive/v1/xchacha/nonce-prefix
95
123
  shieldfive/v1/pq-hybrid/combine
96
124
  shieldfive/v1/pq-hybrid/ml-kem-1024-seed
125
+ shieldfive/v1/argon2id/salt-compression
126
+ ```
127
+
128
+ ### Reserved for future use
129
+
130
+ These strings are reserved by this specification but are NOT yet
131
+ consumed by the reference implementation. They MUST NOT be reused by
132
+ host applications for unrelated purposes, since a future minor
133
+ revision of this spec may begin consuming them:
134
+
135
+ ```
97
136
  shieldfive/v1/envelope-key
98
137
  shieldfive/v1/metadata-key
99
138
  ```
100
139
 
140
+ Interpretation note: the forbidden-list framing above scopes to
141
+ strings the library actually consumes today. The two entries here are
142
+ spec-only reservations carried over from the derivation tree, kept
143
+ separate so the forbidden list can be cross-checked against
144
+ `HKDF_INFO` in `src/internal/types.ts` without phantom entries.
145
+
101
146
  If the host application needs a new derived key, it MUST use a fresh
102
147
  domain string of the form `<application>/<version>/<purpose>` to ensure
103
148
  domain separation from this library's keys.
@@ -31,6 +31,13 @@ A1 cannot recover:
31
31
  Sits between the client and the server. Can drop, reorder, replay, or
32
32
  modify any byte. Cannot break TLS.
33
33
 
34
+ TLS is terminated at the edge platform (Vercel/Cloudflare) and a fresh
35
+ TLS session is used to talk to Supabase and B2. The AEAD layer is
36
+ end-to-end client-to-blob, so an attacker controlling the TLS
37
+ termination is effectively A1 (sees ciphertext, not plaintext). A2's
38
+ "cannot break TLS" is therefore a statement about the client↔edge leg
39
+ specifically.
40
+
34
41
  A2 cannot:
35
42
 
36
43
  - Recover plaintext (TLS + AEAD).
@@ -38,7 +45,27 @@ A2 cannot:
38
45
  authentication).
39
46
  - **Truncate a file undetectably** (final-chunk AAD `is_final` flag).
40
47
  - **Reorder chunks undetectably** (chunk-index AAD).
41
- - **Splice chunks across files** (file_id AAD).
48
+ - **Splice chunks across files** (chunk_key and nonce_prefix are
49
+ derived from file_id via HKDF; see
50
+ [`format-v1.md` § "Suite payloads"](./format-v1.md#suite-payloads)
51
+ for each suite's derivations. file_id is NOT in chunk AAD; the
52
+ binding is structural — see
53
+ [crypto PR #1](https://github.com/shieldfive/crypto/pull/1) for the
54
+ test vector pinning this behavior).
55
+
56
+ #### Legacy v0 data
57
+
58
+ Files encrypted with the v0 wire format (predating this specification —
59
+ see
60
+ [`format-v0.md` § "Limitations of v0"](./format-v0.md#limitations-of-v0-addressed-in-v1))
61
+ do NOT carry the AEAD-bound integrity properties above. Specifically,
62
+ v0 files have no chunk AAD, no `file_id` binding, and no truncation
63
+ detection. Defense-in-depth for v0 files relies on the application's
64
+ stored per-chunk SHA-1 hashes (`cipher_parts_sha1`), verified on
65
+ download. Migration to v1 is required to gain the AEAD-bound integrity
66
+ properties documented above. As of 2026-05-11, the v1 writer is
67
+ enabled but most live data is still v0; migration policy and timeline
68
+ are tracked separately.
42
69
 
43
70
  ### A3 — Future quantum adversary
44
71
 
@@ -54,11 +81,45 @@ A3 cannot recover plaintext from files encrypted with suite `0x03`
54
81
  - XChaCha20-Poly1305 (256-bit key, 128-bit security against Grover-like
55
82
  speedups).
56
83
 
57
- A3 *can* recover plaintext from files encrypted with classical-only suites
84
+ A3 _can_ recover plaintext from files encrypted with classical-only suites
58
85
  (`0x01`, `0x02`) once Shor-feasible quantum computers exist. Files
59
86
  encrypted with classical-only suites SHOULD be re-encrypted with the
60
87
  hybrid suite when migration is feasible.
61
88
 
89
+ #### Current deployment status
90
+
91
+ As of 2026-05-11, the production web client emits suite `0x01`
92
+ (`aes-256-gcm-v1`) for new uploads. Suite `0x03`
93
+ (`pq-hybrid-xchacha-mlkem1024-v1`) is implemented in the
94
+ `@shieldfive/crypto` library but is not yet wired into the web worker;
95
+ until Phase 3 ships, all newly-uploaded files are classical-only and
96
+ are NOT protected against A3. This document will be updated when
97
+ `0x03` becomes the default writer suite.
98
+
99
+ ## Trust principals
100
+
101
+ ### Share-link recipient
102
+
103
+ A third party in possession of a share URL and the share password is
104
+ given decrypt authority for exactly one file. Their reach is bounded
105
+ by:
106
+
107
+ - **One file.** Each share is scoped to a single `file_id`; share URLs
108
+ do not enumerate folder contents or sibling files.
109
+ - **Bounded downloads.** `share_max_downloads` is enforced atomically.
110
+ - **Optional geo-lock and expiry.** Per-share allowed countries and
111
+ expiry timestamp.
112
+ - **No key reach.** The share endpoint never returns `rk`, parent
113
+ folder keys, or other CSKs.
114
+ - **Brute force.** Bcrypt-wrapped `share_password_hash` is rate
115
+ limited per-share, per-IP, and per-burst; lockout state is tracked
116
+ in `share_password_attempts` (Task 7).
117
+
118
+ The recipient is a trusted third party for the single file shared; the
119
+ system makes no confidentiality guarantee against that recipient.
120
+ Confidentiality against A1 is unaffected (the server doesn't have the
121
+ share password in cleartext; it has only the bcrypt hash).
122
+
62
123
  ## Out of scope
63
124
 
64
125
  This crypto layer does not protect against:
@@ -79,10 +140,16 @@ recorders, and keyloggers all see plaintext. The crypto layer cannot help.
79
140
 
80
141
  ### Metadata leakage at the storage layer
81
142
 
82
- File sizes, upload patterns, access timestamps, and folder cardinality are
83
- visible to anyone with database access. This crypto layer encrypts file
84
- *content* and *names*; it does not pad sizes or randomize upload timing.
85
- Applications requiring metadata protection beyond name encryption must
143
+ A non-exhaustive list of metadata visible to anyone with database
144
+ access: file sizes, upload timestamps, access timestamps, folder
145
+ cardinality, deterministic per-user filename hashes (HMAC-SHA-256
146
+ keyed by a per-user secret), per-share viewer geography and per-share
147
+ hashed IP (HMAC-SHA-256 under a server secret), per-share lockout
148
+ state and download counts, per-file owner download counts, and
149
+ aggregate storage usage timestamps. The crypto layer encrypts file
150
+ content and the ciphertext form of filenames; it does not encrypt
151
+ access logs, search-hash material, or share metrics. Applications
152
+ requiring metadata protection beyond filename-content secrecy must
86
153
  build it on top.
87
154
 
88
155
  ### Side channels in WebCrypto / WASM
@@ -97,15 +164,30 @@ underlying browser/runtime.
97
164
  If the user loses their master password and there is no recovery key, the
98
165
  data is unrecoverable. This is a feature.
99
166
 
167
+ ### Recovery-key compromise
168
+
169
+ The recovery key is a 32-byte random value generated client-side at
170
+ signup and shown to the user exactly once (regeneration is supported
171
+ via in-app UI). Possession of the recovery key is functionally
172
+ equivalent to knowing the password — it unwraps the same `rk` via a
173
+ different wrapping key. The threat model treats recovery-key theft as
174
+ out of scope (the host application's recovery-key UX, Task 19, is
175
+ responsible for guiding users to a secure backup channel);
176
+ confidentiality against A1 still holds for users who back the recovery
177
+ key up to a non-leaked location. If a user backs the recovery key up
178
+ to a leaked location (email plaintext, screenshot in cloud-synced
179
+ photos, paper in an insecure environment), an attacker reaching that
180
+ backup obtains the same access as the user.
181
+
100
182
  ## Comparison with comparable products
101
183
 
102
- | Product | File AEAD | PQ | Truncation detection | Format self-describing |
103
- | ------------- | ------------------------------ | ------------------------ | ------------------------- | ---------------------- |
104
- | Proton Drive | AES-256-GCM (chunked) | None (as of audit dates) | Application layer only | No (DB-side metadata) |
105
- | Internxt | AES-256-CTR + Kyber-512 hybrid | Kyber-512 (≈AES-128 PQ) | N/A (CTR is unauthenticated; integrity layered) | Partial |
106
- | MEGA | AES-128-CCM, Ed25519 sigs | None | Application layer | Partial |
107
- | Tresorit | AES-256-GCM, ECC | None (as of public docs) | Application layer | Proprietary |
108
- | **ShieldFive (v1, suite 0x03)** | **XChaCha20-Poly1305 + ML-KEM-1024 hybrid** | **ML-KEM-1024 (≈AES-256 PQ)** | **AEAD-bound** | **Yes** |
184
+ | Product | File AEAD | PQ | Truncation detection | Format self-describing |
185
+ | -------------------------------- | ------------------------------------------- | ----------------------------- | ----------------------------------------------- | ---------------------- |
186
+ | Proton Drive | AES-256-GCM (chunked) | None (as of audit dates) | Application layer only | No (DB-side metadata) |
187
+ | Internxt | AES-256-CTR + Kyber-512 hybrid | Kyber-512 (≈AES-128 PQ) | N/A (CTR is unauthenticated; integrity layered) | Partial |
188
+ | MEGA | AES-128-CCM, Ed25519 sigs | None | Application layer | Partial |
189
+ | Tresorit | AES-256-GCM, ECC | None (as of public docs) | Application layer | Proprietary |
190
+ | **ShieldFive (v1, suite 0x03)†** | **XChaCha20-Poly1305 + ML-KEM-1024 hybrid** | **ML-KEM-1024 (≈AES-256 PQ)** | **AEAD-bound** | **Yes** |
109
191
 
110
192
  This table reflects publicly available specifications and audit reports as
111
193
  of the v1 specification date. It is updated when those specifications
@@ -113,6 +195,10 @@ change. This is not a security claim about which product is "best" — each
113
195
  makes different tradeoffs — but it documents the design positions ShieldFive
114
196
  v1 takes deliberately.
115
197
 
198
+ † Suite `0x03` is available in the crypto library (1.0.0-alpha.3) and
199
+ is the format-v1 spec default; the production web client has not yet
200
+ been updated to emit it. See § "Current deployment status" under A3.
201
+
116
202
  ## Known limitations of v1
117
203
 
118
204
  These are intentional tradeoffs documented for transparency:
@@ -104,6 +104,19 @@ export async function buildAuthenticatedHeader(
104
104
  *
105
105
  * Two-phase parse-then-verify keeps the parser usable for tooling that
106
106
  * inspects encrypted files without holding the key.
107
+ *
108
+ * parseHeader does not verify the header MAC. For non-KEM suites
109
+ * (0x01 aes-gcm-v1, 0x02 xchacha-v1), callers MUST call
110
+ * verifyHeaderMac BEFORE doing anything with parsed.suitePayload,
111
+ * including length checks, field extraction, or downstream parsing.
112
+ * KEM suites (0x03 pq-hybrid-v1) cannot follow this rule by
113
+ * construction; see spec/format-v1.md § "0x03 — pq-hybrid" for the
114
+ * required ordering and security argument.
115
+ *
116
+ * Cross-field consistency (totalChunks / chunkSize / plaintextSize) is
117
+ * enforced here via `assertHeaderConsistency`. The same helper runs in
118
+ * `validateHeaderInputs` so encode and decode share one source of
119
+ * truth; both paths MUST stay in sync.
107
120
  */
108
121
  export function parseHeader(input: Uint8Array): ParsedHeader & {
109
122
  unauthenticatedBytes: Uint8Array
@@ -152,17 +165,7 @@ export function parseHeader(input: Uint8Array): ParsedHeader & {
152
165
  const plaintextSize = readUint64BE(input, offset)
153
166
  offset += HEADER_SIZES.PLAINTEXT_SIZE
154
167
 
155
- // Cross-field consistency: total_chunks must match plaintextSize / chunkSize
156
- if (totalChunks === 0 && plaintextSize !== 0) {
157
- throw new HeaderError('total_chunks_zero_with_plaintext')
158
- }
159
- if (totalChunks > 0) {
160
- const minPlaintext = (totalChunks - 1) * chunkSize + 1
161
- const maxPlaintext = totalChunks * chunkSize
162
- if (plaintextSize < minPlaintext || plaintextSize > maxPlaintext) {
163
- throw new HeaderError('plaintext_size_inconsistent')
164
- }
165
- }
168
+ assertHeaderConsistency({ chunkSize, totalChunks, plaintextSize })
166
169
 
167
170
  const suitePayloadLen = readUint16BE(input, offset)
168
171
  offset += HEADER_SIZES.SUITE_PAYLOAD_LEN
@@ -271,6 +274,35 @@ function validateHeaderInputs(input: HeaderInputs): void {
271
274
  if (input.suitePayload.length > 0xffff) {
272
275
  throw new HeaderError('suite_payload_too_large')
273
276
  }
277
+ assertHeaderConsistency({
278
+ chunkSize: input.chunkSize,
279
+ totalChunks: input.totalChunks,
280
+ plaintextSize: input.plaintextSize,
281
+ })
282
+ }
283
+
284
+ /**
285
+ * Assert the cross-field invariant tying total_chunks, chunk_size, and
286
+ * plaintext_size together. Shared by `parseHeader` (decode path) and
287
+ * `validateHeaderInputs` (encode path) so both layers reject the same
288
+ * malformed combinations with the same error codes.
289
+ */
290
+ function assertHeaderConsistency(fields: {
291
+ chunkSize: number
292
+ totalChunks: number
293
+ plaintextSize: number
294
+ }): void {
295
+ const { chunkSize, totalChunks, plaintextSize } = fields
296
+ if (totalChunks === 0 && plaintextSize !== 0) {
297
+ throw new HeaderError('total_chunks_zero_with_plaintext')
298
+ }
299
+ if (totalChunks > 0) {
300
+ const minPlaintext = (totalChunks - 1) * chunkSize + 1
301
+ const maxPlaintext = totalChunks * chunkSize
302
+ if (plaintextSize < minPlaintext || plaintextSize > maxPlaintext) {
303
+ throw new HeaderError('plaintext_size_inconsistent')
304
+ }
305
+ }
274
306
  }
275
307
 
276
308
  /** Recognizable error class so callers can catch parse failures specifically */
package/src/index.ts CHANGED
@@ -191,7 +191,7 @@ export async function autoDecryptBlob(
191
191
  }
192
192
 
193
193
  /** Library version, also written into format documentation. */
194
- export const SHIELDFIVE_CRYPTO_VERSION = '1.0.0-alpha.2'
194
+ export const SHIELDFIVE_CRYPTO_VERSION = '1.0.0-alpha.3'
195
195
 
196
196
  /** Default cipher suite for new files when not specified by the caller. */
197
197
  export const DEFAULT_SUITE = SUITE.PQ_HYBRID_XCHACHA_MLKEM1024_V1
@@ -83,6 +83,8 @@ export const HKDF_INFO = Object.freeze({
83
83
  XCHACHA_CHUNK_KEY: 'shieldfive/v1/xchacha/chunk-key',
84
84
  XCHACHA_NONCE_PREFIX: 'shieldfive/v1/xchacha/nonce-prefix',
85
85
  PQ_HYBRID_COMBINE: 'shieldfive/v1/pq-hybrid/combine',
86
+ ML_KEM_1024_SEED: 'shieldfive/v1/pq-hybrid/ml-kem-1024-seed',
87
+ ARGON2ID_SALT_COMPRESSION: 'shieldfive/v1/argon2id/salt-compression',
86
88
  })
87
89
 
88
90
  /** AAD domain string mixed into every chunk's authenticator */
@@ -13,6 +13,7 @@
13
13
  import { getSodium } from '../internal/sodium.js'
14
14
  import { hkdfSha256 } from '../internal/hkdf.js'
15
15
  import { randomBytes } from '../internal/runtime.js'
16
+ import { HKDF_INFO } from '../internal/types.js'
16
17
 
17
18
  /**
18
19
  * Argon2id parameter presets.
@@ -103,7 +104,7 @@ export async function deriveMasterSecret(
103
104
  if (salt.length > ARGON2ID_SALT_BYTES) {
104
105
  usableSalt = await hkdfSha256({
105
106
  ikm: salt,
106
- info: 'shieldfive/v1/argon2id/salt-compression',
107
+ info: HKDF_INFO.ARGON2ID_SALT_COMPRESSION,
107
108
  length: ARGON2ID_SALT_BYTES,
108
109
  })
109
110
  }