@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,473 @@
1
+ /**
2
+ * Streaming encrypt/decrypt for the v1 wire format under suite 0x03
3
+ * (PQ-hybrid XChaCha20-Poly1305 + ML-KEM-1024).
4
+ *
5
+ * The whole-blob APIs in `suites/<name>/api.ts` materialize entire files in
6
+ * memory. That's fine for small files; for multi-gigabyte files on a
7
+ * mobile device it isn't.
8
+ *
9
+ * This module exposes a WHATWG TransformStream factory that ingests
10
+ * plaintext (or ciphertext) chunks from any ReadableStream and emits the
11
+ * other side, without ever holding more than one chunk-plus-header in
12
+ * memory at once.
13
+ *
14
+ * Currently implemented:
15
+ * - Suite 0x03 (pq-hybrid-xchacha-mlkem1024-v1) encrypt
16
+ * - Suite 0x03 (pq-hybrid-xchacha-mlkem1024-v1) decrypt
17
+ *
18
+ * Differences from the AES-GCM-v1 streaming module: the encrypt factory
19
+ * requires the caller to pre-run `encapsulateForRecipient` and pass the
20
+ * resulting `{combinedKey, suitePayload, fileId}` — the PQ suite cannot
21
+ * fabricate its own content material the way AES can, because it depends
22
+ * on the recipient's ML-KEM public key. The async helper
23
+ * `encryptStreamPqHybridV1` bundles encapsulation + stream construction.
24
+ * On the decrypt side, the stream itself performs PQ decapsulation as
25
+ * soon as the header has been parsed, then proceeds identically to the
26
+ * AES path.
27
+ */
28
+ import { buildHeaderUnauthenticated, deriveHeaderMacKey, HeaderError, parseHeader, } from '../format/header.js';
29
+ import { PQ_HYBRID_V1_SUITE_PAYLOAD_LENGTH, PQ_HYBRID_V1_TAG_BYTES, createChunkContext, decapsulateFromHeader, decryptChunk, encapsulateForRecipient, encryptChunk, } from '../suites/pq-hybrid-v1/index.js';
30
+ import { DEFAULT_CHUNK_SIZE, HEADER_SIZES, MAX_TOTAL_CHUNKS, SUITE, } from '../internal/types.js';
31
+ import { concatBytes, readUint32BE, uint32BE } from '../internal/encoding.js';
32
+ import { hmacSha256 } from '../internal/hmac.js';
33
+ import { randomBytes } from '../internal/runtime.js';
34
+ import { buildSignatureBlock, deriveEd25519PublicKey, ED25519_SECRET_KEY_LENGTH, SIGNATURE_ALGO_ED25519, signHeaderAndMacs, } from '../identity/sign.js';
35
+ import { finalizeSignatureMetadata, } from './aes-gcm-v1.js';
36
+ const LENGTH_PREFIX_BYTES = 4;
37
+ /**
38
+ * Build a TransformStream that encrypts plaintext into v1 wire-format
39
+ * ciphertext on the fly under suite 0x03. The stream emits the header
40
+ * first, then each chunk as it arrives.
41
+ *
42
+ * The caller MUST pass `plaintextSize` because the header records it.
43
+ * If the caller doesn't know the size up front, they must accumulate
44
+ * the plaintext into a buffer first — there is no way to write a
45
+ * self-describing header otherwise.
46
+ *
47
+ * Unlike the AES-GCM-v1 factory, the PQ-hybrid factory cannot manufacture
48
+ * its own key material — the combined key, file_id, and suite payload
49
+ * are all outputs of `encapsulateForRecipient`. Use the
50
+ * `encryptStreamPqHybridV1` helper when you'd rather pass a recipient
51
+ * public key directly.
52
+ */
53
+ export function createPqHybridV1EncryptStream(options) {
54
+ const chunkSize = options.chunkSize ?? DEFAULT_CHUNK_SIZE;
55
+ if (!Number.isSafeInteger(chunkSize) || chunkSize <= 0) {
56
+ throw new RangeError('encrypt stream: chunkSize must be positive integer');
57
+ }
58
+ if (!Number.isSafeInteger(options.plaintextSize) ||
59
+ options.plaintextSize < 0) {
60
+ throw new RangeError('encrypt stream: plaintextSize must be a non-negative integer');
61
+ }
62
+ const totalChunks = options.plaintextSize === 0
63
+ ? 0
64
+ : Math.ceil(options.plaintextSize / chunkSize);
65
+ if (totalChunks > MAX_TOTAL_CHUNKS) {
66
+ throw new RangeError('encrypt stream: file would exceed total_chunks limit');
67
+ }
68
+ const { combinedKey, fileId, suitePayload } = options;
69
+ if (combinedKey.length !== 32) {
70
+ throw new RangeError('encrypt stream: combinedKey must be 32 bytes');
71
+ }
72
+ if (fileId.length !== HEADER_SIZES.FILE_ID) {
73
+ throw new RangeError('encrypt stream: fileId must be 16 bytes');
74
+ }
75
+ if (suitePayload.length !== PQ_HYBRID_V1_SUITE_PAYLOAD_LENGTH) {
76
+ throw new RangeError(`encrypt stream: suitePayload must be ${PQ_HYBRID_V1_SUITE_PAYLOAD_LENGTH} bytes`);
77
+ }
78
+ const ed25519SecretKey = options.ed25519SecretKey;
79
+ if (ed25519SecretKey && ed25519SecretKey.length !== ED25519_SECRET_KEY_LENGTH) {
80
+ throw new RangeError(`encrypt stream: ed25519SecretKey must be ${ED25519_SECRET_KEY_LENGTH} bytes`);
81
+ }
82
+ // State held across the lifetime of the stream:
83
+ // - pending plaintext buffer (collects until we have a full chunk)
84
+ // - chunk index counter
85
+ // - bytes consumed counter (for sanity check vs plaintextSize)
86
+ // - context (lazily initialized)
87
+ // - unauthenticated header bytes (kept for signing)
88
+ // - per-chunk MAC tags (last 16 bytes of each chunk ciphertext)
89
+ let pending = new Uint8Array(0);
90
+ let chunkIndex = 0;
91
+ let bytesConsumed = 0;
92
+ let contextPromise = null;
93
+ let headerEmitted = false;
94
+ let unauthenticatedHeader = null;
95
+ const chunkMacs = [];
96
+ async function ensureHeader(controller) {
97
+ if (headerEmitted)
98
+ return;
99
+ const unauth = buildHeaderUnauthenticated({
100
+ suite: SUITE.PQ_HYBRID_XCHACHA_MLKEM1024_V1,
101
+ fileId,
102
+ chunkSize,
103
+ totalChunks,
104
+ plaintextSize: options.plaintextSize,
105
+ suitePayload,
106
+ });
107
+ const macKey = await deriveHeaderMacKey(combinedKey, fileId);
108
+ const mac = await hmacSha256(macKey, unauth);
109
+ unauthenticatedHeader = unauth;
110
+ controller.enqueue(concatBytes([unauth, mac]));
111
+ headerEmitted = true;
112
+ }
113
+ async function emitChunk(plaintext, controller) {
114
+ if (!contextPromise) {
115
+ contextPromise = createChunkContext(combinedKey, fileId, totalChunks);
116
+ }
117
+ const ctx = await contextPromise;
118
+ const ct = await encryptChunk(ctx, chunkIndex, plaintext);
119
+ controller.enqueue(uint32BE(ct.length));
120
+ controller.enqueue(ct);
121
+ if (ed25519SecretKey) {
122
+ chunkMacs.push(ct.slice(ct.length - PQ_HYBRID_V1_TAG_BYTES));
123
+ }
124
+ chunkIndex += 1;
125
+ }
126
+ const transformer = {
127
+ async transform(chunk, controller) {
128
+ await ensureHeader(controller);
129
+ bytesConsumed += chunk.length;
130
+ if (bytesConsumed > options.plaintextSize) {
131
+ controller.error(new RangeError('encrypt stream: input exceeded declared plaintextSize'));
132
+ return;
133
+ }
134
+ // Append to pending buffer
135
+ const merged = new Uint8Array(pending.length + chunk.length);
136
+ merged.set(pending, 0);
137
+ merged.set(chunk, pending.length);
138
+ pending = merged;
139
+ // Drain whole chunks
140
+ while (pending.length >= chunkSize && chunkIndex < totalChunks - 1) {
141
+ const slice = pending.subarray(0, chunkSize);
142
+ await emitChunk(slice, controller);
143
+ pending = pending.subarray(chunkSize);
144
+ // Subarray shares the buffer; copy out so we can drop the rest.
145
+ pending = pending.slice(0);
146
+ }
147
+ },
148
+ async flush(controller) {
149
+ await ensureHeader(controller);
150
+ if (bytesConsumed !== options.plaintextSize) {
151
+ controller.error(new RangeError(`encrypt stream: input was ${bytesConsumed} bytes, declared ${options.plaintextSize}`));
152
+ return;
153
+ }
154
+ // Emit any remaining whole chunks plus the final partial chunk.
155
+ while (chunkIndex < totalChunks) {
156
+ const isLastIteration = chunkIndex === totalChunks - 1;
157
+ const sliceSize = isLastIteration
158
+ ? pending.length // final chunk: whatever's left
159
+ : chunkSize;
160
+ const slice = pending.subarray(0, sliceSize);
161
+ await emitChunk(slice, controller);
162
+ pending = pending.subarray(sliceSize).slice(0);
163
+ }
164
+ if (pending.length !== 0) {
165
+ controller.error(new RangeError('encrypt stream: residual bytes after final chunk'));
166
+ return;
167
+ }
168
+ if (ed25519SecretKey) {
169
+ if (!unauthenticatedHeader) {
170
+ controller.error(new Error('encrypt stream: header not finalized before signing'));
171
+ return;
172
+ }
173
+ const signature = signHeaderAndMacs({
174
+ ed25519SecretKey,
175
+ header: unauthenticatedHeader,
176
+ chunkMacs,
177
+ });
178
+ const publicKey = deriveEd25519PublicKey(ed25519SecretKey);
179
+ controller.enqueue(buildSignatureBlock({
180
+ algorithm: SIGNATURE_ALGO_ED25519,
181
+ publicKey,
182
+ signature,
183
+ }));
184
+ }
185
+ },
186
+ };
187
+ return {
188
+ stream: new TransformStream(transformer),
189
+ combinedKey,
190
+ fileId,
191
+ };
192
+ }
193
+ /**
194
+ * Build a TransformStream that decrypts a v1 ciphertext stream produced
195
+ * under suite 0x03 into plaintext. Unlike the whole-blob decryptor, this
196
+ * version processes input incrementally — useful for very large files or
197
+ * when ciphertext arrives chunked over the network.
198
+ *
199
+ * Two key-input modes:
200
+ * - KEM mode (`recipientSecretKey` + `envelopeKey`): the stream runs
201
+ * ML-KEM decapsulation once, the moment the header has been
202
+ * buffered, then proceeds identically to the AES-GCM-v1 decrypt
203
+ * stream.
204
+ * - Combined-key mode (`combinedKey`): skips decapsulation entirely
205
+ * and uses the supplied K for header MAC verification + chunk AEAD.
206
+ * Intended for share-link recipients who hold a wrapped K but no
207
+ * ML-KEM secret.
208
+ */
209
+ export function createPqHybridV1DecryptStream(options) {
210
+ const combinedKeyOverride = options.combinedKey;
211
+ const recipientSecretKey = options.recipientSecretKey;
212
+ const envelopeKey = options.envelopeKey;
213
+ const expectedSignerPublicKey = options.expectedSignerPublicKey;
214
+ let resolveMetadata;
215
+ let rejectMetadata;
216
+ const metadata = new Promise((resolve, reject) => {
217
+ resolveMetadata = resolve;
218
+ rejectMetadata = reject;
219
+ });
220
+ // See aes-gcm-v1.ts createAesGcmV1DecryptStream for rationale.
221
+ metadata.catch(() => { });
222
+ if (combinedKeyOverride) {
223
+ if (combinedKeyOverride.length !== 32) {
224
+ throw new RangeError('decrypt stream: combinedKey must be 32 bytes');
225
+ }
226
+ }
227
+ else {
228
+ if (!recipientSecretKey || !envelopeKey) {
229
+ throw new RangeError('decrypt stream: provide either combinedKey or recipientSecretKey + envelopeKey');
230
+ }
231
+ if (envelopeKey.length !== 32) {
232
+ throw new RangeError('decrypt stream: envelopeKey must be 32 bytes');
233
+ }
234
+ // Length of recipientSecretKey is checked inside decapsulateFromHeader.
235
+ }
236
+ // Phases:
237
+ // 0 = waiting for header bytes
238
+ // 1 = streaming chunks: alternating length-prefix + ciphertext
239
+ let phase = 0;
240
+ let buffer = new Uint8Array(0);
241
+ let parsedHeader = null;
242
+ let chunkIndex = 0;
243
+ let bytesEmitted = 0;
244
+ let nextCipherLen = -1;
245
+ let contextPromise = null;
246
+ const chunkMacs = [];
247
+ function append(input) {
248
+ const merged = new Uint8Array(buffer.length + input.length);
249
+ merged.set(buffer, 0);
250
+ merged.set(input, buffer.length);
251
+ buffer = merged;
252
+ }
253
+ function consume(n) {
254
+ const out = buffer.subarray(0, n).slice(0);
255
+ buffer = buffer.subarray(n).slice(0);
256
+ return out;
257
+ }
258
+ async function tryParseHeader() {
259
+ // Need at least the fixed prefix + MAC (no suite_payload).
260
+ if (buffer.length <
261
+ HEADER_SIZES.MAGIC +
262
+ HEADER_SIZES.SUITE +
263
+ HEADER_SIZES.FLAGS +
264
+ HEADER_SIZES.FILE_ID +
265
+ HEADER_SIZES.CHUNK_SIZE +
266
+ HEADER_SIZES.TOTAL_CHUNKS +
267
+ HEADER_SIZES.PLAINTEXT_SIZE +
268
+ HEADER_SIZES.SUITE_PAYLOAD_LEN) {
269
+ return false;
270
+ }
271
+ // Read suite_payload_len so we know how much more to wait for.
272
+ const suitePayloadLenOffset = HEADER_SIZES.MAGIC +
273
+ HEADER_SIZES.SUITE +
274
+ HEADER_SIZES.FLAGS +
275
+ HEADER_SIZES.FILE_ID +
276
+ HEADER_SIZES.CHUNK_SIZE +
277
+ HEADER_SIZES.TOTAL_CHUNKS +
278
+ HEADER_SIZES.PLAINTEXT_SIZE;
279
+ const suitePayloadLen = (buffer[suitePayloadLenOffset] << 8) |
280
+ buffer[suitePayloadLenOffset + 1];
281
+ const fullHeaderLen = suitePayloadLenOffset +
282
+ HEADER_SIZES.SUITE_PAYLOAD_LEN +
283
+ suitePayloadLen +
284
+ HEADER_SIZES.HEADER_MAC;
285
+ if (buffer.length < fullHeaderLen)
286
+ return false;
287
+ const headerBytes = consume(fullHeaderLen);
288
+ parsedHeader = parseHeader(headerBytes);
289
+ if (parsedHeader.suite !== SUITE.PQ_HYBRID_XCHACHA_MLKEM1024_V1) {
290
+ throw new HeaderError(`decrypt stream: this stream only supports pq-hybrid-xchacha-mlkem1024-v1; got suite 0x${parsedHeader.suite.toString(16)}`);
291
+ }
292
+ // Recover the combined key. Two paths:
293
+ // - KEM mode: run ML-KEM decapsulation now.
294
+ // - Combined-key mode: trust the supplied K. The header MAC check
295
+ // below still cryptographically gates the rest of the stream, so
296
+ // a wrong K fails fast.
297
+ let combinedKey;
298
+ if (combinedKeyOverride) {
299
+ combinedKey = combinedKeyOverride;
300
+ }
301
+ else {
302
+ ;
303
+ ({ combinedKey } = await decapsulateFromHeader({
304
+ suitePayload: parsedHeader.suitePayload,
305
+ recipientSecretKey: recipientSecretKey,
306
+ envelopeKey: envelopeKey,
307
+ fileId: parsedHeader.fileId,
308
+ }));
309
+ }
310
+ const { verifyHeaderMac } = await import('../format/header.js');
311
+ await verifyHeaderMac(parsedHeader, combinedKey);
312
+ contextPromise = createChunkContext(combinedKey, parsedHeader.fileId, parsedHeader.totalChunks);
313
+ phase = 1;
314
+ return true;
315
+ }
316
+ async function tryEmitChunk(controller) {
317
+ if (!parsedHeader)
318
+ return false;
319
+ if (chunkIndex >= parsedHeader.totalChunks) {
320
+ // Already consumed all expected chunks; anything remaining is trailing
321
+ // garbage and must be flagged at flush time.
322
+ return false;
323
+ }
324
+ if (nextCipherLen < 0) {
325
+ if (buffer.length < LENGTH_PREFIX_BYTES)
326
+ return false;
327
+ const lenBytes = consume(LENGTH_PREFIX_BYTES);
328
+ nextCipherLen = readUint32BE(lenBytes);
329
+ const isFinal = chunkIndex === parsedHeader.totalChunks - 1;
330
+ const minCipher = 1 + PQ_HYBRID_V1_TAG_BYTES;
331
+ const maxCipher = parsedHeader.chunkSize + PQ_HYBRID_V1_TAG_BYTES;
332
+ if (nextCipherLen < minCipher || nextCipherLen > maxCipher) {
333
+ throw new HeaderError('chunk_length_out_of_range');
334
+ }
335
+ if (!isFinal && nextCipherLen !== maxCipher) {
336
+ throw new HeaderError('non_final_chunk_wrong_size');
337
+ }
338
+ }
339
+ if (buffer.length < nextCipherLen)
340
+ return false;
341
+ const ctBytes = consume(nextCipherLen);
342
+ nextCipherLen = -1;
343
+ const ctx = await contextPromise;
344
+ const pt = await decryptChunk(ctx, chunkIndex, ctBytes);
345
+ bytesEmitted += pt.length;
346
+ controller.enqueue(pt);
347
+ chunkMacs.push(ctBytes.slice(ctBytes.length - PQ_HYBRID_V1_TAG_BYTES));
348
+ chunkIndex += 1;
349
+ return true;
350
+ }
351
+ return {
352
+ stream: new TransformStream({
353
+ async transform(chunk, controller) {
354
+ append(chunk);
355
+ try {
356
+ if (phase === 0) {
357
+ const ok = await tryParseHeader();
358
+ if (!ok)
359
+ return;
360
+ }
361
+ // Drain as many chunks as we have data for.
362
+ while (await tryEmitChunk(controller)) {
363
+ /* loop */
364
+ }
365
+ }
366
+ catch (err) {
367
+ controller.error(err);
368
+ rejectMetadata(err);
369
+ }
370
+ },
371
+ async flush(controller) {
372
+ try {
373
+ if (phase === 0) {
374
+ throw new HeaderError('header_too_short');
375
+ }
376
+ // No header yet means truncated input.
377
+ if (!parsedHeader) {
378
+ throw new HeaderError('header_too_short');
379
+ }
380
+ // Try once more in case flush is called with everything queued.
381
+ while (await tryEmitChunk(controller)) {
382
+ /* loop */
383
+ }
384
+ if (chunkIndex !== parsedHeader.totalChunks) {
385
+ throw new HeaderError('chunk_truncated');
386
+ }
387
+ if (bytesEmitted !== parsedHeader.plaintextSize) {
388
+ throw new HeaderError('plaintext_size_mismatch');
389
+ }
390
+ const signatureResult = finalizeSignatureMetadata({
391
+ trailingBytes: buffer,
392
+ header: parsedHeader.unauthenticatedBytes,
393
+ chunkMacs,
394
+ expectedSignerPublicKey,
395
+ });
396
+ buffer = new Uint8Array(0);
397
+ resolveMetadata({ signature: signatureResult });
398
+ }
399
+ catch (err) {
400
+ controller.error(err);
401
+ rejectMetadata(err);
402
+ }
403
+ },
404
+ }),
405
+ metadata,
406
+ };
407
+ }
408
+ /**
409
+ * Pipe a ReadableStream<Uint8Array> through the PQ-hybrid-v1 encrypt
410
+ * transform and return the resulting ReadableStream alongside the
411
+ * derived material the caller will need: the 16-byte file_id (safe
412
+ * to persist with the ciphertext), the suite payload (safe to
413
+ * persist with the ciphertext; required for later decapsulation),
414
+ * and the 32-byte combined key.
415
+ *
416
+ * SECURITY: The returned `combinedKey` grants permanent decryption
417
+ * capability for any file whose header was produced with it. Treat
418
+ * as cryptographic secret material: hold only in memory for the
419
+ * duration of the operation, do not persist to disk or storage, do
420
+ * not log, do not transmit. The only safe way to reproduce it on
421
+ * another machine is to re-encapsulate via the recipient's ML-KEM
422
+ * public key.
423
+ *
424
+ * This helper is async because PQ encapsulation requires libsodium
425
+ * init.
426
+ */
427
+ export async function encryptStreamPqHybridV1(source, options) {
428
+ const { recipientPublicKey, envelopeKey } = options;
429
+ const fileId = options.fileId ?? randomBytes(HEADER_SIZES.FILE_ID);
430
+ if (fileId.length !== HEADER_SIZES.FILE_ID) {
431
+ throw new RangeError('encryptStreamPqHybridV1: fileId must be 16 bytes');
432
+ }
433
+ const { suitePayload, combinedKey } = await encapsulateForRecipient({
434
+ recipientPublicKey,
435
+ envelopeKey,
436
+ fileId,
437
+ });
438
+ const streamOptions = {
439
+ plaintextSize: options.plaintextSize,
440
+ combinedKey,
441
+ fileId,
442
+ suitePayload,
443
+ };
444
+ if (options.chunkSize !== undefined) {
445
+ streamOptions.chunkSize = options.chunkSize;
446
+ }
447
+ if (options.ed25519SecretKey !== undefined) {
448
+ streamOptions.ed25519SecretKey = options.ed25519SecretKey;
449
+ }
450
+ const { stream } = createPqHybridV1EncryptStream(streamOptions);
451
+ return {
452
+ ciphertext: source.pipeThrough(stream),
453
+ combinedKey,
454
+ fileId,
455
+ suitePayload,
456
+ };
457
+ }
458
+ /**
459
+ * Pipe a ReadableStream<Uint8Array> through the PQ-hybrid-v1 decrypt
460
+ * transform and return the resulting plaintext ReadableStream + a
461
+ * `metadata` Promise carrying the parsed signature block (or
462
+ * `signature: null` for unsigned / legacy files). See
463
+ * {@link PqHybridV1DecryptStreamOptions} for the two key-input modes
464
+ * (KEM secret + envelope vs. pre-derived combined key K).
465
+ */
466
+ export function decryptStreamPqHybridV1(source, options) {
467
+ const { stream, metadata } = createPqHybridV1DecryptStream(options);
468
+ return {
469
+ plaintext: source.pipeThrough(stream),
470
+ metadata,
471
+ };
472
+ }
473
+ //# sourceMappingURL=pq-hybrid-v1.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pq-hybrid-v1.js","sourceRoot":"","sources":["../../src/streams/pq-hybrid-v1.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,OAAO,EACL,0BAA0B,EAC1B,kBAAkB,EAClB,WAAW,EACX,WAAW,GACZ,MAAM,qBAAqB,CAAA;AAC5B,OAAO,EACL,iCAAiC,EACjC,sBAAsB,EACtB,kBAAkB,EAClB,qBAAqB,EACrB,YAAY,EACZ,uBAAuB,EACvB,YAAY,GACb,MAAM,iCAAiC,CAAA;AACxC,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,gBAAgB,EAChB,KAAK,GACN,MAAM,sBAAsB,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AC,aAAa,CAAC,CAAA;IAE/D,OAAO;QACL,UAAU,EAAE,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC;QACtC,WAAW;QACX,MAAM;QACN,YAAY;KACb,CAAA;AACH,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,uBAAuB,CACrC,MAAkC,EAClC,OAAuC;IAKvC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,6BAA6B,CAAC,OAAO,CAAC,CAAA;IACnE,OAAO;QACL,SAAS,EAAE,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC;QACrC,QAAQ;KACT,CAAA;AACH,CAAC"}
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Cipher suite "0x00" / v0: legacy AES-256-GCM, READ-ONLY.
3
+ *
4
+ * This module decrypts files written by the pre-v1 ShieldFive client.
5
+ * It is intentionally read-only: there is no `encryptV0` exported symbol,
6
+ * and applications MUST NOT write new files in this format.
7
+ *
8
+ * v0 wire format (described in `spec/format-v0.md`):
9
+ *
10
+ * v0_file := chunk_0 || chunk_1 || ... || chunk_n
11
+ * chunk_i := AES-GCM(key=content_key, iv=prefix(4)||counter_be(8), aad=∅, pt=plain_i)
12
+ *
13
+ * No on-disk header. The reader must be told the chunk size and nonce
14
+ * prefix out of band (from the application database).
15
+ */
16
+ export declare const V0_TAG_BYTES = 16;
17
+ export declare const V0_IV_BYTES = 12;
18
+ export declare const V0_KEY_BYTES = 32;
19
+ export declare const V0_NONCE_PREFIX_BYTES = 4;
20
+ export interface V0DecryptOptions {
21
+ /** Encrypted file bytes (concatenated chunks; no header) */
22
+ blob: Blob;
23
+ /** 32-byte AES-256 content key, already unwrapped from the envelope */
24
+ contentKey: Uint8Array;
25
+ /** 4-byte per-file random prefix, stored in the database */
26
+ noncePrefix: Uint8Array;
27
+ /** Plaintext bytes per chunk (5 MiB or 8 MiB in production) */
28
+ chunkSize: number;
29
+ /** Optional progress callback (0..1) */
30
+ onProgress?: (progress: number) => void;
31
+ }
32
+ /**
33
+ * Decrypt a v0 file. Throws if any chunk fails to authenticate, if the
34
+ * blob size is inconsistent with the chunk size (no clean chunk boundary),
35
+ * or if the inputs have wrong sizes.
36
+ */
37
+ export declare function decryptV0(options: V0DecryptOptions): Promise<Blob>;
38
+ /**
39
+ * Convenience wrapper that returns plaintext bytes directly.
40
+ */
41
+ export declare function decryptV0ToBytes(options: V0DecryptOptions): Promise<Uint8Array>;
42
+ /**
43
+ * Detect whether a blob is v0 (legacy) by checking the absence of the v1
44
+ * magic prefix. Use only when out-of-band metadata is unavailable. For
45
+ * normal application use, the database flag `cipher_version` is canonical.
46
+ */
47
+ export declare function looksLikeV0(blob: Blob): Promise<boolean>;
48
+ //# sourceMappingURL=api.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../../../src/suites/aes-gcm-v0/api.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAKH,eAAO,MAAM,YAAY,KAAK,CAAA;AAC9B,eAAO,MAAM,WAAW,KAAK,CAAA;AAC7B,eAAO,MAAM,YAAY,KAAK,CAAA;AAC9B,eAAO,MAAM,qBAAqB,IAAI,CAAA;AAEtC,MAAM,WAAW,gBAAgB;IAC/B,4DAA4D;IAC5D,IAAI,EAAE,IAAI,CAAA;IACV,uEAAuE;IACvE,UAAU,EAAE,UAAU,CAAA;IACtB,4DAA4D;IAC5D,WAAW,EAAE,UAAU,CAAA;IACvB,+DAA+D;IAC/D,SAAS,EAAE,MAAM,CAAA;IACjB,wCAAwC;IACxC,UAAU,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAA;CACxC;AASD;;;;GAIG;AACH,wBAAsB,SAAS,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CA6ExE;AAED;;GAEG;AACH,wBAAsB,gBAAgB,CACpC,OAAO,EAAE,gBAAgB,GACxB,OAAO,CAAC,UAAU,CAAC,CAGrB;AAED;;;;GAIG;AACH,wBAAsB,WAAW,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,CAAC,OAAO,CAAC,CAW9D"}
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Cipher suite "0x00" / v0: legacy AES-256-GCM, READ-ONLY.
3
+ *
4
+ * This module decrypts files written by the pre-v1 ShieldFive client.
5
+ * It is intentionally read-only: there is no `encryptV0` exported symbol,
6
+ * and applications MUST NOT write new files in this format.
7
+ *
8
+ * v0 wire format (described in `spec/format-v0.md`):
9
+ *
10
+ * v0_file := chunk_0 || chunk_1 || ... || chunk_n
11
+ * chunk_i := AES-GCM(key=content_key, iv=prefix(4)||counter_be(8), aad=∅, pt=plain_i)
12
+ *
13
+ * No on-disk header. The reader must be told the chunk size and nonce
14
+ * prefix out of band (from the application database).
15
+ */
16
+ import { uint64BE } from '../../internal/encoding.js';
17
+ import { getSubtle } from '../../internal/runtime.js';
18
+ export const V0_TAG_BYTES = 16;
19
+ export const V0_IV_BYTES = 12;
20
+ export const V0_KEY_BYTES = 32;
21
+ export const V0_NONCE_PREFIX_BYTES = 4;
22
+ function buildIv(prefix, counter) {
23
+ const iv = new Uint8Array(V0_IV_BYTES);
24
+ iv.set(prefix, 0);
25
+ iv.set(uint64BE(counter), 4);
26
+ return iv;
27
+ }
28
+ /**
29
+ * Decrypt a v0 file. Throws if any chunk fails to authenticate, if the
30
+ * blob size is inconsistent with the chunk size (no clean chunk boundary),
31
+ * or if the inputs have wrong sizes.
32
+ */
33
+ export async function decryptV0(options) {
34
+ const { blob, contentKey, noncePrefix, chunkSize, onProgress } = options;
35
+ if (!(blob instanceof Blob)) {
36
+ throw new TypeError('decryptV0: blob must be a Blob or File');
37
+ }
38
+ if (contentKey.length !== V0_KEY_BYTES) {
39
+ throw new RangeError('decryptV0: contentKey must be 32 bytes');
40
+ }
41
+ if (noncePrefix.length !== V0_NONCE_PREFIX_BYTES) {
42
+ throw new RangeError('decryptV0: noncePrefix must be 4 bytes');
43
+ }
44
+ if (!Number.isSafeInteger(chunkSize) || chunkSize <= 0) {
45
+ throw new RangeError('decryptV0: chunkSize must be a positive integer');
46
+ }
47
+ // Compute chunk layout from blob size.
48
+ const fullCipherLen = chunkSize + V0_TAG_BYTES;
49
+ const totalSize = blob.size;
50
+ if (totalSize === 0) {
51
+ return new Blob([], { type: 'application/octet-stream' });
52
+ }
53
+ const fullChunkCount = Math.floor(totalSize / fullCipherLen);
54
+ const trailingBytes = totalSize - fullChunkCount * fullCipherLen;
55
+ let totalChunks;
56
+ if (trailingBytes === 0) {
57
+ totalChunks = fullChunkCount;
58
+ }
59
+ else if (trailingBytes <= V0_TAG_BYTES) {
60
+ throw new Error(`decryptV0: trailing bytes (${trailingBytes}) too small for an AEAD tag — file truncated`);
61
+ }
62
+ else {
63
+ totalChunks = fullChunkCount + 1;
64
+ }
65
+ // Import the AES-GCM key once.
66
+ const key = await getSubtle().importKey('raw', contentKey, { name: 'AES-GCM' }, false, ['decrypt']);
67
+ const plaintextParts = [];
68
+ let cursor = 0;
69
+ for (let i = 0; i < totalChunks; i += 1) {
70
+ const isFinal = i === totalChunks - 1;
71
+ const cipherLen = isFinal && trailingBytes > 0 ? trailingBytes : fullCipherLen;
72
+ const cipherBytes = new Uint8Array(await blob.slice(cursor, cursor + cipherLen).arrayBuffer());
73
+ cursor += cipherLen;
74
+ const iv = buildIv(noncePrefix, i);
75
+ let pt;
76
+ try {
77
+ pt = await getSubtle().decrypt({ name: 'AES-GCM', iv: iv, tagLength: 128 }, key, cipherBytes);
78
+ }
79
+ catch (err) {
80
+ throw new Error(`decryptV0: chunk ${i} failed authentication`, { cause: err });
81
+ }
82
+ plaintextParts.push(pt);
83
+ onProgress?.((i + 1) / totalChunks);
84
+ }
85
+ return new Blob(plaintextParts, { type: 'application/octet-stream' });
86
+ }
87
+ /**
88
+ * Convenience wrapper that returns plaintext bytes directly.
89
+ */
90
+ export async function decryptV0ToBytes(options) {
91
+ const blob = await decryptV0(options);
92
+ return new Uint8Array(await blob.arrayBuffer());
93
+ }
94
+ /**
95
+ * Detect whether a blob is v0 (legacy) by checking the absence of the v1
96
+ * magic prefix. Use only when out-of-band metadata is unavailable. For
97
+ * normal application use, the database flag `cipher_version` is canonical.
98
+ */
99
+ export async function looksLikeV0(blob) {
100
+ if (blob.size < 5)
101
+ return true; // too small to be v1
102
+ const head = new Uint8Array(await blob.slice(0, 5).arrayBuffer());
103
+ // v1 magic is "SF5\x01\x00" = 0x53 0x46 0x35 0x01 0x00
104
+ return !(head[0] === 0x53 &&
105
+ head[1] === 0x46 &&
106
+ head[2] === 0x35 &&
107
+ head[3] === 0x01 &&
108
+ head[4] === 0x00);
109
+ }
110
+ //# sourceMappingURL=api.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api.js","sourceRoot":"","sources":["../../../src/suites/aes-gcm-v0/api.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,4BAA4B,CAAA;AACrD,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAA;AAErD,MAAM,CAAC,MAAM,YAAY,GAAG,EAAE,CAAA;AAC9B,MAAM,CAAC,MAAM,WAAW,GAAG,EAAE,CAAA;AAC7B,MAAM,CAAC,MAAM,YAAY,GAAG,EAAE,CAAA;AAC9B,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,CAAA;AAetC,SAAS,OAAO,CAAC,MAAkB,EAAE,OAAe;IAClD,MAAM,EAAE,GAAG,IAAI,UAAU,CAAC,WAAW,CAAC,CAAA;IACtC,EAAE,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC,CAAA;IACjB,EAAE,CAAC,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAA;IAC5B,OAAO,EAAE,CAAA;AACX,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,SAAS,CAAC,OAAyB;IACvD,MAAM,EAAE,IAAI,EAAE,UAAU,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