@shieldfive/crypto 1.0.1 → 1.1.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 (68) hide show
  1. package/CHANGELOG.md +65 -1
  2. package/README.md +6 -6
  3. package/dist/format/signature-tail.d.ts +12 -0
  4. package/dist/format/signature-tail.d.ts.map +1 -1
  5. package/dist/format/signature-tail.js +24 -0
  6. package/dist/format/signature-tail.js.map +1 -1
  7. package/dist/index.d.ts +1 -1
  8. package/dist/index.js +1 -1
  9. package/dist/internal/byte-queue.d.ts +34 -0
  10. package/dist/internal/byte-queue.d.ts.map +1 -0
  11. package/dist/internal/byte-queue.js +82 -0
  12. package/dist/internal/byte-queue.js.map +1 -0
  13. package/dist/internal/encoding.d.ts +6 -0
  14. package/dist/internal/encoding.d.ts.map +1 -1
  15. package/dist/internal/encoding.js +11 -0
  16. package/dist/internal/encoding.js.map +1 -1
  17. package/dist/migration/v0-bridge.d.ts +5 -0
  18. package/dist/migration/v0-bridge.d.ts.map +1 -1
  19. package/dist/migration/v0-bridge.js +5 -0
  20. package/dist/migration/v0-bridge.js.map +1 -1
  21. package/dist/streams/aes-gcm-v1.d.ts +9 -0
  22. package/dist/streams/aes-gcm-v1.d.ts.map +1 -1
  23. package/dist/streams/aes-gcm-v1.js +18 -26
  24. package/dist/streams/aes-gcm-v1.js.map +1 -1
  25. package/dist/streams/pq-hybrid-v1.d.ts +18 -0
  26. package/dist/streams/pq-hybrid-v1.d.ts.map +1 -1
  27. package/dist/streams/pq-hybrid-v1.js +14 -25
  28. package/dist/streams/pq-hybrid-v1.js.map +1 -1
  29. package/dist/suites/aes-gcm-v0/api.d.ts +10 -3
  30. package/dist/suites/aes-gcm-v0/api.d.ts.map +1 -1
  31. package/dist/suites/aes-gcm-v0/api.js +10 -3
  32. package/dist/suites/aes-gcm-v0/api.js.map +1 -1
  33. package/dist/suites/aes-gcm-v1/api.d.ts +9 -0
  34. package/dist/suites/aes-gcm-v1/api.d.ts.map +1 -1
  35. package/dist/suites/aes-gcm-v1/api.js +7 -1
  36. package/dist/suites/aes-gcm-v1/api.js.map +1 -1
  37. package/dist/suites/aes-gcm-v2/api.d.ts +9 -0
  38. package/dist/suites/aes-gcm-v2/api.d.ts.map +1 -1
  39. package/dist/suites/aes-gcm-v2/api.js +7 -1
  40. package/dist/suites/aes-gcm-v2/api.js.map +1 -1
  41. package/dist/suites/pq-hybrid-v1/api.d.ts +9 -0
  42. package/dist/suites/pq-hybrid-v1/api.d.ts.map +1 -1
  43. package/dist/suites/pq-hybrid-v1/api.js +3 -1
  44. package/dist/suites/pq-hybrid-v1/api.js.map +1 -1
  45. package/dist/suites/xchacha-v1/api.d.ts +9 -0
  46. package/dist/suites/xchacha-v1/api.d.ts.map +1 -1
  47. package/dist/suites/xchacha-v1/api.js +7 -1
  48. package/dist/suites/xchacha-v1/api.js.map +1 -1
  49. package/dist/vault/index.d.ts.map +1 -1
  50. package/dist/vault/index.js +2 -5
  51. package/dist/vault/index.js.map +1 -1
  52. package/package.json +2 -2
  53. package/spec/format-v0.md +11 -3
  54. package/spec/format-v1.md +17 -5
  55. package/spec/intake-link-pin.md +130 -0
  56. package/src/format/signature-tail.ts +36 -0
  57. package/src/index.ts +1 -1
  58. package/src/internal/byte-queue.ts +86 -0
  59. package/src/internal/encoding.ts +11 -0
  60. package/src/migration/v0-bridge.ts +5 -0
  61. package/src/streams/aes-gcm-v1.ts +27 -25
  62. package/src/streams/pq-hybrid-v1.ts +32 -25
  63. package/src/suites/aes-gcm-v0/api.ts +10 -3
  64. package/src/suites/aes-gcm-v1/api.ts +16 -0
  65. package/src/suites/aes-gcm-v2/api.ts +16 -0
  66. package/src/suites/pq-hybrid-v1/api.ts +12 -0
  67. package/src/suites/xchacha-v1/api.ts +16 -0
  68. package/src/vault/index.ts +4 -4
