@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,242 @@
1
+ # ShieldFive Crypto Threat Model
2
+
3
+ This document scopes what the v1 format protects against, what it does not,
4
+ and how it differs from comparable products.
5
+
6
+ ## Adversary model
7
+
8
+ We model three adversaries:
9
+
10
+ ### A1 — Honest-but-curious server
11
+
12
+ Has full access to the storage backend, the application database, network
13
+ logs, and the deployed application server. Cannot modify the client code
14
+ delivered to the user's browser. Cannot compromise the user's device.
15
+
16
+ A1 can observe:
17
+
18
+ - All ciphertext.
19
+ - File sizes, upload timestamps, IP addresses, account identifiers.
20
+ - Encrypted metadata payloads.
21
+ - Folder/file structural relationships.
22
+
23
+ A1 cannot recover:
24
+
25
+ - Plaintext file content.
26
+ - Unwrapped content keys.
27
+ - Plaintext filenames or folder names protected by the metadata layer.
28
+
29
+ ### A2 — Active network adversary
30
+
31
+ Sits between the client and the server. Can drop, reorder, replay, or
32
+ modify any byte. Cannot break TLS.
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
+
41
+ A2 cannot:
42
+
43
+ - Recover plaintext (TLS + AEAD).
44
+ - Inject ciphertext that decrypts to attacker-chosen plaintext (AEAD
45
+ authentication).
46
+ - **Truncate a file undetectably** (final-chunk AAD `is_final` flag).
47
+ - **Reorder chunks undetectably** (chunk-index 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/commit/f3f52ba) 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.
69
+
70
+ ### A3 — Future quantum adversary
71
+
72
+ Holds today's ciphertext. Eventually obtains a cryptographically relevant
73
+ quantum computer. Wants to recover plaintext from "harvest now, decrypt
74
+ later" attacks.
75
+
76
+ A3 cannot recover plaintext from files encrypted with suite `0x03`
77
+ (`pq-hybrid-xchacha-mlkem1024-v1`) unless they break **both**:
78
+
79
+ - ML-KEM-1024 (NIST PQC standard, security level 5, equivalent to AES-256
80
+ against quantum search), AND
81
+ - XChaCha20-Poly1305 (256-bit key, 128-bit security against Grover-like
82
+ speedups).
83
+
84
+ A3 _can_ recover plaintext from files encrypted with classical-only suites
85
+ (`0x01`, `0x02`) once Shor-feasible quantum computers exist. Files
86
+ encrypted with classical-only suites SHOULD be re-encrypted with the
87
+ hybrid suite when migration is feasible.
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
+
123
+ ## Out of scope
124
+
125
+ This crypto layer does not protect against:
126
+
127
+ ### Malicious client delivery
128
+
129
+ If the application server delivers a backdoored JavaScript bundle to the
130
+ user's browser, that bundle can capture the password before encryption
131
+ happens. The crypto library cannot detect this. Reproducible builds and
132
+ client integrity verification (Subresource Integrity, signed
133
+ extensions, audited desktop builds) are required to address this and are
134
+ the responsibility of the host application, not the crypto layer.
135
+
136
+ ### Endpoint compromise
137
+
138
+ Malware on the user's device, malicious browser extensions, screen
139
+ recorders, and keyloggers all see plaintext. The crypto layer cannot help.
140
+
141
+ ### Metadata leakage at the storage layer
142
+
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
153
+ build it on top.
154
+
155
+ ### Side channels in WebCrypto / WASM
156
+
157
+ Browsers' AES-GCM implementations are typically constant-time on hardware
158
+ with AES-NI. WASM-based ChaCha20 is constant-time by construction. We do
159
+ not defend against power analysis or fault injection attacks against the
160
+ underlying browser/runtime.
161
+
162
+ ### User key loss
163
+
164
+ If the user loses their master password and there is no recovery key, the
165
+ data is unrecoverable. This is a feature.
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
+
182
+ ## Comparison with comparable products
183
+
184
+ | Product | File AEAD | PQ | Truncation detection | Format self-describing |
185
+ | -------------------------------- | ------------------------------------------- | ----------------------------- | ----------------------------------------------- | ---------------------- |
186
+ | Proton Drive | AES-256-GCM (chunked) | Proton Mail (sibling product) added optional PQ via OpenPGP v6 in May 2026; Proton Drive's on-disk format had not adopted PQ as of 2026-05-18 | 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** |
191
+
192
+ This table reflects publicly available specifications and audit reports as
193
+ of 2026-05-18 (last access date). It is updated when those specifications
194
+ change — for example, Proton Mail (sibling product to Proton Drive)
195
+ launched optional post-quantum encryption via OpenPGP v6 in May 2026
196
+ (proton.me/blog/introducing-post-quantum-encryption); the Proton Drive
197
+ on-disk wire format had not adopted PQ as of the access date. This is not
198
+ a security claim about which product is "best" — each makes different
199
+ tradeoffs — but it documents the design positions ShieldFive v1 takes
200
+ deliberately.
201
+
202
+ † Suite `0x03` is available in the crypto library (1.0.0-alpha.3) and
203
+ is the format-v1 spec default; the production web client has not yet
204
+ been updated to emit it. See § "Current deployment status" under A3.
205
+
206
+ ## Known limitations of v1
207
+
208
+ These are intentional tradeoffs documented for transparency:
209
+
210
+ 1. **Per-file random nonce prefix is derived, not stored.** Under correct
211
+ use this is safer (no risk of replay due to RNG failure during write).
212
+ Under incorrect use (key reuse across files), it offers no defense
213
+ beyond what AES-GCM/XChaCha already provide. This is acceptable because
214
+ the crypto layer enforces fresh per-file content keys.
215
+
216
+ 2. **No padding for size obfuscation.** A 5MB ciphertext implies a ~5MB
217
+ plaintext (within chunk granularity). Applications wanting size privacy
218
+ must pad at a higher layer. v2 may introduce optional plaintext padding.
219
+
220
+ 3. **No traffic analysis resistance.** Upload/download timing is observable
221
+ to the storage server. This is out of scope.
222
+
223
+ 4. **HMAC-SHA-256 for header authentication, not Poly1305.** Chosen because
224
+ HMAC-SHA-256 is universally available in WebCrypto without WASM. The
225
+ security claim is unchanged: 128-bit MAC strength.
226
+
227
+ 5. **ML-KEM keys are derived deterministically from user master secret.**
228
+ This is an availability tradeoff — the user does not need to back up a
229
+ separate PQ keypair. The cost is that ML-KEM key generation is
230
+ deterministic with respect to the master secret, which means a future
231
+ weakness in the deterministic seed expansion (HKDF-SHA-256) propagates
232
+ to PQ key generation. We accept this because (a) HKDF is conservative,
233
+ (b) the alternative is requiring users to back up PQ keys separately,
234
+ which has a worse failure mode (data loss).
235
+
236
+ ## Reporting
237
+
238
+ Cryptographic vulnerabilities should be reported to
239
+ `security@shieldfive.com` encrypted with the PGP key in `SECURITY.md`. We
240
+ acknowledge within 72 hours and target a patch within 30 days for
241
+ high-severity issues. Researchers acting in good faith are protected under
242
+ the safe-harbor clause in `SECURITY.md`.
@@ -0,0 +1,316 @@
1
+ /**
2
+ * v1 header builder and parser.
3
+ *
4
+ * The header is constructed without the MAC, then the MAC is computed
5
+ * with the content key, then the MAC is appended. On decode, the parser
6
+ * reads everything up to (but not including) the MAC, then the caller
7
+ * verifies the MAC before trusting any field.
8
+ */
9
+
10
+ import {
11
+ CHUNK_AAD_DOMAIN,
12
+ CHUNK_AAD_LENGTH,
13
+ FORMAT_MAGIC,
14
+ FORMAT_MAGIC_LENGTH,
15
+ HEADER_FIXED_PREFIX_LENGTH,
16
+ HEADER_SIZES,
17
+ HKDF_INFO,
18
+ MAX_CHUNK_SIZE,
19
+ MAX_TOTAL_CHUNKS,
20
+ type ParsedHeader,
21
+ SUITE,
22
+ type SuiteId,
23
+ } from '../internal/types.js'
24
+ import {
25
+ concatBytes,
26
+ readUint16BE,
27
+ readUint32BE,
28
+ readUint64BE,
29
+ uint16BE,
30
+ uint32BE,
31
+ uint64BE,
32
+ } from '../internal/encoding.js'
33
+ import { hkdfSha256 } from '../internal/hkdf.js'
34
+ import { hmacSha256, hmacSha256Verify } from '../internal/hmac.js'
35
+
36
+ const TEXT_ENCODER = new TextEncoder()
37
+ const CHUNK_AAD_DOMAIN_BYTES = TEXT_ENCODER.encode(CHUNK_AAD_DOMAIN)
38
+
39
+ const VALID_SUITES = new Set<number>(Object.values(SUITE))
40
+
41
+ export interface HeaderInputs {
42
+ suite: SuiteId
43
+ fileId: Uint8Array
44
+ chunkSize: number
45
+ totalChunks: number
46
+ plaintextSize: number
47
+ suitePayload: Uint8Array
48
+ }
49
+
50
+ /**
51
+ * Build the unauthenticated header bytes (everything before the MAC).
52
+ * The caller appends the MAC after deriving header_mac_key.
53
+ */
54
+ export function buildHeaderUnauthenticated(input: HeaderInputs): Uint8Array {
55
+ validateHeaderInputs(input)
56
+ return concatBytes([
57
+ FORMAT_MAGIC,
58
+ new Uint8Array([input.suite]),
59
+ new Uint8Array([0x00]), // flags reserved
60
+ input.fileId,
61
+ uint32BE(input.chunkSize),
62
+ uint64BE(input.totalChunks),
63
+ uint64BE(input.plaintextSize),
64
+ uint16BE(input.suitePayload.length),
65
+ input.suitePayload,
66
+ ])
67
+ }
68
+
69
+ /**
70
+ * Derive the per-file header MAC key from the content key + file_id.
71
+ */
72
+ export async function deriveHeaderMacKey(
73
+ contentKey: Uint8Array,
74
+ fileId: Uint8Array,
75
+ ): Promise<Uint8Array> {
76
+ return hkdfSha256({
77
+ ikm: contentKey,
78
+ salt: fileId,
79
+ info: HKDF_INFO.HEADER_MAC,
80
+ length: 32,
81
+ })
82
+ }
83
+
84
+ /**
85
+ * Build a complete authenticated header. `contentKey` is the suite-specific
86
+ * key used to authenticate the header. For the PQ-hybrid suite this is the
87
+ * combined key K (post-HKDF); for AES-GCM and XChaCha suites this is the
88
+ * raw 32-byte content key.
89
+ */
90
+ export async function buildAuthenticatedHeader(
91
+ input: HeaderInputs,
92
+ contentKey: Uint8Array,
93
+ ): Promise<Uint8Array> {
94
+ const unauthenticated = buildHeaderUnauthenticated(input)
95
+ const macKey = await deriveHeaderMacKey(contentKey, input.fileId)
96
+ const mac = await hmacSha256(macKey, unauthenticated)
97
+ return concatBytes([unauthenticated, mac])
98
+ }
99
+
100
+ /**
101
+ * Parse a header from a byte slice. Returns the parsed fields and the
102
+ * total bytes consumed. Does NOT verify the MAC — callers must call
103
+ * `verifyHeaderMac` separately, after deriving the key.
104
+ *
105
+ * Two-phase parse-then-verify keeps the parser usable for tooling that
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.
120
+ */
121
+ export function parseHeader(input: Uint8Array): ParsedHeader & {
122
+ unauthenticatedBytes: Uint8Array
123
+ mac: Uint8Array
124
+ } {
125
+ if (input.length < HEADER_FIXED_PREFIX_LENGTH + HEADER_SIZES.HEADER_MAC) {
126
+ throw new HeaderError('header_too_short')
127
+ }
128
+
129
+ // Magic
130
+ for (let i = 0; i < FORMAT_MAGIC_LENGTH; i += 1) {
131
+ if (input[i] !== FORMAT_MAGIC[i]) {
132
+ throw new HeaderError('bad_magic')
133
+ }
134
+ }
135
+
136
+ let offset = FORMAT_MAGIC_LENGTH
137
+
138
+ const suite = input[offset]!
139
+ offset += HEADER_SIZES.SUITE
140
+ if (!VALID_SUITES.has(suite)) {
141
+ throw new HeaderError('unknown_suite')
142
+ }
143
+
144
+ const flags = input[offset]!
145
+ offset += HEADER_SIZES.FLAGS
146
+ if (flags !== 0x00) {
147
+ throw new HeaderError('reserved_flags_set')
148
+ }
149
+
150
+ const fileId = input.slice(offset, offset + HEADER_SIZES.FILE_ID)
151
+ offset += HEADER_SIZES.FILE_ID
152
+
153
+ const chunkSize = readUint32BE(input, offset)
154
+ offset += HEADER_SIZES.CHUNK_SIZE
155
+ if (chunkSize === 0 || chunkSize > MAX_CHUNK_SIZE) {
156
+ throw new HeaderError('chunk_size_out_of_range')
157
+ }
158
+
159
+ const totalChunks = readUint64BE(input, offset)
160
+ offset += HEADER_SIZES.TOTAL_CHUNKS
161
+ if (totalChunks > MAX_TOTAL_CHUNKS) {
162
+ throw new HeaderError('total_chunks_out_of_range')
163
+ }
164
+
165
+ const plaintextSize = readUint64BE(input, offset)
166
+ offset += HEADER_SIZES.PLAINTEXT_SIZE
167
+
168
+ assertHeaderConsistency({ chunkSize, totalChunks, plaintextSize })
169
+
170
+ const suitePayloadLen = readUint16BE(input, offset)
171
+ offset += HEADER_SIZES.SUITE_PAYLOAD_LEN
172
+
173
+ if (offset + suitePayloadLen + HEADER_SIZES.HEADER_MAC > input.length) {
174
+ throw new HeaderError('header_truncated')
175
+ }
176
+
177
+ const suitePayload = input.slice(offset, offset + suitePayloadLen)
178
+ offset += suitePayloadLen
179
+
180
+ const macStart = offset
181
+ const mac = input.slice(macStart, macStart + HEADER_SIZES.HEADER_MAC)
182
+ offset += HEADER_SIZES.HEADER_MAC
183
+
184
+ const unauthenticatedBytes = input.slice(0, macStart)
185
+
186
+ return {
187
+ suite: suite as SuiteId,
188
+ flags,
189
+ fileId,
190
+ chunkSize,
191
+ totalChunks,
192
+ plaintextSize,
193
+ suitePayload,
194
+ headerLength: offset,
195
+ unauthenticatedBytes,
196
+ mac,
197
+ }
198
+ }
199
+
200
+ /**
201
+ * Verify the parsed header's MAC under the supplied content key.
202
+ * Throws on failure; returns the parsed header on success.
203
+ */
204
+ export async function verifyHeaderMac(
205
+ parsed: ReturnType<typeof parseHeader>,
206
+ contentKey: Uint8Array,
207
+ ): Promise<void> {
208
+ const macKey = await deriveHeaderMacKey(contentKey, parsed.fileId)
209
+ const ok = await hmacSha256Verify(
210
+ macKey,
211
+ parsed.unauthenticatedBytes,
212
+ parsed.mac,
213
+ )
214
+ if (!ok) {
215
+ throw new HeaderError('header_mac_mismatch')
216
+ }
217
+ }
218
+
219
+ /**
220
+ * Build the AAD bound into every chunk's AEAD: domain || index || total || is_final.
221
+ */
222
+ export function buildChunkAad(
223
+ chunkIndex: number,
224
+ totalChunks: number,
225
+ isFinal: boolean,
226
+ ): Uint8Array {
227
+ if (!Number.isSafeInteger(chunkIndex) || chunkIndex < 0) {
228
+ throw new RangeError('buildChunkAad: chunkIndex out of range')
229
+ }
230
+ if (!Number.isSafeInteger(totalChunks) || totalChunks < 0) {
231
+ throw new RangeError('buildChunkAad: totalChunks out of range')
232
+ }
233
+ const out = new Uint8Array(CHUNK_AAD_LENGTH)
234
+ out.set(CHUNK_AAD_DOMAIN_BYTES, 0)
235
+ out.set(uint64BE(chunkIndex), CHUNK_AAD_DOMAIN_BYTES.length)
236
+ out.set(uint64BE(totalChunks), CHUNK_AAD_DOMAIN_BYTES.length + 8)
237
+ out[CHUNK_AAD_DOMAIN_BYTES.length + 16] = isFinal ? 0x01 : 0x00
238
+ return out
239
+ }
240
+
241
+ function validateHeaderInputs(input: HeaderInputs): void {
242
+ if (!VALID_SUITES.has(input.suite)) {
243
+ throw new HeaderError('unknown_suite')
244
+ }
245
+ if (!(input.fileId instanceof Uint8Array)) {
246
+ throw new TypeError('fileId must be a Uint8Array')
247
+ }
248
+ if (input.fileId.length !== HEADER_SIZES.FILE_ID) {
249
+ throw new HeaderError('file_id_wrong_length')
250
+ }
251
+ if (
252
+ !Number.isSafeInteger(input.chunkSize) ||
253
+ input.chunkSize <= 0 ||
254
+ input.chunkSize > MAX_CHUNK_SIZE
255
+ ) {
256
+ throw new HeaderError('chunk_size_out_of_range')
257
+ }
258
+ if (
259
+ !Number.isSafeInteger(input.totalChunks) ||
260
+ input.totalChunks < 0 ||
261
+ input.totalChunks > MAX_TOTAL_CHUNKS
262
+ ) {
263
+ throw new HeaderError('total_chunks_out_of_range')
264
+ }
265
+ if (
266
+ !Number.isSafeInteger(input.plaintextSize) ||
267
+ input.plaintextSize < 0
268
+ ) {
269
+ throw new HeaderError('plaintext_size_out_of_range')
270
+ }
271
+ if (!(input.suitePayload instanceof Uint8Array)) {
272
+ throw new TypeError('suitePayload must be a Uint8Array')
273
+ }
274
+ if (input.suitePayload.length > 0xffff) {
275
+ throw new HeaderError('suite_payload_too_large')
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
+ }
306
+ }
307
+
308
+ /** Recognizable error class so callers can catch parse failures specifically */
309
+ export class HeaderError extends Error {
310
+ readonly code: string
311
+ constructor(code: string) {
312
+ super(`shieldfive-crypto: header error: ${code}`)
313
+ this.name = 'HeaderError'
314
+ this.code = code
315
+ }
316
+ }