@shieldfive/crypto 1.0.0-rc.4 → 1.0.0-rc.6

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.
@@ -0,0 +1,805 @@
1
+ /**
2
+ * Vault key chain, name envelopes and agent grants.
3
+ *
4
+ * These are the formats the ShieldFive web app already writes to its
5
+ * database, reproduced here so every non-browser client (the MCP server, the
6
+ * CLI, the mobile app) opens them with ONE reviewed implementation instead of
7
+ * each carrying its own copy.
8
+ *
9
+ * Key chain folders.fk_wrapped / files.csk_wrapped / files.pqk_fk_wrapped:
10
+ * AES-256-GCM, 12-byte random IV stored beside the ciphertext,
11
+ * no AAD. The wrapping key is the parent folder key, or the vault
12
+ * root key for top-level objects.
13
+ *
14
+ * Names files.name / folders.name: a JSON envelope
15
+ * {v, ct, iv, tag, salt, kdf?}. The AES-256-GCM key is
16
+ * Argon2id(password = the base64 text of the parent folder key,
17
+ * salt). v6 additionally authenticates the row UUID as AAD so a
18
+ * server cannot move a name onto another row.
19
+ *
20
+ * Agent grant A fresh 32-byte secret, generated in the owner's browser and
21
+ * never sent to the server, wraps the grant's scope-root keys.
22
+ * Wrapping key = HKDF-SHA-256(secret, salt = grant id,
23
+ * info = HKDF_INFO.AGENT_GRANT_WRAP). Every wrap authenticates
24
+ * the grant id, the object kind and the object id as AAD.
25
+ *
26
+ * Nothing in this module is a new primitive: it composes AES-256-GCM,
27
+ * HKDF-SHA-256, SHA-256 and libsodium's Argon2id13.
28
+ */
29
+
30
+ import { sha256 } from "@noble/hashes/sha2.js";
31
+
32
+ import {
33
+ base64ToBytes,
34
+ bytesToBase64,
35
+ bytesToHex,
36
+ concatBytes,
37
+ hexToBytes,
38
+ } from "../internal/encoding.js";
39
+ import { parseHeader } from "../format/header.js";
40
+ import { hmacSha256 } from "../internal/hmac.js";
41
+ import { hkdfSha256 } from "../internal/hkdf.js";
42
+ import { getSubtle, randomBytes } from "../internal/runtime.js";
43
+ import { getSodium } from "../internal/sodium.js";
44
+ import { HKDF_INFO } from "../internal/types.js";
45
+
46
+ const KEY_BYTES = 32;
47
+ // The upload-proof frame (see buildUploadProofV3): a version byte, the cipher
48
+ // version, then the MAC. The 4-byte big-endian length prefix belongs to the
49
+ // container format, not to the proof.
50
+ const PROOF_VERSION_V3 = 3;
51
+ const CIPHER_VERSION_PQ_HYBRID = 3;
52
+ const LENGTH_PREFIX_BYTES = 4;
53
+ const IV_BYTES = 12;
54
+ const TAG_BYTES = 16;
55
+ const NAME_SALT_BYTES = 16;
56
+ const TEXT_ENCODER = new TextEncoder();
57
+ const TEXT_DECODER = new TextDecoder("utf-8", { fatal: true });
58
+
59
+ /** Raised for any envelope or wrap that does not open. Never carries key bytes. */
60
+ export class VaultCryptoError extends Error {
61
+ readonly code:
62
+ | "unwrap_failed"
63
+ | "name_decrypt_failed"
64
+ | "unsupported_envelope"
65
+ | "invalid_input"
66
+ | "invalid_connection_string";
67
+ constructor(code: VaultCryptoError["code"], message: string) {
68
+ super(message);
69
+ this.name = "VaultCryptoError";
70
+ this.code = code;
71
+ }
72
+ }
73
+
74
+ function assertKey(key: Uint8Array, what: string): void {
75
+ if (!(key instanceof Uint8Array) || key.length !== KEY_BYTES) {
76
+ throw new VaultCryptoError("invalid_input", `${what} must be 32 bytes`);
77
+ }
78
+ }
79
+
80
+ async function importAesKey(key: Uint8Array): Promise<CryptoKey> {
81
+ return getSubtle().importKey(
82
+ "raw",
83
+ key as Uint8Array<ArrayBuffer>,
84
+ { name: "AES-GCM" },
85
+ false,
86
+ ["encrypt", "decrypt"],
87
+ );
88
+ }
89
+
90
+ async function aesGcmSeal(
91
+ key: Uint8Array,
92
+ iv: Uint8Array,
93
+ plaintext: Uint8Array,
94
+ aad?: Uint8Array,
95
+ ): Promise<Uint8Array> {
96
+ const params: AesGcmParams = {
97
+ name: "AES-GCM",
98
+ iv: iv as Uint8Array<ArrayBuffer>,
99
+ };
100
+ if (aad) params.additionalData = aad as Uint8Array<ArrayBuffer>;
101
+ const out = await getSubtle().encrypt(
102
+ params,
103
+ await importAesKey(key),
104
+ plaintext as Uint8Array<ArrayBuffer>,
105
+ );
106
+ return new Uint8Array(out);
107
+ }
108
+
109
+ async function aesGcmOpen(
110
+ key: Uint8Array,
111
+ iv: Uint8Array,
112
+ ciphertext: Uint8Array,
113
+ aad?: Uint8Array,
114
+ ): Promise<Uint8Array | null> {
115
+ const params: AesGcmParams = {
116
+ name: "AES-GCM",
117
+ iv: iv as Uint8Array<ArrayBuffer>,
118
+ };
119
+ if (aad) params.additionalData = aad as Uint8Array<ArrayBuffer>;
120
+ try {
121
+ const out = await getSubtle().decrypt(
122
+ params,
123
+ await importAesKey(key),
124
+ ciphertext as Uint8Array<ArrayBuffer>,
125
+ );
126
+ return new Uint8Array(out);
127
+ } catch {
128
+ return null;
129
+ }
130
+ }
131
+
132
+ // ──────────────────────────────────────────────────────────────────────
133
+ // Key chain
134
+ // ──────────────────────────────────────────────────────────────────────
135
+
136
+ /** A wrapped key as the database stores it: base64 ciphertext+tag and base64 IV. */
137
+ export interface WrappedKey {
138
+ wrapped: string;
139
+ iv: string;
140
+ }
141
+
142
+ /** Wrap a 32-byte key under a 32-byte key (the fk/csk/pqk chain format). */
143
+ export async function wrapChainKey(
144
+ wrappingKey: Uint8Array,
145
+ key: Uint8Array,
146
+ ): Promise<WrappedKey> {
147
+ assertKey(wrappingKey, "wrappingKey");
148
+ assertKey(key, "key");
149
+ const iv = randomBytes(IV_BYTES);
150
+ const ct = await aesGcmSeal(wrappingKey, iv, key);
151
+ return { wrapped: bytesToBase64(ct), iv: bytesToBase64(iv) };
152
+ }
153
+
154
+ /** Open one hop of the key chain. Throws `unwrap_failed` on a wrong key or tampering. */
155
+ export async function unwrapChainKey(
156
+ wrappingKey: Uint8Array,
157
+ wrapped: WrappedKey,
158
+ ): Promise<Uint8Array> {
159
+ assertKey(wrappingKey, "wrappingKey");
160
+ const iv = base64ToBytes(wrapped.iv);
161
+ const ct = base64ToBytes(wrapped.wrapped);
162
+ if (iv.length !== IV_BYTES || ct.length !== KEY_BYTES + TAG_BYTES) {
163
+ throw new VaultCryptoError(
164
+ "unwrap_failed",
165
+ "wrapped key has the wrong shape",
166
+ );
167
+ }
168
+ const key = await aesGcmOpen(wrappingKey, iv, ct);
169
+ if (!key)
170
+ throw new VaultCryptoError("unwrap_failed", "wrapped key did not open");
171
+ return key;
172
+ }
173
+
174
+ // ──────────────────────────────────────────────────────────────────────
175
+ // Name envelopes (v4, v6)
176
+ // ──────────────────────────────────────────────────────────────────────
177
+
178
+ export type NameKdfLevel = "interactive" | "moderate";
179
+
180
+ export interface NameEnvelope {
181
+ v: 4 | 6;
182
+ ct: string;
183
+ iv: string;
184
+ tag: string;
185
+ salt: string;
186
+ kdf?: NameKdfLevel;
187
+ }
188
+
189
+ /** Parse a stored name. Returns null for anything that is not a v4/v6 envelope. */
190
+ export function parseNameEnvelope(
191
+ raw: string | null | undefined,
192
+ ): NameEnvelope | null {
193
+ if (typeof raw !== "string" || raw.length === 0 || raw.length > 8192)
194
+ return null;
195
+ let value: unknown;
196
+ try {
197
+ value = JSON.parse(raw);
198
+ } catch {
199
+ return null;
200
+ }
201
+ if (!value || typeof value !== "object") return null;
202
+ const p = value as Record<string, unknown>;
203
+ if (p.v !== 4 && p.v !== 6) return null;
204
+ for (const f of ["ct", "iv", "tag", "salt"] as const) {
205
+ if (typeof p[f] !== "string") return null;
206
+ }
207
+ if (p.kdf !== undefined && p.kdf !== "interactive" && p.kdf !== "moderate")
208
+ return null;
209
+ const env: NameEnvelope = {
210
+ v: p.v,
211
+ ct: p.ct as string,
212
+ iv: p.iv as string,
213
+ tag: p.tag as string,
214
+ salt: p.salt as string,
215
+ };
216
+ if (p.kdf !== undefined) env.kdf = p.kdf as NameKdfLevel;
217
+ return env;
218
+ }
219
+
220
+ /**
221
+ * Derive the per-envelope name key. The Argon2id password is the base64 TEXT
222
+ * of the folder key, byte-for-byte what the web app passes to libsodium; the
223
+ * input is already 256 bits of entropy, so the cost level is a compatibility
224
+ * parameter, not a security one.
225
+ */
226
+ export async function deriveNameKey(
227
+ folderKey: Uint8Array,
228
+ salt: Uint8Array,
229
+ level: NameKdfLevel,
230
+ ): Promise<Uint8Array> {
231
+ assertKey(folderKey, "folderKey");
232
+ if (salt.length !== NAME_SALT_BYTES) {
233
+ throw new VaultCryptoError("invalid_input", "name salt must be 16 bytes");
234
+ }
235
+ const sodium = await getSodium();
236
+ const ops =
237
+ level === "interactive"
238
+ ? sodium.crypto_pwhash_OPSLIMIT_INTERACTIVE
239
+ : sodium.crypto_pwhash_OPSLIMIT_MODERATE;
240
+ const mem =
241
+ level === "interactive"
242
+ ? sodium.crypto_pwhash_MEMLIMIT_INTERACTIVE
243
+ : sodium.crypto_pwhash_MEMLIMIT_MODERATE;
244
+ return new Uint8Array(
245
+ sodium.crypto_pwhash(
246
+ KEY_BYTES,
247
+ TEXT_ENCODER.encode(bytesToBase64(folderKey)),
248
+ salt,
249
+ ops,
250
+ mem,
251
+ sodium.crypto_pwhash_ALG_ARGON2ID13,
252
+ ),
253
+ );
254
+ }
255
+
256
+ /**
257
+ * Decrypt a v4 or v6 name. `rowId` is the database UUID of the row the name
258
+ * belongs to and is REQUIRED for v6 (it is the AAD). An envelope written
259
+ * without a `kdf` field is tried at interactive, then moderate, which is the
260
+ * web app's own fallback order for a device that cannot know the level.
261
+ */
262
+ export async function decryptName(options: {
263
+ envelope: NameEnvelope;
264
+ folderKey: Uint8Array;
265
+ rowId?: string;
266
+ }): Promise<string> {
267
+ const { envelope, folderKey, rowId } = options;
268
+ if (envelope.v === 6 && !rowId) {
269
+ throw new VaultCryptoError("invalid_input", "v6 names need the row id");
270
+ }
271
+ const iv = base64ToBytes(envelope.iv);
272
+ const salt = base64ToBytes(envelope.salt);
273
+ const sealed = concatBytes([
274
+ base64ToBytes(envelope.ct),
275
+ base64ToBytes(envelope.tag),
276
+ ]);
277
+ const aad =
278
+ envelope.v === 6 ? TEXT_ENCODER.encode(rowId as string) : undefined;
279
+ const levels: NameKdfLevel[] = envelope.kdf
280
+ ? [envelope.kdf]
281
+ : ["interactive", "moderate"];
282
+ for (const level of levels) {
283
+ const key = await deriveNameKey(folderKey, salt, level);
284
+ const pt = await aesGcmOpen(key, iv, sealed, aad);
285
+ if (pt) {
286
+ try {
287
+ return TEXT_DECODER.decode(pt);
288
+ } catch {
289
+ break;
290
+ }
291
+ }
292
+ }
293
+ throw new VaultCryptoError(
294
+ "name_decrypt_failed",
295
+ "name envelope did not open",
296
+ );
297
+ }
298
+
299
+ /**
300
+ * Decrypt a name with an already-derived name key (a grant's `name` wrap),
301
+ * for objects whose parent key the caller does not hold.
302
+ */
303
+ export async function decryptNameWithKey(options: {
304
+ envelope: NameEnvelope;
305
+ nameKey: Uint8Array;
306
+ rowId?: string;
307
+ }): Promise<string> {
308
+ const { envelope, nameKey, rowId } = options;
309
+ assertKey(nameKey, "nameKey");
310
+ if (envelope.v === 6 && !rowId) {
311
+ throw new VaultCryptoError("invalid_input", "v6 names need the row id");
312
+ }
313
+ const sealed = concatBytes([
314
+ base64ToBytes(envelope.ct),
315
+ base64ToBytes(envelope.tag),
316
+ ]);
317
+ const aad =
318
+ envelope.v === 6 ? TEXT_ENCODER.encode(rowId as string) : undefined;
319
+ const pt = await aesGcmOpen(nameKey, base64ToBytes(envelope.iv), sealed, aad);
320
+ if (pt) {
321
+ try {
322
+ return TEXT_DECODER.decode(pt);
323
+ } catch {
324
+ // fall through
325
+ }
326
+ }
327
+ throw new VaultCryptoError(
328
+ "name_decrypt_failed",
329
+ "name envelope did not open",
330
+ );
331
+ }
332
+
333
+ /**
334
+ * The name key for one envelope: what an owner wraps as a grant's `name`
335
+ * object. For an envelope without a `kdf` field the level is found by opening
336
+ * it, the same fallback `decryptName` uses, so the wrapped key always works.
337
+ */
338
+ export async function deriveNameKeyForEnvelope(options: {
339
+ envelope: NameEnvelope;
340
+ parentKey: Uint8Array;
341
+ rowId?: string;
342
+ }): Promise<Uint8Array> {
343
+ const { envelope, parentKey, rowId } = options;
344
+ const salt = base64ToBytes(envelope.salt);
345
+ const levels: NameKdfLevel[] = envelope.kdf
346
+ ? [envelope.kdf]
347
+ : ["interactive", "moderate"];
348
+ for (const level of levels) {
349
+ const nameKey = await deriveNameKey(parentKey, salt, level);
350
+ try {
351
+ await decryptNameWithKey(
352
+ rowId === undefined
353
+ ? { envelope, nameKey }
354
+ : { envelope, nameKey, rowId },
355
+ );
356
+ return nameKey;
357
+ } catch (err) {
358
+ if (
359
+ !(err instanceof VaultCryptoError) ||
360
+ err.code !== "name_decrypt_failed"
361
+ )
362
+ throw err;
363
+ }
364
+ }
365
+ throw new VaultCryptoError(
366
+ "name_decrypt_failed",
367
+ "name envelope did not open",
368
+ );
369
+ }
370
+
371
+ /** Encrypt a name as a v6 envelope bound to `rowId`, at the web app's default level. */
372
+ export async function encryptNameV6(options: {
373
+ name: string;
374
+ folderKey: Uint8Array;
375
+ rowId: string;
376
+ }): Promise<NameEnvelope> {
377
+ const { name, folderKey, rowId } = options;
378
+ if (typeof name !== "string" || name.length === 0) {
379
+ throw new VaultCryptoError(
380
+ "invalid_input",
381
+ "name must be a non-empty string",
382
+ );
383
+ }
384
+ if (typeof rowId !== "string" || rowId.length === 0) {
385
+ throw new VaultCryptoError("invalid_input", "rowId is required");
386
+ }
387
+ const salt = randomBytes(NAME_SALT_BYTES);
388
+ const iv = randomBytes(IV_BYTES);
389
+ const key = await deriveNameKey(folderKey, salt, "interactive");
390
+ const sealed = await aesGcmSeal(
391
+ key,
392
+ iv,
393
+ TEXT_ENCODER.encode(name),
394
+ TEXT_ENCODER.encode(rowId),
395
+ );
396
+ return {
397
+ v: 6,
398
+ ct: bytesToBase64(sealed.slice(0, sealed.length - TAG_BYTES)),
399
+ iv: bytesToBase64(iv),
400
+ tag: bytesToBase64(sealed.slice(sealed.length - TAG_BYTES)),
401
+ salt: bytesToBase64(salt),
402
+ kdf: "interactive",
403
+ };
404
+ }
405
+
406
+ // ──────────────────────────────────────────────────────────────────────
407
+ // Agent grants
408
+ // ──────────────────────────────────────────────────────────────────────
409
+
410
+ export const GRANT_CONNECTION_PREFIX = "sf-grant-v1:";
411
+
412
+ /**
413
+ * What a grant wrap covers.
414
+ *
415
+ * folder a folder key (scope roots, and top-level folders for whole-vault)
416
+ * file the key a file's `csk_wrapped` holds: the content key for suites
417
+ * 0x00-0x02, the classical envelope key for 0x03
418
+ * file_pq the combined content key of a suite-0x03 file
419
+ * name the Argon2id-derived key of ONE name envelope, for objects whose
420
+ * name is sealed under a key outside the grant (a scope root's own
421
+ * name, a file at the vault root). Opens that envelope only.
422
+ *
423
+ * `file`, `file_pq` and `name` are only issued for objects whose parent key the
424
+ * grant does not hold; everything below a scope root is reached by the chain.
425
+ */
426
+ export type GrantObjectKind = "folder" | "file" | "file_pq" | "name";
427
+ const GRANT_KINDS: ReadonlySet<string> = new Set([
428
+ "folder",
429
+ "file",
430
+ "file_pq",
431
+ "name",
432
+ ]);
433
+
434
+ export interface GrantCredential {
435
+ grantId: string;
436
+ /** Sent to the server as a bearer token. The server stores only its SHA-256. */
437
+ token: Uint8Array;
438
+ /** Never leaves the client. Wraps the grant's keys. */
439
+ secret: Uint8Array;
440
+ /** SHA-256 of the owner's ML-KEM public key at grant creation, hex. */
441
+ publicKeyFingerprint: string;
442
+ }
443
+
444
+ const UUID_RE =
445
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
446
+
447
+ function assertUuid(value: string, what: string): void {
448
+ if (typeof value !== "string" || !UUID_RE.test(value)) {
449
+ throw new VaultCryptoError(
450
+ "invalid_input",
451
+ `${what} must be a lowercase UUID`,
452
+ );
453
+ }
454
+ }
455
+
456
+ function toBase64Url(bytes: Uint8Array): string {
457
+ return bytesToBase64(bytes)
458
+ .replace(/\+/g, "-")
459
+ .replace(/\//g, "_")
460
+ .replace(/=+$/, "");
461
+ }
462
+
463
+ function fromBase64Url(value: string): Uint8Array {
464
+ if (!/^[A-Za-z0-9_-]+$/.test(value)) {
465
+ throw new VaultCryptoError("invalid_connection_string", "bad base64url");
466
+ }
467
+ if (value.length % 4 === 1) {
468
+ throw new VaultCryptoError(
469
+ "invalid_connection_string",
470
+ "bad base64url length",
471
+ );
472
+ }
473
+ const b64 = value.replace(/-/g, "+").replace(/_/g, "/");
474
+ try {
475
+ return base64ToBytes(b64 + "=".repeat((4 - (b64.length % 4)) % 4));
476
+ } catch {
477
+ throw new VaultCryptoError("invalid_connection_string", "bad base64url");
478
+ }
479
+ }
480
+
481
+ /** SHA-256 of an ML-KEM public key, hex. Pinned in the connection string. */
482
+ export function publicKeyFingerprint(mlKemPublicKey: Uint8Array): string {
483
+ return bytesToHex(sha256(mlKemPublicKey));
484
+ }
485
+
486
+ /**
487
+ * The upload proof for a PQ-hybrid (Suite 0x03) object, in the frame the
488
+ * ShieldFive server verifies:
489
+ *
490
+ * base64( [0x03][0x03] || HMAC-SHA256(proofKey, [0x03][0x03] || header || chunk_0) )
491
+ *
492
+ * `chunk_0` is the first frame INCLUDING its 4-byte big-endian length prefix.
493
+ * The server re-reads exactly those ranges from storage and recomputes the MAC,
494
+ * so a matching proof says the object storage holds is the object the client
495
+ * encrypted — it does not, and cannot, say anything about the plaintext.
496
+ *
497
+ * It lives here because it is a keyed construction over ShieldFive's own
498
+ * container format, and the clients that produce it (the web app, and the MCP
499
+ * server's upload path) must produce byte-identical frames. A second
500
+ * hand-written implementation is how the two silently diverge.
501
+ */
502
+ export async function buildUploadProofV3(options: {
503
+ /** The per-upload proof key the server issued, hex. */
504
+ proofKeyHex: string;
505
+ /** The complete ciphertext, or at least header + first chunk frame. */
506
+ ciphertext: Uint8Array;
507
+ }): Promise<string> {
508
+ const { proofKeyHex, ciphertext } = options;
509
+ if (!/^[0-9a-f]{64}$/i.test(proofKeyHex)) {
510
+ throw new VaultCryptoError(
511
+ "invalid_input",
512
+ "proofKeyHex must be 32 bytes of hex",
513
+ );
514
+ }
515
+ const header = parseHeader(ciphertext);
516
+ const lengthOffset = header.headerLength;
517
+ if (ciphertext.length < lengthOffset + LENGTH_PREFIX_BYTES) {
518
+ throw new VaultCryptoError(
519
+ "invalid_input",
520
+ "ciphertext is shorter than its header",
521
+ );
522
+ }
523
+ const view = new DataView(
524
+ ciphertext.buffer,
525
+ ciphertext.byteOffset,
526
+ ciphertext.byteLength,
527
+ );
528
+ const chunkZeroLength = view.getUint32(lengthOffset, false);
529
+ const end = lengthOffset + LENGTH_PREFIX_BYTES + chunkZeroLength;
530
+ if (chunkZeroLength === 0 || ciphertext.length < end) {
531
+ throw new VaultCryptoError(
532
+ "invalid_input",
533
+ "ciphertext is missing its first chunk",
534
+ );
535
+ }
536
+
537
+ const prefix = Uint8Array.from([PROOF_VERSION_V3, CIPHER_VERSION_PQ_HYBRID]);
538
+ const macPayload = new Uint8Array(prefix.length + end);
539
+ macPayload.set(prefix, 0);
540
+ macPayload.set(ciphertext.subarray(0, end), prefix.length);
541
+
542
+ const mac = await hmacSha256(hexToBytes(proofKeyHex), macPayload);
543
+ const frame = new Uint8Array(prefix.length + mac.length);
544
+ frame.set(prefix, 0);
545
+ frame.set(mac, prefix.length);
546
+ return bytesToBase64(frame);
547
+ }
548
+
549
+ /** Fresh token + secret for a new grant. Call in the owner's unlocked client. */
550
+ export function createGrantCredential(options: {
551
+ grantId: string;
552
+ mlKemPublicKey: Uint8Array;
553
+ }): GrantCredential {
554
+ assertUuid(options.grantId, "grantId");
555
+ return {
556
+ grantId: options.grantId,
557
+ token: randomBytes(KEY_BYTES),
558
+ secret: randomBytes(KEY_BYTES),
559
+ publicKeyFingerprint: publicKeyFingerprint(options.mlKemPublicKey),
560
+ };
561
+ }
562
+
563
+ /** `sf-grant-v1:<grant_id>.<token>.<secret>.<pk_fingerprint>` (base64url, hex). */
564
+ export function formatConnectionString(c: GrantCredential): string {
565
+ assertUuid(c.grantId, "grantId");
566
+ assertKey(c.token, "token");
567
+ assertKey(c.secret, "secret");
568
+ if (!/^[0-9a-f]{64}$/.test(c.publicKeyFingerprint)) {
569
+ throw new VaultCryptoError(
570
+ "invalid_input",
571
+ "fingerprint must be 64 hex chars",
572
+ );
573
+ }
574
+ return `${GRANT_CONNECTION_PREFIX}${c.grantId}.${toBase64Url(c.token)}.${toBase64Url(c.secret)}.${c.publicKeyFingerprint}`;
575
+ }
576
+
577
+ export function parseConnectionString(value: string): GrantCredential {
578
+ const bad = (why: string) =>
579
+ new VaultCryptoError("invalid_connection_string", why);
580
+ if (typeof value !== "string") throw bad("not a string");
581
+ const trimmed = value.trim();
582
+ if (!trimmed.startsWith(GRANT_CONNECTION_PREFIX)) throw bad("wrong prefix");
583
+ const parts = trimmed.slice(GRANT_CONNECTION_PREFIX.length).split(".");
584
+ if (parts.length !== 4) throw bad("expected four parts");
585
+ const [grantId, tokenPart, secretPart, fingerprint] = parts as [
586
+ string,
587
+ string,
588
+ string,
589
+ string,
590
+ ];
591
+ if (!UUID_RE.test(grantId)) throw bad("bad grant id");
592
+ const token = fromBase64Url(tokenPart);
593
+ const secret = fromBase64Url(secretPart);
594
+ if (token.length !== KEY_BYTES || secret.length !== KEY_BYTES)
595
+ throw bad("bad key length");
596
+ if (!/^[0-9a-f]{64}$/.test(fingerprint)) throw bad("bad fingerprint");
597
+ return { grantId, token, secret, publicKeyFingerprint: fingerprint };
598
+ }
599
+
600
+ /** The bearer value a client sends. */
601
+ export function grantBearerToken(c: Pick<GrantCredential, "token">): string {
602
+ return toBase64Url(c.token);
603
+ }
604
+
605
+ /** What the server stores and looks up: SHA-256 of the bearer token's bytes, hex. */
606
+ export function hashGrantToken(bearer: string): string {
607
+ const bytes = fromBase64Url(bearer);
608
+ if (bytes.length !== KEY_BYTES) {
609
+ throw new VaultCryptoError(
610
+ "invalid_input",
611
+ "bearer token has the wrong length",
612
+ );
613
+ }
614
+ return bytesToHex(sha256(bytes));
615
+ }
616
+
617
+ /** GK = HKDF-SHA-256(secret, salt = utf8(grant id), info = AGENT_GRANT_WRAP). */
618
+ export async function deriveGrantWrapKey(
619
+ secret: Uint8Array,
620
+ grantId: string,
621
+ ): Promise<Uint8Array> {
622
+ assertKey(secret, "secret");
623
+ assertUuid(grantId, "grantId");
624
+ return hkdfSha256({
625
+ ikm: secret,
626
+ salt: TEXT_ENCODER.encode(grantId),
627
+ info: HKDF_INFO.AGENT_GRANT_WRAP,
628
+ length: KEY_BYTES,
629
+ });
630
+ }
631
+
632
+ function grantAad(
633
+ grantId: string,
634
+ kind: GrantObjectKind,
635
+ objectId: string,
636
+ ): Uint8Array {
637
+ if (!GRANT_KINDS.has(kind)) {
638
+ throw new VaultCryptoError("invalid_input", "unknown grant object kind");
639
+ }
640
+ assertUuid(grantId, "grantId");
641
+ assertUuid(objectId, "objectId");
642
+ return TEXT_ENCODER.encode(`sf-grant-v1|${grantId}|${kind}|${objectId}`);
643
+ }
644
+
645
+ /** Wrap a folder key or file content key for a grant, bound to (grant, kind, object). */
646
+ export async function wrapKeyForGrant(options: {
647
+ grantWrapKey: Uint8Array;
648
+ grantId: string;
649
+ kind: GrantObjectKind;
650
+ objectId: string;
651
+ key: Uint8Array;
652
+ }): Promise<WrappedKey> {
653
+ assertKey(options.grantWrapKey, "grantWrapKey");
654
+ assertKey(options.key, "key");
655
+ const aad = grantAad(options.grantId, options.kind, options.objectId);
656
+ const iv = randomBytes(IV_BYTES);
657
+ const ct = await aesGcmSeal(options.grantWrapKey, iv, options.key, aad);
658
+ return { wrapped: bytesToBase64(ct), iv: bytesToBase64(iv) };
659
+ }
660
+
661
+ export async function unwrapKeyForGrant(options: {
662
+ grantWrapKey: Uint8Array;
663
+ grantId: string;
664
+ kind: GrantObjectKind;
665
+ objectId: string;
666
+ wrapped: WrappedKey;
667
+ }): Promise<Uint8Array> {
668
+ assertKey(options.grantWrapKey, "grantWrapKey");
669
+ const aad = grantAad(options.grantId, options.kind, options.objectId);
670
+ const iv = base64ToBytes(options.wrapped.iv);
671
+ const ct = base64ToBytes(options.wrapped.wrapped);
672
+ if (iv.length !== IV_BYTES || ct.length !== KEY_BYTES + TAG_BYTES) {
673
+ throw new VaultCryptoError(
674
+ "unwrap_failed",
675
+ "grant wrap has the wrong shape",
676
+ );
677
+ }
678
+ const key = await aesGcmOpen(options.grantWrapKey, iv, ct, aad);
679
+ if (!key)
680
+ throw new VaultCryptoError("unwrap_failed", "grant wrap did not open");
681
+ return key;
682
+ }
683
+
684
+ // ──────────────────────────────────────────────────────────────────────
685
+ // The owner's copy of a grant secret, bound to the grant's scope
686
+ // ──────────────────────────────────────────────────────────────────────
687
+
688
+ /** What a grant covers, as the owner decided it when creating the grant. */
689
+ export interface GrantScope {
690
+ grantId: string;
691
+ scopeAll: boolean;
692
+ includeMedia: boolean;
693
+ /** Scope-root folder ids (empty for a whole-vault grant). */
694
+ rootIds: readonly string[];
695
+ /** The grant's own trash folder, or null for a read-only grant. */
696
+ trashFolderId: string | null;
697
+ /** Top-level folders a whole-vault grant must never cover (the Bin, and Media unless opted in). */
698
+ excludedIds: readonly string[];
699
+ /**
700
+ * keyFingerprint() of those folders' keys. A server can relabel a row with
701
+ * another folder's wrapped key; it cannot change a key's fingerprint, so the
702
+ * owner's browser refuses to hand an excluded folder's key to the grant under
703
+ * any id.
704
+ */
705
+ excludedKeyFingerprints: readonly string[];
706
+ }
707
+
708
+ /** SHA-256 of a 32-byte key, hex. Reveals nothing usable about a random key. */
709
+ export function keyFingerprint(key: Uint8Array): string {
710
+ assertKey(key, "key");
711
+ return bytesToHex(sha256(key));
712
+ }
713
+
714
+ /** A canonical, order-independent string for a scope. Any change to the scope changes it. */
715
+ export function canonicalGrantScope(scope: GrantScope): string {
716
+ assertUuid(scope.grantId, "grantId");
717
+ const ids = (list: readonly string[], what: string) => {
718
+ for (const id of list) assertUuid(id, what);
719
+ return [...new Set(list)].sort().join(",");
720
+ };
721
+ if (scope.trashFolderId !== null)
722
+ assertUuid(scope.trashFolderId, "trashFolderId");
723
+ return [
724
+ "sf-grant-scope-v1",
725
+ scope.grantId,
726
+ `all=${scope.scopeAll ? 1 : 0}`,
727
+ `media=${scope.includeMedia ? 1 : 0}`,
728
+ `roots=${ids(scope.rootIds, "rootIds")}`,
729
+ `trash=${scope.trashFolderId ?? "-"}`,
730
+ `excluded=${ids(scope.excludedIds, "excludedIds")}`,
731
+ `excludedKeys=${[...new Set(scope.excludedKeyFingerprints)]
732
+ .map((f) => {
733
+ if (!/^[0-9a-f]{64}$/.test(f))
734
+ throw new VaultCryptoError("invalid_input", "bad key fingerprint");
735
+ return f;
736
+ })
737
+ .sort()
738
+ .join(",")}`,
739
+ ].join("|");
740
+ }
741
+
742
+ async function grantSecretKey(
743
+ rootKey: Uint8Array,
744
+ grantId: string,
745
+ ): Promise<Uint8Array> {
746
+ assertKey(rootKey, "rootKey");
747
+ assertUuid(grantId, "grantId");
748
+ return hkdfSha256({
749
+ ikm: rootKey,
750
+ salt: TEXT_ENCODER.encode(grantId),
751
+ info: HKDF_INFO.AGENT_GRANT_SECRET,
752
+ length: KEY_BYTES,
753
+ });
754
+ }
755
+
756
+ /**
757
+ * Wrap a grant secret for the owner: AES-256-GCM under HKDF(RK, grant id,
758
+ * AGENT_GRANT_SECRET), with the canonical scope as AAD. Only the owner's
759
+ * vault root key opens it, and only for exactly this scope.
760
+ */
761
+ export async function wrapGrantSecret(options: {
762
+ rootKey: Uint8Array;
763
+ scope: GrantScope;
764
+ secret: Uint8Array;
765
+ }): Promise<WrappedKey> {
766
+ assertKey(options.secret, "secret");
767
+ const key = await grantSecretKey(options.rootKey, options.scope.grantId);
768
+ const iv = randomBytes(IV_BYTES);
769
+ const ct = await aesGcmSeal(
770
+ key,
771
+ iv,
772
+ options.secret,
773
+ TEXT_ENCODER.encode(canonicalGrantScope(options.scope)),
774
+ );
775
+ return { wrapped: bytesToBase64(ct), iv: bytesToBase64(iv) };
776
+ }
777
+
778
+ /** Open the owner's copy of a grant secret. Fails if the scope differs in any way from the one it was wrapped for. */
779
+ export async function unwrapGrantSecret(options: {
780
+ rootKey: Uint8Array;
781
+ scope: GrantScope;
782
+ wrapped: WrappedKey;
783
+ }): Promise<Uint8Array> {
784
+ const key = await grantSecretKey(options.rootKey, options.scope.grantId);
785
+ const iv = base64ToBytes(options.wrapped.iv);
786
+ const ct = base64ToBytes(options.wrapped.wrapped);
787
+ if (iv.length !== IV_BYTES || ct.length !== KEY_BYTES + TAG_BYTES) {
788
+ throw new VaultCryptoError(
789
+ "unwrap_failed",
790
+ "grant secret wrap has the wrong shape",
791
+ );
792
+ }
793
+ const secret = await aesGcmOpen(
794
+ key,
795
+ iv,
796
+ ct,
797
+ TEXT_ENCODER.encode(canonicalGrantScope(options.scope)),
798
+ );
799
+ if (!secret)
800
+ throw new VaultCryptoError(
801
+ "unwrap_failed",
802
+ "grant secret did not open for this scope",
803
+ );
804
+ return secret;
805
+ }