@@ -62,6 +62,42 @@ export function finalizeSignatureMetadata(input: {
62
62
  trailingBytes: Uint8Array
63
63
  transcriptDigest: Uint8Array
64
64
  expectedSignerPublicKey: Uint8Array | undefined
65
+ /** See `assertSignatureRequirement`. Defaults to false. */
66
+ signatureRequired?: boolean
67
+ }): VerifiedSignature | null {
68
+ const result = parseAndVerifySignature(input)
69
+ if (input.signatureRequired === true) {
70
+ if (result === null) throw new HeaderError('signature_required_missing')
71
+ if (result.verified !== true) {
72
+ throw new HeaderError('signature_required_invalid')
73
+ }
74
+ }
75
+ return result
76
+ }
77
+
78
+ /**
79
+ * Validate the `signatureRequired` / `expectedSignerPublicKey` pair on a
80
+ * decrypt call before any work is done, and return the normalised flag.
81
+ * Requiring a signature without saying whose is a caller bug: there is
82
+ * nothing to verify against, so it throws instead of silently accepting.
83
+ */
84
+ export function assertSignatureRequirement(options: {
85
+ expectedSignerPublicKey?: Uint8Array
86
+ signatureRequired?: boolean
87
+ }): boolean {
88
+ const required = options.signatureRequired === true
89
+ if (required && !options.expectedSignerPublicKey) {
90
+ throw new RangeError(
91
+ 'decrypt: signatureRequired needs expectedSignerPublicKey (the key the file must be signed by)',
92
+ )
93
+ }
94
+ return required
95
+ }
96
+
97
+ function parseAndVerifySignature(input: {
98
+ trailingBytes: Uint8Array
99
+ transcriptDigest: Uint8Array
100
+ expectedSignerPublicKey: Uint8Array | undefined
65
101
  }): VerifiedSignature | null {
66
102
  if (input.trailingBytes.length === 0) {
67
103
  return null
package/src/index.ts CHANGED
@@ -220,7 +220,7 @@ export async function autoDecryptBlob(
220
220
  }
221
221
 
222
222
  /** Library version, also written into format documentation. */
223
- export const SHIELDFIVE_CRYPTO_VERSION = '1.0.1'
223
+ export const SHIELDFIVE_CRYPTO_VERSION = '1.1.1'
224
224
 
225
225
  /** Default cipher suite for new files when not specified by the caller. */
226
226
  export const DEFAULT_SUITE = SUITE.PQ_HYBRID_XCHACHA_MLKEM1024_V1
@@ -0,0 +1,86 @@
1
+ /**
2
+ * A FIFO byte queue for the streaming encoders/decoders.
3
+ *
4
+ * The streams used to keep their pending bytes in a plain Uint8Array and
5
+ * rebuild it on every append (`new Uint8Array(a.length + b.length)`) and
6
+ * on every consume (`buffer.subarray(n).slice(0)`). Both copy everything
7
+ * still buffered, so a stream fed in many small pieces — or a decoder
8
+ * holding a 5 MiB chunk while it arrives in 16 KiB network reads — did
9
+ * O(n²) copying.
10
+ *
11
+ * This keeps one backing buffer with a read offset and a write offset.
12
+ * Appends grow it geometrically (or compact it in place when the dead
13
+ * prefix is large enough), so every byte is copied O(1) times amortised.
14
+ * `take(n)` returns an independent copy, exactly like the old `consume`.
15
+ */
16
+ export class ByteQueue {
17
+ private buf: Uint8Array
18
+ private start = 0
19
+ private end = 0
20
+
21
+ constructor(initialCapacity = 0) {
22
+ this.buf = new Uint8Array(initialCapacity)
23
+ }
24
+
25
+ /** Number of buffered (unread) bytes. */
26
+ get length(): number {
27
+ return this.end - this.start
28
+ }
29
+
30
+ /** Append a copy of `input`. */
31
+ append(input: Uint8Array): void {
32
+ const n = input.length
33
+ if (n === 0) return
34
+ if (this.end + n > this.buf.length) {
35
+ const live = this.end - this.start
36
+ const needed = live + n
37
+ if (needed <= this.buf.length && this.start >= live) {
38
+ // Enough room once the dead prefix is reclaimed, and the live
39
+ // part is no larger than the prefix, so the move is cheap.
40
+ this.buf.copyWithin(0, this.start, this.end)
41
+ } else {
42
+ const next = new Uint8Array(Math.max(needed, this.buf.length * 2, 64))
43
+ next.set(this.buf.subarray(this.start, this.end), 0)
44
+ this.buf = next
45
+ }
46
+ this.start = 0
47
+ this.end = live
48
+ }
49
+ this.buf.set(input, this.end)
50
+ this.end += n
51
+ }
52
+
53
+ /** The byte at `index` (relative to the read offset). */
54
+ byteAt(index: number): number {
55
+ if (index < 0 || index >= this.length) {
56
+ throw new RangeError('ByteQueue.byteAt: index out of range')
57
+ }
58
+ return this.buf[this.start + index]!
59
+ }
60
+
61
+ /** Remove and return the first `n` bytes as an independent copy. */
62
+ take(n: number): Uint8Array {
63
+ if (n < 0 || n > this.length) {
64
+ throw new RangeError('ByteQueue.take: not enough buffered bytes')
65
+ }
66
+ const out = this.buf.slice(this.start, this.start + n)
67
+ this.start += n
68
+ if (this.start === this.end) {
69
+ this.start = 0
70
+ this.end = 0
71
+ }
72
+ return out
73
+ }
74
+
75
+ /** Remove and return everything buffered as an independent copy. */
76
+ takeAll(): Uint8Array {
77
+ return this.take(this.length)
78
+ }
79
+
80
+ /** Overwrite the backing store with zeros and empty the queue. */
81
+ wipe(): void {
82
+ this.buf.fill(0)
83
+ this.start = 0
84
+ this.end = 0
85
+ }
86
+ }
@@ -29,6 +29,17 @@ export function bytesToBase64(bytes: Uint8Array): string {
29
29
  return Buffer.from(bytes).toString('base64')
30
30
  }
31
31
 
32
+ /**
33
+ * Remove trailing `=` padding characters. Linear time: a single backward scan,
34
+ * unlike `/=+$/`, which backtracks quadratically on long runs of `=` that are
35
+ * not at the end of the string.
36
+ */
37
+ export function stripBase64Padding(value: string): string {
38
+ let end = value.length
39
+ while (end > 0 && value.charCodeAt(end - 1) === 61 /* '=' */) end -= 1
40
+ return end === value.length ? value : value.slice(0, end)
41
+ }
42
+
32
43
  export function base64ToBytes(value: string): Uint8Array {
33
44
  if (typeof value !== 'string') {
34
45
  throw new TypeError('base64ToBytes: input must be a string')
@@ -130,6 +130,11 @@ async function sha1Hex(bytes: Uint8Array): Promise<string> {
130
130
  *
131
131
  * **Key handling:** the caller must bring their own pre-unwrapped 32-byte
132
132
  * content key. This module does not wrap or unwrap keys.
133
+ *
134
+ * @deprecated For migration fixtures only. v0 has no truncation detection,
135
+ * no file_id binding and no chunk AAD (spec/format-v0.md), so a file cut at
136
+ * a chunk boundary decrypts to shorter plaintext without an error. New
137
+ * writes must use a v1 suite.
133
138
  */
134
139
  export async function encryptV0(
135
140
  options: V0EncryptOptions,
@@ -41,6 +41,7 @@ import {
41
41
  SUITE,
42
42
  } from '../internal/types.js'
43
43
  import { concatBytes, readUint32BE, uint32BE } from '../internal/encoding.js'
44
+ import { ByteQueue } from '../internal/byte-queue.js'
44
45
  import { hmacSha256 } from '../internal/hmac.js'
45
46
  import {
46
47
  buildSignatureBlock,
@@ -51,6 +52,7 @@ import {
51
52
  signSenderTranscript,
52
53
  } from '../identity/sign.js'
53
54
  import {
55
+ assertSignatureRequirement,
54
56
  finalizeSignatureMetadata,
55
57
  type DecryptionMetadata,
56
58
  } from '../format/signature-tail.js'
@@ -147,6 +149,10 @@ export function createAesGcmV1EncryptStream(
147
149
  `encrypt stream: suitePayloadOverride must be ${AES_GCM_V1_SUITE_PAYLOAD_LENGTH} bytes`,
148
150
  )
149
151
  }
152
+ // Run the reader's own payload check on the writer side, so the library
153
+ // never emits a file its readers refuse (a non-zero reserved pad passed
154
+ // through suitePayloadOverride). Throws RangeError like the checks above.
155
+ parseAesGcmV1SuitePayload(suitePayload)
150
156
 
151
157
  const ed25519SecretKey = options.ed25519SecretKey
152
158
  if (ed25519SecretKey && ed25519SecretKey.length !== ED25519_SECRET_KEY_LENGTH) {
@@ -162,7 +168,7 @@ export function createAesGcmV1EncryptStream(
162
168
  // - context (lazily initialized)
163
169
  // - signature transcript (present only when signing): commits to the
164
170
  // header and every chunk's full ciphertext, hashed incrementally
165
- let pending = new Uint8Array(0)
171
+ const pending = new ByteQueue()
166
172
  let chunkIndex = 0
167
173
  let bytesConsumed = 0
168
174
  let contextPromise: ReturnType<typeof createChunkContext> | null = null
@@ -216,18 +222,11 @@ export function createAesGcmV1EncryptStream(
216
222
  return
217
223
  }
218
224
  // Append to pending buffer
219
- const merged = new Uint8Array(pending.length + chunk.length)
220
- merged.set(pending, 0)
221
- merged.set(chunk, pending.length)
222
- pending = merged
225
+ pending.append(chunk)
223
226
 
224
227
  // Drain whole chunks
225
228
  while (pending.length >= chunkSize && chunkIndex < totalChunks - 1) {
226
- const slice = pending.subarray(0, chunkSize)
227
- await emitChunk(slice, controller)
228
- pending = pending.subarray(chunkSize)
229
- // Subarray shares the buffer; copy out so we can drop the rest.
230
- pending = pending.slice(0)
229
+ await emitChunk(pending.take(chunkSize), controller)
231
230
  }
232
231
  },
233
232
  async flush(controller) {
@@ -246,9 +245,7 @@ export function createAesGcmV1EncryptStream(
246
245
  const sliceSize = isLastIteration
247
246
  ? pending.length // final chunk: whatever's left
248
247
  : chunkSize
249
- const slice = pending.subarray(0, sliceSize)
250
- await emitChunk(slice, controller)
251
- pending = pending.subarray(sliceSize).slice(0)
248
+ await emitChunk(pending.take(sliceSize), controller)
252
249
  }
253
250
  if (pending.length !== 0) {
254
251
  controller.error(
@@ -299,6 +296,15 @@ export interface AesGcmV1DecryptStreamOptions {
299
296
  * block is parsed and surfaced but not verified; `verified` is null.
300
297
  */
301
298
  expectedSignerPublicKey?: Uint8Array
299
+ /**
300
+ * When true, decryption FAILS unless the file carries a trailing
301
+ * signature block that verifies against `expectedSignerPublicKey`
302
+ * (which must then be supplied). Use this wherever the caller relies
303
+ * on sender attribution: without it, an unsigned or wrongly-signed file
304
+ * still decrypts and only `signature.verified` tells them apart.
305
+ * Defaults to false (legacy/unsigned files decrypt as before).
306
+ */
307
+ signatureRequired?: boolean
302
308
  }
303
309
 
304
310
  // `VerifiedSignature` and `DecryptionMetadata` (and the shared
@@ -337,6 +343,7 @@ export function createAesGcmV1DecryptStream(
337
343
  throw new RangeError('decrypt stream: contentKey must be 32 bytes')
338
344
  }
339
345
  const expectedSignerPublicKey = options.expectedSignerPublicKey
346
+ const signatureRequired = assertSignatureRequirement(options)
340
347
 
341
348
  let resolveMetadata!: (m: DecryptionMetadata) => void
342
349
  let rejectMetadata!: (err: unknown) => void
@@ -355,7 +362,7 @@ export function createAesGcmV1DecryptStream(
355
362
  // 0 = waiting for header bytes
356
363
  // 1 = streaming chunks: alternating length-prefix + ciphertext
357
364
  let phase: 0 | 1 = 0
358
- let buffer = new Uint8Array(0)
365
+ const buffer = new ByteQueue()
359
366
  let parsedHeader: ReturnType<typeof parseHeader> | null = null
360
367
  let chunkIndex = 0
361
368
  let bytesEmitted = 0
@@ -366,16 +373,11 @@ export function createAesGcmV1DecryptStream(
366
373
  const transcript = new SenderSigTranscript()
367
374
 
368
375
  function append(input: Uint8Array): void {
369
- const merged = new Uint8Array(buffer.length + input.length)
370
- merged.set(buffer, 0)
371
- merged.set(input, buffer.length)
372
- buffer = merged
376
+ buffer.append(input)
373
377
  }
374
378
 
375
379
  function consume(n: number): Uint8Array {
376
- const out = buffer.subarray(0, n).slice(0)
377
- buffer = buffer.subarray(n).slice(0)
378
- return out
380
+ return buffer.take(n)
379
381
  }
380
382
 
381
383
  async function tryParseHeader(): Promise<boolean> {
@@ -403,8 +405,8 @@ export function createAesGcmV1DecryptStream(
403
405
  HEADER_SIZES.TOTAL_CHUNKS +
404
406
  HEADER_SIZES.PLAINTEXT_SIZE
405
407
  const suitePayloadLen =
406
- (buffer[suitePayloadLenOffset]! << 8) |
407
- buffer[suitePayloadLenOffset + 1]!
408
+ (buffer.byteAt(suitePayloadLenOffset) << 8) |
409
+ buffer.byteAt(suitePayloadLenOffset + 1)
408
410
  const fullHeaderLen =
409
411
  suitePayloadLenOffset +
410
412
  HEADER_SIZES.SUITE_PAYLOAD_LEN +
@@ -527,11 +529,11 @@ export function createAesGcmV1DecryptStream(
527
529
  throw new HeaderError('plaintext_size_mismatch')
528
530
  }
529
531
  const signatureResult = finalizeSignatureMetadata({
530
- trailingBytes: buffer,
532
+ trailingBytes: buffer.takeAll(),
531
533
  transcriptDigest: transcript.digest(),
532
534
  expectedSignerPublicKey,
535
+ signatureRequired,
533
536
  })
534
- buffer = new Uint8Array(0)
535
537
  resolveMetadata({ signature: signatureResult })
536
538
  } catch (err) {
537
539
  controller.error(err as Error)
@@ -49,6 +49,7 @@ import {
49
49
  SUITE,
50
50
  } from '../internal/types.js'
51
51
  import { concatBytes, readUint32BE, uint32BE } from '../internal/encoding.js'
52
+ import { ByteQueue } from '../internal/byte-queue.js'
52
53
  import { hmacSha256 } from '../internal/hmac.js'
53
54
  import { randomBytes } from '../internal/runtime.js'
54
55
  import {
@@ -63,6 +64,7 @@ import {
63
64
  type DecryptionMetadata,
64
65
  finalizeSignatureMetadata,
65
66
  } from './aes-gcm-v1.js'
67
+ import { assertSignatureRequirement } from '../format/signature-tail.js'
66
68
 
67
69
  export type { DecryptionMetadata, VerifiedSignature } from './aes-gcm-v1.js'
68
70
 
@@ -196,7 +198,7 @@ export function createPqHybridV1EncryptStream(
196
198
  // - context (lazily initialized)
197
199
  // - signature transcript (present only when signing): commits to the
198
200
  // header and every chunk's full ciphertext, hashed incrementally
199
- let pending = new Uint8Array(0)
201
+ const pending = new ByteQueue()
200
202
  let chunkIndex = 0
201
203
  let bytesConsumed = 0
202
204
  let contextPromise: ReturnType<typeof createChunkContext> | null = null
@@ -250,18 +252,11 @@ export function createPqHybridV1EncryptStream(
250
252
  return
251
253
  }
252
254
  // Append to pending buffer
253
- const merged = new Uint8Array(pending.length + chunk.length)
254
- merged.set(pending, 0)
255
- merged.set(chunk, pending.length)
256
- pending = merged
255
+ pending.append(chunk)
257
256
 
258
257
  // Drain whole chunks
259
258
  while (pending.length >= chunkSize && chunkIndex < totalChunks - 1) {
260
- const slice = pending.subarray(0, chunkSize)
261
- await emitChunk(slice, controller)
262
- pending = pending.subarray(chunkSize)
263
- // Subarray shares the buffer; copy out so we can drop the rest.
264
- pending = pending.slice(0)
259
+ await emitChunk(pending.take(chunkSize), controller)
265
260
  }
266
261
  },
267
262
  async flush(controller) {
@@ -280,9 +275,7 @@ export function createPqHybridV1EncryptStream(
280
275
  const sliceSize = isLastIteration
281
276
  ? pending.length // final chunk: whatever's left
282
277
  : chunkSize
283
- const slice = pending.subarray(0, sliceSize)
284
- await emitChunk(slice, controller)
285
- pending = pending.subarray(sliceSize).slice(0)
278
+ await emitChunk(pending.take(sliceSize), controller)
286
279
  }
287
280
  if (pending.length !== 0) {
288
281
  controller.error(
@@ -348,6 +341,15 @@ export type PqHybridV1DecryptStreamOptions =
348
341
  * for the verification semantics — they are identical here.
349
342
  */
350
343
  expectedSignerPublicKey?: Uint8Array
344
+ /**
345
+ * When true, decryption FAILS unless the file carries a trailing
346
+ * signature block that verifies against `expectedSignerPublicKey`
347
+ * (which must then be supplied). Use this wherever the caller relies
348
+ * on sender attribution: without it, an unsigned or wrongly-signed file
349
+ * still decrypts and only `signature.verified` tells them apart.
350
+ * Defaults to false (legacy/unsigned files decrypt as before).
351
+ */
352
+ signatureRequired?: boolean
351
353
  }
352
354
  | {
353
355
  /**
@@ -370,6 +372,15 @@ export type PqHybridV1DecryptStreamOptions =
370
372
  envelopeKey?: undefined
371
373
  /** See sibling variant. */
372
374
  expectedSignerPublicKey?: Uint8Array
375
+ /**
376
+ * When true, decryption FAILS unless the file carries a trailing
377
+ * signature block that verifies against `expectedSignerPublicKey`
378
+ * (which must then be supplied). Use this wherever the caller relies
379
+ * on sender attribution: without it, an unsigned or wrongly-signed file
380
+ * still decrypts and only `signature.verified` tells them apart.
381
+ * Defaults to false (legacy/unsigned files decrypt as before).
382
+ */
383
+ signatureRequired?: boolean
373
384
  }
374
385
 
375
386
  export interface PqHybridV1DecryptStreamResult {
@@ -400,6 +411,7 @@ export function createPqHybridV1DecryptStream(
400
411
  const recipientSecretKey = options.recipientSecretKey
401
412
  const envelopeKey = options.envelopeKey
402
413
  const expectedSignerPublicKey = options.expectedSignerPublicKey
414
+ const signatureRequired = assertSignatureRequirement(options)
403
415
 
404
416
  let resolveMetadata!: (m: DecryptionMetadata) => void
405
417
  let rejectMetadata!: (err: unknown) => void
@@ -430,7 +442,7 @@ export function createPqHybridV1DecryptStream(
430
442
  // 0 = waiting for header bytes
431
443
  // 1 = streaming chunks: alternating length-prefix + ciphertext
432
444
  let phase: 0 | 1 = 0
433
- let buffer = new Uint8Array(0)
445
+ const buffer = new ByteQueue()
434
446
  let parsedHeader: ReturnType<typeof parseHeader> | null = null
435
447
  let chunkIndex = 0
436
448
  let bytesEmitted = 0
@@ -441,16 +453,11 @@ export function createPqHybridV1DecryptStream(
441
453
  const transcript = new SenderSigTranscript()
442
454
 
443
455
  function append(input: Uint8Array): void {
444
- const merged = new Uint8Array(buffer.length + input.length)
445
- merged.set(buffer, 0)
446
- merged.set(input, buffer.length)
447
- buffer = merged
456
+ buffer.append(input)
448
457
  }
449
458
 
450
459
  function consume(n: number): Uint8Array {
451
- const out = buffer.subarray(0, n).slice(0)
452
- buffer = buffer.subarray(n).slice(0)
453
- return out
460
+ return buffer.take(n)
454
461
  }
455
462
 
456
463
  async function tryParseHeader(): Promise<boolean> {
@@ -478,8 +485,8 @@ export function createPqHybridV1DecryptStream(
478
485
  HEADER_SIZES.TOTAL_CHUNKS +
479
486
  HEADER_SIZES.PLAINTEXT_SIZE
480
487
  const suitePayloadLen =
481
- (buffer[suitePayloadLenOffset]! << 8) |
482
- buffer[suitePayloadLenOffset + 1]!
488
+ (buffer.byteAt(suitePayloadLenOffset) << 8) |
489
+ buffer.byteAt(suitePayloadLenOffset + 1)
483
490
  const fullHeaderLen =
484
491
  suitePayloadLenOffset +
485
492
  HEADER_SIZES.SUITE_PAYLOAD_LEN +
@@ -620,11 +627,11 @@ export function createPqHybridV1DecryptStream(
620
627
  throw new HeaderError('plaintext_size_mismatch')
621
628
  }
622
629
  const signatureResult = finalizeSignatureMetadata({
623
- trailingBytes: buffer,
630
+ trailingBytes: buffer.takeAll(),
624
631
  transcriptDigest: transcript.digest(),
625
632
  expectedSignerPublicKey,
633
+ signatureRequired,
626
634
  })
627
- buffer = new Uint8Array(0)
628
635
  resolveMetadata({ signature: signatureResult })
629
636
  } catch (err) {
630
637
  controller.error(err as Error)
@@ -1,9 +1,12 @@
1
1
  /**
2
2
  * Cipher suite "0x00" / v0: legacy AES-256-GCM, READ-ONLY.
3
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.
4
+ * This module decrypts files written by the pre-v1 ShieldFive client. It
5
+ * exports no writer. The library does export one, `encryptV0` from
6
+ * `@shieldfive/crypto/migration/v0`, solely to produce migration fixtures;
7
+ * applications MUST NOT write new files in this format (v0 has no truncation
8
+ * detection; see `spec/format-v0.md`). `looksLikeV0` below is a recovery
9
+ * heuristic, never a dispatcher.
7
10
  *
8
11
  * v0 wire format (described in `spec/format-v0.md`):
9
12
  *
@@ -141,6 +144,10 @@ export async function decryptV0ToBytes(
141
144
  * Detect whether a blob is v0 (legacy) by checking the absence of the v1
142
145
  * magic prefix. Use only when out-of-band metadata is unavailable. For
143
146
  * normal application use, the database flag `cipher_version` is canonical.
147
+ *
148
+ * @deprecated Not a dispatcher. spec/format-v1.md requires routing by an
149
+ * explicit version field and forbids cross-format auto-detection; this
150
+ * heuristic is for recovery tooling only.
144
151
  */
145
152
  export async function looksLikeV0(blob: Blob): Promise<boolean> {
146
153
  if (blob.size < 5) return true // too small to be v1
@@ -40,6 +40,7 @@ import {
40
40
  } from '../../internal/encoding.js'
41
41
  import { SenderSigTranscript } from '../../identity/sign.js'
42
42
  import {
43
+ assertSignatureRequirement,
43
44
  finalizeSignatureMetadata,
44
45
  type VerifiedSignature,
45
46
  } from '../../format/signature-tail.js'
@@ -118,6 +119,10 @@ export async function encryptBlob(
118
119
  `encryptBlob: suitePayloadOverride must be ${AES_GCM_V1_SUITE_PAYLOAD_LENGTH} bytes`,
119
120
  )
120
121
  }
122
+ // Run the reader's own payload check on the writer side, so the library
123
+ // never emits a file its readers refuse (a non-zero reserved pad passed
124
+ // through suitePayloadOverride). Throws RangeError like the checks above.
125
+ parseAesGcmV1SuitePayload(suitePayload)
121
126
 
122
127
  const header = await buildAuthenticatedHeader(
123
128
  {
@@ -179,6 +184,15 @@ export interface DecryptOptions {
179
184
  * block"`. Reaches parity with the streaming decoder.
180
185
  */
181
186
  expectedSignerPublicKey?: Uint8Array
187
+ /**
188
+ * When true, decryption FAILS unless the file carries a trailing
189
+ * signature block that verifies against `expectedSignerPublicKey`
190
+ * (which must then be supplied). Use this wherever the caller relies
191
+ * on sender attribution: without it, an unsigned or wrongly-signed file
192
+ * still decrypts and only `signature.verified` tells them apart.
193
+ * Defaults to false (legacy/unsigned files decrypt as before).
194
+ */
195
+ signatureRequired?: boolean
182
196
  /**
183
197
  * Called once, after the plaintext is fully decrypted, with the file's
184
198
  * sender-attribution signature — or `null` for a legacy/unsigned file.
@@ -257,6 +271,7 @@ export async function decryptBlob(options: DecryptOptions): Promise<Blob> {
257
271
  // to verify — otherwise a present block is still surfaced (verified:
258
272
  // null) without paying for the extra hash over every ciphertext byte.
259
273
  const expectedSignerPublicKey = options.expectedSignerPublicKey
274
+ const signatureRequired = assertSignatureRequirement(options)
260
275
  const transcript = expectedSignerPublicKey ? new SenderSigTranscript() : null
261
276
  transcript?.absorbHeader(parsed.unauthenticatedBytes, parsed.totalChunks)
262
277
 
@@ -320,6 +335,7 @@ export async function decryptBlob(options: DecryptOptions): Promise<Blob> {
320
335
  trailingBytes,
321
336
  transcriptDigest: transcript ? transcript.digest() : new Uint8Array(32),
322
337
  expectedSignerPublicKey,
338
+ signatureRequired,
323
339
  })
324
340
  options.onSignature?.(signature)
325
341
 
@@ -36,6 +36,7 @@ import {
36
36
  } from '../../internal/encoding.js'
37
37
  import { SenderSigTranscript } from '../../identity/sign.js'
38
38
  import {
39
+ assertSignatureRequirement,
39
40
  finalizeSignatureMetadata,
40
41
  type VerifiedSignature,
41
42
  } from '../../format/signature-tail.js'
@@ -112,6 +113,10 @@ export async function encryptBlob(
112
113
  `encryptBlob: suitePayloadOverride must be ${AES_GCM_V2_SUITE_PAYLOAD_LENGTH} bytes`,
113
114
  )
114
115
  }
116
+ // Run the reader's own payload check on the writer side, so the library
117
+ // never emits a file its readers refuse (a non-zero reserved pad passed
118
+ // through suitePayloadOverride). Throws RangeError like the checks above.
119
+ parseAesGcmV2SuitePayload(suitePayload)
115
120
 
116
121
  const header = await buildAuthenticatedHeader(
117
122
  {
@@ -168,6 +173,15 @@ export interface DecryptOptions {
168
173
  * block"`.
169
174
  */
170
175
  expectedSignerPublicKey?: Uint8Array
176
+ /**
177
+ * When true, decryption FAILS unless the file carries a trailing
178
+ * signature block that verifies against `expectedSignerPublicKey`
179
+ * (which must then be supplied). Use this wherever the caller relies
180
+ * on sender attribution: without it, an unsigned or wrongly-signed file
181
+ * still decrypts and only `signature.verified` tells them apart.
182
+ * Defaults to false (legacy/unsigned files decrypt as before).
183
+ */
184
+ signatureRequired?: boolean
171
185
  /**
172
186
  * Called once, after the plaintext is fully decrypted, with the file's
173
187
  * sender-attribution signature — or `null` for a legacy/unsigned file.
@@ -235,6 +249,7 @@ export async function decryptBlob(options: DecryptOptions): Promise<Blob> {
235
249
  // Rebuild the sender-attribution transcript only when verifying, so an
236
250
  // unsigned decrypt pays nothing for the extra hash over ciphertext.
237
251
  const expectedSignerPublicKey = options.expectedSignerPublicKey
252
+ const signatureRequired = assertSignatureRequirement(options)
238
253
  const transcript = expectedSignerPublicKey ? new SenderSigTranscript() : null
239
254
  transcript?.absorbHeader(parsed.unauthenticatedBytes, parsed.totalChunks)
240
255
 
@@ -293,6 +308,7 @@ export async function decryptBlob(options: DecryptOptions): Promise<Blob> {
293
308
  trailingBytes,
294
309
  transcriptDigest: transcript ? transcript.digest() : new Uint8Array(32),
295
310
  expectedSignerPublicKey,
311
+ signatureRequired,
296
312
  })
297
313
  options.onSignature?.(signature)
298
314
 
@@ -42,6 +42,7 @@ import {
42
42
  import { randomBytes } from '../../internal/runtime.js'
43
43
  import { SenderSigTranscript } from '../../identity/sign.js'
44
44
  import {
45
+ assertSignatureRequirement,
45
46
  finalizeSignatureMetadata,
46
47
  type VerifiedSignature,
47
48
  } from '../../format/signature-tail.js'
@@ -176,6 +177,15 @@ export interface DecryptOptions {
176
177
  * block"`.
177
178
  */
178
179
  expectedSignerPublicKey?: Uint8Array
180
+ /**
181
+ * When true, decryption FAILS unless the file carries a trailing
182
+ * signature block that verifies against `expectedSignerPublicKey`
183
+ * (which must then be supplied). Use this wherever the caller relies
184
+ * on sender attribution: without it, an unsigned or wrongly-signed file
185
+ * still decrypts and only `signature.verified` tells them apart.
186
+ * Defaults to false (legacy/unsigned files decrypt as before).
187
+ */
188
+ signatureRequired?: boolean
179
189
  /**
180
190
  * Called once, after the plaintext is fully decrypted, with the file's
181
191
  * sender-attribution signature — or `null` for a legacy/unsigned file.
@@ -242,6 +252,7 @@ export async function decryptBlob(
242
252
  // Rebuild the sender-attribution transcript only when verifying, so an
243
253
  // unsigned decrypt pays nothing for the extra hash over ciphertext.
244
254
  const expectedSignerPublicKey = options.expectedSignerPublicKey
255
+ const signatureRequired = assertSignatureRequirement(options)
245
256
  const transcript = expectedSignerPublicKey ? new SenderSigTranscript() : null
246
257
  transcript?.absorbHeader(parsed.unauthenticatedBytes, parsed.totalChunks)
247
258
 
@@ -300,6 +311,7 @@ export async function decryptBlob(
300
311
  trailingBytes,
301
312
  transcriptDigest: transcript ? transcript.digest() : new Uint8Array(32),
302
313
  expectedSignerPublicKey,
314
+ signatureRequired,
303
315
  })
304
316
  options.onSignature?.(signature)
305
317
 
@@ -34,6 +34,7 @@ import {
34
34
  } from '../../internal/encoding.js'
35
35
  import { SenderSigTranscript } from '../../identity/sign.js'
36
36
  import {
37
+ assertSignatureRequirement,
37
38
  finalizeSignatureMetadata,
38
39
  type VerifiedSignature,
39
40
  } from '../../format/signature-tail.js'
@@ -96,6 +97,10 @@ export async function encryptBlob(
96
97
  `encryptBlob: suitePayloadOverride must be ${XCHACHA_V1_SUITE_PAYLOAD_LENGTH} bytes`,
97
98
  )
98
99
  }
100
+ // Run the reader's own payload check on the writer side, so the library
101
+ // never emits a file its readers refuse (a non-zero reserved pad passed
102
+ // through suitePayloadOverride). Throws RangeError like the checks above.
103
+ parseXChaChaV1SuitePayload(suitePayload)
99
104
 
100
105
  const header = await buildAuthenticatedHeader(
101
106
  {
@@ -151,6 +156,15 @@ export interface DecryptOptions {
151
156
  * block"`.
152
157
  */
153
158
  expectedSignerPublicKey?: Uint8Array
159
+ /**
160
+ * When true, decryption FAILS unless the file carries a trailing
161
+ * signature block that verifies against `expectedSignerPublicKey`
162
+ * (which must then be supplied). Use this wherever the caller relies
163
+ * on sender attribution: without it, an unsigned or wrongly-signed file
164
+ * still decrypts and only `signature.verified` tells them apart.
165
+ * Defaults to false (legacy/unsigned files decrypt as before).
166
+ */
167
+ signatureRequired?: boolean
154
168
  /**
155
169
  * Called once, after the plaintext is fully decrypted, with the file's
156
170
  * sender-attribution signature — or `null` for a legacy/unsigned file.
@@ -219,6 +233,7 @@ export async function decryptBlob(
219
233
  // Rebuild the sender-attribution transcript only when verifying, so an
220
234
  // unsigned decrypt pays nothing for the extra hash over ciphertext.
221
235
  const expectedSignerPublicKey = options.expectedSignerPublicKey
236
+ const signatureRequired = assertSignatureRequirement(options)
222
237
  const transcript = expectedSignerPublicKey ? new SenderSigTranscript() : null
223
238
  transcript?.absorbHeader(parsed.unauthenticatedBytes, parsed.totalChunks)
224
239
 
@@ -277,6 +292,7 @@ export async function decryptBlob(
277
292
  trailingBytes,
278
293
  transcriptDigest: transcript ? transcript.digest() : new Uint8Array(32),
279
294
  expectedSignerPublicKey,
295
+ signatureRequired,
280
296
  })
281
297
  options.onSignature?.(signature)
282
298