@shieldfive/crypto 1.0.0-beta.3 → 1.0.0-rc.1

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 (59) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/README.md +73 -20
  3. package/SECURITY.md +38 -24
  4. package/dist/identity/index.d.ts +1 -1
  5. package/dist/identity/index.d.ts.map +1 -1
  6. package/dist/identity/index.js +1 -1
  7. package/dist/identity/index.js.map +1 -1
  8. package/dist/identity/sign.d.ts +73 -21
  9. package/dist/identity/sign.d.ts.map +1 -1
  10. package/dist/identity/sign.js +105 -35
  11. package/dist/identity/sign.js.map +1 -1
  12. package/dist/index.d.ts +3 -2
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +1 -1
  15. package/dist/index.js.map +1 -1
  16. package/dist/streams/aes-gcm-v1.d.ts +9 -5
  17. package/dist/streams/aes-gcm-v1.d.ts.map +1 -1
  18. package/dist/streams/aes-gcm-v1.js +26 -24
  19. package/dist/streams/aes-gcm-v1.js.map +1 -1
  20. package/dist/streams/pq-hybrid-v1.d.ts +4 -3
  21. package/dist/streams/pq-hybrid-v1.d.ts.map +1 -1
  22. package/dist/streams/pq-hybrid-v1.js +20 -18
  23. package/dist/streams/pq-hybrid-v1.js.map +1 -1
  24. package/dist/suites/aes-gcm-v0/api.d.ts +2 -1
  25. package/dist/suites/aes-gcm-v0/api.d.ts.map +1 -1
  26. package/dist/suites/aes-gcm-v0/api.js +1 -0
  27. package/dist/suites/aes-gcm-v0/api.js.map +1 -1
  28. package/dist/suites/aes-gcm-v1/api.d.ts +15 -2
  29. package/dist/suites/aes-gcm-v1/api.d.ts.map +1 -1
  30. package/dist/suites/aes-gcm-v1/api.js.map +1 -1
  31. package/dist/suites/aes-gcm-v2/api.d.ts +15 -2
  32. package/dist/suites/aes-gcm-v2/api.d.ts.map +1 -1
  33. package/dist/suites/aes-gcm-v2/api.js.map +1 -1
  34. package/dist/suites/pq-hybrid-v1/api.d.ts +6 -6
  35. package/dist/suites/pq-hybrid-v1/api.d.ts.map +1 -1
  36. package/dist/suites/pq-hybrid-v1/api.js +2 -1
  37. package/dist/suites/pq-hybrid-v1/api.js.map +1 -1
  38. package/dist/suites/pq-hybrid-v1/index.d.ts.map +1 -1
  39. package/dist/suites/pq-hybrid-v1/index.js +11 -4
  40. package/dist/suites/pq-hybrid-v1/index.js.map +1 -1
  41. package/dist/suites/xchacha-v1/api.d.ts +15 -6
  42. package/dist/suites/xchacha-v1/api.d.ts.map +1 -1
  43. package/dist/suites/xchacha-v1/api.js +2 -1
  44. package/dist/suites/xchacha-v1/api.js.map +1 -1
  45. package/package.json +2 -1
  46. package/spec/format-v1.md +59 -17
  47. package/spec/key-derivation.md +9 -2
  48. package/spec/threat-model.md +8 -2
  49. package/src/identity/index.ts +3 -2
  50. package/src/identity/sign.ts +118 -40
  51. package/src/index.ts +3 -3
  52. package/src/streams/aes-gcm-v1.ts +37 -30
  53. package/src/streams/pq-hybrid-v1.ts +29 -21
  54. package/src/suites/aes-gcm-v0/api.ts +2 -1
  55. package/src/suites/aes-gcm-v1/api.ts +15 -2
  56. package/src/suites/aes-gcm-v2/api.ts +15 -2
  57. package/src/suites/pq-hybrid-v1/api.ts +10 -8
  58. package/src/suites/pq-hybrid-v1/index.ts +14 -8
  59. package/src/suites/xchacha-v1/api.ts +19 -8
@@ -55,8 +55,9 @@ import {
55
55
  buildSignatureBlock,
56
56
  deriveEd25519PublicKey,
57
57
  ED25519_SECRET_KEY_LENGTH,
58
+ SenderSigTranscript,
58
59
  SIGNATURE_ALGO_ED25519,
59
- signHeaderAndMacs,
60
+ signSenderTranscript,
60
61
  } from '../identity/sign.js'
