@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,445 @@
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
+ import { sha256 } from '@noble/hashes/sha2.js';
30
+ import { base64ToBytes, bytesToBase64, bytesToHex, concatBytes, } from '../internal/encoding.js';
31
+ import { hkdfSha256 } from '../internal/hkdf.js';
32
+ import { getSubtle, randomBytes } from '../internal/runtime.js';
33
+ import { getSodium } from '../internal/sodium.js';
34
+ import { HKDF_INFO } from '../internal/types.js';
35
+ const KEY_BYTES = 32;
36
+ const IV_BYTES = 12;
37
+ const TAG_BYTES = 16;
38
+ const NAME_SALT_BYTES = 16;
39
+ const TEXT_ENCODER = new TextEncoder();
40
+ const TEXT_DECODER = new TextDecoder('utf-8', { fatal: true });
41
+ /** Raised for any envelope or wrap that does not open. Never carries key bytes. */
42
+ export class VaultCryptoError extends Error {
43
+ code;
44
+ constructor(code, message) {
45
+ super(message);
46
+ this.name = 'VaultCryptoError';
47
+ this.code = code;
48
+ }
49
+ }
50
+ function assertKey(key, what) {
51
+ if (!(key instanceof Uint8Array) || key.length !== KEY_BYTES) {
52
+ throw new VaultCryptoError('invalid_input', `${what} must be 32 bytes`);
53
+ }
54
+ }
55
+ async function importAesKey(key) {
56
+ return getSubtle().importKey('raw', key, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']);
57
+ }
58
+ async function aesGcmSeal(key, iv, plaintext, aad) {
59
+ const params = { name: 'AES-GCM', iv: iv };
60
+ if (aad)
61
+ params.additionalData = aad;
62
+ const out = await getSubtle().encrypt(params, await importAesKey(key), plaintext);
63
+ return new Uint8Array(out);
64
+ }
65
+ async function aesGcmOpen(key, iv, ciphertext, aad) {
66
+ const params = { name: 'AES-GCM', iv: iv };
67
+ if (aad)
68
+ params.additionalData = aad;
69
+ try {
70
+ const out = await getSubtle().decrypt(params, await importAesKey(key), ciphertext);
71
+ return new Uint8Array(out);
72
+ }
73
+ catch {
74
+ return null;
75
+ }
76
+ }
77
+ /** Wrap a 32-byte key under a 32-byte key (the fk/csk/pqk chain format). */
78
+ export async function wrapChainKey(wrappingKey, key) {
79
+ assertKey(wrappingKey, 'wrappingKey');
80
+ assertKey(key, 'key');
81
+ const iv = randomBytes(IV_BYTES);
82
+ const ct = await aesGcmSeal(wrappingKey, iv, key);
83
+ return { wrapped: bytesToBase64(ct), iv: bytesToBase64(iv) };
84
+ }
85
+ /** Open one hop of the key chain. Throws `unwrap_failed` on a wrong key or tampering. */
86
+ export async function unwrapChainKey(wrappingKey, wrapped) {
87
+ assertKey(wrappingKey, 'wrappingKey');
88
+ const iv = base64ToBytes(wrapped.iv);
89
+ const ct = base64ToBytes(wrapped.wrapped);
90
+ if (iv.length !== IV_BYTES || ct.length !== KEY_BYTES + TAG_BYTES) {
91
+ throw new VaultCryptoError('unwrap_failed', 'wrapped key has the wrong shape');
92
+ }
93
+ const key = await aesGcmOpen(wrappingKey, iv, ct);
94
+ if (!key)
95
+ throw new VaultCryptoError('unwrap_failed', 'wrapped key did not open');
96
+ return key;
97
+ }
98
+ /** Parse a stored name. Returns null for anything that is not a v4/v6 envelope. */
99
+ export function parseNameEnvelope(raw) {
100
+ if (typeof raw !== 'string' || raw.length === 0 || raw.length > 8192)
101
+ return null;
102
+ let value;
103
+ try {
104
+ value = JSON.parse(raw);
105
+ }
106
+ catch {
107
+ return null;
108
+ }
109
+ if (!value || typeof value !== 'object')
110
+ return null;
111
+ const p = value;
112
+ if (p.v !== 4 && p.v !== 6)
113
+ return null;
114
+ for (const f of ['ct', 'iv', 'tag', 'salt']) {
115
+ if (typeof p[f] !== 'string')
116
+ return null;
117
+ }
118
+ if (p.kdf !== undefined && p.kdf !== 'interactive' && p.kdf !== 'moderate')
119
+ return null;
120
+ const env = {
121
+ v: p.v,
122
+ ct: p.ct,
123
+ iv: p.iv,
124
+ tag: p.tag,
125
+ salt: p.salt,
126
+ };
127
+ if (p.kdf !== undefined)
128
+ env.kdf = p.kdf;
129
+ return env;
130
+ }
131
+ /**
132
+ * Derive the per-envelope name key. The Argon2id password is the base64 TEXT
133
+ * of the folder key, byte-for-byte what the web app passes to libsodium; the
134
+ * input is already 256 bits of entropy, so the cost level is a compatibility
135
+ * parameter, not a security one.
136
+ */
137
+ export async function deriveNameKey(folderKey, salt, level) {
138
+ assertKey(folderKey, 'folderKey');
139
+ if (salt.length !== NAME_SALT_BYTES) {
140
+ throw new VaultCryptoError('invalid_input', 'name salt must be 16 bytes');
141
+ }
142
+ const sodium = await getSodium();
143
+ const ops = level === 'interactive'
144
+ ? sodium.crypto_pwhash_OPSLIMIT_INTERACTIVE
145
+ : sodium.crypto_pwhash_OPSLIMIT_MODERATE;
146
+ const mem = level === 'interactive'
147
+ ? sodium.crypto_pwhash_MEMLIMIT_INTERACTIVE
148
+ : sodium.crypto_pwhash_MEMLIMIT_MODERATE;
149
+ return new Uint8Array(sodium.crypto_pwhash(KEY_BYTES, TEXT_ENCODER.encode(bytesToBase64(folderKey)), salt, ops, mem, sodium.crypto_pwhash_ALG_ARGON2ID13));
150
+ }
151
+ /**
152
+ * Decrypt a v4 or v6 name. `rowId` is the database UUID of the row the name
153
+ * belongs to and is REQUIRED for v6 (it is the AAD). An envelope written
154
+ * without a `kdf` field is tried at interactive, then moderate, which is the
155
+ * web app's own fallback order for a device that cannot know the level.
156
+ */
157
+ export async function decryptName(options) {
158
+ const { envelope, folderKey, rowId } = options;
159
+ if (envelope.v === 6 && !rowId) {
160
+ throw new VaultCryptoError('invalid_input', 'v6 names need the row id');
161
+ }
162
+ const iv = base64ToBytes(envelope.iv);
163
+ const salt = base64ToBytes(envelope.salt);
164
+ const sealed = concatBytes([base64ToBytes(envelope.ct), base64ToBytes(envelope.tag)]);
165
+ const aad = envelope.v === 6 ? TEXT_ENCODER.encode(rowId) : undefined;
166
+ const levels = envelope.kdf
167
+ ? [envelope.kdf]
168
+ : ['interactive', 'moderate'];
169
+ for (const level of levels) {
170
+ const key = await deriveNameKey(folderKey, salt, level);
171
+ const pt = await aesGcmOpen(key, iv, sealed, aad);
172
+ if (pt) {
173
+ try {
174
+ return TEXT_DECODER.decode(pt);
175
+ }
176
+ catch {
177
+ break;
178
+ }
179
+ }
180
+ }
181
+ throw new VaultCryptoError('name_decrypt_failed', 'name envelope did not open');
182
+ }
183
+ /**
184
+ * Decrypt a name with an already-derived name key (a grant's `name` wrap),
185
+ * for objects whose parent key the caller does not hold.
186
+ */
187
+ export async function decryptNameWithKey(options) {
188
+ const { envelope, nameKey, rowId } = options;
189
+ assertKey(nameKey, 'nameKey');
190
+ if (envelope.v === 6 && !rowId) {
191
+ throw new VaultCryptoError('invalid_input', 'v6 names need the row id');
192
+ }
193
+ const sealed = concatBytes([base64ToBytes(envelope.ct), base64ToBytes(envelope.tag)]);
194
+ const aad = envelope.v === 6 ? TEXT_ENCODER.encode(rowId) : undefined;
195
+ const pt = await aesGcmOpen(nameKey, base64ToBytes(envelope.iv), sealed, aad);
196
+ if (pt) {
197
+ try {
198
+ return TEXT_DECODER.decode(pt);
199
+ }
200
+ catch {
201
+ // fall through
202
+ }
203
+ }
204
+ throw new VaultCryptoError('name_decrypt_failed', 'name envelope did not open');
205
+ }
206
+ /**
207
+ * The name key for one envelope: what an owner wraps as a grant's `name`
208
+ * object. For an envelope without a `kdf` field the level is found by opening
209
+ * it, the same fallback `decryptName` uses, so the wrapped key always works.
210
+ */
211
+ export async function deriveNameKeyForEnvelope(options) {
212
+ const { envelope, parentKey, rowId } = options;
213
+ const salt = base64ToBytes(envelope.salt);
214
+ const levels = envelope.kdf ? [envelope.kdf] : ['interactive', 'moderate'];
215
+ for (const level of levels) {
216
+ const nameKey = await deriveNameKey(parentKey, salt, level);
217
+ try {
218
+ await decryptNameWithKey(rowId === undefined ? { envelope, nameKey } : { envelope, nameKey, rowId });
219
+ return nameKey;
220
+ }
221
+ catch (err) {
222
+ if (!(err instanceof VaultCryptoError) || err.code !== 'name_decrypt_failed')
223
+ throw err;
224
+ }
225
+ }
226
+ throw new VaultCryptoError('name_decrypt_failed', 'name envelope did not open');
227
+ }
228
+ /** Encrypt a name as a v6 envelope bound to `rowId`, at the web app's default level. */
229
+ export async function encryptNameV6(options) {
230
+ const { name, folderKey, rowId } = options;
231
+ if (typeof name !== 'string' || name.length === 0) {
232
+ throw new VaultCryptoError('invalid_input', 'name must be a non-empty string');
233
+ }
234
+ if (typeof rowId !== 'string' || rowId.length === 0) {
235
+ throw new VaultCryptoError('invalid_input', 'rowId is required');
236
+ }
237
+ const salt = randomBytes(NAME_SALT_BYTES);
238
+ const iv = randomBytes(IV_BYTES);
239
+ const key = await deriveNameKey(folderKey, salt, 'interactive');
240
+ const sealed = await aesGcmSeal(key, iv, TEXT_ENCODER.encode(name), TEXT_ENCODER.encode(rowId));
241
+ return {
242
+ v: 6,
243
+ ct: bytesToBase64(sealed.slice(0, sealed.length - TAG_BYTES)),
244
+ iv: bytesToBase64(iv),
245
+ tag: bytesToBase64(sealed.slice(sealed.length - TAG_BYTES)),
246
+ salt: bytesToBase64(salt),
247
+ kdf: 'interactive',
248
+ };
249
+ }
250
+ // ──────────────────────────────────────────────────────────────────────
251
+ // Agent grants
252
+ // ──────────────────────────────────────────────────────────────────────
253
+ export const GRANT_CONNECTION_PREFIX = 'sf-grant-v1:';
254
+ const GRANT_KINDS = new Set(['folder', 'file', 'file_pq', 'name']);
255
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
256
+ function assertUuid(value, what) {
257
+ if (typeof value !== 'string' || !UUID_RE.test(value)) {
258
+ throw new VaultCryptoError('invalid_input', `${what} must be a lowercase UUID`);
259
+ }
260
+ }
261
+ function toBase64Url(bytes) {
262
+ return bytesToBase64(bytes).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
263
+ }
264
+ function fromBase64Url(value) {
265
+ if (!/^[A-Za-z0-9_-]+$/.test(value)) {
266
+ throw new VaultCryptoError('invalid_connection_string', 'bad base64url');
267
+ }
268
+ if (value.length % 4 === 1) {
269
+ throw new VaultCryptoError('invalid_connection_string', 'bad base64url length');
270
+ }
271
+ const b64 = value.replace(/-/g, '+').replace(/_/g, '/');
272
+ try {
273
+ return base64ToBytes(b64 + '='.repeat((4 - (b64.length % 4)) % 4));
274
+ }
275
+ catch {
276
+ throw new VaultCryptoError('invalid_connection_string', 'bad base64url');
277
+ }
278
+ }
279
+ /** SHA-256 of an ML-KEM public key, hex. Pinned in the connection string. */
280
+ export function publicKeyFingerprint(mlKemPublicKey) {
281
+ return bytesToHex(sha256(mlKemPublicKey));
282
+ }
283
+ /** Fresh token + secret for a new grant. Call in the owner's unlocked client. */
284
+ export function createGrantCredential(options) {
285
+ assertUuid(options.grantId, 'grantId');
286
+ return {
287
+ grantId: options.grantId,
288
+ token: randomBytes(KEY_BYTES),
289
+ secret: randomBytes(KEY_BYTES),
290
+ publicKeyFingerprint: publicKeyFingerprint(options.mlKemPublicKey),
291
+ };
292
+ }
293
+ /** `sf-grant-v1:<grant_id>.<token>.<secret>.<pk_fingerprint>` (base64url, hex). */
294
+ export function formatConnectionString(c) {
295
+ assertUuid(c.grantId, 'grantId');
296
+ assertKey(c.token, 'token');
297
+ assertKey(c.secret, 'secret');
298
+ if (!/^[0-9a-f]{64}$/.test(c.publicKeyFingerprint)) {
299
+ throw new VaultCryptoError('invalid_input', 'fingerprint must be 64 hex chars');
300
+ }
301
+ return `${GRANT_CONNECTION_PREFIX}${c.grantId}.${toBase64Url(c.token)}.${toBase64Url(c.secret)}.${c.publicKeyFingerprint}`;
302
+ }
303
+ export function parseConnectionString(value) {
304
+ const bad = (why) => new VaultCryptoError('invalid_connection_string', why);
305
+ if (typeof value !== 'string')
306
+ throw bad('not a string');
307
+ const trimmed = value.trim();
308
+ if (!trimmed.startsWith(GRANT_CONNECTION_PREFIX))
309
+ throw bad('wrong prefix');
310
+ const parts = trimmed.slice(GRANT_CONNECTION_PREFIX.length).split('.');
311
+ if (parts.length !== 4)
312
+ throw bad('expected four parts');
313
+ const [grantId, tokenPart, secretPart, fingerprint] = parts;
314
+ if (!UUID_RE.test(grantId))
315
+ throw bad('bad grant id');
316
+ const token = fromBase64Url(tokenPart);
317
+ const secret = fromBase64Url(secretPart);
318
+ if (token.length !== KEY_BYTES || secret.length !== KEY_BYTES)
319
+ throw bad('bad key length');
320
+ if (!/^[0-9a-f]{64}$/.test(fingerprint))
321
+ throw bad('bad fingerprint');
322
+ return { grantId, token, secret, publicKeyFingerprint: fingerprint };
323
+ }
324
+ /** The bearer value a client sends. */
325
+ export function grantBearerToken(c) {
326
+ return toBase64Url(c.token);
327
+ }
328
+ /** What the server stores and looks up: SHA-256 of the bearer token's bytes, hex. */
329
+ export function hashGrantToken(bearer) {
330
+ const bytes = fromBase64Url(bearer);
331
+ if (bytes.length !== KEY_BYTES) {
332
+ throw new VaultCryptoError('invalid_input', 'bearer token has the wrong length');
333
+ }
334
+ return bytesToHex(sha256(bytes));
335
+ }
336
+ /** GK = HKDF-SHA-256(secret, salt = utf8(grant id), info = AGENT_GRANT_WRAP). */
337
+ export async function deriveGrantWrapKey(secret, grantId) {
338
+ assertKey(secret, 'secret');
339
+ assertUuid(grantId, 'grantId');
340
+ return hkdfSha256({
341
+ ikm: secret,
342
+ salt: TEXT_ENCODER.encode(grantId),
343
+ info: HKDF_INFO.AGENT_GRANT_WRAP,
344
+ length: KEY_BYTES,
345
+ });
346
+ }
347
+ function grantAad(grantId, kind, objectId) {
348
+ if (!GRANT_KINDS.has(kind)) {
349
+ throw new VaultCryptoError('invalid_input', 'unknown grant object kind');
350
+ }
351
+ assertUuid(grantId, 'grantId');
352
+ assertUuid(objectId, 'objectId');
353
+ return TEXT_ENCODER.encode(`sf-grant-v1|${grantId}|${kind}|${objectId}`);
354
+ }
355
+ /** Wrap a folder key or file content key for a grant, bound to (grant, kind, object). */
356
+ export async function wrapKeyForGrant(options) {
357
+ assertKey(options.grantWrapKey, 'grantWrapKey');
358
+ assertKey(options.key, 'key');
359
+ const aad = grantAad(options.grantId, options.kind, options.objectId);
360
+ const iv = randomBytes(IV_BYTES);
361
+ const ct = await aesGcmSeal(options.grantWrapKey, iv, options.key, aad);
362
+ return { wrapped: bytesToBase64(ct), iv: bytesToBase64(iv) };
363
+ }
364
+ export async function unwrapKeyForGrant(options) {
365
+ assertKey(options.grantWrapKey, 'grantWrapKey');
366
+ const aad = grantAad(options.grantId, options.kind, options.objectId);
367
+ const iv = base64ToBytes(options.wrapped.iv);
368
+ const ct = base64ToBytes(options.wrapped.wrapped);
369
+ if (iv.length !== IV_BYTES || ct.length !== KEY_BYTES + TAG_BYTES) {
370
+ throw new VaultCryptoError('unwrap_failed', 'grant wrap has the wrong shape');
371
+ }
372
+ const key = await aesGcmOpen(options.grantWrapKey, iv, ct, aad);
373
+ if (!key)
374
+ throw new VaultCryptoError('unwrap_failed', 'grant wrap did not open');
375
+ return key;
376
+ }
377
+ /** SHA-256 of a 32-byte key, hex. Reveals nothing usable about a random key. */
378
+ export function keyFingerprint(key) {
379
+ assertKey(key, 'key');
380
+ return bytesToHex(sha256(key));
381
+ }
382
+ /** A canonical, order-independent string for a scope. Any change to the scope changes it. */
383
+ export function canonicalGrantScope(scope) {
384
+ assertUuid(scope.grantId, 'grantId');
385
+ const ids = (list, what) => {
386
+ for (const id of list)
387
+ assertUuid(id, what);
388
+ return [...new Set(list)].sort().join(',');
389
+ };
390
+ if (scope.trashFolderId !== null)
391
+ assertUuid(scope.trashFolderId, 'trashFolderId');
392
+ return [
393
+ 'sf-grant-scope-v1',
394
+ scope.grantId,
395
+ `all=${scope.scopeAll ? 1 : 0}`,
396
+ `media=${scope.includeMedia ? 1 : 0}`,
397
+ `roots=${ids(scope.rootIds, 'rootIds')}`,
398
+ `trash=${scope.trashFolderId ?? '-'}`,
399
+ `excluded=${ids(scope.excludedIds, 'excludedIds')}`,
400
+ `excludedKeys=${[...new Set(scope.excludedKeyFingerprints)]
401
+ .map((f) => {
402
+ if (!/^[0-9a-f]{64}$/.test(f))
403
+ throw new VaultCryptoError('invalid_input', 'bad key fingerprint');
404
+ return f;
405
+ })
406
+ .sort()
407
+ .join(',')}`,
408
+ ].join('|');
409
+ }
410
+ async function grantSecretKey(rootKey, grantId) {
411
+ assertKey(rootKey, 'rootKey');
412
+ assertUuid(grantId, 'grantId');
413
+ return hkdfSha256({
414
+ ikm: rootKey,
415
+ salt: TEXT_ENCODER.encode(grantId),
416
+ info: HKDF_INFO.AGENT_GRANT_SECRET,
417
+ length: KEY_BYTES,
418
+ });
419
+ }
420
+ /**
421
+ * Wrap a grant secret for the owner: AES-256-GCM under HKDF(RK, grant id,
422
+ * AGENT_GRANT_SECRET), with the canonical scope as AAD. Only the owner's
423
+ * vault root key opens it, and only for exactly this scope.
424
+ */
425
+ export async function wrapGrantSecret(options) {
426
+ assertKey(options.secret, 'secret');
427
+ const key = await grantSecretKey(options.rootKey, options.scope.grantId);
428
+ const iv = randomBytes(IV_BYTES);
429
+ const ct = await aesGcmSeal(key, iv, options.secret, TEXT_ENCODER.encode(canonicalGrantScope(options.scope)));
430
+ return { wrapped: bytesToBase64(ct), iv: bytesToBase64(iv) };
431
+ }
432
+ /** Open the owner's copy of a grant secret. Fails if the scope differs in any way from the one it was wrapped for. */
433
+ export async function unwrapGrantSecret(options) {
434
+ const key = await grantSecretKey(options.rootKey, options.scope.grantId);
435
+ const iv = base64ToBytes(options.wrapped.iv);
436
+ const ct = base64ToBytes(options.wrapped.wrapped);
437
+ if (iv.length !== IV_BYTES || ct.length !== KEY_BYTES + TAG_BYTES) {
438
+ throw new VaultCryptoError('unwrap_failed', 'grant secret wrap has the wrong shape');
439
+ }
440
+ const secret = await aesGcmOpen(key, iv, ct, TEXT_ENCODER.encode(canonicalGrantScope(options.scope)));
441
+ if (!secret)
442
+ throw new VaultCryptoError('unwrap_failed', 'grant secret did not open for this scope');
443
+ return secret;
444
+ }
445
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/vault/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAA;AAE9C,OAAO,EACL,aAAa,EACb,aAAa,EACb,UAAU,EACV,WAAW,GACZ,MAAM,yBAAyB,CAAA;AAChC,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAA;AAChD,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAA;AAC/D,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAA;AACjD,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAA;A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,SAAS,GAAG,SAAS,EAAE,CAAC;QAClE,MAAM,IAAI,gBAAgB,CAAC,eAAe,EAAE,uCAAuC,CAAC,CAAA;IACtF,CAAC;IACD,MAAM,MAAM,GAAG,MAAM,UAAU,CAAC,GAAG,EAAE,EAAE,EAAE,EAAE,EAAE,YAAY,CAAC,MAAM,CAAC,mBAAmB,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAA;IACrG,IAAI,CAAC,MAAM;QAAE,MAAM,IAAI,gBAAgB,CAAC,eAAe,EAAE,0CAA0C,CAAC,CAAA;IACpG,OAAO,MAAM,CAAA;AACf,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shieldfive/crypto",
3
- "version": "1.0.0-rc.4",
3
+ "version": "1.0.0-rc.5",
4
4
  "description": "Client-side post-quantum hybrid encryption for cloud storage. The cryptographic core of ShieldFive.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -75,6 +75,10 @@
75
75
  "./format": {
76
76
  "types": "./dist/format/header.d.ts",
77
77
  "default": "./dist/format/header.js"
78
+ },
79
+ "./vault": {
80
+ "types": "./dist/vault/index.d.ts",
81
+ "default": "./dist/vault/index.js"
78
82
  }
79
83
  },
