@geslar/cli 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,3103 @@
1
+ #!/usr/bin/env -S node --
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __commonJS = (cb, mod) => function __require() {
9
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+
28
+ // ../../packages/core/src/crypto/vault-crypto.js
29
+ var require_vault_crypto = __commonJS({
30
+ "../../packages/core/src/crypto/vault-crypto.js"(exports, module) {
31
+ "use strict";
32
+ var VaultCrypto3 = (() => {
33
+ "use strict";
34
+ const PBKDF2_ITERATIONS = 6e5;
35
+ const SALT_BYTES = 32;
36
+ const IV_BYTES = 12;
37
+ const KEY_BITS = 256;
38
+ function generateSalt() {
39
+ return crypto.getRandomValues(new Uint8Array(SALT_BYTES));
40
+ }
41
+ function generateIV() {
42
+ return crypto.getRandomValues(new Uint8Array(IV_BYTES));
43
+ }
44
+ async function deriveMasterKey(password, salt) {
45
+ const encoder = new TextEncoder();
46
+ const keyMaterial = await crypto.subtle.importKey(
47
+ "raw",
48
+ encoder.encode(password),
49
+ "PBKDF2",
50
+ false,
51
+ ["deriveKey"]
52
+ );
53
+ return crypto.subtle.deriveKey(
54
+ { name: "PBKDF2", salt, iterations: PBKDF2_ITERATIONS, hash: "SHA-256" },
55
+ keyMaterial,
56
+ { name: "AES-GCM", length: KEY_BITS },
57
+ true,
58
+ // extractable — needed to export/import via session storage
59
+ ["encrypt", "decrypt"]
60
+ );
61
+ }
62
+ async function deriveVerificationHash(password, salt) {
63
+ const encoder = new TextEncoder();
64
+ const keyMaterial = await crypto.subtle.importKey(
65
+ "raw",
66
+ encoder.encode(password),
67
+ "PBKDF2",
68
+ false,
69
+ ["deriveBits"]
70
+ );
71
+ const bits = await crypto.subtle.deriveBits(
72
+ { name: "PBKDF2", salt, iterations: PBKDF2_ITERATIONS, hash: "SHA-256" },
73
+ keyMaterial,
74
+ 256
75
+ );
76
+ return bufToBase64(new Uint8Array(bits));
77
+ }
78
+ async function encrypt(plaintext, key) {
79
+ const encoder = new TextEncoder();
80
+ const iv = generateIV();
81
+ const encrypted = await crypto.subtle.encrypt(
82
+ { name: "AES-GCM", iv },
83
+ key,
84
+ encoder.encode(plaintext)
85
+ );
86
+ return {
87
+ ciphertext: bufToBase64(new Uint8Array(encrypted)),
88
+ iv: bufToBase64(iv)
89
+ };
90
+ }
91
+ async function decrypt(ciphertext, iv, key) {
92
+ const decrypted = await crypto.subtle.decrypt(
93
+ { name: "AES-GCM", iv: base64ToBuf(iv) },
94
+ key,
95
+ base64ToBuf(ciphertext)
96
+ );
97
+ return new TextDecoder().decode(decrypted);
98
+ }
99
+ async function exportKey(key) {
100
+ const raw = await crypto.subtle.exportKey("raw", key);
101
+ return bufToBase64(new Uint8Array(raw));
102
+ }
103
+ async function importKey(b64) {
104
+ const raw = base64ToBuf(b64);
105
+ return crypto.subtle.importKey(
106
+ "raw",
107
+ raw,
108
+ { name: "AES-GCM", length: KEY_BITS },
109
+ true,
110
+ ["encrypt", "decrypt"]
111
+ );
112
+ }
113
+ function bufToBase64(buf) {
114
+ let binary = "";
115
+ for (let i = 0; i < buf.length; i++) binary += String.fromCharCode(buf[i]);
116
+ return btoa(binary);
117
+ }
118
+ function base64ToBuf(b64) {
119
+ const binary = atob(b64);
120
+ const buf = new Uint8Array(binary.length);
121
+ for (let i = 0; i < binary.length; i++) buf[i] = binary.charCodeAt(i);
122
+ return buf;
123
+ }
124
+ function generateId() {
125
+ return crypto.randomUUID ? crypto.randomUUID() : ("10000000-1000-4000-8000" + -1e11).replace(/[018]/g, (c) => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16));
126
+ }
127
+ return {
128
+ generateSalt,
129
+ generateIV,
130
+ deriveMasterKey,
131
+ deriveVerificationHash,
132
+ encrypt,
133
+ decrypt,
134
+ exportKey,
135
+ importKey,
136
+ bufToBase64,
137
+ base64ToBuf,
138
+ generateId,
139
+ PBKDF2_ITERATIONS
140
+ };
141
+ })();
142
+ if (typeof module !== "undefined") module.exports = VaultCrypto3;
143
+ }
144
+ });
145
+
146
+ // ../../packages/core/src/crypto/vault-cloud-crypto.js
147
+ var require_vault_cloud_crypto = __commonJS({
148
+ "../../packages/core/src/crypto/vault-cloud-crypto.js"(exports, module) {
149
+ "use strict";
150
+ var VaultCloudCrypto2 = (() => {
151
+ "use strict";
152
+ const AUTH_HASH_ITERATIONS = 1;
153
+ const VAULT_KEY_BYTES = 32;
154
+ const RECOVERY_KEY_BYTES = 32;
155
+ const ECDH_PRIVATE_BYTES = 32;
156
+ const IV_BYTES = 12;
157
+ const HKDF_SALT2 = new TextEncoder().encode("geslar-ecdh-hkdf-salt-v1");
158
+ const HKDF_INFO2 = new TextEncoder().encode("geslar-shared-vault-wrap-v1");
159
+ const RECOVERY_V2_MAGIC = Uint8Array.from([71, 82, 2]);
160
+ const FP_CONS_INITIAL = ["b", "d", "f", "g", "k", "l", "m", "n", "p", "r", "s", "t", "v", "z", "h", "j"];
161
+ const FP_VOWELS = ["a", "e", "i", "o"];
162
+ const FP_CONS_FINAL = ["k", "n", "s", "t"];
163
+ const FP_WORD_COUNT = 6;
164
+ async function deriveAuthHash(masterKey, password) {
165
+ const masterKeyRaw = await crypto.subtle.exportKey("raw", masterKey);
166
+ const keyMaterial = await crypto.subtle.importKey(
167
+ "raw",
168
+ masterKeyRaw,
169
+ "PBKDF2",
170
+ false,
171
+ ["deriveBits"]
172
+ );
173
+ const encoder = new TextEncoder();
174
+ const authHashBits = await crypto.subtle.deriveBits(
175
+ {
176
+ name: "PBKDF2",
177
+ salt: encoder.encode(password),
178
+ iterations: AUTH_HASH_ITERATIONS,
179
+ hash: "SHA-256"
180
+ },
181
+ keyMaterial,
182
+ 256
183
+ );
184
+ return VaultCrypto.bufToBase64(new Uint8Array(authHashBits));
185
+ }
186
+ function generateVaultKey() {
187
+ return crypto.getRandomValues(new Uint8Array(VAULT_KEY_BYTES));
188
+ }
189
+ async function wrapVaultKey(masterKey, vaultKey) {
190
+ const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
191
+ const encrypted = await crypto.subtle.encrypt(
192
+ { name: "AES-GCM", iv },
193
+ masterKey,
194
+ vaultKey
195
+ );
196
+ const packed = new Uint8Array(iv.length + encrypted.byteLength);
197
+ packed.set(iv, 0);
198
+ packed.set(new Uint8Array(encrypted), iv.length);
199
+ return VaultCrypto.bufToBase64(packed);
200
+ }
201
+ async function unwrapVaultKey(masterKey, wrappedBase64) {
202
+ const packed = VaultCrypto.base64ToBuf(wrappedBase64);
203
+ const iv = packed.slice(0, IV_BYTES);
204
+ const ciphertext = packed.slice(IV_BYTES);
205
+ const decrypted = await crypto.subtle.decrypt(
206
+ { name: "AES-GCM", iv },
207
+ masterKey,
208
+ ciphertext
209
+ );
210
+ return new Uint8Array(decrypted);
211
+ }
212
+ async function importVaultKey(vaultKeyRaw) {
213
+ return crypto.subtle.importKey(
214
+ "raw",
215
+ vaultKeyRaw,
216
+ { name: "AES-GCM", length: 256 },
217
+ false,
218
+ ["encrypt", "decrypt"]
219
+ );
220
+ }
221
+ async function encryptEntry(vaultKey, entry) {
222
+ const encoder = new TextEncoder();
223
+ const plaintext = encoder.encode(JSON.stringify(entry));
224
+ const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
225
+ const encrypted = await crypto.subtle.encrypt(
226
+ { name: "AES-GCM", iv },
227
+ vaultKey,
228
+ plaintext
229
+ );
230
+ const packed = new Uint8Array(iv.length + encrypted.byteLength);
231
+ packed.set(iv, 0);
232
+ packed.set(new Uint8Array(encrypted), iv.length);
233
+ const blob = VaultCrypto.bufToBase64(packed);
234
+ const hashBuffer = await crypto.subtle.digest("SHA-256", packed);
235
+ const hashArray = new Uint8Array(hashBuffer);
236
+ const blobHash = Array.from(hashArray).map((b) => b.toString(16).padStart(2, "0")).join("");
237
+ return { encrypted_blob: blob, blob_hash: blobHash };
238
+ }
239
+ async function decryptEntry(vaultKey, encryptedBlob) {
240
+ const packed = VaultCrypto.base64ToBuf(encryptedBlob);
241
+ const iv = packed.slice(0, IV_BYTES);
242
+ const ciphertext = packed.slice(IV_BYTES);
243
+ const decrypted = await crypto.subtle.decrypt(
244
+ { name: "AES-GCM", iv },
245
+ vaultKey,
246
+ ciphertext
247
+ );
248
+ return JSON.parse(new TextDecoder().decode(decrypted));
249
+ }
250
+ function generateRecoveryKey() {
251
+ return crypto.getRandomValues(new Uint8Array(RECOVERY_KEY_BYTES));
252
+ }
253
+ function isRecoveryV2(payload) {
254
+ return payload.length > RECOVERY_V2_MAGIC.length + VAULT_KEY_BYTES && payload[0] === RECOVERY_V2_MAGIC[0] && payload[1] === RECOVERY_V2_MAGIC[1] && payload[2] === RECOVERY_V2_MAGIC[2];
255
+ }
256
+ async function wrapVaultKeyWithRecovery(recoveryKey, vaultKey, ecdhPrivateKey) {
257
+ const key = await crypto.subtle.importKey(
258
+ "raw",
259
+ recoveryKey,
260
+ { name: "AES-GCM", length: 256 },
261
+ false,
262
+ ["encrypt"]
263
+ );
264
+ let payload;
265
+ if (ecdhPrivateKey) {
266
+ payload = new Uint8Array(RECOVERY_V2_MAGIC.length + vaultKey.length + ecdhPrivateKey.length);
267
+ payload.set(RECOVERY_V2_MAGIC, 0);
268
+ payload.set(vaultKey, RECOVERY_V2_MAGIC.length);
269
+ payload.set(ecdhPrivateKey, RECOVERY_V2_MAGIC.length + vaultKey.length);
270
+ } else {
271
+ payload = vaultKey;
272
+ }
273
+ const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
274
+ const encrypted = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, payload);
275
+ const packed = new Uint8Array(iv.length + encrypted.byteLength);
276
+ packed.set(iv, 0);
277
+ packed.set(new Uint8Array(encrypted), iv.length);
278
+ return VaultCrypto.bufToBase64(packed);
279
+ }
280
+ async function unwrapRecoveryBlob(recoveryKey, recoveryBlob) {
281
+ const key = await crypto.subtle.importKey(
282
+ "raw",
283
+ recoveryKey,
284
+ { name: "AES-GCM", length: 256 },
285
+ false,
286
+ ["decrypt"]
287
+ );
288
+ const packed = VaultCrypto.base64ToBuf(recoveryBlob);
289
+ const iv = packed.slice(0, IV_BYTES);
290
+ const ciphertext = packed.slice(IV_BYTES);
291
+ const decrypted = new Uint8Array(
292
+ await crypto.subtle.decrypt({ name: "AES-GCM", iv }, key, ciphertext)
293
+ );
294
+ if (isRecoveryV2(decrypted)) {
295
+ const off = RECOVERY_V2_MAGIC.length;
296
+ return {
297
+ vaultKey: decrypted.slice(off, off + VAULT_KEY_BYTES),
298
+ ecdhPrivateKey: decrypted.slice(off + VAULT_KEY_BYTES),
299
+ version: 2
300
+ };
301
+ }
302
+ return { vaultKey: decrypted, ecdhPrivateKey: null, version: 1 };
303
+ }
304
+ async function unwrapVaultKeyWithRecovery(recoveryKey, recoveryBlob) {
305
+ const { vaultKey } = await unwrapRecoveryBlob(recoveryKey, recoveryBlob);
306
+ return vaultKey;
307
+ }
308
+ async function generateEcdhKeyPair() {
309
+ const pair = await crypto.subtle.generateKey({ name: "X25519" }, true, ["deriveBits"]);
310
+ const publicKey = new Uint8Array(await crypto.subtle.exportKey("raw", pair.publicKey));
311
+ const privateKey = new Uint8Array(await crypto.subtle.exportKey("pkcs8", pair.privateKey));
312
+ return { privateKey, publicKey };
313
+ }
314
+ function importEcdhPrivateKey(privatePkcs8) {
315
+ return crypto.subtle.importKey("pkcs8", privatePkcs8, { name: "X25519" }, false, ["deriveBits"]);
316
+ }
317
+ function importEcdhPublicKey(publicRaw) {
318
+ return crypto.subtle.importKey("raw", publicRaw, { name: "X25519" }, false, []);
319
+ }
320
+ async function ecdhPublicFromPrivate(privatePkcs8) {
321
+ const key = await crypto.subtle.importKey("pkcs8", privatePkcs8, { name: "X25519" }, true, ["deriveBits"]);
322
+ const jwk = await crypto.subtle.exportKey("jwk", key);
323
+ const b64 = jwk.x.replace(/-/g, "+").replace(/_/g, "/");
324
+ const padded = b64 + "=".repeat((4 - b64.length % 4) % 4);
325
+ return VaultCrypto.base64ToBuf(padded);
326
+ }
327
+ async function deriveSharedWrapKey(myPrivatePkcs8, peerPublicRaw) {
328
+ const privKey = await importEcdhPrivateKey(myPrivatePkcs8);
329
+ const pubKey = await importEcdhPublicKey(peerPublicRaw);
330
+ const sharedSecret = await crypto.subtle.deriveBits(
331
+ { name: "X25519", public: pubKey },
332
+ privKey,
333
+ 256
334
+ );
335
+ const ikm = await crypto.subtle.importKey("raw", sharedSecret, "HKDF", false, ["deriveBits"]);
336
+ const okm = await crypto.subtle.deriveBits(
337
+ { name: "HKDF", hash: "SHA-256", salt: HKDF_SALT2, info: HKDF_INFO2 },
338
+ ikm,
339
+ 256
340
+ );
341
+ return crypto.subtle.importKey("raw", okm, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
342
+ }
343
+ async function wrapVaultKeyForMember(myPrivatePkcs8, recipientPublicRaw, sharedDEK) {
344
+ const wrapKey = await deriveSharedWrapKey(myPrivatePkcs8, recipientPublicRaw);
345
+ const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
346
+ const encrypted = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, wrapKey, sharedDEK);
347
+ const packed = new Uint8Array(iv.length + encrypted.byteLength);
348
+ packed.set(iv, 0);
349
+ packed.set(new Uint8Array(encrypted), iv.length);
350
+ return VaultCrypto.bufToBase64(packed);
351
+ }
352
+ async function unwrapSharedVaultKey(myPrivatePkcs8, senderPublicRaw, wrappedBase64) {
353
+ const wrapKey = await deriveSharedWrapKey(myPrivatePkcs8, senderPublicRaw);
354
+ const packed = VaultCrypto.base64ToBuf(wrappedBase64);
355
+ const iv = packed.slice(0, IV_BYTES);
356
+ const ciphertext = packed.slice(IV_BYTES);
357
+ const decrypted = await crypto.subtle.decrypt({ name: "AES-GCM", iv }, wrapKey, ciphertext);
358
+ return new Uint8Array(decrypted);
359
+ }
360
+ function fpSyllable(byte) {
361
+ const c1 = FP_CONS_INITIAL[byte >> 4 & 15];
362
+ const v = FP_VOWELS[byte >> 2 & 3];
363
+ const c2 = FP_CONS_FINAL[byte & 3];
364
+ return c1 + v + c2;
365
+ }
366
+ async function deriveFingerprintPhrase(publicKey) {
367
+ const raw = typeof publicKey === "string" ? VaultCrypto.base64ToBuf(publicKey) : publicKey;
368
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", raw));
369
+ const words = [];
370
+ for (let i = 0; i < FP_WORD_COUNT; i++) words.push(fpSyllable(digest[i]));
371
+ return words.join("-");
372
+ }
373
+ async function wrapEcdhPrivateKey(masterKey, privateKey) {
374
+ const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
375
+ const encrypted = await crypto.subtle.encrypt(
376
+ { name: "AES-GCM", iv },
377
+ masterKey,
378
+ privateKey
379
+ );
380
+ const packed = new Uint8Array(iv.length + encrypted.byteLength);
381
+ packed.set(iv, 0);
382
+ packed.set(new Uint8Array(encrypted), iv.length);
383
+ return VaultCrypto.bufToBase64(packed);
384
+ }
385
+ async function prepareRegistration(password, encSalt) {
386
+ const masterKey = await VaultCrypto.deriveMasterKey(password, encSalt);
387
+ const authHash = await deriveAuthHash(masterKey, password);
388
+ const vaultKey = generateVaultKey();
389
+ const recoveryKey = generateRecoveryKey();
390
+ const encryptedVaultKey = await wrapVaultKey(masterKey, vaultKey);
391
+ const ecdh = await generateEcdhKeyPair();
392
+ const encryptedEcdhPrivate = await wrapEcdhPrivateKey(masterKey, ecdh.privateKey);
393
+ const encryptedRecoveryBlob = await wrapVaultKeyWithRecovery(recoveryKey, vaultKey, ecdh.privateKey);
394
+ return {
395
+ auth_hash: authHash,
396
+ enc_salt: VaultCrypto.bufToBase64(encSalt),
397
+ encrypted_vault_key: encryptedVaultKey,
398
+ encrypted_recovery_blob: encryptedRecoveryBlob,
399
+ encrypted_ecdh_private_key: encryptedEcdhPrivate,
400
+ ecdh_public_key: VaultCrypto.bufToBase64(ecdh.publicKey),
401
+ ecdh_key_version: 1,
402
+ // real X25519 from the start
403
+ recovery_key: recoveryKey,
404
+ // Show to user ONCE as BIP39 mnemonic
405
+ vault_key: vaultKey
406
+ // Keep in memory for immediate sync
407
+ };
408
+ }
409
+ async function prepareEcdhMigration(masterKey) {
410
+ const ecdh = await generateEcdhKeyPair();
411
+ const encryptedEcdhPrivate = await wrapEcdhPrivateKey(masterKey, ecdh.privateKey);
412
+ return {
413
+ encrypted_ecdh_private_key: encryptedEcdhPrivate,
414
+ ecdh_public_key: VaultCrypto.bufToBase64(ecdh.publicKey)
415
+ };
416
+ }
417
+ async function prepareLogin(password, encSaltBase64) {
418
+ const encSalt = VaultCrypto.base64ToBuf(encSaltBase64);
419
+ const masterKey = await VaultCrypto.deriveMasterKey(password, encSalt);
420
+ const authHash = await deriveAuthHash(masterKey, password);
421
+ return { auth_hash: authHash, masterKey };
422
+ }
423
+ async function unlockVaultKey(masterKey, encryptedVaultKey) {
424
+ return unwrapVaultKey(masterKey, encryptedVaultKey);
425
+ }
426
+ async function prepareRecovery(recoveryKeyB64, recoveryBlobB64, newPassword) {
427
+ const recoveryKey = VaultCrypto.base64ToBuf(recoveryKeyB64);
428
+ const { vaultKey, ecdhPrivateKey } = await unwrapRecoveryBlob(recoveryKey, recoveryBlobB64);
429
+ const newEncSalt = VaultCrypto.generateSalt();
430
+ const newMasterKey = await VaultCrypto.deriveMasterKey(newPassword, newEncSalt);
431
+ const newAuthHash = await deriveAuthHash(newMasterKey, newPassword);
432
+ const newEncryptedVaultKey = await wrapVaultKey(newMasterKey, vaultKey);
433
+ let ecdhPriv = ecdhPrivateKey;
434
+ const preservedKeypair = !!ecdhPrivateKey;
435
+ if (!ecdhPriv) {
436
+ ecdhPriv = (await generateEcdhKeyPair()).privateKey;
437
+ }
438
+ const ecdhPublicRaw = await ecdhPublicFromPrivate(ecdhPriv);
439
+ const newEncryptedEcdhPrivate = await wrapEcdhPrivateKey(newMasterKey, ecdhPriv);
440
+ const newRecoveryKey = generateRecoveryKey();
441
+ const newEncryptedRecoveryBlob = await wrapVaultKeyWithRecovery(newRecoveryKey, vaultKey, ecdhPriv);
442
+ return {
443
+ new_auth_hash: newAuthHash,
444
+ new_enc_salt: VaultCrypto.bufToBase64(newEncSalt),
445
+ new_encrypted_vault_key: newEncryptedVaultKey,
446
+ new_encrypted_recovery_blob: newEncryptedRecoveryBlob,
447
+ new_encrypted_ecdh_private_key: newEncryptedEcdhPrivate,
448
+ new_ecdh_public_key: VaultCrypto.bufToBase64(ecdhPublicRaw),
449
+ ecdh_keypair_preserved: preservedKeypair,
450
+ new_recovery_key_b64: VaultCrypto.bufToBase64(newRecoveryKey),
451
+ vault_key: vaultKey
452
+ };
453
+ }
454
+ return {
455
+ // Auth hash
456
+ deriveAuthHash,
457
+ // Vault key (DEK)
458
+ generateVaultKey,
459
+ wrapVaultKey,
460
+ unwrapVaultKey,
461
+ importVaultKey,
462
+ // Per-entry encrypt/decrypt
463
+ encryptEntry,
464
+ decryptEntry,
465
+ // Recovery
466
+ generateRecoveryKey,
467
+ wrapVaultKeyWithRecovery,
468
+ unwrapVaultKeyWithRecovery,
469
+ unwrapRecoveryBlob,
470
+ // ECDH key pair
471
+ generateEcdhKeyPair,
472
+ wrapEcdhPrivateKey,
473
+ importEcdhPrivateKey,
474
+ importEcdhPublicKey,
475
+ ecdhPublicFromPrivate,
476
+ // Shared-vault key exchange (T10)
477
+ deriveSharedWrapKey,
478
+ wrapVaultKeyForMember,
479
+ unwrapSharedVaultKey,
480
+ deriveFingerprintPhrase,
481
+ // ECDH migration
482
+ prepareEcdhMigration,
483
+ // Orchestrators
484
+ prepareRegistration,
485
+ prepareLogin,
486
+ unlockVaultKey,
487
+ prepareRecovery
488
+ };
489
+ })();
490
+ if (typeof module !== "undefined") module.exports = VaultCloudCrypto2;
491
+ }
492
+ });
493
+
494
+ // ../../packages/core/src/crypto/recovery-enrollment.js
495
+ var require_recovery_enrollment = __commonJS({
496
+ "../../packages/core/src/crypto/recovery-enrollment.js"(exports, module) {
497
+ "use strict";
498
+ var OrgRecoveryCrypto2 = (() => {
499
+ "use strict";
500
+ const EPHEMERAL_PUB_BYTES = 32;
501
+ const IV_BYTES = 12;
502
+ const HKDF_SALT2 = new TextEncoder().encode("geslar-recovery-seal-salt-v1");
503
+ const HKDF_INFO2 = new TextEncoder().encode("geslar-org-recovery-seal-v1");
504
+ const FP_CONS_INITIAL = ["b", "d", "f", "g", "k", "l", "m", "n", "p", "r", "s", "t", "v", "z", "h", "j"];
505
+ const FP_VOWELS = ["a", "e", "i", "o"];
506
+ const FP_CONS_FINAL = ["k", "n", "s", "t"];
507
+ const FP_WORD_COUNT = 6;
508
+ function fpSyllable(byte) {
509
+ return FP_CONS_INITIAL[byte >> 4 & 15] + FP_VOWELS[byte >> 2 & 3] + FP_CONS_FINAL[byte & 3];
510
+ }
511
+ async function fingerprintFromPub(publicRaw) {
512
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", publicRaw));
513
+ const words = [];
514
+ for (let i = 0; i < FP_WORD_COUNT; i++) words.push(fpSyllable(digest[i]));
515
+ return words.join("-");
516
+ }
517
+ async function deriveWrapKey(sharedSecret, aad) {
518
+ const combinedInfo = new Uint8Array([...HKDF_INFO2, 0, ...aad]);
519
+ const ikm = await crypto.subtle.importKey("raw", sharedSecret, "HKDF", false, ["deriveBits"]);
520
+ const okm = await crypto.subtle.deriveBits(
521
+ { name: "HKDF", hash: "SHA-256", salt: HKDF_SALT2, info: combinedInfo },
522
+ ikm,
523
+ 256
524
+ );
525
+ return crypto.subtle.importKey("raw", okm, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
526
+ }
527
+ function isAllZero(buf) {
528
+ return new Uint8Array(buf).every((b) => b === 0);
529
+ }
530
+ function buildRecoveryAAD(orgId, memberUserId, keyVersion) {
531
+ return new TextEncoder().encode(`${orgId}:${memberUserId}:${keyVersion}`);
532
+ }
533
+ async function verifyOrgRecoveryKeyFingerprint(orgRecoveryPubRaw, expectedFingerprint) {
534
+ const computed = await fingerprintFromPub(orgRecoveryPubRaw);
535
+ return computed === expectedFingerprint;
536
+ }
537
+ async function sealRecoveryPayload(orgRecoveryPubRaw, payload, aad) {
538
+ const ephemeralPair = await crypto.subtle.generateKey({ name: "X25519" }, true, ["deriveBits"]);
539
+ const ephemeralPubRaw = new Uint8Array(
540
+ await crypto.subtle.exportKey("raw", ephemeralPair.publicKey)
541
+ );
542
+ const orgPubKey = await crypto.subtle.importKey(
543
+ "raw",
544
+ orgRecoveryPubRaw,
545
+ { name: "X25519" },
546
+ false,
547
+ []
548
+ );
549
+ const sharedSecret = await crypto.subtle.deriveBits(
550
+ { name: "X25519", public: orgPubKey },
551
+ ephemeralPair.privateKey,
552
+ 256
553
+ );
554
+ if (isAllZero(sharedSecret)) throw new Error("Low-order point: shared secret is all-zero");
555
+ const wrapKey = await deriveWrapKey(sharedSecret, aad);
556
+ const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
557
+ const ciphertext = await crypto.subtle.encrypt(
558
+ { name: "AES-GCM", iv, additionalData: aad },
559
+ wrapKey,
560
+ payload
561
+ );
562
+ const blob = new Uint8Array(EPHEMERAL_PUB_BYTES + IV_BYTES + ciphertext.byteLength);
563
+ blob.set(ephemeralPubRaw, 0);
564
+ blob.set(iv, EPHEMERAL_PUB_BYTES);
565
+ blob.set(new Uint8Array(ciphertext), EPHEMERAL_PUB_BYTES + IV_BYTES);
566
+ return blob;
567
+ }
568
+ async function openRecoveryPayload(orgRecoveryPrivPkcs8, sealedBlob, aad) {
569
+ if (sealedBlob.length <= EPHEMERAL_PUB_BYTES + IV_BYTES) {
570
+ throw new Error("Sealed blob is too short");
571
+ }
572
+ const ephemeralPubRaw = sealedBlob.slice(0, EPHEMERAL_PUB_BYTES);
573
+ const iv = sealedBlob.slice(EPHEMERAL_PUB_BYTES, EPHEMERAL_PUB_BYTES + IV_BYTES);
574
+ const ciphertext = sealedBlob.slice(EPHEMERAL_PUB_BYTES + IV_BYTES);
575
+ const orgPrivKey = await crypto.subtle.importKey(
576
+ "pkcs8",
577
+ orgRecoveryPrivPkcs8,
578
+ { name: "X25519" },
579
+ false,
580
+ ["deriveBits"]
581
+ );
582
+ const ephemeralPubKey = await crypto.subtle.importKey(
583
+ "raw",
584
+ ephemeralPubRaw,
585
+ { name: "X25519" },
586
+ false,
587
+ []
588
+ );
589
+ const sharedSecret = await crypto.subtle.deriveBits(
590
+ { name: "X25519", public: ephemeralPubKey },
591
+ orgPrivKey,
592
+ 256
593
+ );
594
+ if (isAllZero(sharedSecret)) throw new Error("Low-order point: shared secret is all-zero");
595
+ const wrapKey = await deriveWrapKey(sharedSecret, aad);
596
+ const plaintext = await crypto.subtle.decrypt(
597
+ { name: "AES-GCM", iv, additionalData: aad },
598
+ wrapKey,
599
+ ciphertext
600
+ );
601
+ return new Uint8Array(plaintext);
602
+ }
603
+ return {
604
+ buildRecoveryAAD,
605
+ verifyOrgRecoveryKeyFingerprint,
606
+ sealRecoveryPayload,
607
+ openRecoveryPayload
608
+ };
609
+ })();
610
+ if (typeof module !== "undefined") module.exports = OrgRecoveryCrypto2;
611
+ }
612
+ });
613
+
614
+ // src/index.ts
615
+ import { Command } from "commander";
616
+
617
+ // src/commands/signin.ts
618
+ import { hostname, platform } from "node:os";
619
+
620
+ // src/lib/config.ts
621
+ import { randomUUID } from "node:crypto";
622
+ import { readFile, writeFile } from "node:fs/promises";
623
+
624
+ // src/lib/paths.ts
625
+ import { homedir } from "node:os";
626
+ import { join } from "node:path";
627
+ import { mkdir } from "node:fs/promises";
628
+ function configDir() {
629
+ return join(homedir(), ".geslar");
630
+ }
631
+ async function ensureConfigDir() {
632
+ const dir = configDir();
633
+ await mkdir(dir, { recursive: true });
634
+ return dir;
635
+ }
636
+ function configFilePath(name) {
637
+ return join(configDir(), name);
638
+ }
639
+
640
+ // src/lib/config.ts
641
+ var DEFAULT_API_BASE = "https://api.geslar.app";
642
+ var CONFIG_FILE = "config.json";
643
+ async function loadOrInitConfig() {
644
+ const path = configFilePath(CONFIG_FILE);
645
+ try {
646
+ const raw = await readFile(path, "utf-8");
647
+ const parsed = JSON.parse(raw);
648
+ if (parsed.deviceFingerprint && parsed.apiBase) {
649
+ return { deviceFingerprint: parsed.deviceFingerprint, apiBase: parsed.apiBase };
650
+ }
651
+ } catch {
652
+ }
653
+ const config = { deviceFingerprint: `cli-${randomUUID()}`, apiBase: DEFAULT_API_BASE };
654
+ await ensureConfigDir();
655
+ await writeFile(path, JSON.stringify(config, null, 2), "utf-8");
656
+ return config;
657
+ }
658
+
659
+ // src/lib/session.ts
660
+ import { readFile as readFile2, writeFile as writeFile2, rm } from "node:fs/promises";
661
+ var SESSION_FILE = "session.json";
662
+ async function loadSession() {
663
+ try {
664
+ const raw = await readFile2(configFilePath(SESSION_FILE), "utf-8");
665
+ return JSON.parse(raw);
666
+ } catch {
667
+ return null;
668
+ }
669
+ }
670
+ async function saveSession(session) {
671
+ await ensureConfigDir();
672
+ await writeFile2(configFilePath(SESSION_FILE), JSON.stringify(session, null, 2), "utf-8");
673
+ }
674
+ async function clearSession() {
675
+ await rm(configFilePath(SESSION_FILE), { force: true });
676
+ }
677
+
678
+ // src/lib/scrubber.ts
679
+ var registered = /* @__PURE__ */ new Set();
680
+ function registerSecret(value) {
681
+ if (value.length === 0) return;
682
+ registered.add(value);
683
+ }
684
+ function scrub(text) {
685
+ if (registered.size === 0) return text;
686
+ let out = text;
687
+ const values = [...registered].sort((a, b) => b.length - a.length);
688
+ for (const value of values) {
689
+ out = out.split(value).join("***");
690
+ }
691
+ return out;
692
+ }
693
+
694
+ // src/lib/output.ts
695
+ function print(message) {
696
+ process.stdout.write(`${scrub(message)}
697
+ `);
698
+ }
699
+ function printErr(message) {
700
+ process.stderr.write(`geslar: ${scrub(message)}
701
+ `);
702
+ }
703
+
704
+ // src/lib/errors.ts
705
+ var EXIT = {
706
+ OK: 0,
707
+ GENERAL: 1,
708
+ AUTH: 2,
709
+ ENTITLEMENT: 3,
710
+ UNRESOLVABLE_REF: 4,
711
+ GRANT_DENIED: 5,
712
+ VAULT_LOCKED: 6
713
+ };
714
+ var CliError = class extends Error {
715
+ constructor(exitCode, message) {
716
+ super(message);
717
+ this.exitCode = exitCode;
718
+ this.name = "CliError";
719
+ }
720
+ };
721
+
722
+ // src/token-store/windows.ts
723
+ import { spawn } from "node:child_process";
724
+ import { readFile as readFile3, writeFile as writeFile3, rm as rm2 } from "node:fs/promises";
725
+ var PROTECT_SCRIPT = `
726
+ $ErrorActionPreference = 'Stop'
727
+ Add-Type -AssemblyName System.Security
728
+ $b64 = [Console]::In.ReadToEnd()
729
+ $bytes = [Convert]::FromBase64String($b64)
730
+ $protected = [System.Security.Cryptography.ProtectedData]::Protect(
731
+ $bytes, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)
732
+ [Console]::Out.Write([Convert]::ToBase64String($protected))
733
+ `;
734
+ var UNPROTECT_SCRIPT = `
735
+ $ErrorActionPreference = 'Stop'
736
+ Add-Type -AssemblyName System.Security
737
+ $b64 = [Console]::In.ReadToEnd()
738
+ $bytes = [Convert]::FromBase64String($b64)
739
+ $plain = [System.Security.Cryptography.ProtectedData]::Unprotect(
740
+ $bytes, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)
741
+ [Console]::Out.Write([Convert]::ToBase64String($plain))
742
+ `;
743
+ function runPowerShell(script, stdinData) {
744
+ return new Promise((resolve, reject) => {
745
+ const child = spawn("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script], {
746
+ stdio: ["pipe", "pipe", "pipe"],
747
+ windowsHide: true
748
+ });
749
+ let stdout = "";
750
+ let stderr = "";
751
+ child.stdout.on("data", (chunk) => {
752
+ stdout += chunk.toString("utf-8");
753
+ });
754
+ child.stderr.on("data", (chunk) => {
755
+ stderr += chunk.toString("utf-8");
756
+ });
757
+ child.on("error", reject);
758
+ child.on("close", (code) => {
759
+ if (code === 0) resolve(stdout.trim());
760
+ else reject(new Error(`powershell exited ${code}: ${stderr.trim() || "DPAPI operation failed"}`));
761
+ });
762
+ child.stdin.write(stdinData);
763
+ child.stdin.end();
764
+ });
765
+ }
766
+ function createWindowsDpapiBackend(namespace) {
767
+ const tokenFile = `${namespace}.dpapi`;
768
+ return {
769
+ name: "windows-dpapi",
770
+ async load() {
771
+ let protectedB64;
772
+ try {
773
+ protectedB64 = await readFile3(configFilePath(tokenFile), "utf-8");
774
+ } catch {
775
+ return null;
776
+ }
777
+ if (!protectedB64.trim()) return null;
778
+ const plainB64 = await runPowerShell(UNPROTECT_SCRIPT, protectedB64);
779
+ return Buffer.from(plainB64, "base64").toString("utf-8");
780
+ },
781
+ async save(data) {
782
+ const plainB64 = Buffer.from(data, "utf-8").toString("base64");
783
+ const protectedB64 = await runPowerShell(PROTECT_SCRIPT, plainB64);
784
+ await ensureConfigDir();
785
+ await writeFile3(configFilePath(tokenFile), protectedB64, { encoding: "utf-8", mode: 384 });
786
+ },
787
+ async clear() {
788
+ await rm2(configFilePath(tokenFile), { force: true });
789
+ }
790
+ };
791
+ }
792
+ var windowsDpapiBackend = createWindowsDpapiBackend("tokens");
793
+
794
+ // src/token-store/macos.ts
795
+ import { spawn as spawn2 } from "node:child_process";
796
+ import { userInfo } from "node:os";
797
+ function account() {
798
+ return userInfo().username;
799
+ }
800
+ function run(args, input) {
801
+ return new Promise((resolve, reject) => {
802
+ const child = spawn2("security", args, { stdio: ["pipe", "pipe", "pipe"] });
803
+ let stdout = "";
804
+ let stderr = "";
805
+ child.stdout.on("data", (c) => {
806
+ stdout += c.toString("utf-8");
807
+ });
808
+ child.stderr.on("data", (c) => {
809
+ stderr += c.toString("utf-8");
810
+ });
811
+ child.on("error", reject);
812
+ child.on("close", (code) => resolve({ code, stdout, stderr }));
813
+ if (input !== void 0) child.stdin.write(input);
814
+ child.stdin.end();
815
+ });
816
+ }
817
+ function createMacosKeychainBackend(namespace) {
818
+ const service = namespace === "tokens" ? "geslar-cli" : `geslar-cli-${namespace}`;
819
+ return {
820
+ name: "macos-keychain",
821
+ async load() {
822
+ const res = await run(["find-generic-password", "-a", account(), "-s", service, "-w"]);
823
+ if (res.code !== 0) return null;
824
+ return res.stdout.trim();
825
+ },
826
+ async save(data) {
827
+ const res = await run(["add-generic-password", "-a", account(), "-s", service, "-w", data, "-U"]);
828
+ if (res.code !== 0) {
829
+ throw new Error(`security add-generic-password failed: ${res.stderr.trim()}`);
830
+ }
831
+ },
832
+ async clear() {
833
+ await run(["delete-generic-password", "-a", account(), "-s", service]);
834
+ }
835
+ };
836
+ }
837
+ var macosKeychainBackend = createMacosKeychainBackend("tokens");
838
+
839
+ // src/token-store/linux.ts
840
+ import { spawn as spawn3 } from "node:child_process";
841
+ import { userInfo as userInfo2 } from "node:os";
842
+ function account2() {
843
+ return userInfo2().username;
844
+ }
845
+ function run2(args, input) {
846
+ return new Promise((resolve, reject) => {
847
+ const child = spawn3("secret-tool", args, { stdio: ["pipe", "pipe", "pipe"] });
848
+ let stdout = "";
849
+ let stderr = "";
850
+ child.stdout.on("data", (c) => {
851
+ stdout += c.toString("utf-8");
852
+ });
853
+ child.stderr.on("data", (c) => {
854
+ stderr += c.toString("utf-8");
855
+ });
856
+ child.on("error", reject);
857
+ child.on("close", (code) => resolve({ code, stdout, stderr }));
858
+ if (input !== void 0) child.stdin.write(input);
859
+ child.stdin.end();
860
+ });
861
+ }
862
+ async function isSecretToolAvailable() {
863
+ try {
864
+ const res = await run2(["lookup", "service", "geslar-cli-probe", "account", "probe"]);
865
+ return res.code === 0 || res.code === 1;
866
+ } catch {
867
+ return false;
868
+ }
869
+ }
870
+ function createLinuxSecretToolBackend(namespace) {
871
+ const service = namespace === "tokens" ? "geslar-cli" : `geslar-cli-${namespace}`;
872
+ return {
873
+ name: "linux-secret-tool",
874
+ async load() {
875
+ const res = await run2(["lookup", "service", service, "account", account2()]);
876
+ if (res.code !== 0) return null;
877
+ return res.stdout.trim() || null;
878
+ },
879
+ async save(data) {
880
+ const res = await run2(
881
+ ["store", "--label", "Geslar CLI token", "service", service, "account", account2()],
882
+ data
883
+ );
884
+ if (res.code !== 0) {
885
+ throw new Error(`secret-tool store failed: ${res.stderr.trim()}`);
886
+ }
887
+ },
888
+ async clear() {
889
+ await run2(["clear", "service", service, "account", account2()]);
890
+ }
891
+ };
892
+ }
893
+ var linuxSecretToolBackend = createLinuxSecretToolBackend("tokens");
894
+
895
+ // src/token-store/fallback.ts
896
+ import { hkdfSync, randomBytes as randomBytes2, createCipheriv, createDecipheriv } from "node:crypto";
897
+ import { userInfo as userInfo3 } from "node:os";
898
+ import { readFile as readFile5, writeFile as writeFile5, rm as rm3 } from "node:fs/promises";
899
+
900
+ // src/token-store/machine-id.ts
901
+ import { readFile as readFile4, writeFile as writeFile4 } from "node:fs/promises";
902
+ import { randomBytes } from "node:crypto";
903
+ async function getMachineId() {
904
+ const fromOs = await readOsMachineId();
905
+ if (fromOs) return fromOs;
906
+ return getOrCreatePersistedId();
907
+ }
908
+ async function readOsMachineId() {
909
+ if (process.platform === "linux") {
910
+ for (const path of ["/etc/machine-id", "/var/lib/dbus/machine-id"]) {
911
+ try {
912
+ const id = (await readFile4(path, "utf-8")).trim();
913
+ if (id) return id;
914
+ } catch {
915
+ }
916
+ }
917
+ }
918
+ return null;
919
+ }
920
+ var ID_FILE = "machine-salt";
921
+ async function getOrCreatePersistedId() {
922
+ const path = configFilePath(ID_FILE);
923
+ try {
924
+ const existing = (await readFile4(path, "utf-8")).trim();
925
+ if (existing) return existing;
926
+ } catch {
927
+ }
928
+ const id = randomBytes(32).toString("hex");
929
+ await ensureConfigDir();
930
+ await writeFile4(path, id, { encoding: "utf-8", mode: 384 });
931
+ return id;
932
+ }
933
+
934
+ // src/token-store/fallback.ts
935
+ var HKDF_SALT = Buffer.from("geslar-cli-token-store-v1", "utf-8");
936
+ var HKDF_INFO = Buffer.from("geslar-cli-token-store", "utf-8");
937
+ var IV_LEN = 12;
938
+ async function deriveKey() {
939
+ const machineId = await getMachineId();
940
+ const ikm = Buffer.from(`${machineId}|${userInfo3().username}`, "utf-8");
941
+ const key = hkdfSync("sha256", ikm, HKDF_SALT, HKDF_INFO, 32);
942
+ return Buffer.from(key);
943
+ }
944
+ function createFallbackEncryptedFileBackend(namespace) {
945
+ const tokenFile = `${namespace}.enc`;
946
+ return {
947
+ name: "fallback-hkdf-file",
948
+ weak: true,
949
+ async load() {
950
+ let blob;
951
+ try {
952
+ blob = await readFile5(configFilePath(tokenFile));
953
+ } catch {
954
+ return null;
955
+ }
956
+ if (blob.length < IV_LEN + 16) return null;
957
+ const key = await deriveKey();
958
+ const iv = blob.subarray(0, IV_LEN);
959
+ const tag = blob.subarray(blob.length - 16);
960
+ const ciphertext = blob.subarray(IV_LEN, blob.length - 16);
961
+ const decipher = createDecipheriv("aes-256-gcm", key, iv);
962
+ decipher.setAuthTag(tag);
963
+ const plain = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
964
+ return plain.toString("utf-8");
965
+ },
966
+ async save(data) {
967
+ const key = await deriveKey();
968
+ const iv = randomBytes2(IV_LEN);
969
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
970
+ const ciphertext = Buffer.concat([cipher.update(data, "utf-8"), cipher.final()]);
971
+ const tag = cipher.getAuthTag();
972
+ await ensureConfigDir();
973
+ await writeFile5(configFilePath(tokenFile), Buffer.concat([iv, ciphertext, tag]), { mode: 384 });
974
+ },
975
+ async clear() {
976
+ await rm3(configFilePath(tokenFile), { force: true });
977
+ }
978
+ };
979
+ }
980
+ var fallbackEncryptedFileBackend = createFallbackEncryptedFileBackend("tokens");
981
+
982
+ // src/token-store/index.ts
983
+ async function selectBackend(namespace = "tokens") {
984
+ if (process.platform === "win32") return createWindowsDpapiBackend(namespace);
985
+ if (process.platform === "darwin") return createMacosKeychainBackend(namespace);
986
+ if (await isSecretToolAvailable()) return createLinuxSecretToolBackend(namespace);
987
+ return createFallbackEncryptedFileBackend(namespace);
988
+ }
989
+ async function createCliTokenStore(backend) {
990
+ if (backend.weak) {
991
+ printErr("WARNING: no OS credential vault available on this system \u2014 session is stored in a locally-encrypted file instead of DPAPI/Keychain/libsecret. Anyone who can read your files on this machine can decrypt it.");
992
+ }
993
+ let current = null;
994
+ try {
995
+ const raw = await backend.load();
996
+ current = raw ? JSON.parse(raw) : null;
997
+ } catch (err) {
998
+ printErr(`could not read stored session (${err.message}) \u2014 treating as signed out`);
999
+ current = null;
1000
+ }
1001
+ let pending = Promise.resolve();
1002
+ return {
1003
+ backendName: backend.name,
1004
+ get: () => current,
1005
+ set: (tokens) => {
1006
+ current = tokens;
1007
+ pending = pending.then(() => tokens ? backend.save(JSON.stringify(tokens)) : backend.clear()).catch((err) => {
1008
+ printErr(`failed to persist session (${err.message})`);
1009
+ });
1010
+ },
1011
+ flush: () => pending
1012
+ };
1013
+ }
1014
+
1015
+ // src/device-flow.ts
1016
+ async function readJson(res) {
1017
+ const text = await res.text();
1018
+ return text ? JSON.parse(text) : {};
1019
+ }
1020
+ async function startDeviceFlow(baseUrl, info, fetchImpl = fetch) {
1021
+ const res = await fetchImpl(`${baseUrl}/v1/auth/device/start`, {
1022
+ method: "POST",
1023
+ headers: { "Content-Type": "application/json" },
1024
+ body: JSON.stringify(info)
1025
+ });
1026
+ const body = await readJson(res);
1027
+ if (!res.ok) {
1028
+ throw new CliError(EXIT.GENERAL, body["detail"] ?? `Could not start sign-in (HTTP ${res.status})`);
1029
+ }
1030
+ return body;
1031
+ }
1032
+ async function pollDeviceFlow(baseUrl, start, fetchImpl = fetch, opts = {}) {
1033
+ const sleep = opts.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
1034
+ let interval = start.interval;
1035
+ const deadline = Date.now() + start.expires_in * 1e3;
1036
+ for (; ; ) {
1037
+ if (Date.now() >= deadline) {
1038
+ throw new CliError(EXIT.AUTH, "Device code expired \u2014 run `geslar signin` again");
1039
+ }
1040
+ await sleep(interval * 1e3);
1041
+ opts.onTick?.();
1042
+ const res = await fetchImpl(`${baseUrl}/v1/auth/device/poll`, {
1043
+ method: "POST",
1044
+ headers: { "Content-Type": "application/json" },
1045
+ body: JSON.stringify({ device_code: start.device_code })
1046
+ });
1047
+ const body = await readJson(res);
1048
+ if (res.ok) {
1049
+ return body;
1050
+ }
1051
+ switch (body["code"]) {
1052
+ case "device-flow/authorization-pending":
1053
+ continue;
1054
+ case "device-flow/slow-down":
1055
+ interval = typeof body["interval"] === "number" ? body["interval"] : interval + 5;
1056
+ continue;
1057
+ case "device-flow/expired-token":
1058
+ throw new CliError(EXIT.AUTH, "Device code expired \u2014 run `geslar signin` again");
1059
+ case "device-flow/access-denied":
1060
+ throw new CliError(EXIT.GRANT_DENIED, "Sign-in request was denied in the console");
1061
+ default:
1062
+ throw new CliError(EXIT.GENERAL, body["detail"] ?? `Sign-in failed (HTTP ${res.status})`);
1063
+ }
1064
+ }
1065
+ }
1066
+
1067
+ // src/commands/signin.ts
1068
+ var CLI_VERSION = "0.1.0";
1069
+ async function signinCommand(opts) {
1070
+ const config = await loadOrInitConfig();
1071
+ const baseUrl = opts.api ?? config.apiBase;
1072
+ try {
1073
+ const start = await startDeviceFlow(baseUrl, {
1074
+ device_fingerprint: config.deviceFingerprint,
1075
+ hostname: hostname(),
1076
+ os: platform(),
1077
+ cli_version: CLI_VERSION
1078
+ });
1079
+ print("");
1080
+ print(` Your code: ${start.user_code}`);
1081
+ print("");
1082
+ print(` Open ${start.verification_uri} and enter the code above to sign in.`);
1083
+ print(" (Type the code yourself \u2014 never follow a link that already has it filled in.)");
1084
+ print("");
1085
+ print("Waiting for approval...");
1086
+ const result = await pollDeviceFlow(baseUrl, start);
1087
+ const backend = await selectBackend();
1088
+ const tokenStore = await createCliTokenStore(backend);
1089
+ tokenStore.set({ access_token: result.access_token, refresh_token: result.refresh_token });
1090
+ await tokenStore.flush();
1091
+ await saveSession({ email: result.email, userId: result.user_id, plan: result.plan, apiBase: baseUrl });
1092
+ print(`Signed in as ${result.email} (${result.plan} plan).`);
1093
+ return EXIT.OK;
1094
+ } catch (err) {
1095
+ if (err instanceof CliError) {
1096
+ printErr(err.message);
1097
+ return err.exitCode;
1098
+ }
1099
+ printErr(err.message);
1100
+ return EXIT.GENERAL;
1101
+ }
1102
+ }
1103
+
1104
+ // src/vault/grant.ts
1105
+ var DEFAULT_TTL_SEC = 30 * 60;
1106
+ var MAX_TTL_SEC = 8 * 60 * 60;
1107
+ function parseTtl(input) {
1108
+ if (!input) return DEFAULT_TTL_SEC;
1109
+ const m = /^(\d+)\s*(s|m|h)?$/.exec(input.trim());
1110
+ if (!m) {
1111
+ throw new CliError(EXIT.GENERAL, `Invalid --ttl value "${input}" \u2014 use e.g. 30m, 1h, 90s`);
1112
+ }
1113
+ const n = parseInt(m[1], 10);
1114
+ const unit = m[2] ?? "m";
1115
+ const sec = unit === "s" ? n : unit === "h" ? n * 3600 : n * 60;
1116
+ if (sec <= 0) {
1117
+ throw new CliError(EXIT.GENERAL, `--ttl must be positive, got "${input}"`);
1118
+ }
1119
+ return Math.min(sec, MAX_TTL_SEC);
1120
+ }
1121
+ async function saveVaultGrant(unlocked, ttlSec) {
1122
+ const grant = {
1123
+ dek: Buffer.from(unlocked.dekRaw).toString("base64"),
1124
+ ecdhPrivRaw: unlocked.ecdhPrivRaw ? Buffer.from(unlocked.ecdhPrivRaw).toString("base64") : null,
1125
+ createdAt: Date.now(),
1126
+ ttlSec
1127
+ };
1128
+ const backend = await selectBackend("vault-grant");
1129
+ await backend.save(JSON.stringify(grant));
1130
+ }
1131
+ async function loadVaultGrant() {
1132
+ const backend = await selectBackend("vault-grant");
1133
+ const raw = await backend.load();
1134
+ if (!raw) return null;
1135
+ let grant;
1136
+ try {
1137
+ grant = JSON.parse(raw);
1138
+ } catch {
1139
+ return null;
1140
+ }
1141
+ if (Date.now() - grant.createdAt > grant.ttlSec * 1e3) {
1142
+ await backend.clear();
1143
+ return null;
1144
+ }
1145
+ return {
1146
+ dekRaw: new Uint8Array(Buffer.from(grant.dek, "base64")),
1147
+ ecdhPrivRaw: grant.ecdhPrivRaw ? new Uint8Array(Buffer.from(grant.ecdhPrivRaw, "base64")) : null
1148
+ };
1149
+ }
1150
+ async function clearVaultGrant() {
1151
+ const backend = await selectBackend("vault-grant");
1152
+ await backend.clear();
1153
+ }
1154
+
1155
+ // src/commands/signout.ts
1156
+ async function signoutCommand() {
1157
+ const backend = await selectBackend();
1158
+ const tokenStore = await createCliTokenStore(backend);
1159
+ const tokens = tokenStore.get();
1160
+ if (!tokens) {
1161
+ print("Not signed in.");
1162
+ return EXIT.OK;
1163
+ }
1164
+ const config = await loadOrInitConfig();
1165
+ const session = await loadSession();
1166
+ const baseUrl = session?.apiBase ?? config.apiBase;
1167
+ try {
1168
+ await fetch(`${baseUrl}/v1/auth/logout`, {
1169
+ method: "POST",
1170
+ headers: { "Content-Type": "application/json" },
1171
+ body: JSON.stringify({ refresh_token: tokens.refresh_token })
1172
+ });
1173
+ } catch (err) {
1174
+ printErr(`could not reach the server to revoke the session (${err.message}) \u2014 clearing local session anyway`);
1175
+ }
1176
+ tokenStore.set(null);
1177
+ await tokenStore.flush();
1178
+ await clearSession();
1179
+ await clearVaultGrant();
1180
+ print("Signed out.");
1181
+ return EXIT.OK;
1182
+ }
1183
+
1184
+ // ../../packages/core/src/api/client.ts
1185
+ var ERASURE_CONFIRMATION = "DELETE MY ACCOUNT";
1186
+ function memoryTokenStore() {
1187
+ let tokens = null;
1188
+ return {
1189
+ get: () => tokens,
1190
+ set: (t) => {
1191
+ tokens = t;
1192
+ }
1193
+ };
1194
+ }
1195
+ var REFRESH_TIMEOUT_MS = 1e4;
1196
+ var ApiError = class extends Error {
1197
+ status;
1198
+ code;
1199
+ /** Full response body (parsed JSON). Populated for structured error responses. */
1200
+ body;
1201
+ constructor(status, message, code, body) {
1202
+ super(message);
1203
+ this.name = "ApiError";
1204
+ this.status = status;
1205
+ this.code = code;
1206
+ this.body = body ?? {};
1207
+ }
1208
+ };
1209
+ var SYNC_KEY_VERSION_STALE = "sync/key-version-stale";
1210
+ function asConflict(e) {
1211
+ if (e instanceof ApiError && e.status === 409 && e.code !== SYNC_KEY_VERSION_STALE) {
1212
+ const sv = typeof e.body["server_version"] === "number" ? e.body["server_version"] : 0;
1213
+ return { conflict: true, server_version: sv, message: e.message };
1214
+ }
1215
+ throw e;
1216
+ }
1217
+ var ApiClient = class {
1218
+ baseUrl;
1219
+ tokens;
1220
+ doFetch;
1221
+ credentials;
1222
+ /** Single-flight guard: concurrent 401s share one in-flight refresh. */
1223
+ refreshing = null;
1224
+ /** Dedup concurrent getVaultEntries calls for the same vaultId. */
1225
+ _inflightEntries = /* @__PURE__ */ new Map();
1226
+ constructor(opts = {}) {
1227
+ this.baseUrl = opts.baseUrl ?? "https://api.geslar.app";
1228
+ this.tokens = opts.tokenStore ?? memoryTokenStore();
1229
+ this.doFetch = opts.fetchImpl ?? globalThis.fetch.bind(globalThis);
1230
+ this.credentials = opts.credentials;
1231
+ }
1232
+ /** True when refresh can ride a cookie (no refresh token needs to be in store). */
1233
+ get cookieMode() {
1234
+ return this.credentials === "include";
1235
+ }
1236
+ isLoggedIn() {
1237
+ return !!this.tokens.get()?.access_token;
1238
+ }
1239
+ /** Force a refresh (e.g. on rehydrate): pulls a new access token via the cookie. */
1240
+ refreshSession() {
1241
+ return this.tryRefresh();
1242
+ }
1243
+ /** Server-side logout: invalidate the refresh token + clear the cookie, then drop local tokens. */
1244
+ async serverLogout() {
1245
+ try {
1246
+ await this.doFetch(`${this.baseUrl}/v1/auth/logout`, {
1247
+ method: "POST",
1248
+ headers: { "Content-Type": "application/json" },
1249
+ body: "{}",
1250
+ ...this.credentials ? { credentials: this.credentials } : {}
1251
+ });
1252
+ } catch {
1253
+ }
1254
+ this.tokens.set(null);
1255
+ }
1256
+ logout() {
1257
+ this.tokens.set(null);
1258
+ }
1259
+ // ── Auth ────────────────────────────────────────────────────────────────
1260
+ prelogin(email) {
1261
+ return this.request("/v1/auth/prelogin", {
1262
+ method: "POST",
1263
+ body: JSON.stringify({ email })
1264
+ });
1265
+ }
1266
+ /**
1267
+ * Prijava. Račun s aktivnim MFA dobiva `MfaRequiredResponse` (BEZ tokena) —
1268
+ * klijent tada zove `loginMfa()` s challenge tokenom. Račun bez MFA dobiva
1269
+ * puni `LoginResponse` kao i dosad (tokeni se usvajaju).
1270
+ */
1271
+ async login(params) {
1272
+ const body = await this.request("/v1/auth/login", {
1273
+ method: "POST",
1274
+ body: JSON.stringify(params)
1275
+ });
1276
+ if (!("mfa_required" in body)) {
1277
+ this.tokens.set({ access_token: body.access_token, refresh_token: body.refresh_token });
1278
+ }
1279
+ return body;
1280
+ }
1281
+ /** Korak 2 prijave: MFA dokaz → puni login response (tokeni se usvajaju). */
1282
+ async loginMfa(params) {
1283
+ const body = await this.request("/v1/auth/login/mfa", {
1284
+ method: "POST",
1285
+ body: JSON.stringify(params)
1286
+ });
1287
+ this.tokens.set({ access_token: body.access_token, refresh_token: body.refresh_token });
1288
+ return body;
1289
+ }
1290
+ // ── Oporavak računa (zaboravljen glavni ključ) ────────────────────────────
1291
+ /**
1292
+ * Korak 1 oporavka: e-mail → recovery session + šifrirani recovery blob.
1293
+ * Uvijek 200 (anti-enumeracija) — nepoznat račun dobiva lažni blob koji se
1294
+ * lokalno ne da otvoriti.
1295
+ */
1296
+ recoverInit(email) {
1297
+ return this.request("/v1/auth/recover/init", {
1298
+ method: "POST",
1299
+ body: JSON.stringify({ email })
1300
+ });
1301
+ }
1302
+ /**
1303
+ * Korak 2 oporavka: novi auth_hash + novi wrapani blobovi (sve izvedeno u
1304
+ * pregledniku — prepareRecovery). MFA-gated kad je MFA aktivan (mfa_code /
1305
+ * mfa_recovery_code). Server revoka sve ostale sesije; tokeni se usvajaju.
1306
+ */
1307
+ async recoverComplete(params) {
1308
+ const body = await this.request("/v1/auth/recover/complete", {
1309
+ method: "POST",
1310
+ body: JSON.stringify(params)
1311
+ });
1312
+ this.tokens.set({ access_token: body.access_token, refresh_token: body.refresh_token });
1313
+ return body;
1314
+ }
1315
+ // ── MFA upravljanje (modularni auth-methods sustav) ───────────────────────
1316
+ /** Aktivne MFA metode + broj preostalih recovery kodova. */
1317
+ mfaList() {
1318
+ return this.request("/v1/account/mfa", { method: "GET" });
1319
+ }
1320
+ /**
1321
+ * Korak 1 enrollmenta — step-up lozinkom (auth_hash deriviran u pregledniku).
1322
+ * TOTP vraća secret + otpauth URI (QR renderira klijent); budući provideri
1323
+ * vraćaju svoj clientPayload.
1324
+ */
1325
+ mfaEnroll(method, authHash) {
1326
+ return this.request(`/v1/account/mfa/${encodeURIComponent(method)}/enroll`, {
1327
+ method: "POST",
1328
+ body: JSON.stringify({ auth_hash: authHash })
1329
+ });
1330
+ }
1331
+ /**
1332
+ * Korak 2 enrollmenta — dokaz (TOTP: prvi kod). Prva metoda vraća recovery
1333
+ * kodove (plaintext JEDINI PUT).
1334
+ */
1335
+ mfaVerifyEnroll(method, proof) {
1336
+ return this.request(`/v1/account/mfa/${encodeURIComponent(method)}/verify-enroll`, {
1337
+ method: "POST",
1338
+ body: JSON.stringify({ proof })
1339
+ });
1340
+ }
1341
+ /** Isključi metodu: lozinka OBAVEZNA + (kod aktivne metode ILI recovery kod). */
1342
+ mfaDisable(method, params) {
1343
+ return this.request(`/v1/account/mfa/${encodeURIComponent(method)}/disable`, {
1344
+ method: "POST",
1345
+ body: JSON.stringify(params)
1346
+ });
1347
+ }
1348
+ /** Novih 10 recovery kodova (stari prestaju vrijediti) — plaintext JEDINI PUT. */
1349
+ mfaRegenerateRecoveryCodes(params) {
1350
+ return this.request("/v1/account/mfa/recovery-codes/regenerate", {
1351
+ method: "POST",
1352
+ body: JSON.stringify(params)
1353
+ });
1354
+ }
1355
+ /** F2 — dismiss the "set up 2FA again" nudge after an admin reset ("Not now").
1356
+ * Clears the caller's own mfa_reenroll_prompt flag. No body. */
1357
+ dismissReenroll() {
1358
+ return this.request("/v1/account/mfa/dismiss-reenroll", { method: "POST" });
1359
+ }
1360
+ // ── Agentic Access — CLI device-flow approval (M1) ─────────────────────────
1361
+ /** Console /device page: request context to show BEFORE approve/deny. */
1362
+ getDeviceContext(userCode) {
1363
+ return this.request("/v1/auth/device/lookup", {
1364
+ method: "POST",
1365
+ body: JSON.stringify({ user_code: userCode })
1366
+ });
1367
+ }
1368
+ /** Approve a pending `geslar signin` request. Always requires a FRESH 2FA
1369
+ * proof — no session-freshness cache, same step-up model as mfaDisable. */
1370
+ approveDevice(params) {
1371
+ return this.request("/v1/auth/device/approve", {
1372
+ method: "POST",
1373
+ body: JSON.stringify(params)
1374
+ });
1375
+ }
1376
+ /** Deny a pending request — the safe path, no 2FA gate. */
1377
+ denyDevice(userCode) {
1378
+ return this.request("/v1/auth/device/deny", {
1379
+ method: "POST",
1380
+ body: JSON.stringify({ user_code: userCode })
1381
+ });
1382
+ }
1383
+ /** M2 — caller's own wrapped vault-key material (enc_salt + encrypted_vault_key
1384
+ * + ECDH blobs), for `geslar unlock`'s local KDF chain. See VaultKeyMaterial. */
1385
+ getVaultKeyMaterial() {
1386
+ return this.request("/v1/account/vault-key-material", { method: "GET" });
1387
+ }
1388
+ /**
1389
+ * Create an account. All crypto happens in @geslar/core/crypto
1390
+ * (prepareRegistration) — this only ships auth_hash + opaque wrapped blobs.
1391
+ * Adopts the issued token pair so the fresh session is live immediately.
1392
+ */
1393
+ async register(params) {
1394
+ const body = await this.request("/v1/auth/register", {
1395
+ method: "POST",
1396
+ body: JSON.stringify(params)
1397
+ });
1398
+ this.tokens.set({ access_token: body.access_token, refresh_token: body.refresh_token });
1399
+ return body;
1400
+ }
1401
+ /** Consume an email-verification token (from the verification link). */
1402
+ verifyEmail(token) {
1403
+ return this.request("/v1/auth/verify-email", {
1404
+ method: "POST",
1405
+ body: JSON.stringify({ token })
1406
+ });
1407
+ }
1408
+ /** Re-send the verification email. Server rate-limits (3/h per email); always 200. */
1409
+ resendVerification(email) {
1410
+ return this.request("/v1/auth/resend-verification", {
1411
+ method: "POST",
1412
+ body: JSON.stringify({ email })
1413
+ });
1414
+ }
1415
+ /** Mark the recovery key as stored by the user (onboarding ack). */
1416
+ acknowledgeRecoveryKey() {
1417
+ return this.request("/v1/account/acknowledge-recovery-key", {
1418
+ method: "POST",
1419
+ body: JSON.stringify({ acknowledged: true })
1420
+ });
1421
+ }
1422
+ /**
1423
+ * Replace the recovery blob with one wrapped under a FRESH recovery key (#44).
1424
+ * The new key + blob are generated in the browser; the server only stores the
1425
+ * opaque blob and resets the acknowledge flag.
1426
+ */
1427
+ regenerateRecoveryKey(encryptedRecoveryBlob) {
1428
+ return this.request("/v1/account/regenerate-recovery-key", {
1429
+ method: "POST",
1430
+ body: JSON.stringify({ encrypted_recovery_blob: encryptedRecoveryBlob })
1431
+ });
1432
+ }
1433
+ // ── Orgs / members (read-only, T13) ───────────────────────────────────────
1434
+ getOrgs() {
1435
+ return this.request("/v1/orgs", { method: "GET" });
1436
+ }
1437
+ /** Fire-and-forget audit trail for "who switched into which org, when" —
1438
+ * MSP compliance groundwork. Caller must belong to orgId; server 403s otherwise. */
1439
+ logContextSwitch(orgId) {
1440
+ return this.request("/v1/context-switch", {
1441
+ method: "POST",
1442
+ body: JSON.stringify({ org_id: orgId })
1443
+ });
1444
+ }
1445
+ patchOrgBranding(orgId, body) {
1446
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/branding`, {
1447
+ method: "PATCH",
1448
+ body: JSON.stringify(body)
1449
+ });
1450
+ }
1451
+ getOrgMembers(orgId) {
1452
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/members`, {
1453
+ method: "GET"
1454
+ });
1455
+ }
1456
+ getEntitlements(orgId) {
1457
+ const url = orgId ? `/v1/account/entitlements?org=${encodeURIComponent(orgId)}` : "/v1/account/entitlements";
1458
+ return this.request(url, { method: "GET" });
1459
+ }
1460
+ /** Public plan catalogue (single source of truth for pricing). No auth needed. */
1461
+ async getPlans() {
1462
+ const res = await this.request("/v1/plans", { method: "GET" });
1463
+ return res.plans;
1464
+ }
1465
+ /** Provider-agnostic checkout. Server attaches custom_data; returns the URL. */
1466
+ async createCheckout(plan, interval) {
1467
+ return this.request("/v1/billing/checkout", {
1468
+ method: "POST",
1469
+ body: JSON.stringify({ plan, interval })
1470
+ });
1471
+ }
1472
+ /** Faza 2 — što bi change-plan napravio (za ISTINIT copy prije potvrde):
1473
+ * interval_update (Lemon proration) / upgrade_checkout (Premium→Family:
1474
+ * checkout + auto-otkaz + proration refund starog suba) / checkout / noop. */
1475
+ async changePlanPreview(plan, interval) {
1476
+ return this.request(
1477
+ `/v1/billing/change-plan/preview?plan=${plan}&interval=${interval}`,
1478
+ { method: "GET" }
1479
+ );
1480
+ }
1481
+ /** Faza 3 (#11) — native otkaz iz konzole: sub vrijedi do kraja plaćenog
1482
+ * perioda (bez daljnjih naplata), zatim grace (D-010). 404 bez aktivnog suba. */
1483
+ async cancelPlan(plan) {
1484
+ return this.request("/v1/billing/cancel", {
1485
+ method: "POST",
1486
+ body: JSON.stringify({ plan })
1487
+ });
1488
+ }
1489
+ /** Faza 2 — THE change-plan ulaz. Server odlučuje (autoritativno):
1490
+ * 'updated' = interval promijenjen u mjestu (bez checkouta); 'checkout' =
1491
+ * otvori vraćeni URL. 409 kad je korisnik već na traženom planu/intervalu. */
1492
+ async changePlan(plan, interval) {
1493
+ return this.request("/v1/billing/change-plan", {
1494
+ method: "POST",
1495
+ body: JSON.stringify({ plan, interval })
1496
+ });
1497
+ }
1498
+ /** Authenticated deep-link to the provider's hosted customer/billing portal
1499
+ * (manage payment method, cancel a plan, view invoices). 404 when the caller
1500
+ * has no subscription to manage; 503 when the portal is not configured. */
1501
+ async getCustomerPortalUrl() {
1502
+ return this.request("/v1/billing/portal", { method: "GET" });
1503
+ }
1504
+ // ── Sharing (T11) ─────────────────────────────────────────────────────────
1505
+ // "admin = razina" Track A Faza 3/4b: optional role_id assigns a management
1506
+ // role via PDP grant (parallel to the legacy `role` enum — see BE accept flow).
1507
+ createInvite(orgId, email, role, roleId) {
1508
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/invites`, {
1509
+ method: "POST",
1510
+ body: JSON.stringify({ email, role, ...roleId ? { role_id: roleId } : {} })
1511
+ });
1512
+ }
1513
+ listInvites(orgId) {
1514
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/invites`, { method: "GET" });
1515
+ }
1516
+ revokeInvite(orgId, inviteId) {
1517
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/invites/${encodeURIComponent(inviteId)}`, { method: "DELETE" });
1518
+ }
1519
+ async resendInvite(orgId, inviteId, email, role) {
1520
+ await this.revokeInvite(orgId, inviteId);
1521
+ return this.createInvite(orgId, email, role);
1522
+ }
1523
+ acceptInvite(token) {
1524
+ return this.request(`/v1/invites/${encodeURIComponent(token)}/accept`, { method: "POST" });
1525
+ }
1526
+ /** Upsert the caller's OWN wrapped DEK (bootstrapping a team_collection). */
1527
+ putOwnMemberKey(vaultId, encryptedKeyB64) {
1528
+ return this.request(`/v1/vaults/${encodeURIComponent(vaultId)}/member-keys`, {
1529
+ method: "POST",
1530
+ body: JSON.stringify({ encrypted_key: encryptedKeyB64 })
1531
+ });
1532
+ }
1533
+ /** Fetch the caller's wrapped DEK + the wrapper's public key (for unwrap). */
1534
+ getMemberKey(vaultId) {
1535
+ return this.request(`/v1/vaults/${encodeURIComponent(vaultId)}/member-keys`, { method: "GET" });
1536
+ }
1537
+ /** Cross-org: all team_collection vaults the caller holds a DEK for. */
1538
+ getCollections() {
1539
+ return this.request("/v1/collections", { method: "GET" });
1540
+ }
1541
+ // ── Collection management (D-053) ─────────────────────────────────────────
1542
+ /** idempotencyKey (B1): caller generates ONE UUID per logical submit and reuses
1543
+ * it on automatic retry of the SAME request (e.g. the 401-refresh retry in
1544
+ * request() below reuses this same init). Optional — server does not require
1545
+ * it yet (B2 lands after clients ship this).
1546
+ * isDefault (business-default-vault plan, 2026-07-14): creates the org's
1547
+ * singleton "Opća škrinja" instead of a regular collection. A second
1548
+ * is_default=true create 409s with code 'vault/default-collection-exists'
1549
+ * and body.existing_vault_id — the caller should open that vault instead. */
1550
+ createCollection(orgId, name, idempotencyKey, isDefault) {
1551
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections`, {
1552
+ method: "POST",
1553
+ body: JSON.stringify({ name, is_default: isDefault ?? false }),
1554
+ ...idempotencyKey ? { headers: { "Idempotency-Key": idempotencyKey } } : {}
1555
+ });
1556
+ }
1557
+ /** F4 B3: promote a folder subtree from a business vault into a NEW collection.
1558
+ * Enterprise-gated server-side (403 without the promote_folder module). The
1559
+ * server only creates the collection + (optionally) replicates the source's
1560
+ * access state; the ZK entry move + folder recreation happen client-side.
1561
+ * idempotencyKey (B1): see createCollection above. */
1562
+ promoteFolder(orgId, body, idempotencyKey) {
1563
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/promote-folder`, {
1564
+ method: "POST",
1565
+ body: JSON.stringify(body),
1566
+ ...idempotencyKey ? { headers: { "Idempotency-Key": idempotencyKey } } : {}
1567
+ });
1568
+ }
1569
+ renameCollection(orgId, cid, name) {
1570
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}`, {
1571
+ method: "PATCH",
1572
+ body: JSON.stringify({ name })
1573
+ });
1574
+ }
1575
+ deleteCollection(orgId, cid) {
1576
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}`, {
1577
+ method: "DELETE"
1578
+ });
1579
+ }
1580
+ listCollectionMembers(orgId, cid) {
1581
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/members`, {
1582
+ method: "GET"
1583
+ });
1584
+ }
1585
+ /** keyVersion: version of the DEK encryptedKeyB64 was wrapped with. Optional for
1586
+ * back-compat; omitting it keeps the server's pre-existing grace behavior
1587
+ * (tags the row as whatever version is current at insert time). Sending it lets
1588
+ * the server reject a stale wrap (409 sync/key-version-stale) instead of
1589
+ * silently tagging a rotation-raced wrap with the wrong version — same
1590
+ * contract as CollectionWrappedKey.key_version in the grants fan-out. */
1591
+ addCollectionMember(orgId, cid, userId, encryptedKeyB64, keyVersion) {
1592
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/members`, {
1593
+ method: "POST",
1594
+ body: JSON.stringify({ user_id: userId, encrypted_key: encryptedKeyB64, ...keyVersion !== void 0 ? { key_version: keyVersion } : {} })
1595
+ });
1596
+ }
1597
+ /** Remove a collection member (F4 Rez 1d-B Faza 4). Severs the removed member's
1598
+ * access immediately and flags rotation_required if they held the DEK; the
1599
+ * actual re-encryption runs staged (stage/commit/complete). No payload. */
1600
+ removeCollectionMember(orgId, cid, uid) {
1601
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/members/${encodeURIComponent(uid)}/remove`, {
1602
+ method: "POST"
1603
+ });
1604
+ }
1605
+ /** Faza 4 stage: insert the target-version key for every remaining holder. */
1606
+ stageCollectionRotation(orgId, cid, body) {
1607
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/rotate/stage`, {
1608
+ method: "POST",
1609
+ body: JSON.stringify(body)
1610
+ });
1611
+ }
1612
+ /** Faza 4 commit: apply one chunk (≤500) of re-encrypted entries. */
1613
+ commitCollectionRotation(orgId, cid, body) {
1614
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/rotate/commit`, {
1615
+ method: "POST",
1616
+ body: JSON.stringify(body)
1617
+ });
1618
+ }
1619
+ /** Faza 4 complete: sweep old key versions once all entries are on target.
1620
+ * `completed:false` means NOT actually done — `already` = this rotation was a
1621
+ * prior no-op retry, `stale` = a NEWER rotation debt appeared meanwhile (caller
1622
+ * must re-fetch + re-derive rotation_required from the server, never assume done). */
1623
+ completeCollectionRotation(orgId, cid, keyVersion) {
1624
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/rotate/complete`, {
1625
+ method: "POST",
1626
+ body: JSON.stringify({ key_version: keyVersion })
1627
+ });
1628
+ }
1629
+ /** Owner-override: clear the collection's rotation_required flag WITHOUT
1630
+ * rotating the key (residual exposure explicitly accepted; audited). */
1631
+ resetCollectionRotation(orgId, cid) {
1632
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/rotation-reset`, {
1633
+ method: "POST"
1634
+ });
1635
+ }
1636
+ updateCollectionMemberPermissions(orgId, cid, uid, perms) {
1637
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/members/${encodeURIComponent(uid)}/permissions`, {
1638
+ method: "PATCH",
1639
+ body: JSON.stringify(perms)
1640
+ });
1641
+ }
1642
+ // ── Collection-scope data grants (F4 Rez 1d B2) ────────────────────────────
1643
+ /** Effective access for the "Pristup" tab: grant subjects + key-holders. */
1644
+ getCollectionAccess(orgId, cid) {
1645
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/access`, { method: "GET" });
1646
+ }
1647
+ /** List collection-scope grants (one row per subject × capability). */
1648
+ getCollectionGrants(orgId, cid) {
1649
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/grants`, { method: "GET" });
1650
+ }
1651
+ /** Create a collection-scope data grant + eager key-wrap fan-out (ZK: keys are
1652
+ * wrapped in the browser and delivered as wrapped_keys). */
1653
+ createCollectionGrant(orgId, cid, body) {
1654
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/grants`, {
1655
+ method: "POST",
1656
+ body: JSON.stringify(body)
1657
+ });
1658
+ }
1659
+ /** Revoke a grant; server severs orphaned keys + flags rotation as needed. */
1660
+ deleteCollectionGrant(orgId, cid, grantId) {
1661
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/grants/${encodeURIComponent(grantId)}`, {
1662
+ method: "DELETE"
1663
+ });
1664
+ }
1665
+ /** Key-holder-driven pending → active: wrap the DEK for pending members. */
1666
+ reconcileCollectionKeys(orgId, cid, wrappedKeys) {
1667
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/reconcile-keys`, {
1668
+ method: "POST",
1669
+ body: JSON.stringify({ wrapped_keys: wrappedKeys })
1670
+ });
1671
+ }
1672
+ /** F4 Rez 1d C-B: set (REPLACE) per-member deny override on a collection.
1673
+ * Enterprise-gated server-side (403 without the per_member_override module).
1674
+ * Server severs the key + flags rotation only when 'view' is actually lost. */
1675
+ setCollectionMemberOverride(orgId, cid, uid, deniedCapabilities) {
1676
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/members/${encodeURIComponent(uid)}/overrides`, {
1677
+ method: "PUT",
1678
+ body: JSON.stringify({ denied_capabilities: deniedCapabilities })
1679
+ });
1680
+ }
1681
+ /** Clear a member's deny override (un-override). NOT entitlement-gated —
1682
+ * removing restrictions must stay available after a downgrade. */
1683
+ clearCollectionMemberOverride(orgId, cid, uid) {
1684
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/members/${encodeURIComponent(uid)}/overrides`, {
1685
+ method: "DELETE"
1686
+ });
1687
+ }
1688
+ /** Confirm a pending member — unconditional for every org type (no DEK-wrap
1689
+ * ceremony): flips the member active and joins them to "Svi članovi". Access
1690
+ * to the org's default collection is grant + reconcile-keys driven, same as
1691
+ * any other team_collection. `vault_id` in the response is always `null`. */
1692
+ confirmMember(orgId, memberId) {
1693
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/members/${encodeURIComponent(memberId)}/confirm`, {
1694
+ method: "POST",
1695
+ body: JSON.stringify({})
1696
+ });
1697
+ }
1698
+ // ── Offboarding + audit (T12) ──────────────────────────────────────────────
1699
+ /** All encrypted entries in a vault. Follows next_cursor pages until exhausted.
1700
+ * Concurrent calls for the same vaultId share one in-flight request so a
1701
+ * parallel listPersonalEntries + loadFolders pair only hits the network once.
1702
+ * Safety cap: aborts after 100 000 total entries to prevent unbounded loops. */
1703
+ async getVaultEntries(vaultId) {
1704
+ const cached = this._inflightEntries.get(vaultId);
1705
+ if (cached) return cached;
1706
+ const promise = this._paginateEntries(vaultId);
1707
+ this._inflightEntries.set(vaultId, promise);
1708
+ promise.finally(() => this._inflightEntries.delete(vaultId));
1709
+ return promise;
1710
+ }
1711
+ async _paginateEntries(vaultId) {
1712
+ const PAGE_LIMIT = 1e3;
1713
+ const MAX_ENTRIES = 1e5;
1714
+ const all = [];
1715
+ let cursor;
1716
+ while (all.length < MAX_ENTRIES) {
1717
+ const params = new URLSearchParams({ vault_id: vaultId, limit: String(PAGE_LIMIT) });
1718
+ if (cursor) params.set("cursor", cursor);
1719
+ const res = await this.request(
1720
+ `/v1/sync/entries?${params.toString()}`,
1721
+ { method: "GET" }
1722
+ );
1723
+ all.push(...res.entries);
1724
+ if (!res.next_cursor) break;
1725
+ cursor = res.next_cursor;
1726
+ }
1727
+ return all;
1728
+ }
1729
+ // ── Vault entry write (T14 — full editor; reuses existing sync endpoints) ────
1730
+ /** Ensure the caller's personal vault exists; returns id + whether it was just created
1731
+ * (is_new=true means first-ever or revival after erasure). */
1732
+ async ensurePersonalVault() {
1733
+ return this.request("/v1/sync/vault", {
1734
+ method: "POST",
1735
+ body: JSON.stringify({})
1736
+ });
1737
+ }
1738
+ /** Tombstone a collection or shared vault (DELETE /v1/sync/vault/:id).
1739
+ * Server sets vault.deleted_at + cascades to all entries. 400 if vault_type=personal. */
1740
+ deleteVault(vaultId) {
1741
+ return this.request(`/v1/sync/vault/${encodeURIComponent(vaultId)}`, {
1742
+ method: "DELETE"
1743
+ });
1744
+ }
1745
+ /** Soft-delete all entries in a vault without touching the vault row itself.
1746
+ * Use for personal vault "wipe cloud, keep local" — vault_id stays stable.
1747
+ * auth_hash: re-derived master-password hash for server-side re-auth (same as purgeCloudData). */
1748
+ clearVaultEntries(vaultId, authHash) {
1749
+ return this.request(
1750
+ `/v1/sync/vault/${encodeURIComponent(vaultId)}/clear-entries`,
1751
+ {
1752
+ method: "POST",
1753
+ body: authHash ? JSON.stringify({ auth_hash: authHash }) : JSON.stringify({})
1754
+ }
1755
+ );
1756
+ }
1757
+ /** Pull vault tombstones (vaults deleted since `since`). Suite uses this to evict
1758
+ * deleted collections/shared vaults from the UI without requiring re-login. */
1759
+ getVaultTombstones(since) {
1760
+ const q = since ? `?since=${encodeURIComponent(since)}` : "";
1761
+ return this.request(
1762
+ `/v1/sync/vault-tombstones${q}`,
1763
+ { method: "GET" }
1764
+ );
1765
+ }
1766
+ /**
1767
+ * Upsert a single encrypted entry (create when expected_version=0, else update
1768
+ * with optimistic concurrency). The server stores opaque blobs only — all crypto
1769
+ * happens in the browser. Returns the new server version, or a conflict.
1770
+ */
1771
+ async putEntry(entryId, args) {
1772
+ try {
1773
+ return await this.request(`/v1/sync/entries/${encodeURIComponent(entryId)}`, {
1774
+ method: "PUT",
1775
+ body: JSON.stringify({
1776
+ vault_id: args.vaultId,
1777
+ entry_type: args.entryType,
1778
+ encrypted_blob: args.encryptedBlob,
1779
+ blob_hash: args.blobHash,
1780
+ expected_version: args.expectedVersion,
1781
+ // F4 Rez 1d-B Faza 3: envelope-tag DEK-a kojim je blob enkriptiran.
1782
+ // Izostavljeno = server grace-taga (stari klijenti).
1783
+ ...args.keyVersion !== void 0 ? { key_version: args.keyVersion } : {}
1784
+ })
1785
+ });
1786
+ } catch (e) {
1787
+ return asConflict(e);
1788
+ }
1789
+ }
1790
+ /** Soft-delete a single entry (optimistic concurrency on expected_version). */
1791
+ async deleteEntry(entryId, args) {
1792
+ try {
1793
+ return await this.request(`/v1/sync/entries/${encodeURIComponent(entryId)}`, {
1794
+ method: "DELETE",
1795
+ body: JSON.stringify({ vault_id: args.vaultId, expected_version: args.expectedVersion })
1796
+ });
1797
+ } catch (e) {
1798
+ return asConflict(e);
1799
+ }
1800
+ }
1801
+ /**
1802
+ * Batch push (up to 500 ops). 200 = all OK, 207 = partial (some conflicts).
1803
+ * For delete ops: { op: 'delete', id, expected_version }.
1804
+ * For upsert ops: { op: 'upsert', id, entry_type, encrypted_blob, blob_hash, expected_version }.
1805
+ */
1806
+ async batchEntries(vaultId, operations) {
1807
+ return this.request("/v1/sync/entries/batch", {
1808
+ method: "POST",
1809
+ body: JSON.stringify({ vault_id: vaultId, operations })
1810
+ });
1811
+ }
1812
+ /** Remove a member. "Škrinja je Škrinja" unification: no client-side DEK
1813
+ * rotation anymore — the server flags any team_collection the member held a
1814
+ * key on (rotation_required); an existing key-holder rotates it later via
1815
+ * the staged /collections/:cid/rotate flow. */
1816
+ removeMember(orgId, memberId) {
1817
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/members/${encodeURIComponent(memberId)}/remove`, {
1818
+ method: "POST",
1819
+ body: JSON.stringify({})
1820
+ });
1821
+ }
1822
+ /** Leave an org. 'delete' starts the grace→purge on the caller's personal cloud. */
1823
+ leaveOrg(orgId, memberId, choice) {
1824
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/members/${encodeURIComponent(memberId)}/leave`, {
1825
+ method: "POST",
1826
+ body: JSON.stringify({ choice })
1827
+ });
1828
+ }
1829
+ /** Owner cancels a shared plan WITH members (danger zone). */
1830
+ cancelOrg(orgId) {
1831
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/cancel`, {
1832
+ method: "POST",
1833
+ body: JSON.stringify({ confirm: true })
1834
+ });
1835
+ }
1836
+ setOrgRequire2fa(orgId, enabled) {
1837
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/settings/require-member-2fa`, {
1838
+ method: "PATCH",
1839
+ body: JSON.stringify({ enabled })
1840
+ });
1841
+ }
1842
+ setOrgClipboardClearPolicy(orgId, enabled, seconds) {
1843
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/settings/clipboard-clear-policy`, {
1844
+ method: "PUT",
1845
+ body: JSON.stringify({ enabled, seconds })
1846
+ });
1847
+ }
1848
+ unsetOrgClipboardClearPolicy(orgId) {
1849
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/settings/clipboard-clear-policy`, {
1850
+ method: "DELETE"
1851
+ });
1852
+ }
1853
+ /** F2 — owner/admin resets a member's 2FA (login-factor only; server enforces the
1854
+ * manage_member_2fa capability + escalation guard). No body. */
1855
+ resetMemberMfa(orgId, memberId) {
1856
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/members/${encodeURIComponent(memberId)}/mfa`, {
1857
+ method: "DELETE"
1858
+ });
1859
+ }
1860
+ /** F3b — owner/admin sets (exempt=true → PUT) or clears (exempt=false → DELETE) a
1861
+ * member's exemption from the org's require_member_2fa policy. Server enforces the
1862
+ * manage_org capability + self-block + owner-rank guard. */
1863
+ setMemberMfaExemption(orgId, memberId, exempt) {
1864
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/members/${encodeURIComponent(memberId)}/mfa-exemption`, {
1865
+ method: exempt ? "PUT" : "DELETE"
1866
+ });
1867
+ }
1868
+ /** Append an access record (reference only — never the plaintext). */
1869
+ logCredentialAccess(args) {
1870
+ return this.request("/v1/credential-access", {
1871
+ method: "POST",
1872
+ body: JSON.stringify({ org_id: args.orgId, entry_id: args.entryId, vault_id: args.vaultId, action: args.action })
1873
+ });
1874
+ }
1875
+ /** Entries a member has revealed/copied/autofilled — drives guided rotation. */
1876
+ getPasswordsKnownBy(orgId, userId) {
1877
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/audit/passwords-known-by/${encodeURIComponent(userId)}`, { method: "GET" });
1878
+ }
1879
+ /** Per-active-member count of entries they revealed/copied/autofilled. Business+ only. */
1880
+ getExposureSummary(orgId) {
1881
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/audit/exposure-summary`, { method: "GET" });
1882
+ }
1883
+ /** Who touched a given entry (access feed). Cursor-paginated (Faza A). */
1884
+ getCredentialAudit(orgId, entryId, cursor) {
1885
+ const q = new URLSearchParams();
1886
+ if (cursor) {
1887
+ q.set("before_ts", cursor.before_ts);
1888
+ q.set("before_id", String(cursor.before_id));
1889
+ }
1890
+ const qs = q.toString();
1891
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/audit/credential/${encodeURIComponent(entryId)}${qs ? `?${qs}` : ""}`, { method: "GET" });
1892
+ }
1893
+ /** The caller's own general audit log (GET /v1/audit). Per-user, not org-wide —
1894
+ * surfaces the signed-in admin's security-relevant events (DEK rotations,
1895
+ * failed logins, membership changes) for the dashboard. */
1896
+ getAudit(params) {
1897
+ const q = new URLSearchParams();
1898
+ if (params?.limit) q.set("limit", String(params.limit));
1899
+ if (params?.action) q.set("action", params.action);
1900
+ if (params?.since) q.set("since", params.since);
1901
+ const qs = q.toString();
1902
+ return this.request(`/v1/audit${qs ? `?${qs}` : ""}`, { method: "GET" });
1903
+ }
1904
+ /** Cross-tenant search: orgs and collections matching the query. MSP use case. */
1905
+ searchTenants(q) {
1906
+ const params = new URLSearchParams({ q });
1907
+ return this.request(`/v1/search/tenants?${params.toString()}`, { method: "GET" });
1908
+ }
1909
+ // ── Devices / sessions (K4) ─────────────────────────────────────────────────
1910
+ /** Registered devices/sessions for the signed-in user. */
1911
+ async getDevices() {
1912
+ const res = await this.request("/v1/devices", { method: "GET" });
1913
+ return res.devices;
1914
+ }
1915
+ /** Revoke a single device (deletes its refresh tokens). */
1916
+ revokeDevice(deviceId) {
1917
+ return this.request(`/v1/devices/${encodeURIComponent(deviceId)}`, { method: "DELETE" });
1918
+ }
1919
+ /** Panic button — revoke every device except the current one. */
1920
+ revokeOtherDevices() {
1921
+ return this.request("/v1/devices", { method: "DELETE" });
1922
+ }
1923
+ // ── Account erasure (K4 — GDPR art. 17) ──────────────────────────────────────
1924
+ /** Current scheduled-deletion state (none → all-null shape). */
1925
+ getDeletionStatus() {
1926
+ return this.request("/v1/account/deletion-status", { method: "GET" });
1927
+ }
1928
+ /**
1929
+ * Request erasure of the account (30-day grace). `masterPasswordHash` is the
1930
+ * SAME auth_hash sent at login (re-derived in the browser from the master
1931
+ * password the user re-enters) — the server verifies it before scheduling.
1932
+ */
1933
+ requestAccountErasure(masterPasswordHash) {
1934
+ return this.request("/v1/account/data-erasure-confirm", {
1935
+ method: "POST",
1936
+ body: JSON.stringify({ confirmation: ERASURE_CONFIRMATION, master_password_hash: masterPasswordHash })
1937
+ });
1938
+ }
1939
+ /** Cancel a scheduled deletion during the grace period. */
1940
+ cancelAccountDeletion() {
1941
+ return this.request("/v1/auth/account/cancel-deletion", { method: "POST" });
1942
+ }
1943
+ /** GDPR Art. 20 — request full account data export. Backend queues a ZIP
1944
+ * and sends a download link via email when ready. Rate-limited to 1×/24h
1945
+ * (429 with Retry-After if called again within the window). */
1946
+ requestDataExport() {
1947
+ return this.request("/v1/account/data-export", { method: "GET" });
1948
+ }
1949
+ /**
1950
+ * Self-serve "wipe cloud data only" — purges the cloud copy of the caller's
1951
+ * PERSONAL org (local vault untouched). Re-auth: auth_hash re-derived in the
1952
+ * browser, the master password never leaves the device.
1953
+ */
1954
+ purgeCloudData(authHash) {
1955
+ return this.request("/v1/account/purge-cloud-data", {
1956
+ method: "POST",
1957
+ body: JSON.stringify({ auth_hash: authHash })
1958
+ });
1959
+ }
1960
+ /** Rename an organization (owner-only server-side). Returns the saved name. */
1961
+ renameOrg(orgId, name) {
1962
+ return this.request(`/v1/orgs/${orgId}`, {
1963
+ method: "PATCH",
1964
+ body: JSON.stringify({ name })
1965
+ });
1966
+ }
1967
+ // ── ECDH migration (T10/K5 — placeholder v0 → real X25519 v1) ─────────────────
1968
+ /**
1969
+ * Upload a real X25519 public key + its master-key-wrapped private key during
1970
+ * the placeholder→real migration; the server sets ecdh_key_version = 1. SAME
1971
+ * route the extension's T10 migration uses (PUT /v1/account/ecdh-public-key) —
1972
+ * identical envelope ⇒ cross-client parity.
1973
+ */
1974
+ updateEcdhPublicKey(ecdhPublicKey, encryptedEcdhPrivateKey) {
1975
+ return this.request("/v1/account/ecdh-public-key", {
1976
+ method: "PUT",
1977
+ body: JSON.stringify({ ecdh_public_key: ecdhPublicKey, encrypted_ecdh_private_key: encryptedEcdhPrivateKey })
1978
+ });
1979
+ }
1980
+ // ── Master password change (K4b) ──────────────────────────────────────────
1981
+ /**
1982
+ * Rotate the master password (user knows the current one). All crypto happens
1983
+ * in the browser: the caller re-wraps the unchanged vault_key + ECDH private key
1984
+ * under the new master_key and passes the opaque blobs here. The server re-checks
1985
+ * `current_auth_hash`, rotates the credentials, revokes every other session and
1986
+ * re-issues this device's tokens — which we adopt so the session stays live.
1987
+ */
1988
+ async changeMasterPassword(params) {
1989
+ const body = await this.request(
1990
+ "/v1/account/change-master-password",
1991
+ { method: "POST", body: JSON.stringify(params) }
1992
+ );
1993
+ this.tokens.set({ access_token: body.access_token, refresh_token: body.refresh_token });
1994
+ return { success: body.success, enc_salt: body.enc_salt };
1995
+ }
1996
+ // ── Account profile + email change (#34) ──────────────────────────────────
1997
+ /** Set or clear the optional display name. Returns the stored value. */
1998
+ updateProfile(displayName) {
1999
+ return this.request("/v1/account/profile", {
2000
+ method: "PATCH",
2001
+ body: JSON.stringify({ display_name: displayName })
2002
+ });
2003
+ }
2004
+ /**
2005
+ * Begin an email change: step-up re-verifies the current master password
2006
+ * (`current_auth_hash`, re-derived in the browser), then the server mails a
2007
+ * 6-digit code to the NEW address and an alert to the OLD one. enc_salt/auth_hash
2008
+ * are untouched — the email is not part of the KDF.
2009
+ */
2010
+ changeEmailInit(newEmail, currentAuthHash) {
2011
+ return this.request("/v1/account/change-email/init", {
2012
+ method: "POST",
2013
+ body: JSON.stringify({ new_email: newEmail, current_auth_hash: currentAuthHash })
2014
+ });
2015
+ }
2016
+ /** Confirm the email change with the 6-digit code; returns the new email. */
2017
+ changeEmailConfirm(code) {
2018
+ return this.request("/v1/account/change-email/confirm", {
2019
+ method: "POST",
2020
+ body: JSON.stringify({ code })
2021
+ });
2022
+ }
2023
+ // ── UI preferences ────────────────────────────────────────────────────────
2024
+ /** Fetch user's stored UI preferences (e.g. dashboard_layout). */
2025
+ getUserPreferences() {
2026
+ return this.request("/v1/account/preferences", { method: "GET" });
2027
+ }
2028
+ /** Persist UI preferences (merged server-side). */
2029
+ updateUserPreferences(prefs) {
2030
+ return this.request("/v1/account/preferences", {
2031
+ method: "PUT",
2032
+ body: JSON.stringify(prefs)
2033
+ });
2034
+ }
2035
+ /** Patch site-icon display preferences. */
2036
+ updateSiteIconPrefs(patch) {
2037
+ return this.request("/v1/users/me/preferences", {
2038
+ method: "PATCH",
2039
+ body: JSON.stringify(patch)
2040
+ });
2041
+ }
2042
+ /** Patch clipboard-auto-clear personal preferences. No-op fields are omitted from the body. */
2043
+ updateClipboardClearPrefs(patch) {
2044
+ return this.request("/v1/users/me/preferences", {
2045
+ method: "PATCH",
2046
+ body: JSON.stringify(patch)
2047
+ });
2048
+ }
2049
+ // ── Offboarding reviews (#20) ──────────────────────────────────────────────
2050
+ /** Open offboarding reviews for the org (one header per departed member). */
2051
+ getOffboardReviews(orgId) {
2052
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/offboard-reviews`, { method: "GET" });
2053
+ }
2054
+ /** Cursor-paginated entries the departed member had revealed/copied. */
2055
+ getOffboardSeen(orgId, userId, params) {
2056
+ const q = new URLSearchParams();
2057
+ if (params?.limit) q.set("limit", String(params.limit));
2058
+ if (params?.sort) q.set("sort", params.sort);
2059
+ if (params?.before_ts) q.set("before_ts", params.before_ts);
2060
+ if (params?.before_entry_id) q.set("before_entry_id", params.before_entry_id);
2061
+ if (params?.before_high_risk !== void 0) q.set("before_high_risk", String(params.before_high_risk));
2062
+ const qs = q.toString();
2063
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/offboard-reviews/${encodeURIComponent(userId)}/seen${qs ? `?${qs}` : ""}`, { method: "GET" });
2064
+ }
2065
+ /** Shared vault entries the departed member had access to. */
2066
+ getOffboardAccess(orgId, userId, params) {
2067
+ const q = new URLSearchParams();
2068
+ if (params?.limit) q.set("limit", String(params.limit));
2069
+ if (params?.before_ts) q.set("before_ts", params.before_ts);
2070
+ if (params?.before_entry_id) q.set("before_entry_id", params.before_entry_id);
2071
+ const qs = q.toString();
2072
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/offboard-reviews/${encodeURIComponent(userId)}/access${qs ? `?${qs}` : ""}`, { method: "GET" });
2073
+ }
2074
+ /** Upsert a review item status (rotated | reviewed). */
2075
+ patchOffboardItem(orgId, userId, entryId, status) {
2076
+ return this.request(
2077
+ `/v1/orgs/${encodeURIComponent(orgId)}/offboard-reviews/${encodeURIComponent(userId)}/items/${encodeURIComponent(entryId)}`,
2078
+ { method: "PATCH", body: JSON.stringify({ status }) }
2079
+ );
2080
+ }
2081
+ /** Close the offboarding review for a departed member. */
2082
+ closeOffboardReview(orgId, userId) {
2083
+ return this.request(
2084
+ `/v1/orgs/${encodeURIComponent(orgId)}/offboard-reviews/${encodeURIComponent(userId)}/close`,
2085
+ { method: "POST" }
2086
+ );
2087
+ }
2088
+ // ── RBAC: Permission Levels, Security Groups, Grants (Rez 1c) ─────────────
2089
+ getRoles(orgId) {
2090
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/roles`, { method: "GET" });
2091
+ }
2092
+ createRole(orgId, body) {
2093
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/roles`, {
2094
+ method: "POST",
2095
+ body: JSON.stringify(body)
2096
+ });
2097
+ }
2098
+ updateRole(orgId, roleId, body) {
2099
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/roles/${encodeURIComponent(roleId)}`, {
2100
+ method: "PATCH",
2101
+ body: JSON.stringify(body)
2102
+ });
2103
+ }
2104
+ deleteRole(orgId, roleId) {
2105
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/roles/${encodeURIComponent(roleId)}`, { method: "DELETE" });
2106
+ }
2107
+ getGroups(orgId) {
2108
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/groups`, { method: "GET" });
2109
+ }
2110
+ createGroup(orgId, body) {
2111
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/groups`, {
2112
+ method: "POST",
2113
+ body: JSON.stringify(body)
2114
+ });
2115
+ }
2116
+ updateGroup(orgId, gid, body) {
2117
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/groups/${encodeURIComponent(gid)}`, {
2118
+ method: "PATCH",
2119
+ body: JSON.stringify(body)
2120
+ });
2121
+ }
2122
+ deleteGroup(orgId, gid) {
2123
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/groups/${encodeURIComponent(gid)}`, { method: "DELETE" });
2124
+ }
2125
+ getGroupMembers(orgId, gid) {
2126
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/groups/${encodeURIComponent(gid)}/members`, { method: "GET" });
2127
+ }
2128
+ /** F4 Rez 2 Faza 1: collections a group holds a grant on (group-inheritance fan-out). */
2129
+ getGroupCollections(orgId, gid) {
2130
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/groups/${encodeURIComponent(gid)}/collections`, { method: "GET" });
2131
+ }
2132
+ addGroupMember(orgId, gid, userId) {
2133
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/groups/${encodeURIComponent(gid)}/members`, {
2134
+ method: "POST",
2135
+ body: JSON.stringify({ user_id: userId })
2136
+ });
2137
+ }
2138
+ removeGroupMember(orgId, gid, userId) {
2139
+ return this.request(
2140
+ `/v1/orgs/${encodeURIComponent(orgId)}/groups/${encodeURIComponent(gid)}/members/${encodeURIComponent(userId)}`,
2141
+ { method: "DELETE" }
2142
+ );
2143
+ }
2144
+ getGrants(orgId) {
2145
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/grants`, { method: "GET" });
2146
+ }
2147
+ createGrant(orgId, body) {
2148
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/grants`, {
2149
+ method: "POST",
2150
+ body: JSON.stringify(body)
2151
+ });
2152
+ }
2153
+ deleteGrant(orgId, grantId) {
2154
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/grants/${encodeURIComponent(grantId)}`, { method: "DELETE" });
2155
+ }
2156
+ getCapabilities(orgId) {
2157
+ return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/capabilities`, { method: "GET" });
2158
+ }
2159
+ // ── Internals ─────────────────────────────────────────────────────────────
2160
+ async request(path, init, isRetry = false) {
2161
+ const headers = new Headers(init.headers);
2162
+ if (init.body) headers.set("Content-Type", "application/json");
2163
+ const access = this.tokens.get()?.access_token;
2164
+ if (access) headers.set("Authorization", `Bearer ${access}`);
2165
+ const res = await this.doFetch(`${this.baseUrl}${path}`, {
2166
+ ...init,
2167
+ headers,
2168
+ ...this.credentials ? { credentials: this.credentials } : {}
2169
+ });
2170
+ if (res.status === 401 && !isRetry && (this.tokens.get()?.refresh_token || this.cookieMode)) {
2171
+ if (await this.tryRefresh()) return this.request(path, init, true);
2172
+ this.tokens.set(null);
2173
+ }
2174
+ const text = await res.text();
2175
+ const data = text ? JSON.parse(text) : null;
2176
+ if (!res.ok) {
2177
+ const body = data ?? {};
2178
+ throw new ApiError(res.status, body.detail ?? body.title ?? body.message ?? `API error ${res.status}`, body.code, body);
2179
+ }
2180
+ return data;
2181
+ }
2182
+ tryRefresh() {
2183
+ if (this.refreshing) return this.refreshing;
2184
+ this.refreshing = this.doRefresh().finally(() => {
2185
+ this.refreshing = null;
2186
+ });
2187
+ return this.refreshing;
2188
+ }
2189
+ // ── Token refresh (internal) ──────────────────────────────────────────────
2190
+ async doRefresh() {
2191
+ const current = this.tokens.get();
2192
+ if (!current?.refresh_token && !this.cookieMode) return false;
2193
+ const controller = new AbortController();
2194
+ const timer = setTimeout(() => controller.abort(), REFRESH_TIMEOUT_MS);
2195
+ try {
2196
+ const headers = { "Content-Type": "application/json" };
2197
+ if (current?.access_token) headers["Authorization"] = `Bearer ${current.access_token}`;
2198
+ const res = await this.doFetch(`${this.baseUrl}/v1/auth/refresh`, {
2199
+ method: "POST",
2200
+ headers,
2201
+ body: JSON.stringify(current?.refresh_token ? { refresh_token: current.refresh_token } : {}),
2202
+ signal: controller.signal,
2203
+ ...this.credentials ? { credentials: this.credentials } : {}
2204
+ });
2205
+ if (!res.ok) {
2206
+ if (typeof console !== "undefined") console.warn(`[auth] refresh failed: ${res.status}`);
2207
+ return false;
2208
+ }
2209
+ const data = await res.json();
2210
+ this.tokens.set({ access_token: data.access_token, refresh_token: data.refresh_token });
2211
+ return true;
2212
+ } catch (e) {
2213
+ if (typeof console !== "undefined") console.warn("[auth] refresh error", e);
2214
+ return false;
2215
+ } finally {
2216
+ clearTimeout(timer);
2217
+ }
2218
+ }
2219
+ };
2220
+
2221
+ // ../../packages/core/src/entitlements/index.ts
2222
+ function planOf(bundle) {
2223
+ const raw = bundle?.primary_org?.plan_slug ?? "free";
2224
+ if (raw === "trial") return "premium";
2225
+ if (raw === "trial_expired") return "free";
2226
+ return raw;
2227
+ }
2228
+ function hasFeature(bundle, key) {
2229
+ const f = bundle?.features?.[key];
2230
+ if (f === true) return true;
2231
+ if (f && typeof f === "object") return f.enabled === true;
2232
+ return false;
2233
+ }
2234
+
2235
+ // ../../packages/core/src/pdp.ts
2236
+ var PDP_REASON = {
2237
+ FORBIDDEN: "pdp/forbidden",
2238
+ ACCOUNT_INACTIVE: "pdp/account-inactive",
2239
+ EMAIL_UNVERIFIED: "pdp/email-unverified",
2240
+ MFA_SETUP_REQUIRED: "pdp/mfa-setup-required",
2241
+ SCOPE_INSUFFICIENT: "pdp/scope-insufficient",
2242
+ PLAN_REQUIRED: "pdp/plan-required",
2243
+ CAPABILITY_DENIED: "pdp/capability-denied",
2244
+ ORG_TYPE_RESTRICTION: "pdp/org-type-restriction"
2245
+ };
2246
+ var _PDP_CODES = new Set(Object.values(PDP_REASON));
2247
+
2248
+ // ../../packages/core/src/security/health.ts
2249
+ var OLD_THRESHOLD_MS = 365 * 24 * 60 * 60 * 1e3;
2250
+
2251
+ // src/lib/core.ts
2252
+ function buildApiClient(baseUrl, tokenStore) {
2253
+ return new ApiClient({ baseUrl, tokenStore });
2254
+ }
2255
+
2256
+ // src/commands/whoami.ts
2257
+ async function whoamiCommand() {
2258
+ const backend = await selectBackend();
2259
+ const tokenStore = await createCliTokenStore(backend);
2260
+ const tokens = tokenStore.get();
2261
+ if (!tokens) {
2262
+ printErr("not signed in \u2014 run `geslar signin`");
2263
+ return EXIT.AUTH;
2264
+ }
2265
+ const session = await loadSession();
2266
+ const config = await loadOrInitConfig();
2267
+ const baseUrl = session?.apiBase ?? config.apiBase;
2268
+ const api = buildApiClient(baseUrl, tokenStore);
2269
+ try {
2270
+ const entitlements = await api.getEntitlements();
2271
+ await tokenStore.flush();
2272
+ const plan = planOf(entitlements);
2273
+ const org = entitlements.primary_org;
2274
+ print(`Account: ${session?.email ?? "(unknown \u2014 re-run `geslar signin`)"}`);
2275
+ print(`Plan: ${plan}`);
2276
+ if (org?.id) {
2277
+ print(`Org: ${org.id}${org.role ? ` (${org.role})` : ""}`);
2278
+ }
2279
+ print(`API: ${baseUrl}`);
2280
+ print(`Storage: ${backend.name}`);
2281
+ return EXIT.OK;
2282
+ } catch (err) {
2283
+ await tokenStore.flush();
2284
+ if (err instanceof ApiError && (err.status === 401 || err.status === 403)) {
2285
+ printErr("session expired \u2014 run `geslar signin` again");
2286
+ return EXIT.AUTH;
2287
+ }
2288
+ printErr(err.message);
2289
+ return EXIT.GENERAL;
2290
+ }
2291
+ }
2292
+
2293
+ // src/lib/prompt.ts
2294
+ var CTRL_C = "";
2295
+ var CTRL_D = "";
2296
+ var BACKSPACE = "\x7F";
2297
+ function promptPassword(promptText) {
2298
+ return new Promise((resolve, reject) => {
2299
+ if (!process.stdin.isTTY) {
2300
+ reject(new CliError(EXIT.VAULT_LOCKED, "No TTY available for a master-password prompt \u2014 run `geslar unlock` first"));
2301
+ return;
2302
+ }
2303
+ process.stdout.write(promptText);
2304
+ const stdin = process.stdin;
2305
+ stdin.setRawMode(true);
2306
+ stdin.resume();
2307
+ stdin.setEncoding("utf8");
2308
+ let input = "";
2309
+ const onData = (chunk) => {
2310
+ const char = chunk.toString();
2311
+ if (char === "\n" || char === "\r" || char === CTRL_D) {
2312
+ cleanup();
2313
+ process.stdout.write("\n");
2314
+ resolve(input);
2315
+ return;
2316
+ }
2317
+ if (char === CTRL_C) {
2318
+ cleanup();
2319
+ process.stdout.write("\n");
2320
+ reject(new CliError(EXIT.GENERAL, "Aborted"));
2321
+ return;
2322
+ }
2323
+ if (char === BACKSPACE || char === "\b") {
2324
+ input = input.slice(0, -1);
2325
+ return;
2326
+ }
2327
+ input += char;
2328
+ };
2329
+ function cleanup() {
2330
+ stdin.setRawMode(false);
2331
+ stdin.pause();
2332
+ stdin.removeListener("data", onData);
2333
+ }
2334
+ stdin.on("data", onData);
2335
+ });
2336
+ }
2337
+
2338
+ // ../../packages/core/src/crypto/index.mjs
2339
+ var import_vault_crypto = __toESM(require_vault_crypto(), 1);
2340
+ var import_vault_cloud_crypto = __toESM(require_vault_cloud_crypto(), 1);
2341
+ var import_recovery_enrollment = __toESM(require_recovery_enrollment(), 1);
2342
+ globalThis.VaultCrypto = import_vault_crypto.default;
2343
+
2344
+ // src/vault/unlock.ts
2345
+ var WrongMasterPasswordError = class extends Error {
2346
+ constructor() {
2347
+ super("Incorrect master password");
2348
+ this.name = "WrongMasterPasswordError";
2349
+ }
2350
+ };
2351
+ async function deriveAndUnlock(password, material) {
2352
+ if (!material.encrypted_vault_key) {
2353
+ throw new Error("This account has no vault key yet \u2014 sign in via the console first to finish setup.");
2354
+ }
2355
+ const salt = import_vault_crypto.default.base64ToBuf(material.enc_salt);
2356
+ const masterKey = await import_vault_crypto.default.deriveMasterKey(password, salt);
2357
+ let dekRaw;
2358
+ try {
2359
+ dekRaw = await import_vault_cloud_crypto.default.unwrapVaultKey(masterKey, material.encrypted_vault_key);
2360
+ } catch {
2361
+ throw new WrongMasterPasswordError();
2362
+ }
2363
+ let ecdhPrivRaw = null;
2364
+ if (material.encrypted_ecdh_private_key) {
2365
+ ecdhPrivRaw = await import_vault_cloud_crypto.default.unwrapVaultKey(masterKey, material.encrypted_ecdh_private_key);
2366
+ }
2367
+ return { dekRaw, ecdhPrivRaw };
2368
+ }
2369
+
2370
+ // src/commands/unlock.ts
2371
+ async function unlockCommand(opts) {
2372
+ try {
2373
+ const ttlSec = parseTtl(opts.ttl);
2374
+ const config = await loadOrInitConfig();
2375
+ const session = await loadSession();
2376
+ const baseUrl = session?.apiBase ?? config.apiBase;
2377
+ const backend = await selectBackend();
2378
+ const tokenStore = await createCliTokenStore(backend);
2379
+ if (!tokenStore.get()) {
2380
+ printErr("not signed in \u2014 run `geslar signin`");
2381
+ return EXIT.AUTH;
2382
+ }
2383
+ const api = buildApiClient(baseUrl, tokenStore);
2384
+ const material = await api.getVaultKeyMaterial();
2385
+ await tokenStore.flush();
2386
+ const password = await promptPassword("Master password: ");
2387
+ const unlocked = await deriveAndUnlock(password, material);
2388
+ await saveVaultGrant(unlocked, ttlSec);
2389
+ const mins = Math.round(ttlSec / 60);
2390
+ print(`Vault unlocked for ${mins} minute${mins === 1 ? "" : "s"}.`);
2391
+ return EXIT.OK;
2392
+ } catch (err) {
2393
+ if (err instanceof CliError) {
2394
+ printErr(err.message);
2395
+ return err.exitCode;
2396
+ }
2397
+ printErr(err.message);
2398
+ return EXIT.GENERAL;
2399
+ }
2400
+ }
2401
+
2402
+ // src/commands/lock.ts
2403
+ async function lockCommand() {
2404
+ await clearVaultGrant();
2405
+ print("Vault locked.");
2406
+ return EXIT.OK;
2407
+ }
2408
+
2409
+ // src/vault/session.ts
2410
+ async function obtainUnlockedKeys(api) {
2411
+ const grant = await loadVaultGrant();
2412
+ if (grant) return grant;
2413
+ if (!process.stdin.isTTY) {
2414
+ throw new CliError(EXIT.VAULT_LOCKED, "Vault is locked and no TTY is available \u2014 run `geslar unlock` first");
2415
+ }
2416
+ const material = await api.getVaultKeyMaterial();
2417
+ const password = await promptPassword("Master password: ");
2418
+ return deriveAndUnlock(password, material);
2419
+ }
2420
+
2421
+ // src/vault/vaults.ts
2422
+ var PERSONAL_VAULT_NAME = "Osobno";
2423
+ async function buildCollectionDekMap(keys, fallback, ecdhPrivRaw) {
2424
+ const source = keys && keys.length > 0 ? keys.map((k) => ({ key_version: k.key_version, encrypted_key: k.encrypted_key, ecdh_public_key: k.wrapped_by?.ecdh_public_key ?? null })) : fallback ? [{ key_version: fallback.key_version, encrypted_key: fallback.encrypted_key, ecdh_public_key: fallback.wrapper_ecdh_pub }] : [];
2425
+ const map = /* @__PURE__ */ new Map();
2426
+ for (const k of source) {
2427
+ if (!k.encrypted_key || !k.ecdh_public_key) continue;
2428
+ const wrapperPub = import_vault_crypto.default.base64ToBuf(k.ecdh_public_key);
2429
+ const dekRaw = await import_vault_cloud_crypto.default.unwrapSharedVaultKey(ecdhPrivRaw, wrapperPub, k.encrypted_key);
2430
+ map.set(k.key_version, await import_vault_cloud_crypto.default.importVaultKey(dekRaw));
2431
+ }
2432
+ return map;
2433
+ }
2434
+ async function listVaultHandles(api, unlocked) {
2435
+ const handles = [];
2436
+ const personal = await api.ensurePersonalVault();
2437
+ handles.push({
2438
+ id: personal.vault_id,
2439
+ name: PERSONAL_VAULT_NAME,
2440
+ kind: "personal",
2441
+ orgId: null,
2442
+ orgType: null,
2443
+ isDefault: true,
2444
+ dekMap: /* @__PURE__ */ new Map([[1, await import_vault_cloud_crypto.default.importVaultKey(unlocked.dekRaw)]])
2445
+ });
2446
+ if (unlocked.ecdhPrivRaw) {
2447
+ const [{ collections }, orgs] = await Promise.all([api.getCollections(), api.getOrgs()]);
2448
+ const orgTypeById = new Map(orgs.map((o) => [o.id, o.type]));
2449
+ for (const c of collections) {
2450
+ if (!c.can_view || !c.name) continue;
2451
+ const isDefault = c.is_default === true;
2452
+ const name = isDefault ? c.org_name ?? c.name : c.name;
2453
+ const dekMap = await buildCollectionDekMap(
2454
+ c.keys,
2455
+ { key_version: c.key_version, encrypted_key: c.encrypted_key, wrapper_ecdh_pub: c.wrapper_ecdh_pub },
2456
+ unlocked.ecdhPrivRaw
2457
+ );
2458
+ if (dekMap.size === 0) continue;
2459
+ handles.push({
2460
+ id: c.vault_id,
2461
+ name,
2462
+ kind: "collection",
2463
+ orgId: c.org_id,
2464
+ orgType: c.org_id ? orgTypeById.get(c.org_id) ?? null : null,
2465
+ isDefault,
2466
+ dekMap
2467
+ });
2468
+ }
2469
+ }
2470
+ return handles;
2471
+ }
2472
+
2473
+ // src/vault/totp.ts
2474
+ var B32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
2475
+ function base32Decode(input) {
2476
+ const clean = input.replace(/[\s=]/g, "").toUpperCase();
2477
+ let bits = 0;
2478
+ let value = 0;
2479
+ const out = [];
2480
+ for (const ch of clean) {
2481
+ const idx = B32.indexOf(ch);
2482
+ if (idx === -1) continue;
2483
+ value = value << 5 | idx;
2484
+ bits += 5;
2485
+ if (bits >= 8) {
2486
+ bits -= 8;
2487
+ out.push(value >>> bits & 255);
2488
+ }
2489
+ }
2490
+ return new Uint8Array(out);
2491
+ }
2492
+ function counterBytes(counter) {
2493
+ const buf = new Uint8Array(8);
2494
+ let hi = Math.floor(counter / 4294967296);
2495
+ let lo = counter >>> 0;
2496
+ for (let i = 7; i >= 4; i--) {
2497
+ buf[i] = lo & 255;
2498
+ lo = Math.floor(lo / 256);
2499
+ }
2500
+ for (let i = 3; i >= 0; i--) {
2501
+ buf[i] = hi & 255;
2502
+ hi = Math.floor(hi / 256);
2503
+ }
2504
+ return buf;
2505
+ }
2506
+ async function generateTotp(params, nowMs) {
2507
+ const digits = params.digits ?? 6;
2508
+ const period = params.period ?? 30;
2509
+ const algorithm = params.algorithm ?? "SHA-1";
2510
+ const now = Math.floor((nowMs ?? Date.now()) / 1e3);
2511
+ const counter = Math.floor(now / period);
2512
+ const remaining = period - now % period;
2513
+ const keyRaw = base32Decode(params.secret);
2514
+ const key = await crypto.subtle.importKey("raw", keyRaw, { name: "HMAC", hash: algorithm }, false, ["sign"]);
2515
+ const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, counterBytes(counter)));
2516
+ const offset = mac[mac.length - 1] & 15;
2517
+ const bin = (mac[offset] & 127) << 24 | (mac[offset + 1] & 255) << 16 | (mac[offset + 2] & 255) << 8 | mac[offset + 3] & 255;
2518
+ const code = (bin % 10 ** digits).toString().padStart(digits, "0");
2519
+ return { code, remaining };
2520
+ }
2521
+
2522
+ // src/vault/entries.ts
2523
+ async function listDecryptedEntries(api, vault) {
2524
+ const wire = await api.getVaultEntries(vault.id);
2525
+ const out = [];
2526
+ for (const w of wire) {
2527
+ if (w.deleted_at) continue;
2528
+ const keyVersion = w.key_version ?? 1;
2529
+ const key = vault.dekMap.get(keyVersion);
2530
+ if (!key) {
2531
+ continue;
2532
+ }
2533
+ const raw = await import_vault_cloud_crypto.default.decryptEntry(key, w.encrypted_blob);
2534
+ if (raw.deleted_at) continue;
2535
+ if ((raw.type ?? w.entry_type) === "_folders") continue;
2536
+ out.push({
2537
+ id: raw.id ?? w.id,
2538
+ type: raw.type ?? w.entry_type,
2539
+ label: raw.label ?? raw.name ?? "(untitled)",
2540
+ username: raw.username,
2541
+ password: raw.password,
2542
+ url: raw.url ?? raw.uris?.[0]?.uri,
2543
+ notes: raw.notes,
2544
+ totp: raw.totp,
2545
+ customFields: raw.customFields?.map((f) => ({ label: f.label, value: f.value }))
2546
+ });
2547
+ }
2548
+ return out;
2549
+ }
2550
+ async function resolveTotpCode(entry) {
2551
+ if (!entry.totp) {
2552
+ throw new Error(`Item "${entry.label}" has no TOTP configured`);
2553
+ }
2554
+ const { code } = await generateTotp(entry.totp);
2555
+ return code;
2556
+ }
2557
+
2558
+ // src/resolver.ts
2559
+ var UnresolvableRefError = class extends CliError {
2560
+ constructor(message) {
2561
+ super(EXIT.UNRESOLVABLE_REF, message);
2562
+ this.name = "UnresolvableRefError";
2563
+ }
2564
+ };
2565
+ var PREFIX = "geslar://";
2566
+ function decodeSegment(seg) {
2567
+ try {
2568
+ return decodeURIComponent(seg);
2569
+ } catch {
2570
+ throw new UnresolvableRefError(`Malformed percent-encoding in "${seg}"`);
2571
+ }
2572
+ }
2573
+ function parseRef(ref) {
2574
+ if (!ref.startsWith(PREFIX)) {
2575
+ throw new UnresolvableRefError(`Not a geslar:// reference: "${ref}"`);
2576
+ }
2577
+ const rest = ref.slice(PREFIX.length);
2578
+ if (rest.length === 0) {
2579
+ throw new UnresolvableRefError("Empty geslar:// reference");
2580
+ }
2581
+ const segments = rest.split("/");
2582
+ if (segments.length < 2) {
2583
+ throw new UnresolvableRefError(`geslar:// reference needs at least <vault>/<item> \u2014 got "${ref}"`);
2584
+ }
2585
+ if (segments.length > 3) {
2586
+ throw new UnresolvableRefError(`Too many "/"-separated parts in "${ref}" \u2014 escape a literal "/" as %2F`);
2587
+ }
2588
+ const vaultQuery = decodeSegment(segments[0]);
2589
+ if (vaultQuery.toLowerCase().startsWith("org:")) {
2590
+ throw new UnresolvableRefError("The org: qualifier is not implemented yet (v1) \u2014 use a unique collection name instead");
2591
+ }
2592
+ const itemRaw = decodeSegment(segments[1]);
2593
+ let itemId = null;
2594
+ let itemQuery = itemRaw;
2595
+ if (itemRaw.startsWith("id:")) {
2596
+ itemId = itemRaw.slice(3);
2597
+ itemQuery = "";
2598
+ if (itemId.length === 0) throw new UnresolvableRefError("Empty id: qualifier");
2599
+ }
2600
+ const field = segments[2] !== void 0 ? decodeSegment(segments[2]) : "password";
2601
+ if (field.length === 0) {
2602
+ throw new UnresolvableRefError('Empty field name after the last "/"');
2603
+ }
2604
+ return { vaultQuery, itemQuery, itemId, field };
2605
+ }
2606
+ function levenshtein(a, b) {
2607
+ const al = a.length;
2608
+ const bl = b.length;
2609
+ if (al === 0) return bl;
2610
+ if (bl === 0) return al;
2611
+ const dp = Array.from({ length: al + 1 }, () => new Array(bl + 1).fill(0));
2612
+ for (let i = 0; i <= al; i++) dp[i][0] = i;
2613
+ for (let j = 0; j <= bl; j++) dp[0][j] = j;
2614
+ for (let i = 1; i <= al; i++) {
2615
+ for (let j = 1; j <= bl; j++) {
2616
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
2617
+ dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost);
2618
+ }
2619
+ }
2620
+ return dp[al][bl];
2621
+ }
2622
+ function closestMatch(query, candidates) {
2623
+ if (candidates.length === 0 || query.length === 0) return null;
2624
+ const q = query.toLowerCase();
2625
+ let best = null;
2626
+ for (const c of candidates) {
2627
+ const dist = levenshtein(q, c.toLowerCase());
2628
+ if (!best || dist < best.dist) best = { name: c, dist };
2629
+ }
2630
+ const threshold = Math.max(2, Math.ceil(query.length * 0.4));
2631
+ return best && best.dist <= threshold ? best.name : null;
2632
+ }
2633
+ function requireNonEmpty(value, label, field) {
2634
+ if (!value) throw new UnresolvableRefError(`Field "${field}" on item "${label}" is empty`);
2635
+ return value;
2636
+ }
2637
+ async function resolveField(entry, field) {
2638
+ switch (field.toLowerCase()) {
2639
+ case "username":
2640
+ return requireNonEmpty(entry.username, entry.label, field);
2641
+ case "password":
2642
+ return requireNonEmpty(entry.password, entry.label, field);
2643
+ case "url":
2644
+ return requireNonEmpty(entry.url, entry.label, field);
2645
+ case "notes":
2646
+ return requireNonEmpty(entry.notes, entry.label, field);
2647
+ case "totp":
2648
+ return resolveTotpCode(entry);
2649
+ default: {
2650
+ const custom = entry.customFields?.find((f) => f.label.toLowerCase() === field.toLowerCase());
2651
+ if (!custom) {
2652
+ const known = ["username", "password", "url", "notes", "totp", ...entry.customFields?.map((f) => f.label) ?? []];
2653
+ const suggestion = closestMatch(field, known);
2654
+ throw new UnresolvableRefError(
2655
+ `Item "${entry.label}" has no field "${field}"${suggestion ? ` \u2014 did you mean "${suggestion}"?` : ""}. Available fields: ${known.join(", ")}`
2656
+ );
2657
+ }
2658
+ return requireNonEmpty(custom.value, entry.label, field);
2659
+ }
2660
+ }
2661
+ }
2662
+ var PERSONAL_VAULT_ALIAS = "personal";
2663
+ function matchesVaultQuery(v, query) {
2664
+ const q = query.toLowerCase();
2665
+ if (v.name.toLowerCase() === q) return true;
2666
+ return v.kind === "personal" && q === PERSONAL_VAULT_ALIAS;
2667
+ }
2668
+ var ORG_TYPE_TOKENS = {
2669
+ family: ["family"],
2670
+ company: ["business", "enterprise"],
2671
+ work: ["business", "enterprise"]
2672
+ };
2673
+ function resolveOrgTypeToken(query, vaults) {
2674
+ const types = ORG_TYPE_TOKENS[query.toLowerCase()];
2675
+ if (!types) return null;
2676
+ const matches = vaults.filter((v) => v.isDefault && v.orgType !== null && types.includes(v.orgType));
2677
+ if (matches.length > 1) {
2678
+ throw new UnresolvableRefError(
2679
+ `Multiple "${query}" orgs \u2014 ${matches.map((v) => v.name).join(", ")} \u2014 use the exact org name instead of "${query}"`
2680
+ );
2681
+ }
2682
+ return matches[0] ?? null;
2683
+ }
2684
+ function resolveVaultByQuery(query, vaults) {
2685
+ const vaultMatches = vaults.filter((v) => matchesVaultQuery(v, query));
2686
+ const orgTokenVault = resolveOrgTypeToken(query, vaults);
2687
+ if (orgTokenVault && !vaultMatches.includes(orgTokenVault)) {
2688
+ vaultMatches.push(orgTokenVault);
2689
+ }
2690
+ if (vaultMatches.length === 0) {
2691
+ const suggestion = closestMatch(query, vaults.map((v) => v.name));
2692
+ const available = vaults.map((v) => v.name).join(", ") || "(none)";
2693
+ throw new UnresolvableRefError(
2694
+ `No vault named "${query}"${suggestion ? ` \u2014 did you mean "${suggestion}"?` : ""}. Available: ${available}`
2695
+ );
2696
+ }
2697
+ if (vaultMatches.length > 1) {
2698
+ throw new UnresolvableRefError(`Multiple vaults named "${query}" \u2014 rename one, this isn't disambiguated yet`);
2699
+ }
2700
+ return vaultMatches[0];
2701
+ }
2702
+ async function resolveRef(ref, ctx) {
2703
+ const parsed = parseRef(ref);
2704
+ const vault = resolveVaultByQuery(parsed.vaultQuery, ctx.vaults);
2705
+ const entries = await ctx.getEntries(vault);
2706
+ let entry;
2707
+ if (parsed.itemId) {
2708
+ const found = entries.find((e) => e.id.toLowerCase() === parsed.itemId.toLowerCase());
2709
+ if (!found) throw new UnresolvableRefError(`No item with id "${parsed.itemId}" in "${vault.name}"`);
2710
+ entry = found;
2711
+ } else {
2712
+ const matches = entries.filter((e) => e.label.toLowerCase() === parsed.itemQuery.toLowerCase());
2713
+ if (matches.length === 0) {
2714
+ const suggestion = closestMatch(parsed.itemQuery, entries.map((e) => e.label));
2715
+ throw new UnresolvableRefError(
2716
+ `No item named "${parsed.itemQuery}" in "${vault.name}"${suggestion ? ` \u2014 did you mean "${suggestion}"?` : ""}`
2717
+ );
2718
+ }
2719
+ if (matches.length > 1) {
2720
+ const ids = matches.map((e) => e.id).join(", ");
2721
+ throw new UnresolvableRefError(
2722
+ `Multiple items named "${parsed.itemQuery}" in "${vault.name}" \u2014 use an id: qualifier (e.g. geslar://${vault.name}/id:${matches[0].id}/${parsed.field}). Matching ids: ${ids}`
2723
+ );
2724
+ }
2725
+ entry = matches[0];
2726
+ }
2727
+ const value = await resolveField(entry, parsed.field);
2728
+ return { vault, entry, field: parsed.field, value };
2729
+ }
2730
+
2731
+ // src/commands/list.ts
2732
+ async function listCommand(vaultFilter) {
2733
+ try {
2734
+ const config = await loadOrInitConfig();
2735
+ const session = await loadSession();
2736
+ const baseUrl = session?.apiBase ?? config.apiBase;
2737
+ const backend = await selectBackend();
2738
+ const tokenStore = await createCliTokenStore(backend);
2739
+ if (!tokenStore.get()) {
2740
+ printErr("not signed in \u2014 run `geslar signin`");
2741
+ return EXIT.AUTH;
2742
+ }
2743
+ const api = buildApiClient(baseUrl, tokenStore);
2744
+ const unlocked = await obtainUnlockedKeys(api);
2745
+ await tokenStore.flush();
2746
+ const vaults = await listVaultHandles(api, unlocked);
2747
+ const targets = vaultFilter ? [resolveVaultByQuery(vaultFilter, vaults)] : vaults;
2748
+ for (const vault of targets) {
2749
+ print(`${vault.name} (${vault.id})`);
2750
+ const entries = await listDecryptedEntries(api, vault);
2751
+ for (const entry of entries) {
2752
+ print(` ${entry.label} (${entry.id})`);
2753
+ }
2754
+ }
2755
+ return EXIT.OK;
2756
+ } catch (err) {
2757
+ if (err instanceof CliError) {
2758
+ printErr(err.message);
2759
+ return err.exitCode;
2760
+ }
2761
+ printErr(err.message);
2762
+ return EXIT.GENERAL;
2763
+ }
2764
+ }
2765
+
2766
+ // src/commands/read.ts
2767
+ import { writeFile as writeFile6 } from "node:fs/promises";
2768
+
2769
+ // src/vault/resolve-context.ts
2770
+ function createResolveContext(api, vaults) {
2771
+ const entryCache = /* @__PURE__ */ new Map();
2772
+ return {
2773
+ vaults,
2774
+ getEntries: async (vault) => {
2775
+ const cached = entryCache.get(vault.id);
2776
+ if (cached) return cached;
2777
+ const entries = await listDecryptedEntries(api, vault);
2778
+ entryCache.set(vault.id, entries);
2779
+ return entries;
2780
+ }
2781
+ };
2782
+ }
2783
+
2784
+ // src/lib/entitlements.ts
2785
+ var UPGRADE_URL = "https://geslar.app/pricing";
2786
+ var QUALIFYING_PLANS = /* @__PURE__ */ new Set(["premium", "family", "business", "enterprise"]);
2787
+ async function requireAgenticCli(api) {
2788
+ const entitlements = await api.getEntitlements();
2789
+ if (hasFeature(entitlements, "agentic_cli")) return;
2790
+ const plan = planOf(entitlements);
2791
+ if (QUALIFYING_PLANS.has(plan)) {
2792
+ throw new CliError(
2793
+ EXIT.ENTITLEMENT,
2794
+ `Your plan (${plan}) should include this feature but the server isn't reporting it yet. Run \`geslar whoami\` to confirm your plan, or contact support if this persists.`
2795
+ );
2796
+ }
2797
+ throw new CliError(
2798
+ EXIT.ENTITLEMENT,
2799
+ `This command requires a Premium plan or higher (your plan: ${plan}). Upgrade at ${UPGRADE_URL}`
2800
+ );
2801
+ }
2802
+
2803
+ // src/commands/read.ts
2804
+ async function readCommand(ref, opts) {
2805
+ try {
2806
+ const config = await loadOrInitConfig();
2807
+ const session = await loadSession();
2808
+ const baseUrl = session?.apiBase ?? config.apiBase;
2809
+ const backend = await selectBackend();
2810
+ const tokenStore = await createCliTokenStore(backend);
2811
+ if (!tokenStore.get()) {
2812
+ printErr("not signed in \u2014 run `geslar signin`");
2813
+ return EXIT.AUTH;
2814
+ }
2815
+ const api = buildApiClient(baseUrl, tokenStore);
2816
+ await requireAgenticCli(api);
2817
+ const unlocked = await obtainUnlockedKeys(api);
2818
+ await tokenStore.flush();
2819
+ const vaults = await listVaultHandles(api, unlocked);
2820
+ const resolved = await resolveRef(ref, createResolveContext(api, vaults));
2821
+ registerSecret(resolved.value);
2822
+ if (opts.output) {
2823
+ await writeFile6(opts.output, resolved.value, { mode: 384 });
2824
+ print(`Written to ${opts.output}`);
2825
+ } else {
2826
+ process.stdout.write(`${resolved.value}
2827
+ `);
2828
+ }
2829
+ return EXIT.OK;
2830
+ } catch (err) {
2831
+ if (err instanceof CliError) {
2832
+ printErr(err.message);
2833
+ return err.exitCode;
2834
+ }
2835
+ printErr(err.message);
2836
+ return EXIT.GENERAL;
2837
+ }
2838
+ }
2839
+
2840
+ // src/commands/run.ts
2841
+ import { spawn as spawn4 } from "node:child_process";
2842
+ import { readFile as readFile6 } from "node:fs/promises";
2843
+
2844
+ // src/vault/resolve-many.ts
2845
+ async function resolveRefsOrLiteral(values, ctx) {
2846
+ const resolved = {};
2847
+ const fromRef = /* @__PURE__ */ new Set();
2848
+ const failures = [];
2849
+ for (const [key, value] of Object.entries(values)) {
2850
+ if (!value.startsWith("geslar://")) {
2851
+ resolved[key] = value;
2852
+ continue;
2853
+ }
2854
+ try {
2855
+ const result = await resolveRef(value, ctx);
2856
+ resolved[key] = result.value;
2857
+ fromRef.add(key);
2858
+ } catch (err) {
2859
+ failures.push(`${key}: ${err.message}`);
2860
+ }
2861
+ }
2862
+ if (failures.length > 0) {
2863
+ throw new CliError(
2864
+ EXIT.UNRESOLVABLE_REF,
2865
+ `${failures.length} reference${failures.length === 1 ? "" : "s"} could not be resolved \u2014 nothing was run:
2866
+ ${failures.join("\n ")}`
2867
+ );
2868
+ }
2869
+ for (const key of fromRef) {
2870
+ registerSecret(resolved[key]);
2871
+ }
2872
+ return resolved;
2873
+ }
2874
+
2875
+ // src/lib/dotenv.ts
2876
+ function parseDotenv(content) {
2877
+ const out = {};
2878
+ for (const rawLine of content.split(/\r\n|\n|\r/)) {
2879
+ const line = rawLine.trim();
2880
+ if (line.length === 0 || line.startsWith("#")) continue;
2881
+ const withoutExport = line.startsWith("export ") ? line.slice("export ".length).trim() : line;
2882
+ const eq = withoutExport.indexOf("=");
2883
+ if (eq === -1) continue;
2884
+ const key = withoutExport.slice(0, eq).trim();
2885
+ if (key.length === 0) continue;
2886
+ let value = withoutExport.slice(eq + 1).trim();
2887
+ if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) {
2888
+ value = value.slice(1, -1).replace(/\\n/g, "\n").replace(/\\"/g, '"').replace(/\\\\/g, "\\");
2889
+ } else if (value.length >= 2 && value.startsWith("'") && value.endsWith("'")) {
2890
+ value = value.slice(1, -1);
2891
+ }
2892
+ out[key] = value;
2893
+ }
2894
+ return out;
2895
+ }
2896
+
2897
+ // src/commands/run.ts
2898
+ var SIGNAL_NUMBERS = {
2899
+ SIGHUP: 1,
2900
+ SIGINT: 2,
2901
+ SIGQUIT: 3,
2902
+ SIGILL: 4,
2903
+ SIGTRAP: 5,
2904
+ SIGABRT: 6,
2905
+ SIGBUS: 7,
2906
+ SIGFPE: 8,
2907
+ SIGKILL: 9,
2908
+ SIGUSR1: 10,
2909
+ SIGSEGV: 11,
2910
+ SIGUSR2: 12,
2911
+ SIGPIPE: 13,
2912
+ SIGALRM: 14,
2913
+ SIGTERM: 15
2914
+ };
2915
+ function exitCodeForSignal(signal) {
2916
+ return 128 + (SIGNAL_NUMBERS[signal] ?? 1);
2917
+ }
2918
+ async function runCommand(command, args, opts) {
2919
+ try {
2920
+ const values = await buildEnvValues(opts);
2921
+ const config = await loadOrInitConfig();
2922
+ const session = await loadSession();
2923
+ const baseUrl = session?.apiBase ?? config.apiBase;
2924
+ const backend = await selectBackend();
2925
+ const tokenStore = await createCliTokenStore(backend);
2926
+ if (!tokenStore.get()) {
2927
+ printErr("not signed in \u2014 run `geslar signin`");
2928
+ return EXIT.AUTH;
2929
+ }
2930
+ const api = buildApiClient(baseUrl, tokenStore);
2931
+ await requireAgenticCli(api);
2932
+ const unlocked = await obtainUnlockedKeys(api);
2933
+ await tokenStore.flush();
2934
+ const vaults = await listVaultHandles(api, unlocked);
2935
+ const ctx = createResolveContext(api, vaults);
2936
+ const resolvedEnv = await resolveRefsOrLiteral(values, ctx);
2937
+ return await spawnChild(command, args, resolvedEnv);
2938
+ } catch (err) {
2939
+ if (err instanceof CliError) {
2940
+ printErr(err.message);
2941
+ return err.exitCode;
2942
+ }
2943
+ printErr(err.message);
2944
+ return EXIT.GENERAL;
2945
+ }
2946
+ }
2947
+ async function buildEnvValues(opts) {
2948
+ const values = {};
2949
+ if (opts.envFile) {
2950
+ let content;
2951
+ try {
2952
+ content = await readFile6(opts.envFile, "utf-8");
2953
+ } catch (err) {
2954
+ throw new CliError(EXIT.GENERAL, `Could not read --env-file "${opts.envFile}": ${err.message}`);
2955
+ }
2956
+ Object.assign(values, parseDotenv(content));
2957
+ }
2958
+ for (const mapping of opts.env ?? []) {
2959
+ const eq = mapping.indexOf("=");
2960
+ if (eq === -1) {
2961
+ throw new CliError(EXIT.GENERAL, `Invalid -e value "${mapping}" \u2014 expected KEY=ref`);
2962
+ }
2963
+ const key = mapping.slice(0, eq);
2964
+ const value = mapping.slice(eq + 1);
2965
+ if (key in values) {
2966
+ printErr(`-e ${key} overrides the same key from --env-file`);
2967
+ }
2968
+ values[key] = value;
2969
+ }
2970
+ if (Object.keys(values).length === 0) {
2971
+ throw new CliError(EXIT.GENERAL, "No environment variables to set \u2014 pass --env-file and/or -e");
2972
+ }
2973
+ return values;
2974
+ }
2975
+ function spawnChild(command, args, resolvedEnv) {
2976
+ return new Promise((resolve) => {
2977
+ const child = spawn4(command, args, {
2978
+ env: { ...process.env, ...resolvedEnv },
2979
+ stdio: "inherit"
2980
+ });
2981
+ const forward = (signal) => child.kill(signal);
2982
+ process.on("SIGINT", forward);
2983
+ process.on("SIGTERM", forward);
2984
+ function cleanup() {
2985
+ process.removeListener("SIGINT", forward);
2986
+ process.removeListener("SIGTERM", forward);
2987
+ }
2988
+ child.on("error", (err) => {
2989
+ cleanup();
2990
+ if (err.code === "ENOENT") {
2991
+ printErr(`command not found: ${command}`);
2992
+ resolve(127);
2993
+ } else {
2994
+ printErr(`failed to run ${command}: ${err.message}`);
2995
+ resolve(EXIT.GENERAL);
2996
+ }
2997
+ });
2998
+ child.on("exit", (code, signal) => {
2999
+ cleanup();
3000
+ resolve(signal ? exitCodeForSignal(signal) : code ?? EXIT.GENERAL);
3001
+ });
3002
+ });
3003
+ }
3004
+
3005
+ // src/commands/inject.ts
3006
+ import { readFile as readFile7, writeFile as writeFile7 } from "node:fs/promises";
3007
+ var PLACEHOLDER_RE = /\{\{\s*(geslar:\/\/.+?)\s*\}\}/g;
3008
+ async function injectCommand(opts) {
3009
+ try {
3010
+ let template;
3011
+ try {
3012
+ template = await readFile7(opts.input, "utf-8");
3013
+ } catch (err) {
3014
+ throw new CliError(EXIT.GENERAL, `Could not read -i "${opts.input}": ${err.message}`);
3015
+ }
3016
+ const refByPlaceholder = /* @__PURE__ */ new Map();
3017
+ for (const m of template.matchAll(PLACEHOLDER_RE)) {
3018
+ refByPlaceholder.set(m[0], m[1]);
3019
+ }
3020
+ if (refByPlaceholder.size === 0) {
3021
+ await writeFile7(opts.output, template, { mode: 384 });
3022
+ print(`Written to ${opts.output} (no placeholders found)`);
3023
+ return EXIT.OK;
3024
+ }
3025
+ const config = await loadOrInitConfig();
3026
+ const session = await loadSession();
3027
+ const baseUrl = session?.apiBase ?? config.apiBase;
3028
+ const backend = await selectBackend();
3029
+ const tokenStore = await createCliTokenStore(backend);
3030
+ if (!tokenStore.get()) {
3031
+ printErr("not signed in \u2014 run `geslar signin`");
3032
+ return EXIT.AUTH;
3033
+ }
3034
+ const api = buildApiClient(baseUrl, tokenStore);
3035
+ await requireAgenticCli(api);
3036
+ const unlocked = await obtainUnlockedKeys(api);
3037
+ await tokenStore.flush();
3038
+ const vaults = await listVaultHandles(api, unlocked);
3039
+ const ctx = createResolveContext(api, vaults);
3040
+ const uniqueRefs = {};
3041
+ for (const ref of new Set(refByPlaceholder.values())) uniqueRefs[ref] = ref;
3042
+ const resolved = await resolveRefsOrLiteral(uniqueRefs, ctx);
3043
+ let output = template;
3044
+ for (const [placeholder, ref] of refByPlaceholder) {
3045
+ output = output.split(placeholder).join(resolved[ref]);
3046
+ }
3047
+ await writeFile7(opts.output, output, { mode: 384 });
3048
+ print(`Written to ${opts.output}`);
3049
+ return EXIT.OK;
3050
+ } catch (err) {
3051
+ if (err instanceof CliError) {
3052
+ printErr(err.message);
3053
+ return err.exitCode;
3054
+ }
3055
+ printErr(err.message);
3056
+ return EXIT.GENERAL;
3057
+ }
3058
+ }
3059
+
3060
+ // src/index.ts
3061
+ var program = new Command();
3062
+ program.name("geslar").description("Geslar Agentic Access CLI").enablePositionalOptions().version(CLI_VERSION);
3063
+ program.command("signin").description("Sign in via device-flow (opens a code to enter at the console)").option("--api <url>", "override the API base URL").action(async (opts) => {
3064
+ process.exitCode = await signinCommand(opts);
3065
+ });
3066
+ program.command("signout").description("Revoke this session and clear the local token").action(async () => {
3067
+ process.exitCode = await signoutCommand();
3068
+ });
3069
+ program.command("whoami").description("Show the signed-in account, plan, and org context").action(async () => {
3070
+ process.exitCode = await whoamiCommand();
3071
+ });
3072
+ program.command("unlock").description("Unlock the vault for headless use (stores a TTL-bound grant, OS-wrapped)").option("--ttl <duration>", "grant lifetime, e.g. 30m, 1h (default 30m, max 8h)").action(async (opts) => {
3073
+ process.exitCode = await unlockCommand(opts);
3074
+ });
3075
+ program.command("lock").description("Clear the unlock grant immediately").action(async () => {
3076
+ process.exitCode = await lockCommand();
3077
+ });
3078
+ program.command("list").argument("[vault]", "only list this vault (by name)").description("List vaults and item names (no values)").action(async (vaultFilter) => {
3079
+ process.exitCode = await listCommand(vaultFilter);
3080
+ });
3081
+ program.command("read").argument("<ref>", "a geslar://<vault>/<item>[/<field>] reference").option("-o, --output <file>", "write the value to this file (mode 0600) instead of stdout").description("Resolve a geslar:// reference and print (or write) its value").action(async (ref, opts) => {
3082
+ process.exitCode = await readCommand(ref, opts);
3083
+ });
3084
+ program.command("run").description("Run a command with geslar:// references resolved into its environment (fail-closed)").option("--env-file <file>", "dotenv file \u2014 geslar:// values are resolved, everything else passed through literally").option(
3085
+ "-e, --env <mapping>",
3086
+ "KEY=ref (repeatable) \u2014 overrides the same key from --env-file",
3087
+ (val, prev) => [...prev, val],
3088
+ []
3089
+ ).argument("<command>", "command to run").argument("[args...]", "arguments for the command").enablePositionalOptions().passThroughOptions().action(async (command, args, opts) => {
3090
+ process.exitCode = await runCommand(command, args, opts);
3091
+ });
3092
+ program.command("inject").description("Substitute {{ geslar://... }} placeholders in a template file (fail-closed)").requiredOption("-i, --input <file>", "template file").requiredOption("-o, --output <file>", "output file (mode 0600)").action(async (opts) => {
3093
+ process.exitCode = await injectCommand(opts);
3094
+ });
3095
+ void (async () => {
3096
+ try {
3097
+ await program.parseAsync(process.argv);
3098
+ } catch (err) {
3099
+ printErr(err.message);
3100
+ process.exitCode = EXIT.GENERAL;
3101
+ }
3102
+ })();
3103
+ //# sourceMappingURL=index.js.map