@shieldfive/crypto 1.0.0 → 1.1.0
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.
- package/CHANGELOG.md +77 -0
- package/README.md +6 -6
- package/dist/format/signature-tail.d.ts +12 -0
- package/dist/format/signature-tail.d.ts.map +1 -1
- package/dist/format/signature-tail.js +24 -0
- package/dist/format/signature-tail.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/internal/byte-queue.d.ts +34 -0
- package/dist/internal/byte-queue.d.ts.map +1 -0
- package/dist/internal/byte-queue.js +82 -0
- package/dist/internal/byte-queue.js.map +1 -0
- package/dist/internal/encoding.d.ts +6 -0
- package/dist/internal/encoding.d.ts.map +1 -1
- package/dist/internal/encoding.js +11 -0
- package/dist/internal/encoding.js.map +1 -1
- package/dist/migration/v0-bridge.d.ts +5 -0
- package/dist/migration/v0-bridge.d.ts.map +1 -1
- package/dist/migration/v0-bridge.js +5 -0
- package/dist/migration/v0-bridge.js.map +1 -1
- package/dist/streams/aes-gcm-v1.d.ts +9 -0
- package/dist/streams/aes-gcm-v1.d.ts.map +1 -1
- package/dist/streams/aes-gcm-v1.js +18 -26
- package/dist/streams/aes-gcm-v1.js.map +1 -1
- package/dist/streams/pq-hybrid-v1.d.ts +18 -0
- package/dist/streams/pq-hybrid-v1.d.ts.map +1 -1
- package/dist/streams/pq-hybrid-v1.js +14 -25
- package/dist/streams/pq-hybrid-v1.js.map +1 -1
- package/dist/suites/aes-gcm-v0/api.d.ts +10 -3
- package/dist/suites/aes-gcm-v0/api.d.ts.map +1 -1
- package/dist/suites/aes-gcm-v0/api.js +10 -3
- package/dist/suites/aes-gcm-v0/api.js.map +1 -1
- package/dist/suites/aes-gcm-v1/api.d.ts +9 -0
- package/dist/suites/aes-gcm-v1/api.d.ts.map +1 -1
- package/dist/suites/aes-gcm-v1/api.js +7 -1
- package/dist/suites/aes-gcm-v1/api.js.map +1 -1
- package/dist/suites/aes-gcm-v2/api.d.ts +9 -0
- package/dist/suites/aes-gcm-v2/api.d.ts.map +1 -1
- package/dist/suites/aes-gcm-v2/api.js +7 -1
- package/dist/suites/aes-gcm-v2/api.js.map +1 -1
- package/dist/suites/pq-hybrid-v1/api.d.ts +9 -0
- package/dist/suites/pq-hybrid-v1/api.d.ts.map +1 -1
- package/dist/suites/pq-hybrid-v1/api.js +3 -1
- package/dist/suites/pq-hybrid-v1/api.js.map +1 -1
- package/dist/suites/xchacha-v1/api.d.ts +9 -0
- package/dist/suites/xchacha-v1/api.d.ts.map +1 -1
- package/dist/suites/xchacha-v1/api.js +7 -1
- package/dist/suites/xchacha-v1/api.js.map +1 -1
- package/dist/vault/index.d.ts +7 -3
- package/dist/vault/index.d.ts.map +1 -1
- package/dist/vault/index.js +71 -27
- package/dist/vault/index.js.map +1 -1
- package/package.json +2 -2
- package/spec/format-v0.md +11 -3
- package/spec/format-v1.md +3 -1
- package/spec/intake-link-pin.md +130 -0
- package/spec/vault-formats.md +5 -0
- package/src/format/signature-tail.ts +36 -0
- package/src/index.ts +1 -1
- package/src/internal/byte-queue.ts +86 -0
- package/src/internal/encoding.ts +11 -0
- package/src/migration/v0-bridge.ts +5 -0
- package/src/streams/aes-gcm-v1.ts +27 -25
- package/src/streams/pq-hybrid-v1.ts +32 -25
- package/src/suites/aes-gcm-v0/api.ts +10 -3
- package/src/suites/aes-gcm-v1/api.ts +16 -0
- package/src/suites/aes-gcm-v2/api.ts +16 -0
- package/src/suites/pq-hybrid-v1/api.ts +12 -0
- package/src/suites/xchacha-v1/api.ts +16 -0
- package/src/vault/index.ts +92 -26
package/spec/format-v1.md
CHANGED
|
@@ -560,7 +560,9 @@ magic/suite/file_id bytes do not form a valid GCM tag). A v0 blob fed to
|
|
|
560
560
|
`parseHeader` fails the magic-byte check with probability `1 - 2^-40`
|
|
561
561
|
per file. Application dispatchers MUST route by an explicit version
|
|
562
562
|
field (e.g. a database column) and MUST NOT auto-detect across formats.
|
|
563
|
-
The library
|
|
563
|
+
The library exports one heuristic detector, `looksLikeV0`
|
|
564
|
+
(`@shieldfive/crypto/legacy-v0`), for recovery tooling that has lost its
|
|
565
|
+
metadata. It is not a dispatcher, and the rule above still applies to it.
|
|
564
566
|
|
|
565
567
|
## Test vectors
|
|
566
568
|
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
# Intake link signing-key pin (`#f=`)
|
|
2
|
+
|
|
3
|
+
Used by the ShieldFive web app's request links (`/r/<slug>`) and form links
|
|
4
|
+
(`/form/<slug>`). The reference implementation is `utils/inboundIntake.ts` in
|
|
5
|
+
`shieldfive/web` (`signingKeyPin`, `signingKeyPinFromHash`,
|
|
6
|
+
`buildIntakeFragment`, `checkSigningKeyPin`, `encryptFileForRequest`). This
|
|
7
|
+
library does not implement it. This file specifies it so that any client that
|
|
8
|
+
mints or opens intake links can interoperate.
|
|
9
|
+
|
|
10
|
+
## 1. Threat
|
|
11
|
+
|
|
12
|
+
A guest who opens an intake link fetches the firm's key bundle from the
|
|
13
|
+
server: an ML-KEM public key, an X25519 public key, an Ed25519 signing public
|
|
14
|
+
key and a signature over the encryption keys. All four come from one server
|
|
15
|
+
response. Checking the signature against the signing key from that same
|
|
16
|
+
response proves nothing. Anyone who can write the request or form row (a
|
|
17
|
+
compromised server, a database attacker, an insider) can put in their own
|
|
18
|
+
keys signed with their own signing key, and the guest would encrypt to them.
|
|
19
|
+
|
|
20
|
+
The pin anchors the signing key outside the server. The URL fragment is never
|
|
21
|
+
sent to the server, so the firm's browser puts a digest of the firm's signing
|
|
22
|
+
key there when it mints or copies a link. It computes the pin from the firm
|
|
23
|
+
identity key it holds locally, never from the database row. The guest
|
|
24
|
+
refuses to encrypt unless the served signing key hashes to the pin.
|
|
25
|
+
|
|
26
|
+
Out of scope:
|
|
27
|
+
|
|
28
|
+
- An attacker who can change the link itself before the guest opens it (for
|
|
29
|
+
example in the email or chat that carries it). That attacker can also
|
|
30
|
+
replace `k=`.
|
|
31
|
+
- An attacker who serves a modified web app to the guest. The check runs in
|
|
32
|
+
the page the server delivers.
|
|
33
|
+
- Legacy links with no `f=` (section 5).
|
|
34
|
+
|
|
35
|
+
## 2. Pin
|
|
36
|
+
|
|
37
|
+
```
|
|
38
|
+
domain = UTF-8("shieldfive/inbound/signing-key-pin/v1") // 37 bytes, no terminator
|
|
39
|
+
pk = Ed25519 signing public key, raw // 32 bytes
|
|
40
|
+
pin = base64url_nopad( SHA-256( domain || pk ) ) // 43 chars
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
- `||` is plain concatenation. There is no length prefix and no separator.
|
|
44
|
+
The input is always 69 bytes.
|
|
45
|
+
- `base64url_nopad` is RFC 4648 section 5 (`-` and `_` in place of `+` and
|
|
46
|
+
`/`) with the `=` padding removed. A 32-byte digest always encodes to
|
|
47
|
+
exactly 43 characters.
|
|
48
|
+
- The key bundle carries the signing key as standard base64. Decode it to the
|
|
49
|
+
raw 32 bytes before hashing. Never hash the base64 text.
|
|
50
|
+
|
|
51
|
+
A valid pin matches `^[A-Za-z0-9_-]{43}$`.
|
|
52
|
+
|
|
53
|
+
The pin covers the signing (identity) key only, not the encryption keys. The
|
|
54
|
+
firm can replace its encryption keys under the same identity by signing the
|
|
55
|
+
new keys with the pinned key, and links already sent keep working.
|
|
56
|
+
|
|
57
|
+
## 3. Link fragment
|
|
58
|
+
|
|
59
|
+
```
|
|
60
|
+
/r/<slug>#f=<pin>&k=<fragment key>
|
|
61
|
+
/form/<slug>#f=<pin>&k=<fragment key>
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
New links put `f=` before `k=`. If a chat client truncates the link, it cuts
|
|
65
|
+
`k=` before it can cut `f=`. A link with no `k=` is refused outright, so
|
|
66
|
+
truncation can never turn a pinned link into an unpinned one.
|
|
67
|
+
|
|
68
|
+
To parse, take the value after the first `f=` that follows `#` or `&`, up to
|
|
69
|
+
the next `&` or the end. The result is one of:
|
|
70
|
+
|
|
71
|
+
| State | Condition |
|
|
72
|
+
|-------------|-------------------------------------------------|
|
|
73
|
+
| `absent` | No `f=` parameter |
|
|
74
|
+
| `pinned` | `f=` value matches `^[A-Za-z0-9_-]{43}$` |
|
|
75
|
+
| `malformed` | `f=` present, any other value (including empty) |
|
|
76
|
+
|
|
77
|
+
A malformed pin is a failed check. It is never treated as `absent`, because
|
|
78
|
+
only the firm puts an `f=` in a link, so anything else means the link was
|
|
79
|
+
altered.
|
|
80
|
+
|
|
81
|
+
## 4. Check
|
|
82
|
+
|
|
83
|
+
The guest computes the pin from the served signing key and compares it with
|
|
84
|
+
the link's pin:
|
|
85
|
+
|
|
86
|
+
| Link state | Served key | Verdict |
|
|
87
|
+
|-------------|--------------------------------------------------|------------|
|
|
88
|
+
| `absent` | any | `unpinned` |
|
|
89
|
+
| `malformed` | any | `mismatch` |
|
|
90
|
+
| `pinned` | missing, not a string, or not decodable | `mismatch` |
|
|
91
|
+
| `pinned` | pin of served key equals link pin | `verified` |
|
|
92
|
+
| `pinned` | pin of served key differs | `mismatch` |
|
|
93
|
+
|
|
94
|
+
The comparison is over the 43-character strings and does not exit early.
|
|
95
|
+
Both sides are public, so this is habit, not a secrecy requirement.
|
|
96
|
+
|
|
97
|
+
The check runs in two places:
|
|
98
|
+
|
|
99
|
+
1. When the page loads, after the bundle is resolved and before any file is
|
|
100
|
+
chosen or any form field is typed. On `mismatch` the request page shows an
|
|
101
|
+
error and disables upload. The form page refuses to render the form.
|
|
102
|
+
2. Inside the encrypt call (`encryptFileForRequest`, and the form-answer
|
|
103
|
+
sealing that calls the same check). The pin argument is required. On
|
|
104
|
+
`mismatch` the call throws `SigningKeyPinMismatchError` before it touches
|
|
105
|
+
the plaintext, so a page that skips the first check still cannot encrypt
|
|
106
|
+
to a substituted bundle.
|
|
107
|
+
|
|
108
|
+
After `verified` or `unpinned`, the Ed25519 signature on the encryption keys
|
|
109
|
+
is verified against the served signing key as before. Under `verified`, that
|
|
110
|
+
signature now binds the encryption keys to the firm's identity.
|
|
111
|
+
|
|
112
|
+
## 5. Legacy links
|
|
113
|
+
|
|
114
|
+
Links minted before pinning have no `f=`. They give `unpinned`. Uploads and
|
|
115
|
+
form answers still work. The request page tells the guest that the firm's key
|
|
116
|
+
could not be confirmed. Against a server that replaces the whole bundle, the
|
|
117
|
+
signature check alone proves nothing for these links. Copying a link again
|
|
118
|
+
from the firm's dashboard produces a pinned link.
|
|
119
|
+
|
|
120
|
+
## 6. Test vectors
|
|
121
|
+
|
|
122
|
+
| Signing public key (hex) | SHA-256 input digest (hex) | Pin |
|
|
123
|
+
|--------------------------------------------------------------------|--------------------------------------------------------------------|-----------------------------------------------|
|
|
124
|
+
| `000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f` | `e4bb2fc925069ec2d6e24bf42f144047482b99c5e6fda485397011ec59320f94` | `5LsvySUGnsLW4kv0LxRAR0grmcXm_aSFOXAR7FkyD5Q` |
|
|
125
|
+
| `ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff` | `27d8d54994db80a1e2c09f07961f1e6bcc85032f9a5ab956284f7803cce6df15` | `J9jVSZTbgKHiwJ8Hlh8ea8yFAy-aWrlWKE94A8zm3xU` |
|
|
126
|
+
|
|
127
|
+
The digest column is `SHA-256(domain || pk)`. The first vector is asserted
|
|
128
|
+
against the reference implementation in `shieldfive/web`
|
|
129
|
+
`tests/inboundKeyPinning.test.ts`. As carried in a key bundle, its key is
|
|
130
|
+
`AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=`.
|
package/spec/vault-formats.md
CHANGED
|
@@ -40,6 +40,11 @@ v6: AES-256-GCM(name key, iv, aad = UTF-8 of row UUID, pt = UTF-8 name)
|
|
|
40
40
|
```
|
|
41
41
|
|
|
42
42
|
If `kdf` is missing, a reader tries interactive first and then moderate.
|
|
43
|
+
The stored `kdf` is server-writable data, so it may only narrow that search:
|
|
44
|
+
`"interactive"` means interactive alone, and any other value is read as
|
|
45
|
+
interactive then moderate. It never makes a reader start at the higher cost.
|
|
46
|
+
A field that is not valid base64, or an `iv`/`tag`/`salt` of the wrong length,
|
|
47
|
+
is `unsupported_envelope`.
|
|
43
48
|
Writers always emit v6 with `kdf: "interactive"`. The password already
|
|
44
49
|
carries 256 bits of entropy, so the cost level only exists for compatibility.
|
|
45
50
|
|
|
@@ -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.
|
|
223
|
+
export const SHIELDFIVE_CRYPTO_VERSION = '1.1.0'
|
|
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
|
+
}
|
package/src/internal/encoding.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
407
|
-
buffer
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
482
|
-
buffer
|
|
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
|
-
*
|
|
6
|
-
*
|
|
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
|