61
62
  import {
62
63
  type DecryptionMetadata,
@@ -99,9 +100,10 @@ export interface PqHybridV1EncryptStreamOptions {
99
100
  suitePayload: Uint8Array
100
101
  /**
101
102
  * Optional 32-byte Ed25519 secret seed. When provided, the stream
102
- * appends a signature block over `header_unauthenticated_bytes ||
103
- * concat(chunk_macs)` after the final chunk. When omitted, no block
104
- * is emitted and the file decrypts as unsigned (legacy behavior).
103
+ * appends a signature block after the final chunk, signing a transcript
104
+ * that commits to the header and every chunk's full ciphertext (see
105
+ * {@link SenderSigTranscript}). When omitted, no block is emitted and
106
+ * the file decrypts as unsigned (legacy behavior).
105
107
  */
106
108
  ed25519SecretKey?: Uint8Array
107
109
  }
@@ -192,15 +194,14 @@ export function createPqHybridV1EncryptStream(
192
194
  // - chunk index counter
193
195
  // - bytes consumed counter (for sanity check vs plaintextSize)
194
196
  // - context (lazily initialized)
195
- // - unauthenticated header bytes (kept for signing)
196
- // - per-chunk MAC tags (last 16 bytes of each chunk ciphertext)
197
+ // - signature transcript (present only when signing): commits to the
198
+ // header and every chunk's full ciphertext, hashed incrementally
197
199
  let pending = new Uint8Array(0)
198
200
  let chunkIndex = 0
199
201
  let bytesConsumed = 0
200
202
  let contextPromise: ReturnType<typeof createChunkContext> | null = null
201
203
  let headerEmitted = false
202
- let unauthenticatedHeader: Uint8Array | null = null
203
- const chunkMacs: Uint8Array[] = []
204
+ const transcript = ed25519SecretKey ? new SenderSigTranscript() : null
204
205
 
205
206
  async function ensureHeader(
206
207
  controller: TransformStreamDefaultController<Uint8Array>,
@@ -216,7 +217,7 @@ export function createPqHybridV1EncryptStream(
216
217
  })
217
218
  const macKey = await deriveHeaderMacKey(combinedKey, fileId)
218
219
  const mac = await hmacSha256(macKey, unauth)
219
- unauthenticatedHeader = unauth
220
+ transcript?.absorbHeader(unauth, totalChunks)
220
221
  controller.enqueue(concatBytes([unauth, mac]))
221
222
  headerEmitted = true
222
223
  }
@@ -232,9 +233,9 @@ export function createPqHybridV1EncryptStream(
232
233
  const ct = await encryptChunk(ctx, chunkIndex, plaintext)
233
234
  controller.enqueue(uint32BE(ct.length))
234
235
  controller.enqueue(ct)
235
- if (ed25519SecretKey) {
236
- chunkMacs.push(ct.slice(ct.length - PQ_HYBRID_V1_TAG_BYTES))
237
- }
236
+ // Commit the FULL chunk ciphertext (body + tag) to the signature
237
+ // transcript, not just the malleable Poly1305 tag.
238
+ transcript?.absorbChunk(chunkIndex, ct)
238
239
  chunkIndex += 1
239
240
  }
240
241
 
@@ -290,16 +291,15 @@ export function createPqHybridV1EncryptStream(
290
291
  return
291
292
  }
292
293
  if (ed25519SecretKey) {
293
- if (!unauthenticatedHeader) {
294
+ if (!transcript) {
294
295
  controller.error(
295
- new Error('encrypt stream: header not finalized before signing'),
296
+ new Error('encrypt stream: signature transcript not initialized'),
296
297
  )
297
298
  return
298
299
  }
299
- const signature = signHeaderAndMacs({
300
+ const signature = signSenderTranscript({
300
301
  ed25519SecretKey,
301
- header: unauthenticatedHeader,
302
- chunkMacs,
302
+ transcriptDigest: transcript.digest(),
303
303
  })
304
304
  const publicKey = deriveEd25519PublicKey(ed25519SecretKey)
305
305
  controller.enqueue(
@@ -436,7 +436,9 @@ export function createPqHybridV1DecryptStream(
436
436
  let bytesEmitted = 0
437
437
  let nextCipherLen = -1
438
438
  let contextPromise: ReturnType<typeof createChunkContext> | null = null
439
- const chunkMacs: Uint8Array[] = []
439
+ // Rebuilds the signer's transcript as chunks arrive so a trailing
440
+ // signature block can be verified against the actual ciphertext.
441
+ const transcript = new SenderSigTranscript()
440
442
 
441
443
  function append(input: Uint8Array): void {
442
444
  const merged = new Uint8Array(buffer.length + input.length)
@@ -522,6 +524,11 @@ export function createPqHybridV1DecryptStream(
522
524
  parsePqHybridV1SuitePayload(parsedHeader.suitePayload)
523
525
  }
524
526
 
527
+ transcript.absorbHeader(
528
+ parsedHeader.unauthenticatedBytes,
529
+ parsedHeader.totalChunks,
530
+ )
531
+
525
532
  contextPromise = createChunkContext(
526
533
  combinedKey,
527
534
  parsedHeader.fileId,
@@ -568,7 +575,9 @@ export function createPqHybridV1DecryptStream(
568
575
  const pt = await decryptChunk(ctx, chunkIndex, ctBytes)
569
576
  bytesEmitted += pt.length
570
577
  controller.enqueue(pt)
571
- chunkMacs.push(ctBytes.slice(ctBytes.length - PQ_HYBRID_V1_TAG_BYTES))
578
+ // Commit the FULL chunk ciphertext (body + tag) to the transcript for
579
+ // optional signature verification at flush time.
580
+ transcript.absorbChunk(chunkIndex, ctBytes)
572
581
  chunkIndex += 1
573
582
  return true
574
583
  }
@@ -612,8 +621,7 @@ export function createPqHybridV1DecryptStream(
612
621
  }
613
622
  const signatureResult = finalizeSignatureMetadata({
614
623
  trailingBytes: buffer,
615
- header: parsedHeader.unauthenticatedBytes,
616
- chunkMacs,
624
+ transcriptDigest: transcript.digest(),
617
625
  expectedSignerPublicKey,
618
626
  })
619
627
  buffer = new Uint8Array(0)
@@ -16,6 +16,7 @@
16
16
 
17
17
  import { uint64BE } from '../../internal/encoding.js'
18
18
  import { getSubtle } from '../../internal/runtime.js'
19
+ import { type ProgressCallback } from '../../internal/types.js'
19
20
 
20
21
  export const V0_TAG_BYTES = 16
21
22
  export const V0_IV_BYTES = 12
@@ -32,7 +33,7 @@ export interface V0DecryptOptions {
32
33
  /** Plaintext bytes per chunk (5 MiB or 8 MiB in production) */
33
34
  chunkSize: number
34
35
  /** Optional progress callback (0..1) */
35
- onProgress?: (progress: number) => void
36
+ onProgress?: ProgressCallback
36
37
  }
37
38
 
38
39
  function buildIv(prefix: Uint8Array, counter: number): Uint8Array {
@@ -43,9 +43,22 @@ const LENGTH_PREFIX_BYTES = 4
43
43
 
44
44
  export interface EncryptOptions {
45
45
  blob: Blob
46
- /** Optional pre-existing content key (32 bytes). If omitted, generated. */
46
+ /**
47
+ * Optional pre-existing content key (32 bytes). If omitted, generated fresh.
48
+ *
49
+ * SECURITY: `contentKey` and `fileId` together form a one-use AEAD nonce
50
+ * namespace. Supplying BOTH overrides transfers the uniqueness obligation to
51
+ * the caller — reusing the same (contentKey, fileId) pair across two
52
+ * different plaintexts reuses the AEAD key and nonce and is catastrophic
53
+ * (enables plaintext recovery and authenticated chunk substitution). Never
54
+ * reuse a pair. Omitting both (the default) generates fresh material per file.
55
+ */
47
56
  contentKey?: Uint8Array
48
- /** Optional pre-existing file_id (16 bytes). If omitted, generated. */
57
+ /**
58
+ * Optional pre-existing file_id (16 bytes). If omitted, generated fresh.
59
+ * See the SECURITY note on `contentKey` — do not reuse a (contentKey, fileId)
60
+ * pair across different plaintexts.
61
+ */
49
62
  fileId?: Uint8Array
50
63
  /** Optional embedded wrapped key + IV (60 + 12 bytes). Defaults to zeros. */
51
64
  suitePayloadOverride?: Uint8Array
@@ -39,9 +39,22 @@ const LENGTH_PREFIX_BYTES = 4
39
39
 
40
40
  export interface EncryptOptions {
41
41
  blob: Blob
42
- /** Optional pre-existing content key (32 bytes). If omitted, generated. */
42
+ /**
43
+ * Optional pre-existing content key (32 bytes). If omitted, generated fresh.
44
+ *
45
+ * SECURITY: `contentKey` and `fileId` together form a one-use AEAD nonce
46
+ * namespace. Supplying BOTH overrides transfers the uniqueness obligation to
47
+ * the caller — reusing the same (contentKey, fileId) pair across two
48
+ * different plaintexts reuses the AEAD key and nonce and is catastrophic
49
+ * (enables plaintext recovery and authenticated chunk substitution). Never
50
+ * reuse a pair. Omitting both (the default) generates fresh material per file.
51
+ */
43
52
  contentKey?: Uint8Array
44
- /** Optional pre-existing file_id (16 bytes). If omitted, generated. */
53
+ /**
54
+ * Optional pre-existing file_id (16 bytes). If omitted, generated fresh.
55
+ * See the SECURITY note on `contentKey` — do not reuse a (contentKey, fileId)
56
+ * pair across different plaintexts.
57
+ */
45
58
  fileId?: Uint8Array
46
59
  /** Optional embedded wrapped key + IV (60 + 12 bytes). Defaults to zeros. */
47
60
  suitePayloadOverride?: Uint8Array
@@ -57,7 +57,7 @@ export {
57
57
 
58
58
  const LENGTH_PREFIX_BYTES = 4
59
59
 
60
- export interface PqHybridEncryptOptions {
60
+ export interface EncryptOptions {
61
61
  blob: Blob
62
62
  /** Recipient's ML-KEM-1024 public key (1568 bytes) */
63
63
  recipientPublicKey: Uint8Array
@@ -82,7 +82,7 @@ export interface PqHybridEncryptOptions {
82
82
  * public key.
83
83
  */
84
84
  export async function encryptBlob(
85
- options: PqHybridEncryptOptions,
85
+ options: EncryptOptions,
86
86
  ): Promise<EncryptedFile & { combinedKey: Uint8Array }> {
87
87
  const { blob, recipientPublicKey, envelopeKey, onProgress } = options
88
88
  if (!(blob instanceof Blob)) {
@@ -155,7 +155,7 @@ export async function encryptBlob(
155
155
  }
156
156
  }
157
157
 
158
- export interface PqHybridDecryptOptions {
158
+ export interface DecryptOptions {
159
159
  blob: Blob
160
160
  /** Recipient's ML-KEM-1024 secret key (3168 bytes) */
161
161
  recipientSecretKey: Uint8Array
@@ -165,7 +165,7 @@ export interface PqHybridDecryptOptions {
165
165
  }
166
166
 
167
167
  export async function decryptBlob(
168
- options: PqHybridDecryptOptions,
168
+ options: DecryptOptions,
169
169
  ): Promise<Blob> {
170
170
  const { blob, recipientSecretKey, envelopeKey, onProgress } = options
171
171
  if (!(blob instanceof Blob)) {
@@ -284,15 +284,17 @@ export async function decryptBlob(
284
284
  * public key.
285
285
  */
286
286
  export async function encryptBytes(
287
- bytes: Uint8Array,
288
- options: Omit<PqHybridEncryptOptions, 'blob'>,
287
+ bytes: Uint8Array | ArrayBuffer,
288
+ options: Omit<EncryptOptions, 'blob'>,
289
289
  ): Promise<EncryptedFile & { combinedKey: Uint8Array }> {
290
- const blob = new Blob([asBlobPart(bytes)])
290
+ const part: BlobPart =
291
+ bytes instanceof ArrayBuffer ? bytes : asBlobPart(bytes)
292
+ const blob = new Blob([part])
291
293
  return encryptBlob({ blob, ...options })
292
294
  }
293
295
 
294
296
  export async function decryptToBytes(
295
- options: PqHybridDecryptOptions,
297
+ options: DecryptOptions,
296
298
  ): Promise<Uint8Array> {
297
299
  const blob = await decryptBlob(options)
298
300
  return new Uint8Array(await blob.arrayBuffer())
@@ -332,15 +332,21 @@ export async function decapsulateFromHeader(options: {
332
332
  recipientSecretKey,
333
333
  )
334
334
 
335
- // 2) Classical unwrap.
335
+ // 2) Classical unwrap. libsodium-wrappers THROWS on Poly1305 MAC failure
336
+ // (it does not return false), so the previous `if (!classicalShare)` guard
337
+ // was unreachable dead code. Catch the throw and re-raise a single generic
338
+ // error, folding the classical-unwrap failure into one message instead of
339
+ // surfacing libsodium's internal "wrong secret key" string to the caller.
336
340
  const wrapped48 = parsed.classicalWrapped.slice(0, 48)
337
- const classicalShare = sodium.crypto_secretbox_open_easy(
338
- wrapped48,
339
- parsed.classicalNonce,
340
- envelopeKey,
341
- )
342
- if (!classicalShare) {
343
- throw new Error('decapsulate: classical unwrap failed')
341
+ let classicalShare: Uint8Array
342
+ try {
343
+ classicalShare = sodium.crypto_secretbox_open_easy(
344
+ wrapped48,
345
+ parsed.classicalNonce,
346
+ envelopeKey,
347
+ )
348
+ } catch {
349
+ throw new Error('decapsulate: unwrap failed')
344
350
  }
345
351
 
346
352
  // 3) Combine.
@@ -35,9 +35,18 @@ import {
35
35
 
36
36
  const LENGTH_PREFIX_BYTES = 4
37
37
 
38
- export interface XChaChaEncryptOptions {
38
+ export interface EncryptOptions {
39
39
  blob: Blob
40
+ /**
41
+ * SECURITY: `contentKey` and `fileId` together form a one-use AEAD nonce
42
+ * namespace. Supplying BOTH overrides transfers the uniqueness obligation to
43
+ * the caller — reusing the same (contentKey, fileId) pair across two
44
+ * different plaintexts reuses the AEAD key and nonce and is catastrophic
45
+ * (enables plaintext recovery and authenticated chunk substitution). Never
46
+ * reuse a pair. Omitting both (the default) generates fresh material per file.
47
+ */
40
48
  contentKey?: Uint8Array
49
+ /** See the SECURITY note on `contentKey`. */
41
50
  fileId?: Uint8Array
42
51
  suitePayloadOverride?: Uint8Array
43
52
  chunkSize?: number
@@ -45,7 +54,7 @@ export interface XChaChaEncryptOptions {
45
54
  }
46
55
 
47
56
  export async function encryptBlob(
48
- options: XChaChaEncryptOptions,
57
+ options: EncryptOptions,
49
58
  ): Promise<EncryptedFile & { contentKey: Uint8Array }> {
50
59
  const { blob, onProgress } = options
51
60
  if (!(blob instanceof Blob)) {
@@ -123,7 +132,7 @@ export async function encryptBlob(
123
132
  }
124
133
  }
125
134
 
126
- export interface XChaChaDecryptOptions {
135
+ export interface DecryptOptions {
127
136
  blob: Blob
128
137
  contentKey: Uint8Array
129
138
  onProgress?: ProgressCallback
@@ -131,7 +140,7 @@ export interface XChaChaDecryptOptions {
131
140
  }
132
141
 
133
142
  export async function decryptBlob(
134
- options: XChaChaDecryptOptions,
143
+ options: DecryptOptions,
135
144
  ): Promise<Blob> {
136
145
  const { blob, contentKey, onProgress } = options
137
146
  if (!(blob instanceof Blob)) {
@@ -239,15 +248,17 @@ export async function decryptBlob(
239
248
  }
240
249
 
241
250
  export async function encryptBytes(
242
- bytes: Uint8Array,
243
- options: Omit<XChaChaEncryptOptions, 'blob'>,
251
+ bytes: Uint8Array | ArrayBuffer,
252
+ options: Omit<EncryptOptions, 'blob'>,
244
253
  ): Promise<EncryptedFile & { contentKey: Uint8Array }> {
245
- const blob = new Blob([asBlobPart(bytes)])
254
+ const part: BlobPart =
255
+ bytes instanceof ArrayBuffer ? bytes : asBlobPart(bytes)
256
+ const blob = new Blob([part])
246
257
  return encryptBlob({ blob, ...options })
247
258
  }
248
259
 
249
260
  export async function decryptToBytes(
250
- options: XChaChaDecryptOptions,
261
+ options: DecryptOptions,
251
262
  ): Promise<Uint8Array> {
252
263
  const blob = await decryptBlob(options)
253
264
  return new Uint8Array(await blob.arrayBuffer())