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

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,626 @@
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
+ } from '../internal/encoding.js'
38
+ import { hkdfSha256 } from '../internal/hkdf.js'
39
+ import { getSubtle, randomBytes } from '../internal/runtime.js'
40
+ import { getSodium } from '../internal/sodium.js'
41
+ import { HKDF_INFO } from '../internal/types.js'
42
+
43
+ const KEY_BYTES = 32
44
+ const IV_BYTES = 12
45
+ const TAG_BYTES = 16
46
+ const NAME_SALT_BYTES = 16
47
+ const TEXT_ENCODER = new TextEncoder()
48
+ const TEXT_DECODER = new TextDecoder('utf-8', { fatal: true })
49
+
50
+ /** Raised for any envelope or wrap that does not open. Never carries key bytes. */
51
+ export class VaultCryptoError extends Error {
52
+ readonly code:
53
+ | 'unwrap_failed'
54
+ | 'name_decrypt_failed'
55
+ | 'unsupported_envelope'
56
+ | 'invalid_input'
57
+ | 'invalid_connection_string'
58
+ constructor(code: VaultCryptoError['code'], message: string) {
59
+ super(message)
60
+ this.name = 'VaultCryptoError'
61
+ this.code = code
62
+ }
63
+ }
64
+
65
+ function assertKey(key: Uint8Array, what: string): void {
66
+ if (!(key instanceof Uint8Array) || key.length !== KEY_BYTES) {
67
+ throw new VaultCryptoError('invalid_input', `${what} must be 32 bytes`)
68
+ }
69
+ }
70
+
71
+ async function importAesKey(key: Uint8Array): Promise<CryptoKey> {
72
+ return getSubtle().importKey(
73
+ 'raw',
74
+ key as Uint8Array<ArrayBuffer>,
75
+ { name: 'AES-GCM' },
76
+ false,
77
+ ['encrypt', 'decrypt'],
78
+ )
79
+ }
80
+
81
+ async function aesGcmSeal(
82
+ key: Uint8Array,
83
+ iv: Uint8Array,
84
+ plaintext: Uint8Array,
85
+ aad?: Uint8Array,
86
+ ): Promise<Uint8Array> {
87
+ const params: AesGcmParams = { name: 'AES-GCM', iv: iv as Uint8Array<ArrayBuffer> }
88
+ if (aad) params.additionalData = aad as Uint8Array<ArrayBuffer>
89
+ const out = await getSubtle().encrypt(
90
+ params,
91
+ await importAesKey(key),
92
+ plaintext as Uint8Array<ArrayBuffer>,
93
+ )
94
+ return new Uint8Array(out)
95
+ }
96
+
97
+ async function aesGcmOpen(
98
+ key: Uint8Array,
99
+ iv: Uint8Array,
100
+ ciphertext: Uint8Array,
101
+ aad?: Uint8Array,
102
+ ): Promise<Uint8Array | null> {
103
+ const params: AesGcmParams = { name: 'AES-GCM', iv: iv as Uint8Array<ArrayBuffer> }
104
+ if (aad) params.additionalData = aad as Uint8Array<ArrayBuffer>
105
+ try {
106
+ const out = await getSubtle().decrypt(
107
+ params,
108
+ await importAesKey(key),
109
+ ciphertext as Uint8Array<ArrayBuffer>,
110
+ )
111
+ return new Uint8Array(out)
112
+ } catch {
113
+ return null
114
+ }
115
+ }
116
+
117
+ // ──────────────────────────────────────────────────────────────────────
118
+ // Key chain
119
+ // ──────────────────────────────────────────────────────────────────────
120
+
121
+ /** A wrapped key as the database stores it: base64 ciphertext+tag and base64 IV. */
122
+ export interface WrappedKey {
123
+ wrapped: string
124
+ iv: string
125
+ }
126
+
127
+ /** Wrap a 32-byte key under a 32-byte key (the fk/csk/pqk chain format). */
128
+ export async function wrapChainKey(
129
+ wrappingKey: Uint8Array,
130
+ key: Uint8Array,
131
+ ): Promise<WrappedKey> {
132
+ assertKey(wrappingKey, 'wrappingKey')
133
+ assertKey(key, 'key')
134
+ const iv = randomBytes(IV_BYTES)
135
+ const ct = await aesGcmSeal(wrappingKey, iv, key)
136
+ return { wrapped: bytesToBase64(ct), iv: bytesToBase64(iv) }
137
+ }
138
+
139
+ /** Open one hop of the key chain. Throws `unwrap_failed` on a wrong key or tampering. */
140
+ export async function unwrapChainKey(
141
+ wrappingKey: Uint8Array,
142
+ wrapped: WrappedKey,
143
+ ): Promise<Uint8Array> {
144
+ assertKey(wrappingKey, 'wrappingKey')
145
+ const iv = base64ToBytes(wrapped.iv)
146
+ const ct = base64ToBytes(wrapped.wrapped)
147
+ if (iv.length !== IV_BYTES || ct.length !== KEY_BYTES + TAG_BYTES) {
148
+ throw new VaultCryptoError('unwrap_failed', 'wrapped key has the wrong shape')
149
+ }
150
+ const key = await aesGcmOpen(wrappingKey, iv, ct)
151
+ if (!key) throw new VaultCryptoError('unwrap_failed', 'wrapped key did not open')
152
+ return key
153
+ }
154
+
155
+ // ──────────────────────────────────────────────────────────────────────
156
+ // Name envelopes (v4, v6)
157
+ // ──────────────────────────────────────────────────────────────────────
158
+
159
+ export type NameKdfLevel = 'interactive' | 'moderate'
160
+
161
+ export interface NameEnvelope {
162
+ v: 4 | 6
163
+ ct: string
164
+ iv: string
165
+ tag: string
166
+ salt: string
167
+ kdf?: NameKdfLevel
168
+ }
169
+
170
+ /** Parse a stored name. Returns null for anything that is not a v4/v6 envelope. */
171
+ export function parseNameEnvelope(raw: string | null | undefined): NameEnvelope | null {
172
+ if (typeof raw !== 'string' || raw.length === 0 || raw.length > 8192) return null
173
+ let value: unknown
174
+ try {
175
+ value = JSON.parse(raw)
176
+ } catch {
177
+ return null
178
+ }
179
+ if (!value || typeof value !== 'object') return null
180
+ const p = value as Record<string, unknown>
181
+ if (p.v !== 4 && p.v !== 6) return null
182
+ for (const f of ['ct', 'iv', 'tag', 'salt'] as const) {
183
+ if (typeof p[f] !== 'string') return null
184
+ }
185
+ if (p.kdf !== undefined && p.kdf !== 'interactive' && p.kdf !== 'moderate') return null
186
+ const env: NameEnvelope = {
187
+ v: p.v,
188
+ ct: p.ct as string,
189
+ iv: p.iv as string,
190
+ tag: p.tag as string,
191
+ salt: p.salt as string,
192
+ }
193
+ if (p.kdf !== undefined) env.kdf = p.kdf as NameKdfLevel
194
+ return env
195
+ }
196
+
197
+ /**
198
+ * Derive the per-envelope name key. The Argon2id password is the base64 TEXT
199
+ * of the folder key, byte-for-byte what the web app passes to libsodium; the
200
+ * input is already 256 bits of entropy, so the cost level is a compatibility
201
+ * parameter, not a security one.
202
+ */
203
+ export async function deriveNameKey(
204
+ folderKey: Uint8Array,
205
+ salt: Uint8Array,
206
+ level: NameKdfLevel,
207
+ ): Promise<Uint8Array> {
208
+ assertKey(folderKey, 'folderKey')
209
+ if (salt.length !== NAME_SALT_BYTES) {
210
+ throw new VaultCryptoError('invalid_input', 'name salt must be 16 bytes')
211
+ }
212
+ const sodium = await getSodium()
213
+ const ops =
214
+ level === 'interactive'
215
+ ? sodium.crypto_pwhash_OPSLIMIT_INTERACTIVE
216
+ : sodium.crypto_pwhash_OPSLIMIT_MODERATE
217
+ const mem =
218
+ level === 'interactive'
219
+ ? sodium.crypto_pwhash_MEMLIMIT_INTERACTIVE
220
+ : sodium.crypto_pwhash_MEMLIMIT_MODERATE
221
+ return new Uint8Array(
222
+ sodium.crypto_pwhash(
223
+ KEY_BYTES,
224
+ TEXT_ENCODER.encode(bytesToBase64(folderKey)),
225
+ salt,
226
+ ops,
227
+ mem,
228
+ sodium.crypto_pwhash_ALG_ARGON2ID13,
229
+ ),
230
+ )
231
+ }
232
+
233
+ /**
234
+ * Decrypt a v4 or v6 name. `rowId` is the database UUID of the row the name
235
+ * belongs to and is REQUIRED for v6 (it is the AAD). An envelope written
236
+ * without a `kdf` field is tried at interactive, then moderate, which is the
237
+ * web app's own fallback order for a device that cannot know the level.
238
+ */
239
+ export async function decryptName(options: {
240
+ envelope: NameEnvelope
241
+ folderKey: Uint8Array
242
+ rowId?: string
243
+ }): Promise<string> {
244
+ const { envelope, folderKey, rowId } = options
245
+ if (envelope.v === 6 && !rowId) {
246
+ throw new VaultCryptoError('invalid_input', 'v6 names need the row id')
247
+ }
248
+ const iv = base64ToBytes(envelope.iv)
249
+ const salt = base64ToBytes(envelope.salt)
250
+ const sealed = concatBytes([base64ToBytes(envelope.ct), base64ToBytes(envelope.tag)])
251
+ const aad = envelope.v === 6 ? TEXT_ENCODER.encode(rowId as string) : undefined
252
+ const levels: NameKdfLevel[] = envelope.kdf
253
+ ? [envelope.kdf]
254
+ : ['interactive', 'moderate']
255
+ for (const level of levels) {
256
+ const key = await deriveNameKey(folderKey, salt, level)
257
+ const pt = await aesGcmOpen(key, iv, sealed, aad)
258
+ if (pt) {
259
+ try {
260
+ return TEXT_DECODER.decode(pt)
261
+ } catch {
262
+ break
263
+ }
264
+ }
265
+ }
266
+ throw new VaultCryptoError('name_decrypt_failed', 'name envelope did not open')
267
+ }
268
+
269
+ /**
270
+ * Decrypt a name with an already-derived name key (a grant's `name` wrap),
271
+ * for objects whose parent key the caller does not hold.
272
+ */
273
+ export async function decryptNameWithKey(options: {
274
+ envelope: NameEnvelope
275
+ nameKey: Uint8Array
276
+ rowId?: string
277
+ }): Promise<string> {
278
+ const { envelope, nameKey, rowId } = options
279
+ assertKey(nameKey, 'nameKey')
280
+ if (envelope.v === 6 && !rowId) {
281
+ throw new VaultCryptoError('invalid_input', 'v6 names need the row id')
282
+ }
283
+ const sealed = concatBytes([base64ToBytes(envelope.ct), base64ToBytes(envelope.tag)])
284
+ const aad = envelope.v === 6 ? TEXT_ENCODER.encode(rowId as string) : undefined
285
+ const pt = await aesGcmOpen(nameKey, base64ToBytes(envelope.iv), sealed, aad)
286
+ if (pt) {
287
+ try {
288
+ return TEXT_DECODER.decode(pt)
289
+ } catch {
290
+ // fall through
291
+ }
292
+ }
293
+ throw new VaultCryptoError('name_decrypt_failed', 'name envelope did not open')
294
+ }
295
+
296
+ /**
297
+ * The name key for one envelope: what an owner wraps as a grant's `name`
298
+ * object. For an envelope without a `kdf` field the level is found by opening
299
+ * it, the same fallback `decryptName` uses, so the wrapped key always works.
300
+ */
301
+ export async function deriveNameKeyForEnvelope(options: {
302
+ envelope: NameEnvelope
303
+ parentKey: Uint8Array
304
+ rowId?: string
305
+ }): Promise<Uint8Array> {
306
+ const { envelope, parentKey, rowId } = options
307
+ const salt = base64ToBytes(envelope.salt)
308
+ const levels: NameKdfLevel[] = envelope.kdf ? [envelope.kdf] : ['interactive', 'moderate']
309
+ for (const level of levels) {
310
+ const nameKey = await deriveNameKey(parentKey, salt, level)
311
+ try {
312
+ await decryptNameWithKey(rowId === undefined ? { envelope, nameKey } : { envelope, nameKey, rowId })
313
+ return nameKey
314
+ } catch (err) {
315
+ if (!(err instanceof VaultCryptoError) || err.code !== 'name_decrypt_failed') throw err
316
+ }
317
+ }
318
+ throw new VaultCryptoError('name_decrypt_failed', 'name envelope did not open')
319
+ }
320
+
321
+ /** Encrypt a name as a v6 envelope bound to `rowId`, at the web app's default level. */
322
+ export async function encryptNameV6(options: {
323
+ name: string
324
+ folderKey: Uint8Array
325
+ rowId: string
326
+ }): Promise<NameEnvelope> {
327
+ const { name, folderKey, rowId } = options
328
+ if (typeof name !== 'string' || name.length === 0) {
329
+ throw new VaultCryptoError('invalid_input', 'name must be a non-empty string')
330
+ }
331
+ if (typeof rowId !== 'string' || rowId.length === 0) {
332
+ throw new VaultCryptoError('invalid_input', 'rowId is required')
333
+ }
334
+ const salt = randomBytes(NAME_SALT_BYTES)
335
+ const iv = randomBytes(IV_BYTES)
336
+ const key = await deriveNameKey(folderKey, salt, 'interactive')
337
+ const sealed = await aesGcmSeal(key, iv, TEXT_ENCODER.encode(name), TEXT_ENCODER.encode(rowId))
338
+ return {
339
+ v: 6,
340
+ ct: bytesToBase64(sealed.slice(0, sealed.length - TAG_BYTES)),
341
+ iv: bytesToBase64(iv),
342
+ tag: bytesToBase64(sealed.slice(sealed.length - TAG_BYTES)),
343
+ salt: bytesToBase64(salt),
344
+ kdf: 'interactive',
345
+ }
346
+ }
347
+
348
+ // ──────────────────────────────────────────────────────────────────────
349
+ // Agent grants
350
+ // ──────────────────────────────────────────────────────────────────────
351
+
352
+ export const GRANT_CONNECTION_PREFIX = 'sf-grant-v1:'
353
+
354
+ /**
355
+ * What a grant wrap covers.
356
+ *
357
+ * folder a folder key (scope roots, and top-level folders for whole-vault)
358
+ * file the key a file's `csk_wrapped` holds: the content key for suites
359
+ * 0x00-0x02, the classical envelope key for 0x03
360
+ * file_pq the combined content key of a suite-0x03 file
361
+ * name the Argon2id-derived key of ONE name envelope, for objects whose
362
+ * name is sealed under a key outside the grant (a scope root's own
363
+ * name, a file at the vault root). Opens that envelope only.
364
+ *
365
+ * `file`, `file_pq` and `name` are only issued for objects whose parent key the
366
+ * grant does not hold; everything below a scope root is reached by the chain.
367
+ */
368
+ export type GrantObjectKind = 'folder' | 'file' | 'file_pq' | 'name'
369
+ const GRANT_KINDS: ReadonlySet<string> = new Set(['folder', 'file', 'file_pq', 'name'])
370
+
371
+ export interface GrantCredential {
372
+ grantId: string
373
+ /** Sent to the server as a bearer token. The server stores only its SHA-256. */
374
+ token: Uint8Array
375
+ /** Never leaves the client. Wraps the grant's keys. */
376
+ secret: Uint8Array
377
+ /** SHA-256 of the owner's ML-KEM public key at grant creation, hex. */
378
+ publicKeyFingerprint: string
379
+ }
380
+
381
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
382
+
383
+ function assertUuid(value: string, what: string): void {
384
+ if (typeof value !== 'string' || !UUID_RE.test(value)) {
385
+ throw new VaultCryptoError('invalid_input', `${what} must be a lowercase UUID`)
386
+ }
387
+ }
388
+
389
+ function toBase64Url(bytes: Uint8Array): string {
390
+ return bytesToBase64(bytes).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
391
+ }
392
+
393
+ function fromBase64Url(value: string): Uint8Array {
394
+ if (!/^[A-Za-z0-9_-]+$/.test(value)) {
395
+ throw new VaultCryptoError('invalid_connection_string', 'bad base64url')
396
+ }
397
+ if (value.length % 4 === 1) {
398
+ throw new VaultCryptoError('invalid_connection_string', 'bad base64url length')
399
+ }
400
+ const b64 = value.replace(/-/g, '+').replace(/_/g, '/')
401
+ try {
402
+ return base64ToBytes(b64 + '='.repeat((4 - (b64.length % 4)) % 4))
403
+ } catch {
404
+ throw new VaultCryptoError('invalid_connection_string', 'bad base64url')
405
+ }
406
+ }
407
+
408
+ /** SHA-256 of an ML-KEM public key, hex. Pinned in the connection string. */
409
+ export function publicKeyFingerprint(mlKemPublicKey: Uint8Array): string {
410
+ return bytesToHex(sha256(mlKemPublicKey))
411
+ }
412
+
413
+ /** Fresh token + secret for a new grant. Call in the owner's unlocked client. */
414
+ export function createGrantCredential(options: {
415
+ grantId: string
416
+ mlKemPublicKey: Uint8Array
417
+ }): GrantCredential {
418
+ assertUuid(options.grantId, 'grantId')
419
+ return {
420
+ grantId: options.grantId,
421
+ token: randomBytes(KEY_BYTES),
422
+ secret: randomBytes(KEY_BYTES),
423
+ publicKeyFingerprint: publicKeyFingerprint(options.mlKemPublicKey),
424
+ }
425
+ }
426
+
427
+ /** `sf-grant-v1:<grant_id>.<token>.<secret>.<pk_fingerprint>` (base64url, hex). */
428
+ export function formatConnectionString(c: GrantCredential): string {
429
+ assertUuid(c.grantId, 'grantId')
430
+ assertKey(c.token, 'token')
431
+ assertKey(c.secret, 'secret')
432
+ if (!/^[0-9a-f]{64}$/.test(c.publicKeyFingerprint)) {
433
+ throw new VaultCryptoError('invalid_input', 'fingerprint must be 64 hex chars')
434
+ }
435
+ return `${GRANT_CONNECTION_PREFIX}${c.grantId}.${toBase64Url(c.token)}.${toBase64Url(c.secret)}.${c.publicKeyFingerprint}`
436
+ }
437
+
438
+ export function parseConnectionString(value: string): GrantCredential {
439
+ const bad = (why: string) => new VaultCryptoError('invalid_connection_string', why)
440
+ if (typeof value !== 'string') throw bad('not a string')
441
+ const trimmed = value.trim()
442
+ if (!trimmed.startsWith(GRANT_CONNECTION_PREFIX)) throw bad('wrong prefix')
443
+ const parts = trimmed.slice(GRANT_CONNECTION_PREFIX.length).split('.')
444
+ if (parts.length !== 4) throw bad('expected four parts')
445
+ const [grantId, tokenPart, secretPart, fingerprint] = parts as [string, string, string, string]
446
+ if (!UUID_RE.test(grantId)) throw bad('bad grant id')
447
+ const token = fromBase64Url(tokenPart)
448
+ const secret = fromBase64Url(secretPart)
449
+ if (token.length !== KEY_BYTES || secret.length !== KEY_BYTES) throw bad('bad key length')
450
+ if (!/^[0-9a-f]{64}$/.test(fingerprint)) throw bad('bad fingerprint')
451
+ return { grantId, token, secret, publicKeyFingerprint: fingerprint }
452
+ }
453
+
454
+ /** The bearer value a client sends. */
455
+ export function grantBearerToken(c: Pick<GrantCredential, 'token'>): string {
456
+ return toBase64Url(c.token)
457
+ }
458
+
459
+ /** What the server stores and looks up: SHA-256 of the bearer token's bytes, hex. */
460
+ export function hashGrantToken(bearer: string): string {
461
+ const bytes = fromBase64Url(bearer)
462
+ if (bytes.length !== KEY_BYTES) {
463
+ throw new VaultCryptoError('invalid_input', 'bearer token has the wrong length')
464
+ }
465
+ return bytesToHex(sha256(bytes))
466
+ }
467
+
468
+ /** GK = HKDF-SHA-256(secret, salt = utf8(grant id), info = AGENT_GRANT_WRAP). */
469
+ export async function deriveGrantWrapKey(
470
+ secret: Uint8Array,
471
+ grantId: string,
472
+ ): Promise<Uint8Array> {
473
+ assertKey(secret, 'secret')
474
+ assertUuid(grantId, 'grantId')
475
+ return hkdfSha256({
476
+ ikm: secret,
477
+ salt: TEXT_ENCODER.encode(grantId),
478
+ info: HKDF_INFO.AGENT_GRANT_WRAP,
479
+ length: KEY_BYTES,
480
+ })
481
+ }
482
+
483
+ function grantAad(grantId: string, kind: GrantObjectKind, objectId: string): Uint8Array {
484
+ if (!GRANT_KINDS.has(kind)) {
485
+ throw new VaultCryptoError('invalid_input', 'unknown grant object kind')
486
+ }
487
+ assertUuid(grantId, 'grantId')
488
+ assertUuid(objectId, 'objectId')
489
+ return TEXT_ENCODER.encode(`sf-grant-v1|${grantId}|${kind}|${objectId}`)
490
+ }
491
+
492
+ /** Wrap a folder key or file content key for a grant, bound to (grant, kind, object). */
493
+ export async function wrapKeyForGrant(options: {
494
+ grantWrapKey: Uint8Array
495
+ grantId: string
496
+ kind: GrantObjectKind
497
+ objectId: string
498
+ key: Uint8Array
499
+ }): Promise<WrappedKey> {
500
+ assertKey(options.grantWrapKey, 'grantWrapKey')
501
+ assertKey(options.key, 'key')
502
+ const aad = grantAad(options.grantId, options.kind, options.objectId)
503
+ const iv = randomBytes(IV_BYTES)
504
+ const ct = await aesGcmSeal(options.grantWrapKey, iv, options.key, aad)
505
+ return { wrapped: bytesToBase64(ct), iv: bytesToBase64(iv) }
506
+ }
507
+
508
+ export async function unwrapKeyForGrant(options: {
509
+ grantWrapKey: Uint8Array
510
+ grantId: string
511
+ kind: GrantObjectKind
512
+ objectId: string
513
+ wrapped: WrappedKey
514
+ }): Promise<Uint8Array> {
515
+ assertKey(options.grantWrapKey, 'grantWrapKey')
516
+ const aad = grantAad(options.grantId, options.kind, options.objectId)
517
+ const iv = base64ToBytes(options.wrapped.iv)
518
+ const ct = base64ToBytes(options.wrapped.wrapped)
519
+ if (iv.length !== IV_BYTES || ct.length !== KEY_BYTES + TAG_BYTES) {
520
+ throw new VaultCryptoError('unwrap_failed', 'grant wrap has the wrong shape')
521
+ }
522
+ const key = await aesGcmOpen(options.grantWrapKey, iv, ct, aad)
523
+ if (!key) throw new VaultCryptoError('unwrap_failed', 'grant wrap did not open')
524
+ return key
525
+ }
526
+
527
+ // ──────────────────────────────────────────────────────────────────────
528
+ // The owner's copy of a grant secret, bound to the grant's scope
529
+ // ──────────────────────────────────────────────────────────────────────
530
+
531
+ /** What a grant covers, as the owner decided it when creating the grant. */
532
+ export interface GrantScope {
533
+ grantId: string
534
+ scopeAll: boolean
535
+ includeMedia: boolean
536
+ /** Scope-root folder ids (empty for a whole-vault grant). */
537
+ rootIds: readonly string[]
538
+ /** The grant's own trash folder, or null for a read-only grant. */
539
+ trashFolderId: string | null
540
+ /** Top-level folders a whole-vault grant must never cover (the Bin, and Media unless opted in). */
541
+ excludedIds: readonly string[]
542
+ /**
543
+ * keyFingerprint() of those folders' keys. A server can relabel a row with
544
+ * another folder's wrapped key; it cannot change a key's fingerprint, so the
545
+ * owner's browser refuses to hand an excluded folder's key to the grant under
546
+ * any id.
547
+ */
548
+ excludedKeyFingerprints: readonly string[]
549
+ }
550
+
551
+ /** SHA-256 of a 32-byte key, hex. Reveals nothing usable about a random key. */
552
+ export function keyFingerprint(key: Uint8Array): string {
553
+ assertKey(key, 'key')
554
+ return bytesToHex(sha256(key))
555
+ }
556
+
557
+ /** A canonical, order-independent string for a scope. Any change to the scope changes it. */
558
+ export function canonicalGrantScope(scope: GrantScope): string {
559
+ assertUuid(scope.grantId, 'grantId')
560
+ const ids = (list: readonly string[], what: string) => {
561
+ for (const id of list) assertUuid(id, what)
562
+ return [...new Set(list)].sort().join(',')
563
+ }
564
+ if (scope.trashFolderId !== null) assertUuid(scope.trashFolderId, 'trashFolderId')
565
+ return [
566
+ 'sf-grant-scope-v1',
567
+ scope.grantId,
568
+ `all=${scope.scopeAll ? 1 : 0}`,
569
+ `media=${scope.includeMedia ? 1 : 0}`,
570
+ `roots=${ids(scope.rootIds, 'rootIds')}`,
571
+ `trash=${scope.trashFolderId ?? '-'}`,
572
+ `excluded=${ids(scope.excludedIds, 'excludedIds')}`,
573
+ `excludedKeys=${[...new Set(scope.excludedKeyFingerprints)]
574
+ .map((f) => {
575
+ if (!/^[0-9a-f]{64}$/.test(f)) throw new VaultCryptoError('invalid_input', 'bad key fingerprint')
576
+ return f
577
+ })
578
+ .sort()
579
+ .join(',')}`,
580
+ ].join('|')
581
+ }
582
+
583
+ async function grantSecretKey(rootKey: Uint8Array, grantId: string): Promise<Uint8Array> {
584
+ assertKey(rootKey, 'rootKey')
585
+ assertUuid(grantId, 'grantId')
586
+ return hkdfSha256({
587
+ ikm: rootKey,
588
+ salt: TEXT_ENCODER.encode(grantId),
589
+ info: HKDF_INFO.AGENT_GRANT_SECRET,
590
+ length: KEY_BYTES,
591
+ })
592
+ }
593
+
594
+ /**
595
+ * Wrap a grant secret for the owner: AES-256-GCM under HKDF(RK, grant id,
596
+ * AGENT_GRANT_SECRET), with the canonical scope as AAD. Only the owner's
597
+ * vault root key opens it, and only for exactly this scope.
598
+ */
599
+ export async function wrapGrantSecret(options: {
600
+ rootKey: Uint8Array
601
+ scope: GrantScope
602
+ secret: Uint8Array
603
+ }): Promise<WrappedKey> {
604
+ assertKey(options.secret, 'secret')
605
+ const key = await grantSecretKey(options.rootKey, options.scope.grantId)
606
+ const iv = randomBytes(IV_BYTES)
607
+ const ct = await aesGcmSeal(key, iv, options.secret, TEXT_ENCODER.encode(canonicalGrantScope(options.scope)))
608
+ return { wrapped: bytesToBase64(ct), iv: bytesToBase64(iv) }
609
+ }
610
+
611
+ /** Open the owner's copy of a grant secret. Fails if the scope differs in any way from the one it was wrapped for. */
612
+ export async function unwrapGrantSecret(options: {
613
+ rootKey: Uint8Array
614
+ scope: GrantScope
615
+ wrapped: WrappedKey
616
+ }): Promise<Uint8Array> {
617
+ const key = await grantSecretKey(options.rootKey, options.scope.grantId)
618
+ const iv = base64ToBytes(options.wrapped.iv)
619
+ const ct = base64ToBytes(options.wrapped.wrapped)
620
+ if (iv.length !== IV_BYTES || ct.length !== KEY_BYTES + TAG_BYTES) {
621
+ throw new VaultCryptoError('unwrap_failed', 'grant secret wrap has the wrong shape')
622
+ }
623
+ const secret = await aesGcmOpen(key, iv, ct, TEXT_ENCODER.encode(canonicalGrantScope(options.scope)))
624
+ if (!secret) throw new VaultCryptoError('unwrap_failed', 'grant secret did not open for this scope')
625
+ return secret
626
+ }