80
84
  "files": [
@@ -96,6 +100,7 @@
96
100
  "clean": "rm -rf dist",
97
101
  "lint": "eslint src tests",
98
102
  "pretest": "npm run build",
103
+ "version": "node scripts/sync-version.mjs && git add src/index.ts",
99
104
  "test": "node --experimental-vm-modules --test --import tsx tests/**/*.test.ts",
100
105
  "test:unit": "node --experimental-vm-modules --test --import tsx tests/unit/*.test.ts",
101
106
  "test:integration": "node --experimental-vm-modules --test --import tsx tests/integration/*.test.ts",
@@ -149,6 +149,8 @@ shieldfive/v1/inbound/x25519-static-seed
149
149
  shieldfive/v1/inbound/envelope-key
150
150
  shieldfive/v1/inbound/ed25519-signing-seed
151
151
  shieldfive/v1/argon2id/salt-compression
152
+ shieldfive/v1/agent-grant/wrap
153
+ shieldfive/v1/agent-grant/secret
152
154
  ```
153
155
 
154
156
  The three `shieldfive/v1/inbound/*` labels drive the zero-knowledge
@@ -0,0 +1,101 @@
1
+ # Vault key chain, name envelopes and agent grants
2
+
3
+ Implemented in `src/vault/index.ts` (`@shieldfive/crypto/vault`). The first
4
+ two formats already exist in the ShieldFive web app's database. This file
5
+ specifies them so that any client can interoperate. The third, agent grants,
6
+ is new.
7
+
8
+ ## 1. Key chain
9
+
10
+ Each folder has a 32-byte folder key (FK). A top-level folder's FK is
11
+ wrapped under the vault root key (RK). Every other FK is wrapped under its
12
+ parent's FK. A file's content key is wrapped under the key of the folder that
13
+ contains it, or under RK for a file at the vault root.
14
+
15
+ ```
16
+ wrapped = AES-256-GCM(key = parent key, iv = 12 random bytes, aad = none, pt = child key)
17
+ stored = base64(ciphertext || 16-byte tag), base64(iv)
18
+ ```
19
+
20
+ Columns: `folders.fk_wrapped/fk_iv`, `files.csk_wrapped/csk_iv`,
21
+ `files.pqk_fk_wrapped/pqk_fk_iv`.
22
+
23
+ For suite 0x03 (PQ-hybrid) files, `csk_wrapped` holds only the classical
24
+ envelope key. The key that decrypts the file is the combined key, which also
25
+ needs the owner's ML-KEM secret key. `pqk_fk_wrapped` is the combined key
26
+ wrapped under the parent FK. The owner's client writes it only when a share
27
+ or grant needs it.
28
+
29
+ ## 2. Name envelopes
30
+
31
+ ```json
32
+ {"v": 4 | 6, "ct": b64, "iv": b64(12), "tag": b64(16), "salt": b64(16), "kdf": "interactive" | "moderate"}
33
+ ```
34
+
35
+ ```
36
+ name key = Argon2id13(password = UTF-8 of base64(parent key), salt,
37
+ interactive: ops=2 mem=64 MiB | moderate: ops=3 mem=256 MiB, 32 bytes)
38
+ v4: AES-256-GCM(name key, iv, aad = none, pt = UTF-8 name)
39
+ v6: AES-256-GCM(name key, iv, aad = UTF-8 of row UUID, pt = UTF-8 name)
40
+ ```
41
+
42
+ If `kdf` is missing, a reader tries interactive first and then moderate.
43
+ Writers always emit v6 with `kdf: "interactive"`. The password already
44
+ carries 256 bits of entropy, so the cost level only exists for compatibility.
45
+
46
+ v3 (fragment-keyed) and the server-keyed `v2|…` shape are outside this
47
+ module.
48
+
49
+ ## 3. Agent grants
50
+
51
+ A grant lets a local agent open a subtree of the vault without the root key.
52
+
53
+ ```
54
+ connection string = "sf-grant-v1:" grant_id "." b64url(token) "." b64url(secret) "." hex(sha256(ml_kem_pk))
55
+ token = 32 random bytes. It is the bearer credential, and the server stores hex(sha256(token)).
56
+ secret = 32 random bytes. It never leaves a client.
57
+ GK = HKDF-SHA-256(ikm = secret, salt = UTF-8(grant_id), info = "shieldfive/v1/agent-grant/wrap", L = 32)
58
+ wrap = AES-256-GCM(GK, iv = 12 random bytes,
59
+ aad = UTF-8("sf-grant-v1|" grant_id "|" kind "|" object_id), pt = key)
60
+ kind = "folder" a folder key
61
+ | "file" the key csk_wrapped holds (the classical envelope key for suite 0x03)
62
+ | "file_pq" the combined content key of a suite-0x03 file
63
+ | "name" the derived key of ONE name envelope
64
+ ```
65
+
66
+ `file`, `file_pq` and `name` are issued only for objects whose parent key
67
+ the grant does not hold: the scope roots' own names, and files at the vault
68
+ root when the grant covers the whole vault. A `name` wrap opens one envelope.
69
+ It is useless for writing a new name under the same parent.
70
+
71
+ The AAD stops a server from presenting one object's wrap as another's. The
72
+ public-key fingerprint lets a grant that writes files detect a substituted
73
+ ML-KEM public key.
74
+
75
+ The owner keeps a copy of the secret so their browser can extend the grant
76
+ later (new top-level folders, renamed roots, post-quantum aux wraps):
77
+
78
+ ```
79
+ scope = "sf-grant-scope-v1|" grant_id "|all=" 0|1 "|media=" 0|1 "|roots=" sorted,unique ids
80
+ "|trash=" id or "-" "|excluded=" sorted,unique ids
81
+ "|excludedKeys=" sorted,unique hex(sha256(key)) of the excluded folders' keys
82
+ SK = HKDF-SHA-256(ikm = RK, salt = UTF-8(grant_id), info = "shieldfive/v1/agent-grant/secret", L = 32)
83
+ owner = AES-256-GCM(SK, iv = 12 random bytes, aad = UTF-8(scope), pt = secret)
84
+ ```
85
+
86
+ The scope is authenticated rather than trusted. A server that edits a grant's
87
+ scope makes the owner's copy stop opening, so the owner's browser never
88
+ extends a grant beyond what the owner chose. The separate label means no
89
+ other key wrapped under RK can stand in for the secret.
90
+
91
+ Security properties and limits:
92
+
93
+ - Leaking the secret without the token gives nothing. The server returns no
94
+ wraps without the token.
95
+ - Leaking both gives the grant's subtree only. It never gives RK, the master
96
+ secret or the ML-KEM secret key.
97
+ - Revocation is enforced by the server. It does not re-key, so wraps and
98
+ ciphertext fetched before revocation stay decryptable by whoever holds
99
+ the secret.
100
+
101
+ Vectors: `tests/vectors/vault-vectors.json`.
package/src/index.ts CHANGED
@@ -99,6 +99,7 @@ export * as kdfArgon2id from './kdf/argon2id.js'
99
99
  export * as identity from './identity/index.js'
100
100
  export * as inbound from './identity/inbound.js'
101
101
  export * as migrationV0 from './migration/v0-bridge.js'
102
+ export * as vault from './vault/index.js'
102
103
 
103
104
  // ──────────────────────────────────────────────────────────────────────
104
105
  // Auto-routing decryptor
@@ -219,7 +220,7 @@ export async function autoDecryptBlob(
219
220
  }
220
221
 
221
222
  /** Library version, also written into format documentation. */
222
- export const SHIELDFIVE_CRYPTO_VERSION = '1.0.0-rc.4'
223
+ export const SHIELDFIVE_CRYPTO_VERSION = '1.0.0-rc.5'
223
224
 
224
225
  /** Default cipher suite for new files when not specified by the caller. */
225
226
  export const DEFAULT_SUITE = SUITE.PQ_HYBRID_XCHACHA_MLKEM1024_V1
@@ -106,6 +106,15 @@ export const HKDF_INFO = Object.freeze({
106
106
  // published (ml_kem || x25519) bundle so a guest can detect a key swap.
107
107
  INBOUND_SIGNING_SEED: 'shieldfive/v1/inbound/ed25519-signing-seed',
108
108
  ARGON2ID_SALT_COMPRESSION: 'shieldfive/v1/argon2id/salt-compression',
109
+ // Agent grants (src/vault): the grant secret, generated in the owner's client
110
+ // and never sent to the server, is expanded into the key that wraps the
111
+ // grant's scope-root folder keys. Salt = the grant id.
112
+ AGENT_GRANT_WRAP: 'shieldfive/v1/agent-grant/wrap',
113
+ // The owner's copy of a grant secret is wrapped under a key derived from the
114
+ // vault root key with this label, authenticated against the grant's scope,
115
+ // so no other key wrapped under RK can stand in for it and a server that
116
+ // edits the grant's scope makes the secret stop opening.
117
+ AGENT_GRANT_SECRET: 'shieldfive/v1/agent-grant/secret',
109
118
  })
110
119
 
111
120
  /** AAD domain string mixed into every chunk's authenticator */