@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.
- package/CHANGELOG.md +228 -0
- package/LICENSE +201 -0
- package/README.md +275 -0
- package/SECURITY.md +130 -0
- package/dist/format/header.d.ts +73 -0
- package/dist/format/header.d.ts.map +1 -0
- package/dist/format/header.js +230 -0
- package/dist/format/header.js.map +1 -0
- package/dist/identity/index.d.ts +119 -0
- package/dist/identity/index.d.ts.map +1 -0
- package/dist/identity/index.js +217 -0
- package/dist/identity/index.js.map +1 -0
- package/dist/identity/sign.d.ts +92 -0
- package/dist/identity/sign.d.ts.map +1 -0
- package/dist/identity/sign.js +182 -0
- package/dist/identity/sign.js.map +1 -0
- package/dist/index.d.ts +58 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +146 -0
- package/dist/index.js.map +1 -0
- package/dist/internal/encoding.d.ts +33 -0
- package/dist/internal/encoding.d.ts.map +1 -0
- package/dist/internal/encoding.js +135 -0
- package/dist/internal/encoding.js.map +1 -0
- package/dist/internal/hkdf.d.ts +14 -0
- package/dist/internal/hkdf.d.ts.map +1 -0
- package/dist/internal/hkdf.js +27 -0
- package/dist/internal/hkdf.js.map +1 -0
- package/dist/internal/hmac.d.ts +9 -0
- package/dist/internal/hmac.d.ts.map +1 -0
- package/dist/internal/hmac.js +18 -0
- package/dist/internal/hmac.js.map +1 -0
- package/dist/internal/runtime.d.ts +29 -0
- package/dist/internal/runtime.d.ts.map +1 -0
- package/dist/internal/runtime.js +67 -0
- package/dist/internal/runtime.js.map +1 -0
- package/dist/internal/sodium.d.ts +12 -0
- package/dist/internal/sodium.d.ts.map +1 -0
- package/dist/internal/sodium.js +34 -0
- package/dist/internal/sodium.js.map +1 -0
- package/dist/internal/types.d.ts +98 -0
- package/dist/internal/types.d.ts.map +1 -0
- package/dist/internal/types.js +70 -0
- package/dist/internal/types.js.map +1 -0
- package/dist/kdf/argon2id.d.ts +72 -0
- package/dist/kdf/argon2id.d.ts.map +1 -0
- package/dist/kdf/argon2id.js +98 -0
- package/dist/kdf/argon2id.js.map +1 -0
- package/dist/migration/v0-bridge.d.ts +94 -0
- package/dist/migration/v0-bridge.d.ts.map +1 -0
- package/dist/migration/v0-bridge.js +203 -0
- package/dist/migration/v0-bridge.js.map +1 -0
- package/dist/streams/aes-gcm-v1.d.ts +144 -0
- package/dist/streams/aes-gcm-v1.d.ts.map +1 -0
- package/dist/streams/aes-gcm-v1.js +456 -0
- package/dist/streams/aes-gcm-v1.js.map +1 -0
- package/dist/streams/pq-hybrid-v1.d.ts +219 -0
- package/dist/streams/pq-hybrid-v1.d.ts.map +1 -0
- package/dist/streams/pq-hybrid-v1.js +473 -0
- package/dist/streams/pq-hybrid-v1.js.map +1 -0
- package/dist/suites/aes-gcm-v0/api.d.ts +48 -0
- package/dist/suites/aes-gcm-v0/api.d.ts.map +1 -0
- package/dist/suites/aes-gcm-v0/api.js +110 -0
- package/dist/suites/aes-gcm-v0/api.js.map +1 -0
- package/dist/suites/aes-gcm-v1/api.d.ts +54 -0
- package/dist/suites/aes-gcm-v1/api.d.ts.map +1 -0
- package/dist/suites/aes-gcm-v1/api.js +181 -0
- package/dist/suites/aes-gcm-v1/api.js.map +1 -0
- package/dist/suites/aes-gcm-v1/index.d.ts +59 -0
- package/dist/suites/aes-gcm-v1/index.d.ts.map +1 -0
- package/dist/suites/aes-gcm-v1/index.js +177 -0
- package/dist/suites/aes-gcm-v1/index.js.map +1 -0
- package/dist/suites/aes-gcm-v2/api.d.ts +44 -0
- package/dist/suites/aes-gcm-v2/api.d.ts.map +1 -0
- package/dist/suites/aes-gcm-v2/api.js +162 -0
- package/dist/suites/aes-gcm-v2/api.js.map +1 -0
- package/dist/suites/aes-gcm-v2/index.d.ts +63 -0
- package/dist/suites/aes-gcm-v2/index.d.ts.map +1 -0
- package/dist/suites/aes-gcm-v2/index.js +193 -0
- package/dist/suites/aes-gcm-v2/index.js.map +1 -0
- package/dist/suites/pq-hybrid-v1/api.d.ts +67 -0
- package/dist/suites/pq-hybrid-v1/api.d.ts.map +1 -0
- package/dist/suites/pq-hybrid-v1/api.js +190 -0
- package/dist/suites/pq-hybrid-v1/api.js.map +1 -0
- package/dist/suites/pq-hybrid-v1/index.d.ts +101 -0
- package/dist/suites/pq-hybrid-v1/index.d.ts.map +1 -0
- package/dist/suites/pq-hybrid-v1/index.js +225 -0
- package/dist/suites/pq-hybrid-v1/index.js.map +1 -0
- package/dist/suites/xchacha-v1/api.d.ts +29 -0
- package/dist/suites/xchacha-v1/api.d.ts.map +1 -0
- package/dist/suites/xchacha-v1/api.js +154 -0
- package/dist/suites/xchacha-v1/api.js.map +1 -0
- package/dist/suites/xchacha-v1/index.d.ts +50 -0
- package/dist/suites/xchacha-v1/index.d.ts.map +1 -0
- package/dist/suites/xchacha-v1/index.js +133 -0
- package/dist/suites/xchacha-v1/index.js.map +1 -0
- package/package.json +124 -0
- package/spec/format-v0.md +81 -0
- package/spec/format-v1.md +400 -0
- package/spec/key-derivation.md +167 -0
- package/spec/threat-model.md +242 -0
- package/src/format/header.ts +316 -0
- package/src/identity/index.ts +371 -0
- package/src/identity/sign.ts +221 -0
- package/src/index.ts +224 -0
- package/src/internal/encoding.ts +152 -0
- package/src/internal/hkdf.ts +47 -0
- package/src/internal/hmac.ts +33 -0
- package/src/internal/runtime.ts +80 -0
- package/src/internal/sodium.ts +38 -0
- package/src/internal/types.ts +134 -0
- package/src/kdf/argon2id.ts +165 -0
- package/src/migration/v0-bridge.ts +347 -0
- package/src/streams/aes-gcm-v1.ts +647 -0
- package/src/streams/pq-hybrid-v1.ts +722 -0
- package/src/suites/aes-gcm-v0/api.ts +155 -0
- package/src/suites/aes-gcm-v1/api.ts +292 -0
- package/src/suites/aes-gcm-v1/index.ts +269 -0
- package/src/suites/aes-gcm-v2/api.ts +268 -0
- package/src/suites/aes-gcm-v2/index.ts +289 -0
- package/src/suites/pq-hybrid-v1/api.ts +299 -0
- package/src/suites/pq-hybrid-v1/index.ts +343 -0
- package/src/suites/xchacha-v1/api.ts +254 -0
- package/src/suites/xchacha-v1/index.ts +213 -0
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* User identity & public-key directory helpers.
|
|
3
|
+
*
|
|
4
|
+
* In a multi-user system, the PQ-hybrid suite needs the recipient's public
|
|
5
|
+
* key to encrypt to. This module provides:
|
|
6
|
+
*
|
|
7
|
+
* - A canonical wire format for publishing a user's public-key bundle
|
|
8
|
+
* (ML-KEM-1024 public key + a self-signed-by-application identity tag).
|
|
9
|
+
* - Helpers for creating, parsing, and verifying public-key bundles.
|
|
10
|
+
* - Helpers for re-encrypting a file's content key to additional
|
|
11
|
+
* recipients (sharing) without re-uploading the file.
|
|
12
|
+
*
|
|
13
|
+
* Cryptographic identity beyond the application's own auth layer is
|
|
14
|
+
* deliberately NOT in scope. The bundle format does not sign the public
|
|
15
|
+
* key with any user-controlled key — the trust anchor is the application's
|
|
16
|
+
* authenticated channel for publishing keys (TLS + auth token). If callers
|
|
17
|
+
* want stronger identity (e.g. SAS verification, gossiped signatures),
|
|
18
|
+
* they wrap this module rather than modify it.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import {
|
|
22
|
+
ML_KEM_1024_PUBLIC_KEY_BYTES,
|
|
23
|
+
ML_KEM_1024_SECRET_KEY_BYTES,
|
|
24
|
+
deriveMlKemKeypair,
|
|
25
|
+
generateMlKemKeypair,
|
|
26
|
+
encapsulateForRecipient,
|
|
27
|
+
decapsulateFromHeader,
|
|
28
|
+
parsePqHybridV1SuitePayload,
|
|
29
|
+
buildPqHybridV1SuitePayload,
|
|
30
|
+
} from '../suites/pq-hybrid-v1/index.js'
|
|
31
|
+
export {
|
|
32
|
+
SIGNATURE_ALGO_ED25519,
|
|
33
|
+
SIGNATURE_ALGO_ML_DSA_65,
|
|
34
|
+
ED25519_PUBLIC_KEY_LENGTH,
|
|
35
|
+
ED25519_SECRET_KEY_LENGTH,
|
|
36
|
+
ED25519_SIGNATURE_LENGTH,
|
|
37
|
+
SignatureError,
|
|
38
|
+
buildSignatureBlock,
|
|
39
|
+
deriveEd25519PublicKey,
|
|
40
|
+
parseSignatureBlock,
|
|
41
|
+
signHeaderAndMacs,
|
|
42
|
+
verifyHeaderAndMacs,
|
|
43
|
+
} from './sign.js'
|
|
44
|
+
export type { SignatureBlock } from './sign.js'
|
|
45
|
+
import {
|
|
46
|
+
bytesToBase64,
|
|
47
|
+
base64ToBytes,
|
|
48
|
+
concatBytes,
|
|
49
|
+
uint16BE,
|
|
50
|
+
uint32BE,
|
|
51
|
+
readUint16BE,
|
|
52
|
+
readUint32BE,
|
|
53
|
+
} from '../internal/encoding.js'
|
|
54
|
+
import { randomBytes } from '../internal/runtime.js'
|
|
55
|
+
import { getSodium } from '../internal/sodium.js'
|
|
56
|
+
|
|
57
|
+
const IDENTITY_BUNDLE_MAGIC = new Uint8Array([0x53, 0x46, 0x35, 0x49, 0x01]) // "SF5I" + version
|
|
58
|
+
|
|
59
|
+
export interface PublicIdentityBundle {
|
|
60
|
+
/** ML-KEM-1024 public key (1568 bytes) */
|
|
61
|
+
mlKemPublicKey: Uint8Array
|
|
62
|
+
/** Application-assigned user ID (UTF-8 string, ≤255 bytes) */
|
|
63
|
+
userId: string
|
|
64
|
+
/** Optional metadata blob (≤4 KiB), e.g. a profile JSON */
|
|
65
|
+
metadata?: Uint8Array
|
|
66
|
+
/** Issuance timestamp (UNIX seconds, uint32) */
|
|
67
|
+
issuedAt: number
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Wire format for an identity bundle:
|
|
72
|
+
*
|
|
73
|
+
* magic 5 bytes "SF5I" + version
|
|
74
|
+
* issued_at 4 bytes uint32 BE (UNIX seconds)
|
|
75
|
+
* user_id_len 1 byte
|
|
76
|
+
* user_id variable UTF-8
|
|
77
|
+
* ml_kem_pk 1568 bytes
|
|
78
|
+
* metadata_len 2 bytes uint16 BE
|
|
79
|
+
* metadata variable opaque
|
|
80
|
+
*
|
|
81
|
+
* Unsigned. Trust comes from the channel that publishes it.
|
|
82
|
+
*/
|
|
83
|
+
|
|
84
|
+
export function encodeIdentityBundle(bundle: PublicIdentityBundle): Uint8Array {
|
|
85
|
+
if (bundle.mlKemPublicKey.length !== ML_KEM_1024_PUBLIC_KEY_BYTES) {
|
|
86
|
+
throw new RangeError(
|
|
87
|
+
`encodeIdentityBundle: mlKemPublicKey must be ${ML_KEM_1024_PUBLIC_KEY_BYTES} bytes`,
|
|
88
|
+
)
|
|
89
|
+
}
|
|
90
|
+
const userIdBytes = new TextEncoder().encode(bundle.userId)
|
|
91
|
+
if (userIdBytes.length === 0 || userIdBytes.length > 255) {
|
|
92
|
+
throw new RangeError(
|
|
93
|
+
'encodeIdentityBundle: userId must be 1..255 UTF-8 bytes',
|
|
94
|
+
)
|
|
95
|
+
}
|
|
96
|
+
if (
|
|
97
|
+
!Number.isSafeInteger(bundle.issuedAt) ||
|
|
98
|
+
bundle.issuedAt < 0 ||
|
|
99
|
+
bundle.issuedAt > 0xffff_ffff
|
|
100
|
+
) {
|
|
101
|
+
throw new RangeError('encodeIdentityBundle: issuedAt must fit in uint32')
|
|
102
|
+
}
|
|
103
|
+
const metadata = bundle.metadata ?? new Uint8Array(0)
|
|
104
|
+
if (metadata.length > 4096) {
|
|
105
|
+
throw new RangeError(
|
|
106
|
+
'encodeIdentityBundle: metadata must be at most 4096 bytes',
|
|
107
|
+
)
|
|
108
|
+
}
|
|
109
|
+
return concatBytes([
|
|
110
|
+
IDENTITY_BUNDLE_MAGIC,
|
|
111
|
+
uint32BE(bundle.issuedAt),
|
|
112
|
+
new Uint8Array([userIdBytes.length]),
|
|
113
|
+
userIdBytes,
|
|
114
|
+
bundle.mlKemPublicKey,
|
|
115
|
+
uint16BE(metadata.length),
|
|
116
|
+
metadata,
|
|
117
|
+
])
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function decodeIdentityBundle(bytes: Uint8Array): PublicIdentityBundle {
|
|
121
|
+
if (bytes.length < IDENTITY_BUNDLE_MAGIC.length + 4 + 1) {
|
|
122
|
+
throw new RangeError('decodeIdentityBundle: input too short')
|
|
123
|
+
}
|
|
124
|
+
for (let i = 0; i < IDENTITY_BUNDLE_MAGIC.length; i += 1) {
|
|
125
|
+
if (bytes[i] !== IDENTITY_BUNDLE_MAGIC[i]) {
|
|
126
|
+
throw new Error('decodeIdentityBundle: bad magic / unknown bundle version')
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
let offset = IDENTITY_BUNDLE_MAGIC.length
|
|
131
|
+
const issuedAt = readUint32BE(bytes, offset)
|
|
132
|
+
offset += 4
|
|
133
|
+
|
|
134
|
+
const userIdLen = bytes[offset]!
|
|
135
|
+
offset += 1
|
|
136
|
+
if (userIdLen === 0) {
|
|
137
|
+
throw new Error('decodeIdentityBundle: empty user_id')
|
|
138
|
+
}
|
|
139
|
+
if (offset + userIdLen + ML_KEM_1024_PUBLIC_KEY_BYTES + 2 > bytes.length) {
|
|
140
|
+
throw new Error('decodeIdentityBundle: truncated')
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const userId = new TextDecoder('utf-8', { fatal: true }).decode(
|
|
144
|
+
bytes.slice(offset, offset + userIdLen),
|
|
145
|
+
)
|
|
146
|
+
offset += userIdLen
|
|
147
|
+
|
|
148
|
+
const mlKemPublicKey = bytes.slice(
|
|
149
|
+
offset,
|
|
150
|
+
offset + ML_KEM_1024_PUBLIC_KEY_BYTES,
|
|
151
|
+
)
|
|
152
|
+
offset += ML_KEM_1024_PUBLIC_KEY_BYTES
|
|
153
|
+
|
|
154
|
+
const metadataLen = readUint16BE(bytes, offset)
|
|
155
|
+
offset += 2
|
|
156
|
+
if (offset + metadataLen !== bytes.length) {
|
|
157
|
+
throw new Error('decodeIdentityBundle: trailing bytes or wrong metadata_len')
|
|
158
|
+
}
|
|
159
|
+
const metadata = bytes.slice(offset, offset + metadataLen)
|
|
160
|
+
|
|
161
|
+
const result: PublicIdentityBundle = {
|
|
162
|
+
mlKemPublicKey,
|
|
163
|
+
userId,
|
|
164
|
+
issuedAt,
|
|
165
|
+
}
|
|
166
|
+
if (metadata.length > 0) result.metadata = metadata
|
|
167
|
+
return result
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Serialize a bundle as a base64 string suitable for storing in a database
|
|
172
|
+
* column or transmitting over a JSON API.
|
|
173
|
+
*/
|
|
174
|
+
export function bundleToBase64(bundle: PublicIdentityBundle): string {
|
|
175
|
+
return bytesToBase64(encodeIdentityBundle(bundle))
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export function bundleFromBase64(b64: string): PublicIdentityBundle {
|
|
179
|
+
return decodeIdentityBundle(base64ToBytes(b64))
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
183
|
+
// Identity creation
|
|
184
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
185
|
+
|
|
186
|
+
export interface CreateIdentityOptions {
|
|
187
|
+
userId: string
|
|
188
|
+
metadata?: Uint8Array
|
|
189
|
+
/**
|
|
190
|
+
* If provided, the ML-KEM keypair is derived deterministically from
|
|
191
|
+
* this master secret. Otherwise a fresh keypair is generated. Most
|
|
192
|
+
* applications should pass the user's master secret here so that
|
|
193
|
+
* loss of an ML-KEM secret key does not lock the user out.
|
|
194
|
+
*/
|
|
195
|
+
masterSecret?: Uint8Array
|
|
196
|
+
/** Defaults to current time. */
|
|
197
|
+
issuedAt?: number
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
export interface IdentityKeypair {
|
|
201
|
+
publicBundle: PublicIdentityBundle
|
|
202
|
+
/** Encoded form of the public bundle for direct publishing. */
|
|
203
|
+
publicBundleBytes: Uint8Array
|
|
204
|
+
/** ML-KEM-1024 secret key. Treat as highly sensitive. */
|
|
205
|
+
mlKemSecretKey: Uint8Array
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
export async function createIdentity(
|
|
209
|
+
options: CreateIdentityOptions,
|
|
210
|
+
): Promise<IdentityKeypair> {
|
|
211
|
+
const keypair = options.masterSecret
|
|
212
|
+
? await deriveMlKemKeypair(options.masterSecret)
|
|
213
|
+
: generateMlKemKeypair()
|
|
214
|
+
|
|
215
|
+
const bundle: PublicIdentityBundle = {
|
|
216
|
+
mlKemPublicKey: keypair.publicKey,
|
|
217
|
+
userId: options.userId,
|
|
218
|
+
issuedAt: options.issuedAt ?? Math.floor(Date.now() / 1000),
|
|
219
|
+
}
|
|
220
|
+
if (options.metadata) bundle.metadata = options.metadata
|
|
221
|
+
|
|
222
|
+
if (keypair.secretKey.length !== ML_KEM_1024_SECRET_KEY_BYTES) {
|
|
223
|
+
throw new Error(
|
|
224
|
+
`createIdentity: unexpected secret key length ${keypair.secretKey.length}`,
|
|
225
|
+
)
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
return {
|
|
229
|
+
publicBundle: bundle,
|
|
230
|
+
publicBundleBytes: encodeIdentityBundle(bundle),
|
|
231
|
+
mlKemSecretKey: keypair.secretKey,
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
236
|
+
// Sharing: re-encrypt a file's content key to additional recipients
|
|
237
|
+
// ──────────────────────────────────────────────────────────────────────
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* The PQ-hybrid suite encrypts each file's combined key for exactly one
|
|
241
|
+
* recipient (whoever owns the ML-KEM public key the encryptor used).
|
|
242
|
+
* Sharing a file with N additional recipients means: recover the
|
|
243
|
+
* original combined key (only the owner can do this), then produce N new
|
|
244
|
+
* suite_payloads — one per recipient — that decrypt to the SAME combined
|
|
245
|
+
* key. The chunks themselves are not re-encrypted.
|
|
246
|
+
*
|
|
247
|
+
* Each per-recipient suite_payload is stored alongside the file's chunks
|
|
248
|
+
* in the application's database (one row per recipient). The on-disk
|
|
249
|
+
* blob remains unchanged.
|
|
250
|
+
*/
|
|
251
|
+
|
|
252
|
+
export interface ShareFileInput {
|
|
253
|
+
/** The file's combined key, recovered by the owner. */
|
|
254
|
+
combinedKey: Uint8Array
|
|
255
|
+
/** The file's 16-byte file_id. */
|
|
256
|
+
fileId: Uint8Array
|
|
257
|
+
/** The recipient's identity bundle (provides their ML-KEM public key). */
|
|
258
|
+
recipient: PublicIdentityBundle
|
|
259
|
+
/** Classical envelope key the recipient holds. */
|
|
260
|
+
recipientEnvelopeKey: Uint8Array
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Build a new suite_payload that decrypts to `combinedKey` for the given
|
|
265
|
+
* recipient. Stored alongside the file as a per-recipient share record.
|
|
266
|
+
*
|
|
267
|
+
* NOTE: the standard `encapsulateForRecipient` produces a NEW combined
|
|
268
|
+
* key. To make sharing work, we use a different construction: we wrap
|
|
269
|
+
* the existing combined key under (recipient PQ KEM ⊕ recipient
|
|
270
|
+
* envelope) and emit only the wrapped form.
|
|
271
|
+
*/
|
|
272
|
+
export async function buildShareForRecipient(
|
|
273
|
+
input: ShareFileInput,
|
|
274
|
+
): Promise<{ shareBundle: Uint8Array }> {
|
|
275
|
+
const sodium = await getSodium()
|
|
276
|
+
|
|
277
|
+
// Generate a fresh transport key for this share.
|
|
278
|
+
// ML-KEM encapsulation gives us the PQ-half of the transport secret.
|
|
279
|
+
const { suitePayload: pqPayload, combinedKey: transportKey } =
|
|
280
|
+
await encapsulateForRecipient({
|
|
281
|
+
recipientPublicKey: input.recipient.mlKemPublicKey,
|
|
282
|
+
envelopeKey: input.recipientEnvelopeKey,
|
|
283
|
+
fileId: input.fileId,
|
|
284
|
+
})
|
|
285
|
+
|
|
286
|
+
// Now wrap the original combined key under the transport key using
|
|
287
|
+
// XSalsa20-Poly1305 secretbox.
|
|
288
|
+
if (transportKey.length !== 32) {
|
|
289
|
+
throw new Error('buildShareForRecipient: transport key length wrong')
|
|
290
|
+
}
|
|
291
|
+
const wrapNonce = randomBytes(24)
|
|
292
|
+
const wrappedCombinedKey = sodium.crypto_secretbox_easy(
|
|
293
|
+
input.combinedKey,
|
|
294
|
+
wrapNonce,
|
|
295
|
+
transportKey,
|
|
296
|
+
)
|
|
297
|
+
if (wrappedCombinedKey.length !== 32 + 16) {
|
|
298
|
+
throw new Error('buildShareForRecipient: secretbox produced unexpected length')
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// Share record format:
|
|
302
|
+
// [4 bytes BE length of pqPayload][pqPayload][24-byte wrap nonce][48-byte wrapped combined key]
|
|
303
|
+
return {
|
|
304
|
+
shareBundle: concatBytes([
|
|
305
|
+
uint32BE(pqPayload.length),
|
|
306
|
+
pqPayload,
|
|
307
|
+
wrapNonce,
|
|
308
|
+
wrappedCombinedKey,
|
|
309
|
+
]),
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* Recipient side: open a share bundle to recover the file's combined key.
|
|
315
|
+
* The recipient then uses that combined key with the standard PQ-hybrid
|
|
316
|
+
* decrypt path (via the original on-disk file).
|
|
317
|
+
*/
|
|
318
|
+
export async function openShareAsRecipient(input: {
|
|
319
|
+
shareBundle: Uint8Array
|
|
320
|
+
fileId: Uint8Array
|
|
321
|
+
recipientSecretKey: Uint8Array
|
|
322
|
+
recipientEnvelopeKey: Uint8Array
|
|
323
|
+
}): Promise<Uint8Array> {
|
|
324
|
+
const sodium = await getSodium()
|
|
325
|
+
if (input.shareBundle.length < 4) {
|
|
326
|
+
throw new Error('openShareAsRecipient: share too short')
|
|
327
|
+
}
|
|
328
|
+
let offset = 0
|
|
329
|
+
const pqLen = readUint32BE(input.shareBundle, offset)
|
|
330
|
+
offset += 4
|
|
331
|
+
if (offset + pqLen + 24 + 48 !== input.shareBundle.length) {
|
|
332
|
+
throw new Error('openShareAsRecipient: malformed share')
|
|
333
|
+
}
|
|
334
|
+
const pqPayload = input.shareBundle.slice(offset, offset + pqLen)
|
|
335
|
+
offset += pqLen
|
|
336
|
+
const wrapNonce = input.shareBundle.slice(offset, offset + 24)
|
|
337
|
+
offset += 24
|
|
338
|
+
const wrappedCombinedKey = input.shareBundle.slice(offset, offset + 48)
|
|
339
|
+
|
|
340
|
+
// Sanity-check the suite payload structure (this throws if malformed).
|
|
341
|
+
parsePqHybridV1SuitePayload(pqPayload)
|
|
342
|
+
// Round-trip through builder to ensure we got back the same bytes.
|
|
343
|
+
const checkBytes = buildPqHybridV1SuitePayload(
|
|
344
|
+
parsePqHybridV1SuitePayload(pqPayload),
|
|
345
|
+
)
|
|
346
|
+
if (checkBytes.length !== pqPayload.length) {
|
|
347
|
+
throw new Error('openShareAsRecipient: pq payload self-check failed')
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
const { combinedKey: transportKey } = await decapsulateFromHeader({
|
|
351
|
+
suitePayload: pqPayload,
|
|
352
|
+
recipientSecretKey: input.recipientSecretKey,
|
|
353
|
+
envelopeKey: input.recipientEnvelopeKey,
|
|
354
|
+
fileId: input.fileId,
|
|
355
|
+
})
|
|
356
|
+
|
|
357
|
+
const unwrapped = sodium.crypto_secretbox_open_easy(
|
|
358
|
+
wrappedCombinedKey,
|
|
359
|
+
wrapNonce,
|
|
360
|
+
transportKey,
|
|
361
|
+
)
|
|
362
|
+
if (!unwrapped) {
|
|
363
|
+
throw new Error(
|
|
364
|
+
'openShareAsRecipient: secretbox unwrap failed — wrong recipient or tampered share',
|
|
365
|
+
)
|
|
366
|
+
}
|
|
367
|
+
if (unwrapped.length !== 32) {
|
|
368
|
+
throw new Error('openShareAsRecipient: bad combined key length')
|
|
369
|
+
}
|
|
370
|
+
return new Uint8Array(unwrapped)
|
|
371
|
+
}
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sender-attribution signatures over the v1 wire format.
|
|
3
|
+
*
|
|
4
|
+
* The v1 file format already authenticates with HMAC under the content
|
|
5
|
+
* key (`header_mac`) and per-chunk AEAD tags, so a recipient can be sure
|
|
6
|
+
* the file decrypts to bytes the encryptor produced. What it does NOT
|
|
7
|
+
* tell them is WHO encrypted it — anyone with the content key could have
|
|
8
|
+
* written the file.
|
|
9
|
+
*
|
|
10
|
+
* This module adds an optional detached signature over
|
|
11
|
+
* `header_unauthenticated_bytes || concat(per-chunk MAC tags)` so that a
|
|
12
|
+
* recipient who trusts a sender's public key can verify authorship. The
|
|
13
|
+
* signature lives in an optional trailing structure (see
|
|
14
|
+
* `spec/format-v1.md § "Signature block"`); legacy files without that
|
|
15
|
+
* structure continue to decrypt unchanged, with the receiving side
|
|
16
|
+
* reporting `signature: null`.
|
|
17
|
+
*
|
|
18
|
+
* Algorithm 0x01 (Ed25519) is the only algorithm defined in v1. 0x02 is
|
|
19
|
+
* reserved for ML-DSA-65; the format leaves room for it but does not yet
|
|
20
|
+
* implement it.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import { ed25519 } from '@noble/curves/ed25519.js'
|
|
24
|
+
|
|
25
|
+
import {
|
|
26
|
+
concatBytes,
|
|
27
|
+
readUint16BE,
|
|
28
|
+
uint16BE,
|
|
29
|
+
} from '../internal/encoding.js'
|
|
30
|
+
|
|
31
|
+
/** Signature algorithm: Ed25519 (RFC 8032). 32-byte key, 64-byte signature. */
|
|
32
|
+
export const SIGNATURE_ALGO_ED25519 = 0x01
|
|
33
|
+
|
|
34
|
+
/** Signature algorithm reserved for ML-DSA-65 (FIPS 204). Not yet implemented. */
|
|
35
|
+
export const SIGNATURE_ALGO_ML_DSA_65 = 0x02
|
|
36
|
+
|
|
37
|
+
export const ED25519_PUBLIC_KEY_LENGTH = 32
|
|
38
|
+
export const ED25519_SECRET_KEY_LENGTH = 32
|
|
39
|
+
export const ED25519_SIGNATURE_LENGTH = 64
|
|
40
|
+
|
|
41
|
+
export interface SignatureBlock {
|
|
42
|
+
/** Algorithm identifier; see `SIGNATURE_ALGO_*`. */
|
|
43
|
+
algorithm: number
|
|
44
|
+
/** Sender's verifying key. Length depends on the algorithm. */
|
|
45
|
+
publicKey: Uint8Array
|
|
46
|
+
/** Detached signature over `signed_message`. */
|
|
47
|
+
signature: Uint8Array
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export class SignatureError extends Error {
|
|
51
|
+
readonly code: string
|
|
52
|
+
constructor(code: string) {
|
|
53
|
+
super(`shieldfive-crypto: signature error: ${code}`)
|
|
54
|
+
this.name = 'SignatureError'
|
|
55
|
+
this.code = code
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function buildSignedMessage(
|
|
60
|
+
header: Uint8Array,
|
|
61
|
+
chunkMacs: ReadonlyArray<Uint8Array>,
|
|
62
|
+
): Uint8Array {
|
|
63
|
+
let totalMacLen = 0
|
|
64
|
+
for (const mac of chunkMacs) totalMacLen += mac.length
|
|
65
|
+
const out = new Uint8Array(header.length + totalMacLen)
|
|
66
|
+
out.set(header, 0)
|
|
67
|
+
let offset = header.length
|
|
68
|
+
for (const mac of chunkMacs) {
|
|
69
|
+
out.set(mac, offset)
|
|
70
|
+
offset += mac.length
|
|
71
|
+
}
|
|
72
|
+
return out
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Produce a detached Ed25519 signature over
|
|
77
|
+
* `header_unauthenticated_bytes || concat(chunk_macs)`.
|
|
78
|
+
*
|
|
79
|
+
* `header` MUST be the exact bytes covered by the file's `header_mac`
|
|
80
|
+
* (i.e. the output of `buildHeaderUnauthenticated` or
|
|
81
|
+
* `parseHeader().unauthenticatedBytes`). `chunkMacs` MUST be the per-chunk
|
|
82
|
+
* AEAD tags in chunk-index order. For suites defined in v1 (AES-GCM-128,
|
|
83
|
+
* ChaCha20-Poly1305) the tag is the trailing 16 bytes of the chunk's
|
|
84
|
+
* ciphertext field.
|
|
85
|
+
*
|
|
86
|
+
* Returns the raw 64-byte signature. Callers wrap it in a signature block
|
|
87
|
+
* via `buildSignatureBlock`.
|
|
88
|
+
*/
|
|
89
|
+
export function signHeaderAndMacs(input: {
|
|
90
|
+
ed25519SecretKey: Uint8Array
|
|
91
|
+
header: Uint8Array
|
|
92
|
+
chunkMacs: ReadonlyArray<Uint8Array>
|
|
93
|
+
}): Uint8Array {
|
|
94
|
+
if (input.ed25519SecretKey.length !== ED25519_SECRET_KEY_LENGTH) {
|
|
95
|
+
throw new SignatureError('ed25519_secret_key_wrong_length')
|
|
96
|
+
}
|
|
97
|
+
const message = buildSignedMessage(input.header, input.chunkMacs)
|
|
98
|
+
return ed25519.sign(message, input.ed25519SecretKey)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Verify a detached Ed25519 signature produced by `signHeaderAndMacs`.
|
|
103
|
+
* Returns `true` on success, `false` on any failure (wrong length,
|
|
104
|
+
* malformed point, bad signature). Never throws on a verification
|
|
105
|
+
* mismatch — failures are not exceptional.
|
|
106
|
+
*/
|
|
107
|
+
export function verifyHeaderAndMacs(input: {
|
|
108
|
+
ed25519PublicKey: Uint8Array
|
|
109
|
+
header: Uint8Array
|
|
110
|
+
chunkMacs: ReadonlyArray<Uint8Array>
|
|
111
|
+
signature: Uint8Array
|
|
112
|
+
}): boolean {
|
|
113
|
+
if (input.ed25519PublicKey.length !== ED25519_PUBLIC_KEY_LENGTH) return false
|
|
114
|
+
if (input.signature.length !== ED25519_SIGNATURE_LENGTH) return false
|
|
115
|
+
const message = buildSignedMessage(input.header, input.chunkMacs)
|
|
116
|
+
try {
|
|
117
|
+
return ed25519.verify(input.signature, message, input.ed25519PublicKey)
|
|
118
|
+
} catch {
|
|
119
|
+
// Malformed pubkey or sig encoding — noble throws; we treat as not-verified.
|
|
120
|
+
return false
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Derive the Ed25519 public key from a 32-byte secret seed.
|
|
126
|
+
*/
|
|
127
|
+
export function deriveEd25519PublicKey(
|
|
128
|
+
ed25519SecretKey: Uint8Array,
|
|
129
|
+
): Uint8Array {
|
|
130
|
+
if (ed25519SecretKey.length !== ED25519_SECRET_KEY_LENGTH) {
|
|
131
|
+
throw new SignatureError('ed25519_secret_key_wrong_length')
|
|
132
|
+
}
|
|
133
|
+
return ed25519.getPublicKey(ed25519SecretKey)
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Serialize a signature block:
|
|
138
|
+
* 1 byte algorithm || 2 bytes BE pubkey_len || pubkey || 2 bytes BE sig_len || sig
|
|
139
|
+
*/
|
|
140
|
+
export function buildSignatureBlock(block: SignatureBlock): Uint8Array {
|
|
141
|
+
if (
|
|
142
|
+
block.algorithm < 0 ||
|
|
143
|
+
block.algorithm > 0xff ||
|
|
144
|
+
!Number.isInteger(block.algorithm)
|
|
145
|
+
) {
|
|
146
|
+
throw new SignatureError('algorithm_out_of_range')
|
|
147
|
+
}
|
|
148
|
+
if (block.algorithm === 0x00) {
|
|
149
|
+
throw new SignatureError('algorithm_reserved')
|
|
150
|
+
}
|
|
151
|
+
if (block.publicKey.length > 0xffff) {
|
|
152
|
+
throw new SignatureError('public_key_too_large')
|
|
153
|
+
}
|
|
154
|
+
if (block.signature.length > 0xffff) {
|
|
155
|
+
throw new SignatureError('signature_too_large')
|
|
156
|
+
}
|
|
157
|
+
if (block.algorithm === SIGNATURE_ALGO_ED25519) {
|
|
158
|
+
if (block.publicKey.length !== ED25519_PUBLIC_KEY_LENGTH) {
|
|
159
|
+
throw new SignatureError('ed25519_public_key_wrong_length')
|
|
160
|
+
}
|
|
161
|
+
if (block.signature.length !== ED25519_SIGNATURE_LENGTH) {
|
|
162
|
+
throw new SignatureError('ed25519_signature_wrong_length')
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return concatBytes([
|
|
166
|
+
new Uint8Array([block.algorithm]),
|
|
167
|
+
uint16BE(block.publicKey.length),
|
|
168
|
+
block.publicKey,
|
|
169
|
+
uint16BE(block.signature.length),
|
|
170
|
+
block.signature,
|
|
171
|
+
])
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Parse a signature block starting at `offset` in `bytes`. Returns the
|
|
176
|
+
* parsed block and the number of bytes consumed. Throws on malformed
|
|
177
|
+
* input (truncation, oversize, or — for known algorithms — wrong key /
|
|
178
|
+
* signature length). Unknown algorithms parse successfully; verification
|
|
179
|
+
* against an unknown algorithm is the caller's policy decision.
|
|
180
|
+
*/
|
|
181
|
+
export function parseSignatureBlock(
|
|
182
|
+
bytes: Uint8Array,
|
|
183
|
+
offset = 0,
|
|
184
|
+
): { block: SignatureBlock; consumed: number } {
|
|
185
|
+
const FIXED_HEADER = 1 + 2 // algorithm + pubkey_len
|
|
186
|
+
if (bytes.length - offset < FIXED_HEADER) {
|
|
187
|
+
throw new SignatureError('block_truncated')
|
|
188
|
+
}
|
|
189
|
+
let pos = offset
|
|
190
|
+
const algorithm = bytes[pos]!
|
|
191
|
+
pos += 1
|
|
192
|
+
if (algorithm === 0x00) {
|
|
193
|
+
throw new SignatureError('algorithm_reserved')
|
|
194
|
+
}
|
|
195
|
+
const pubkeyLen = readUint16BE(bytes, pos)
|
|
196
|
+
pos += 2
|
|
197
|
+
if (bytes.length - pos < pubkeyLen + 2) {
|
|
198
|
+
throw new SignatureError('block_truncated')
|
|
199
|
+
}
|
|
200
|
+
const publicKey = bytes.slice(pos, pos + pubkeyLen)
|
|
201
|
+
pos += pubkeyLen
|
|
202
|
+
const sigLen = readUint16BE(bytes, pos)
|
|
203
|
+
pos += 2
|
|
204
|
+
if (bytes.length - pos < sigLen) {
|
|
205
|
+
throw new SignatureError('block_truncated')
|
|
206
|
+
}
|
|
207
|
+
const signature = bytes.slice(pos, pos + sigLen)
|
|
208
|
+
pos += sigLen
|
|
209
|
+
if (algorithm === SIGNATURE_ALGO_ED25519) {
|
|
210
|
+
if (publicKey.length !== ED25519_PUBLIC_KEY_LENGTH) {
|
|
211
|
+
throw new SignatureError('ed25519_public_key_wrong_length')
|
|
212
|
+
}
|
|
213
|
+
if (signature.length !== ED25519_SIGNATURE_LENGTH) {
|
|
214
|
+
throw new SignatureError('ed25519_signature_wrong_length')
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
return {
|
|
218
|
+
block: { algorithm, publicKey, signature },
|
|
219
|
+
consumed: pos - offset,
|
|
220
|
+
}
|
|
221
|
+
}
|