@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,122 @@
1
+ # ShieldFive Crypto — Key Derivation
2
+
3
+ This document specifies how application-level keys (envelope keys, ML-KEM
4
+ keypairs, header MAC keys, chunk keys) are derived from the user's master
5
+ secret. It is normative for the v1 release.
6
+
7
+ ## Master secret
8
+
9
+ The library does not generate or manage the master secret directly. The
10
+ host application is responsible for producing 32 bytes of high-entropy
11
+ secret material — typically by stretching a user passphrase through
12
+ Argon2id, by reading a hardware token, or by combining the two.
13
+
14
+ This document assumes the master secret has been derived. From there:
15
+
16
+ ```
17
+ master_secret ∈ bytes[32]
18
+ ```
19
+
20
+ Everything below is a deterministic function of this secret.
21
+
22
+ ## Derivation tree
23
+
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.
27
+
28
+ ```
29
+ master_secret
30
+ ├── envelope_key = HKDF(master, info="shieldfive/v1/envelope-key")
31
+ │
32
+ ├── metadata_key = HKDF(master, info="shieldfive/v1/metadata-key")
33
+ │ (used to encrypt filenames, folder names — outside this library's scope)
34
+ │
35
+ └── ml_kem_seed = HKDF(master, info="shieldfive/v1/pq-hybrid/ml-kem-1024-seed", L=64)
36
+ └── (ml_kem_pk, ml_kem_sk) = ML-KEM-1024.KeyGen(ml_kem_seed)
37
+ ```
38
+
39
+ The function `deriveMlKemKeypair(masterSecret)` exported from
40
+ `@shieldfive/crypto/pq-hybrid-v1` performs the seed derivation and the
41
+ ML-KEM keygen step in one call.
42
+
43
+ ## Why deterministic ML-KEM keys?
44
+
45
+ ML-KEM-1024 secret keys are 3168 bytes. Asking the user to back up an
46
+ extra 3168 bytes alongside their master secret would create a new failure
47
+ mode: losing the PQ key while still holding the master secret would mean
48
+ losing access to PQ-hybrid files.
49
+
50
+ Instead, we derive the PQ keypair from the master secret. The user backs
51
+ up only the master secret (or, more typically, only their passphrase plus
52
+ the Argon2id parameters). Everything else regenerates deterministically.
53
+
54
+ The cost of this choice: a future cryptanalytic break in HKDF-SHA-256's
55
+ seed expansion would propagate to the PQ keypair. We accept this because
56
+ HKDF-SHA-256 is conservative, and the alternative (separate PQ key
57
+ backup) has a worse failure mode (data loss).
58
+
59
+ ## Per-file key derivation (recap from format-v1.md)
60
+
61
+ Once the envelope key is in hand, per-file keys are derived as:
62
+
63
+ ```
64
+ content_key = randomBytes(32) (fresh per file, never derived)
65
+ file_id = randomBytes(16) (fresh per file, never derived)
66
+
67
+ header_mac_key = HKDF(content_key, salt=file_id,
68
+ info="shieldfive/v1/header-mac")
69
+
70
+ chunk_key = HKDF(content_key, salt=file_id,
71
+ info="shieldfive/v1/<suite>/chunk-key")
72
+
73
+ nonce_prefix = HKDF(file_id,
74
+ info="shieldfive/v1/<suite>/nonce-prefix",
75
+ L = 4 (AES-GCM) or 16 (XChaCha))
76
+
77
+ iv / nonce_i = nonce_prefix || uint64_be(chunk_index)
78
+ ```
79
+
80
+ For the PQ-hybrid suite, `content_key` is replaced by the combined key
81
+ `K = HKDF(classical_share || pq_share, salt=file_id,
82
+ info="shieldfive/v1/pq-hybrid/combine")`.
83
+
84
+ ## Forbidden cross-context usage
85
+
86
+ These domain strings are consumed *only* by the crypto layer. The host
87
+ application MUST NOT reuse any of them for unrelated purposes:
88
+
89
+ ```
90
+ shieldfive/v1/header-mac
91
+ shieldfive/v1/aes-gcm/chunk-key
92
+ shieldfive/v1/aes-gcm/nonce-prefix
93
+ shieldfive/v1/xchacha/chunk-key
94
+ shieldfive/v1/xchacha/nonce-prefix
95
+ shieldfive/v1/pq-hybrid/combine
96
+ shieldfive/v1/pq-hybrid/ml-kem-1024-seed
97
+ shieldfive/v1/envelope-key
98
+ shieldfive/v1/metadata-key
99
+ ```
100
+
101
+ If the host application needs a new derived key, it MUST use a fresh
102
+ domain string of the form `<application>/<version>/<purpose>` to ensure
103
+ domain separation from this library's keys.
104
+
105
+ ## Test vectors
106
+
107
+ Deterministic test vectors for each derivation step live in
108
+ `tests/vectors/key-derivation.json`. They are used by
109
+ `tests/integration/key-derivation.test.ts` to ensure cross-implementation
110
+ consistency.
111
+
112
+ A reference vector:
113
+
114
+ ```
115
+ master_secret = 0000…0000 (32 bytes of zero)
116
+ envelope_key = (computed) — see tests/vectors/key-derivation.json
117
+ ml_kem_seed = (computed)
118
+ ml_kem_pk[0..7] = (computed first 8 bytes)
119
+ ```
120
+
121
+ These vectors are committed to the repository so that any reimplementation
122
+ of the v1 spec can self-check.
@@ -0,0 +1,152 @@
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
+ A2 cannot:
35
+
36
+ - Recover plaintext (TLS + AEAD).
37
+ - Inject ciphertext that decrypts to attacker-chosen plaintext (AEAD
38
+ authentication).
39
+ - **Truncate a file undetectably** (final-chunk AAD `is_final` flag).
40
+ - **Reorder chunks undetectably** (chunk-index AAD).
41
+ - **Splice chunks across files** (file_id AAD).
42
+
43
+ ### A3 — Future quantum adversary
44
+
45
+ Holds today's ciphertext. Eventually obtains a cryptographically relevant
46
+ quantum computer. Wants to recover plaintext from "harvest now, decrypt
47
+ later" attacks.
48
+
49
+ A3 cannot recover plaintext from files encrypted with suite `0x03`
50
+ (`pq-hybrid-xchacha-mlkem1024-v1`) unless they break **both**:
51
+
52
+ - ML-KEM-1024 (NIST PQC standard, security level 5, equivalent to AES-256
53
+ against quantum search), AND
54
+ - XChaCha20-Poly1305 (256-bit key, 128-bit security against Grover-like
55
+ speedups).
56
+
57
+ A3 *can* recover plaintext from files encrypted with classical-only suites
58
+ (`0x01`, `0x02`) once Shor-feasible quantum computers exist. Files
59
+ encrypted with classical-only suites SHOULD be re-encrypted with the
60
+ hybrid suite when migration is feasible.
61
+
62
+ ## Out of scope
63
+
64
+ This crypto layer does not protect against:
65
+
66
+ ### Malicious client delivery
67
+
68
+ If the application server delivers a backdoored JavaScript bundle to the
69
+ user's browser, that bundle can capture the password before encryption
70
+ happens. The crypto library cannot detect this. Reproducible builds and
71
+ client integrity verification (Subresource Integrity, signed
72
+ extensions, audited desktop builds) are required to address this and are
73
+ the responsibility of the host application, not the crypto layer.
74
+
75
+ ### Endpoint compromise
76
+
77
+ Malware on the user's device, malicious browser extensions, screen
78
+ recorders, and keyloggers all see plaintext. The crypto layer cannot help.
79
+
80
+ ### Metadata leakage at the storage layer
81
+
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
86
+ build it on top.
87
+
88
+ ### Side channels in WebCrypto / WASM
89
+
90
+ Browsers' AES-GCM implementations are typically constant-time on hardware
91
+ with AES-NI. WASM-based ChaCha20 is constant-time by construction. We do
92
+ not defend against power analysis or fault injection attacks against the
93
+ underlying browser/runtime.
94
+
95
+ ### User key loss
96
+
97
+ If the user loses their master password and there is no recovery key, the
98
+ data is unrecoverable. This is a feature.
99
+
100
+ ## Comparison with comparable products
101
+
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** |
109
+
110
+ This table reflects publicly available specifications and audit reports as
111
+ of the v1 specification date. It is updated when those specifications
112
+ change. This is not a security claim about which product is "best" — each
113
+ makes different tradeoffs — but it documents the design positions ShieldFive
114
+ v1 takes deliberately.
115
+
116
+ ## Known limitations of v1
117
+
118
+ These are intentional tradeoffs documented for transparency:
119
+
120
+ 1. **Per-file random nonce prefix is derived, not stored.** Under correct
121
+ use this is safer (no risk of replay due to RNG failure during write).
122
+ Under incorrect use (key reuse across files), it offers no defense
123
+ beyond what AES-GCM/XChaCha already provide. This is acceptable because
124
+ the crypto layer enforces fresh per-file content keys.
125
+
126
+ 2. **No padding for size obfuscation.** A 5MB ciphertext implies a ~5MB
127
+ plaintext (within chunk granularity). Applications wanting size privacy
128
+ must pad at a higher layer. v2 may introduce optional plaintext padding.
129
+
130
+ 3. **No traffic analysis resistance.** Upload/download timing is observable
131
+ to the storage server. This is out of scope.
132
+
133
+ 4. **HMAC-SHA-256 for header authentication, not Poly1305.** Chosen because
134
+ HMAC-SHA-256 is universally available in WebCrypto without WASM. The
135
+ security claim is unchanged: 128-bit MAC strength.
136
+
137
+ 5. **ML-KEM keys are derived deterministically from user master secret.**
138
+ This is an availability tradeoff — the user does not need to back up a
139
+ separate PQ keypair. The cost is that ML-KEM key generation is
140
+ deterministic with respect to the master secret, which means a future
141
+ weakness in the deterministic seed expansion (HKDF-SHA-256) propagates
142
+ to PQ key generation. We accept this because (a) HKDF is conservative,
143
+ (b) the alternative is requiring users to back up PQ keys separately,
144
+ which has a worse failure mode (data loss).
145
+
146
+ ## Reporting
147
+
148
+ Cryptographic vulnerabilities should be reported to
149
+ `security@shieldfive.com` encrypted with the PGP key in `SECURITY.md`. We
150
+ acknowledge within 72 hours and target a patch within 30 days for
151
+ high-severity issues. Researchers acting in good faith are protected under
152
+ the safe-harbor clause in `SECURITY.md`.
@@ -0,0 +1,284 @@
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
+ export function parseHeader(input: Uint8Array): ParsedHeader & {
109
+ unauthenticatedBytes: Uint8Array
110
+ mac: Uint8Array
111
+ } {
112
+ if (input.length < HEADER_FIXED_PREFIX_LENGTH + HEADER_SIZES.HEADER_MAC) {
113
+ throw new HeaderError('header_too_short')
114
+ }
115
+
116
+ // Magic
117
+ for (let i = 0; i < FORMAT_MAGIC_LENGTH; i += 1) {
118
+ if (input[i] !== FORMAT_MAGIC[i]) {
119
+ throw new HeaderError('bad_magic')
120
+ }
121
+ }
122
+
123
+ let offset = FORMAT_MAGIC_LENGTH
124
+
125
+ const suite = input[offset]!
126
+ offset += HEADER_SIZES.SUITE
127
+ if (!VALID_SUITES.has(suite)) {
128
+ throw new HeaderError('unknown_suite')
129
+ }
130
+
131
+ const flags = input[offset]!
132
+ offset += HEADER_SIZES.FLAGS
133
+ if (flags !== 0x00) {
134
+ throw new HeaderError('reserved_flags_set')
135
+ }
136
+
137
+ const fileId = input.slice(offset, offset + HEADER_SIZES.FILE_ID)
138
+ offset += HEADER_SIZES.FILE_ID
139
+
140
+ const chunkSize = readUint32BE(input, offset)
141
+ offset += HEADER_SIZES.CHUNK_SIZE
142
+ if (chunkSize === 0 || chunkSize > MAX_CHUNK_SIZE) {
143
+ throw new HeaderError('chunk_size_out_of_range')
144
+ }
145
+
146
+ const totalChunks = readUint64BE(input, offset)
147
+ offset += HEADER_SIZES.TOTAL_CHUNKS
148
+ if (totalChunks > MAX_TOTAL_CHUNKS) {
149
+ throw new HeaderError('total_chunks_out_of_range')
150
+ }
151
+
152
+ const plaintextSize = readUint64BE(input, offset)
153
+ offset += HEADER_SIZES.PLAINTEXT_SIZE
154
+
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
+ }
166
+
167
+ const suitePayloadLen = readUint16BE(input, offset)
168
+ offset += HEADER_SIZES.SUITE_PAYLOAD_LEN
169
+
170
+ if (offset + suitePayloadLen + HEADER_SIZES.HEADER_MAC > input.length) {
171
+ throw new HeaderError('header_truncated')
172
+ }
173
+
174
+ const suitePayload = input.slice(offset, offset + suitePayloadLen)
175
+ offset += suitePayloadLen
176
+
177
+ const macStart = offset
178
+ const mac = input.slice(macStart, macStart + HEADER_SIZES.HEADER_MAC)
179
+ offset += HEADER_SIZES.HEADER_MAC
180
+
181
+ const unauthenticatedBytes = input.slice(0, macStart)
182
+
183
+ return {
184
+ suite: suite as SuiteId,
185
+ flags,
186
+ fileId,
187
+ chunkSize,
188
+ totalChunks,
189
+ plaintextSize,
190
+ suitePayload,
191
+ headerLength: offset,
192
+ unauthenticatedBytes,
193
+ mac,
194
+ }
195
+ }
196
+
197
+ /**
198
+ * Verify the parsed header's MAC under the supplied content key.
199
+ * Throws on failure; returns the parsed header on success.
200
+ */
201
+ export async function verifyHeaderMac(
202
+ parsed: ReturnType<typeof parseHeader>,
203
+ contentKey: Uint8Array,
204
+ ): Promise<void> {
205
+ const macKey = await deriveHeaderMacKey(contentKey, parsed.fileId)
206
+ const ok = await hmacSha256Verify(
207
+ macKey,
208
+ parsed.unauthenticatedBytes,
209
+ parsed.mac,
210
+ )
211
+ if (!ok) {
212
+ throw new HeaderError('header_mac_mismatch')
213
+ }
214
+ }
215
+
216
+ /**
217
+ * Build the AAD bound into every chunk's AEAD: domain || index || total || is_final.
218
+ */
219
+ export function buildChunkAad(
220
+ chunkIndex: number,
221
+ totalChunks: number,
222
+ isFinal: boolean,
223
+ ): Uint8Array {
224
+ if (!Number.isSafeInteger(chunkIndex) || chunkIndex < 0) {
225
+ throw new RangeError('buildChunkAad: chunkIndex out of range')
226
+ }
227
+ if (!Number.isSafeInteger(totalChunks) || totalChunks < 0) {
228
+ throw new RangeError('buildChunkAad: totalChunks out of range')
229
+ }
230
+ const out = new Uint8Array(CHUNK_AAD_LENGTH)
231
+ out.set(CHUNK_AAD_DOMAIN_BYTES, 0)
232
+ out.set(uint64BE(chunkIndex), CHUNK_AAD_DOMAIN_BYTES.length)
233
+ out.set(uint64BE(totalChunks), CHUNK_AAD_DOMAIN_BYTES.length + 8)
234
+ out[CHUNK_AAD_DOMAIN_BYTES.length + 16] = isFinal ? 0x01 : 0x00
235
+ return out
236
+ }
237
+
238
+ function validateHeaderInputs(input: HeaderInputs): void {
239
+ if (!VALID_SUITES.has(input.suite)) {
240
+ throw new HeaderError('unknown_suite')
241
+ }
242
+ if (!(input.fileId instanceof Uint8Array)) {
243
+ throw new TypeError('fileId must be a Uint8Array')
244
+ }
245
+ if (input.fileId.length !== HEADER_SIZES.FILE_ID) {
246
+ throw new HeaderError('file_id_wrong_length')
247
+ }
248
+ if (
249
+ !Number.isSafeInteger(input.chunkSize) ||
250
+ input.chunkSize <= 0 ||
251
+ input.chunkSize > MAX_CHUNK_SIZE
252
+ ) {
253
+ throw new HeaderError('chunk_size_out_of_range')
254
+ }
255
+ if (
256
+ !Number.isSafeInteger(input.totalChunks) ||
257
+ input.totalChunks < 0 ||
258
+ input.totalChunks > MAX_TOTAL_CHUNKS
259
+ ) {
260
+ throw new HeaderError('total_chunks_out_of_range')
261
+ }
262
+ if (
263
+ !Number.isSafeInteger(input.plaintextSize) ||
264
+ input.plaintextSize < 0
265
+ ) {
266
+ throw new HeaderError('plaintext_size_out_of_range')
267
+ }
268
+ if (!(input.suitePayload instanceof Uint8Array)) {
269
+ throw new TypeError('suitePayload must be a Uint8Array')
270
+ }
271
+ if (input.suitePayload.length > 0xffff) {
272
+ throw new HeaderError('suite_payload_too_large')
273
+ }
274
+ }
275
+
276
+ /** Recognizable error class so callers can catch parse failures specifically */
277
+ export class HeaderError extends Error {
278
+ readonly code: string
279
+ constructor(code: string) {
280
+ super(`shieldfive-crypto: header error: ${code}`)
281
+ this.name = 'HeaderError'
282
+ this.code = code
283
+ }
284
+ }