@geslar/cli 0.2.0 → 0.3.1

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.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../../packages/core/src/crypto/vault-crypto.js", "../../../packages/core/src/crypto/vault-cloud-crypto.js", "../../../packages/core/src/crypto/recovery-enrollment.js", "../src/index.ts", "../src/commands/signin.ts", "../src/lib/config.ts", "../src/lib/paths.ts", "../src/lib/session.ts", "../src/lib/scrubber.ts", "../src/lib/output.ts", "../src/lib/errors.ts", "../src/token-store/windows.ts", "../src/token-store/macos.ts", "../src/token-store/linux.ts", "../src/token-store/fallback.ts", "../src/token-store/machine-id.ts", "../src/token-store/index.ts", "../src/device-flow.ts", "../src/vault/grant.ts", "../src/commands/signout.ts", "../../../packages/core/src/api/client.ts", "../../../packages/core/src/entitlements/index.ts", "../../../packages/core/src/pdp.ts", "../../../packages/core/src/security/health.ts", "../src/lib/core.ts", "../src/commands/whoami.ts", "../src/lib/prompt.ts", "../../../packages/core/src/crypto/index.mjs", "../src/vault/unlock.ts", "../src/commands/unlock.ts", "../src/commands/lock.ts", "../src/vault/session.ts", "../src/vault/vaults.ts", "../src/vault/agent-vaults.ts", "../src/vault/totp.ts", "../src/vault/entries.ts", "../src/resolver.ts", "../src/agent/token-store.ts", "../src/lib/agent-context.ts", "../src/commands/list.ts", "../src/commands/read.ts", "../src/vault/resolve-context.ts", "../src/lib/entitlements.ts", "../src/commands/run.ts", "../src/vault/resolve-many.ts", "../src/lib/dotenv.ts", "../src/commands/inject.ts", "../src/commands/agent-create.ts", "../src/commands/agent-list.ts", "../src/commands/agent-revoke.ts"],
4
- "sourcesContent": ["// \u2500\u2500\u2500 Geslar Vault \u2014 Crypto Module \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Pure Web Crypto API \u2014 zero external dependencies\n// AES-256-GCM encryption with PBKDF2 key derivation\n\nconst VaultCrypto = (() => {\n 'use strict';\n\n const PBKDF2_ITERATIONS = 600000;\n const SALT_BYTES = 32;\n const IV_BYTES = 12;\n const KEY_BITS = 256;\n\n /** Generate a random salt (32 bytes) */\n function generateSalt() {\n return crypto.getRandomValues(new Uint8Array(SALT_BYTES));\n }\n\n /** Generate a random IV (12 bytes) */\n function generateIV() {\n return crypto.getRandomValues(new Uint8Array(IV_BYTES));\n }\n\n /** Derive a CryptoKey from master password + salt using PBKDF2 */\n async function deriveMasterKey(password, salt) {\n const encoder = new TextEncoder();\n const keyMaterial = await crypto.subtle.importKey(\n 'raw', encoder.encode(password), 'PBKDF2', false, ['deriveKey']\n );\n return crypto.subtle.deriveKey(\n { name: 'PBKDF2', salt, iterations: PBKDF2_ITERATIONS, hash: 'SHA-256' },\n keyMaterial,\n { name: 'AES-GCM', length: KEY_BITS },\n true, // extractable \u2014 needed to export/import via session storage\n ['encrypt', 'decrypt']\n );\n }\n\n /**\n * Derive a verification hash (separate from master key).\n * Uses a different salt to prevent key reuse.\n * Returns base64 string for quick master password verification.\n */\n async function deriveVerificationHash(password, salt) {\n const encoder = new TextEncoder();\n const keyMaterial = await crypto.subtle.importKey(\n 'raw', encoder.encode(password), 'PBKDF2', false, ['deriveBits']\n );\n const bits = await crypto.subtle.deriveBits(\n { name: 'PBKDF2', salt, iterations: PBKDF2_ITERATIONS, hash: 'SHA-256' },\n keyMaterial,\n 256\n );\n return bufToBase64(new Uint8Array(bits));\n }\n\n /** Encrypt plaintext string \u2192 { ciphertext: base64, iv: base64 } */\n async function encrypt(plaintext, key) {\n const encoder = new TextEncoder();\n const iv = generateIV();\n const encrypted = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv },\n key,\n encoder.encode(plaintext)\n );\n return {\n ciphertext: bufToBase64(new Uint8Array(encrypted)),\n iv: bufToBase64(iv)\n };\n }\n\n /** Decrypt { ciphertext: base64, iv: base64 } \u2192 plaintext string */\n async function decrypt(ciphertext, iv, key) {\n const decrypted = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv: base64ToBuf(iv) },\n key,\n base64ToBuf(ciphertext)\n );\n return new TextDecoder().decode(decrypted);\n }\n\n // \u2500\u2500\u2500 Key export/import (for session storage persistence) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Export CryptoKey to base64 string */\n async function exportKey(key) {\n const raw = await crypto.subtle.exportKey('raw', key);\n return bufToBase64(new Uint8Array(raw));\n }\n\n /** Import base64 string back to CryptoKey */\n async function importKey(b64) {\n const raw = base64ToBuf(b64);\n return crypto.subtle.importKey(\n 'raw', raw, { name: 'AES-GCM', length: KEY_BITS },\n true, ['encrypt', 'decrypt']\n );\n }\n\n // \u2500\u2500\u2500 Base64 helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n function bufToBase64(buf) {\n let binary = '';\n for (let i = 0; i < buf.length; i++) binary += String.fromCharCode(buf[i]);\n return btoa(binary);\n }\n\n function base64ToBuf(b64) {\n const binary = atob(b64);\n const buf = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) buf[i] = binary.charCodeAt(i);\n return buf;\n }\n\n // \u2500\u2500\u2500 UUID v4 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n function generateId() {\n return crypto.randomUUID ? crypto.randomUUID() : ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>\n (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16));\n }\n\n // \u2500\u2500\u2500 Public API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n return {\n generateSalt,\n generateIV,\n deriveMasterKey,\n deriveVerificationHash,\n encrypt,\n decrypt,\n exportKey,\n importKey,\n bufToBase64,\n base64ToBuf,\n generateId,\n PBKDF2_ITERATIONS\n };\n})();\n\nif (typeof module !== 'undefined') module.exports = VaultCrypto;\n", "// \u2500\u2500\u2500 Geslar Vault \u2014 Cloud Crypto \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Crypto operations specific to cloud sync: auth_hash derivation, vault_key\n// (DEK) management, per-entry encryption, and recovery key generation.\n// Uses existing VaultCrypto helpers. Never called directly from UI.\n\nconst VaultCloudCrypto = (() => {\n 'use strict';\n\n const AUTH_HASH_ITERATIONS = 1; // Intentionally 1 \u2014 see spec \"auth hash flow\"\n const VAULT_KEY_BYTES = 32; // AES-256\n const RECOVERY_KEY_BYTES = 32; // 256-bit recovery key\n const ECDH_PRIVATE_BYTES = 32; // X25519 private key (raw scalar)\n const IV_BYTES = 12; // AES-GCM nonce\n\n // \u2500\u2500\u2500 Shared-vault key exchange (T10) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Static-static X25519 ECDH \u2192 HKDF-SHA256 \u2192 AES-256-GCM wrap key.\n // Domain-separated salt/info so a shared secret can never be reused as a\n // different key by accident. MUST match server-side derivation.\n const HKDF_SALT = new TextEncoder().encode('geslar-ecdh-hkdf-salt-v1');\n const HKDF_INFO = new TextEncoder().encode('geslar-shared-vault-wrap-v1');\n\n // Recovery blob format marker. v1 (legacy) = raw 32-byte DEK wrapped by the\n // recovery key. v2 (O3, keypair-preserving) = MAGIC \u2016 DEK(32) \u2016 ECDH_priv.\n // The marker lets unwrap stay backward compatible with every blob already in\n // production (those have no prefix and decrypt to exactly 32 bytes).\n const RECOVERY_V2_MAGIC = Uint8Array.from([0x47, 0x52, 0x02]); // 'G','R',0x02\n\n // Fingerprint phrase: deterministic, bijective byte\u2192syllable mapping so the\n // exact same algorithm reproduces on the server with no shared word table to\n // drift. 16\u00D74\u00D74 = 256 distinct CVC syllables \u2194 one byte. MUST match server.\n const FP_CONS_INITIAL = ['b','d','f','g','k','l','m','n','p','r','s','t','v','z','h','j']; // 16\n const FP_VOWELS = ['a','e','i','o']; // 4\n const FP_CONS_FINAL = ['k','n','s','t']; // 4\n const FP_WORD_COUNT = 6; // 6 syllables \u2192 48 bits of the pubkey hash\n\n // \u2500\u2500\u2500 Auth hash derivation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // PBKDF2-SHA256(master_key_raw, password_bytes, 1 iteration) \u2192 auth_hash\n // This is NOT stretching (server does Argon2id for that).\n // It's a one-way derivation so server never sees master_key.\n\n /**\n * Derive auth_hash from master_key for server authentication.\n * @param {CryptoKey} masterKey \u2014 derived via VaultCrypto.deriveMasterKey()\n * @param {string} password \u2014 the user's master password (used as PBKDF2 salt)\n * @returns {Promise<string>} Base64-encoded 256-bit auth_hash\n */\n async function deriveAuthHash(masterKey, password) {\n // Export master_key to raw bytes (it's extractable)\n const masterKeyRaw = await crypto.subtle.exportKey('raw', masterKey);\n\n // Import raw master_key bytes as PBKDF2 key material\n const keyMaterial = await crypto.subtle.importKey(\n 'raw', masterKeyRaw, 'PBKDF2', false, ['deriveBits']\n );\n\n // Derive auth_hash: PBKDF2(master_key, password_as_salt, 1 iter)\n const encoder = new TextEncoder();\n const authHashBits = await crypto.subtle.deriveBits(\n {\n name: 'PBKDF2',\n salt: encoder.encode(password),\n iterations: AUTH_HASH_ITERATIONS,\n hash: 'SHA-256',\n },\n keyMaterial,\n 256\n );\n\n return VaultCrypto.bufToBase64(new Uint8Array(authHashBits));\n }\n\n // \u2500\u2500\u2500 Vault key (DEK) management \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // vault_key is a random AES-256 key that encrypts individual vault entries.\n // master_key (KEK) wraps vault_key \u2014 password change = re-wrap, not re-encrypt.\n\n /** Generate a fresh vault_key (DEK) \u2014 256-bit random. */\n function generateVaultKey() {\n return crypto.getRandomValues(new Uint8Array(VAULT_KEY_BYTES));\n }\n\n /**\n * Wrap (encrypt) vault_key with master_key (KEK).\n * @param {CryptoKey} masterKey \u2014 KEK derived from password\n * @param {Uint8Array} vaultKey \u2014 32-byte DEK\n * @returns {Promise<string>} Base64-encoded IV+ciphertext\n */\n async function wrapVaultKey(masterKey, vaultKey) {\n const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));\n const encrypted = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv },\n masterKey,\n vaultKey\n );\n // Pack: IV (12) + ciphertext (32 + 16 tag)\n const packed = new Uint8Array(iv.length + encrypted.byteLength);\n packed.set(iv, 0);\n packed.set(new Uint8Array(encrypted), iv.length);\n return VaultCrypto.bufToBase64(packed);\n }\n\n /**\n * Unwrap (decrypt) vault_key with master_key (KEK).\n * @param {CryptoKey} masterKey \u2014 KEK derived from password\n * @param {string} wrappedBase64 \u2014 Base64 IV+ciphertext from server\n * @returns {Promise<Uint8Array>} 32-byte vault_key (DEK)\n */\n async function unwrapVaultKey(masterKey, wrappedBase64) {\n const packed = VaultCrypto.base64ToBuf(wrappedBase64);\n const iv = packed.slice(0, IV_BYTES);\n const ciphertext = packed.slice(IV_BYTES);\n const decrypted = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv },\n masterKey,\n ciphertext\n );\n return new Uint8Array(decrypted);\n }\n\n /**\n * Import raw vault_key bytes as a CryptoKey for encrypt/decrypt operations.\n * @param {Uint8Array} vaultKeyRaw \u2014 32-byte DEK\n * @returns {Promise<CryptoKey>}\n */\n async function importVaultKey(vaultKeyRaw) {\n return crypto.subtle.importKey(\n 'raw', vaultKeyRaw, { name: 'AES-GCM', length: 256 },\n false, ['encrypt', 'decrypt']\n );\n }\n\n // \u2500\u2500\u2500 Per-entry encryption \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Each vault entry is individually encrypted with vault_key (DEK).\n // AES-256-GCM(vault_key, entry_json) \u2192 { encrypted_blob, blob_hash }\n\n /**\n * Encrypt a single vault entry for cloud push.\n * @param {CryptoKey} vaultKey \u2014 imported vault_key (DEK)\n * @param {object} entry \u2014 plaintext entry object\n * @returns {Promise<{ encrypted_blob: string, blob_hash: string }>}\n * encrypted_blob: Base64(IV + ciphertext+tag)\n * blob_hash: hex SHA-256 of the encrypted blob (for dedup/integrity)\n */\n async function encryptEntry(vaultKey, entry) {\n const encoder = new TextEncoder();\n const plaintext = encoder.encode(JSON.stringify(entry));\n\n const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));\n const encrypted = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv },\n vaultKey,\n plaintext\n );\n\n // Pack IV + ciphertext\n const packed = new Uint8Array(iv.length + encrypted.byteLength);\n packed.set(iv, 0);\n packed.set(new Uint8Array(encrypted), iv.length);\n\n const blob = VaultCrypto.bufToBase64(packed);\n\n // SHA-256 hash of the encrypted blob for integrity/dedup\n const hashBuffer = await crypto.subtle.digest('SHA-256', packed);\n const hashArray = new Uint8Array(hashBuffer);\n const blobHash = Array.from(hashArray).map(b => b.toString(16).padStart(2, '0')).join('');\n\n return { encrypted_blob: blob, blob_hash: blobHash };\n }\n\n /**\n * Decrypt a single vault entry from cloud pull.\n * @param {CryptoKey} vaultKey \u2014 imported vault_key (DEK)\n * @param {string} encryptedBlob \u2014 Base64(IV + ciphertext+tag)\n * @returns {Promise<object>} Plaintext entry object\n */\n async function decryptEntry(vaultKey, encryptedBlob) {\n const packed = VaultCrypto.base64ToBuf(encryptedBlob);\n const iv = packed.slice(0, IV_BYTES);\n const ciphertext = packed.slice(IV_BYTES);\n\n const decrypted = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv },\n vaultKey,\n ciphertext\n );\n\n return JSON.parse(new TextDecoder().decode(decrypted));\n }\n\n // \u2500\u2500\u2500 Recovery key \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // 256-bit random key that wraps the same vault_key (DEK).\n // Enables vault recovery without master password.\n\n /** Generate a 256-bit recovery key. */\n function generateRecoveryKey() {\n return crypto.getRandomValues(new Uint8Array(RECOVERY_KEY_BYTES));\n }\n\n /** True when a decrypted recovery payload carries the v2 (keypair) marker. */\n function isRecoveryV2(payload) {\n return payload.length > RECOVERY_V2_MAGIC.length + VAULT_KEY_BYTES &&\n payload[0] === RECOVERY_V2_MAGIC[0] &&\n payload[1] === RECOVERY_V2_MAGIC[1] &&\n payload[2] === RECOVERY_V2_MAGIC[2];\n }\n\n /**\n * Wrap vault_key (and optionally the ECDH private key) with recovery_key\n * \u2192 encrypted_recovery_blob.\n *\n * When `ecdhPrivateKey` is supplied the blob uses the v2 layout\n * (MAGIC \u2016 DEK \u2016 ECDH_priv) so recovery can preserve the user's key pair\n * (O3). Omitting it produces the legacy v1 layout (raw DEK) \u2014 byte-identical\n * to every blob already in production, so existing flows are untouched.\n *\n * @param {Uint8Array} recoveryKey \u2014 32-byte recovery key\n * @param {Uint8Array} vaultKey \u2014 32-byte DEK\n * @param {Uint8Array} [ecdhPrivateKey] \u2014 PKCS#8 X25519 private key (v2 only)\n * @returns {Promise<string>} Base64 IV+ciphertext\n */\n async function wrapVaultKeyWithRecovery(recoveryKey, vaultKey, ecdhPrivateKey) {\n const key = await crypto.subtle.importKey(\n 'raw', recoveryKey, { name: 'AES-GCM', length: 256 },\n false, ['encrypt']\n );\n\n let payload;\n if (ecdhPrivateKey) {\n payload = new Uint8Array(RECOVERY_V2_MAGIC.length + vaultKey.length + ecdhPrivateKey.length);\n payload.set(RECOVERY_V2_MAGIC, 0);\n payload.set(vaultKey, RECOVERY_V2_MAGIC.length);\n payload.set(ecdhPrivateKey, RECOVERY_V2_MAGIC.length + vaultKey.length);\n } else {\n payload = vaultKey;\n }\n\n const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));\n const encrypted = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, payload);\n const packed = new Uint8Array(iv.length + encrypted.byteLength);\n packed.set(iv, 0);\n packed.set(new Uint8Array(encrypted), iv.length);\n return VaultCrypto.bufToBase64(packed);\n }\n\n /**\n * Decrypt encrypted_recovery_blob and split it into its parts.\n * Handles both v1 (DEK only) and v2 (DEK + ECDH private key) layouts.\n * @param {Uint8Array} recoveryKey \u2014 32-byte recovery key\n * @param {string} recoveryBlob \u2014 Base64 IV+ciphertext\n * @returns {Promise<{ vaultKey: Uint8Array, ecdhPrivateKey: Uint8Array|null, version: number }>}\n * Throws DOMException (OperationError) if recovery key is wrong / blob tampered.\n */\n async function unwrapRecoveryBlob(recoveryKey, recoveryBlob) {\n const key = await crypto.subtle.importKey(\n 'raw', recoveryKey, { name: 'AES-GCM', length: 256 },\n false, ['decrypt']\n );\n const packed = VaultCrypto.base64ToBuf(recoveryBlob);\n const iv = packed.slice(0, IV_BYTES);\n const ciphertext = packed.slice(IV_BYTES);\n const decrypted = new Uint8Array(\n await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, key, ciphertext)\n );\n\n if (isRecoveryV2(decrypted)) {\n const off = RECOVERY_V2_MAGIC.length;\n return {\n vaultKey: decrypted.slice(off, off + VAULT_KEY_BYTES),\n ecdhPrivateKey: decrypted.slice(off + VAULT_KEY_BYTES),\n version: 2,\n };\n }\n return { vaultKey: decrypted, ecdhPrivateKey: null, version: 1 };\n }\n\n /**\n * Unwrap vault_key from encrypted_recovery_blob using recovery_key.\n * Backward-compatible accessor that always returns the DEK, regardless of\n * blob version. Existing callers keep working unchanged.\n * @param {Uint8Array} recoveryKey \u2014 32-byte recovery key\n * @param {string} recoveryBlob \u2014 Base64 IV+ciphertext\n * @returns {Promise<Uint8Array>} 32-byte vault_key (DEK)\n */\n async function unwrapVaultKeyWithRecovery(recoveryKey, recoveryBlob) {\n const { vaultKey } = await unwrapRecoveryBlob(recoveryKey, recoveryBlob);\n return vaultKey;\n }\n\n // \u2500\u2500\u2500 X25519 ECDH key pair \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Real X25519 (SubtleCrypto, Chrome 113+). Used for shared vaults (key\n // exchange) and trusted device transfer. Generated at registration, private\n // key wrapped by master_key. The public key is DERIVED from the private key.\n //\n // Storage convention:\n // privateKey \u2192 PKCS#8 DER bytes (48 B) \u2014 the only WebCrypto export format\n // that round-trips an X25519 private key via importKey().\n // publicKey \u2192 raw 32-byte u-coordinate.\n\n /**\n * Generate a real X25519 key pair.\n * @returns {Promise<{ privateKey: Uint8Array, publicKey: Uint8Array }>}\n * privateKey = PKCS#8 DER (48 B), publicKey = raw 32-byte u-coordinate.\n */\n async function generateEcdhKeyPair() {\n const pair = await crypto.subtle.generateKey({ name: 'X25519' }, true, ['deriveBits']);\n const publicKey = new Uint8Array(await crypto.subtle.exportKey('raw', pair.publicKey));\n const privateKey = new Uint8Array(await crypto.subtle.exportKey('pkcs8', pair.privateKey));\n return { privateKey, publicKey };\n }\n\n /** Import a PKCS#8 X25519 private key for ECDH deriveBits. */\n function importEcdhPrivateKey(privatePkcs8) {\n return crypto.subtle.importKey('pkcs8', privatePkcs8, { name: 'X25519' }, false, ['deriveBits']);\n }\n\n /** Import a raw 32-byte X25519 public key as an ECDH peer key. */\n function importEcdhPublicKey(publicRaw) {\n return crypto.subtle.importKey('raw', publicRaw, { name: 'X25519' }, false, []);\n }\n\n /**\n * Recover the raw 32-byte public key from a PKCS#8 X25519 private key.\n * WebCrypto cannot raw-export a public key from a private CryptoKey, but a\n * JWK export of the private key carries the public component in `x`.\n * @param {Uint8Array} privatePkcs8\n * @returns {Promise<Uint8Array>} raw 32-byte public key\n */\n async function ecdhPublicFromPrivate(privatePkcs8) {\n const key = await crypto.subtle.importKey('pkcs8', privatePkcs8, { name: 'X25519' }, true, ['deriveBits']);\n const jwk = await crypto.subtle.exportKey('jwk', key);\n const b64 = jwk.x.replace(/-/g, '+').replace(/_/g, '/');\n const padded = b64 + '='.repeat((4 - (b64.length % 4)) % 4);\n return VaultCrypto.base64ToBuf(padded);\n }\n\n /**\n * Derive the AES-256-GCM wrap key shared with a peer:\n * X25519(myPriv, peerPub) \u2192 HKDF-SHA256 \u2192 AES-256 key.\n * Static-static ECDH: identical key on both ends when the roles are swapped\n * (wrap uses myPriv+recipientPub, unwrap uses recipientPriv+myPub).\n * @param {Uint8Array} myPrivatePkcs8 \u2014 my X25519 private key (PKCS#8)\n * @param {Uint8Array} peerPublicRaw \u2014 peer's raw 32-byte public key\n * @returns {Promise<CryptoKey>} AES-256-GCM key (non-extractable)\n */\n async function deriveSharedWrapKey(myPrivatePkcs8, peerPublicRaw) {\n const privKey = await importEcdhPrivateKey(myPrivatePkcs8);\n const pubKey = await importEcdhPublicKey(peerPublicRaw);\n\n const sharedSecret = await crypto.subtle.deriveBits(\n { name: 'X25519', public: pubKey }, privKey, 256\n );\n\n // HKDF-extract+expand the raw DH secret into a clean 256-bit AES key.\n const ikm = await crypto.subtle.importKey('raw', sharedSecret, 'HKDF', false, ['deriveBits']);\n const okm = await crypto.subtle.deriveBits(\n { name: 'HKDF', hash: 'SHA-256', salt: HKDF_SALT, info: HKDF_INFO }, ikm, 256\n );\n return crypto.subtle.importKey('raw', okm, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);\n }\n\n /**\n * Wrap a shared vault DEK for a member.\n * wrapKey = ECDH(myPriv, recipientPub) \u2192 HKDF \u2192 AES-256-GCM.\n * @param {Uint8Array} myPrivatePkcs8 \u2014 sender's X25519 private key (PKCS#8)\n * @param {Uint8Array} recipientPublicRaw \u2014 recipient's raw 32-byte public key\n * @param {Uint8Array} sharedDEK \u2014 32-byte shared vault key to wrap\n * @returns {Promise<string>} Base64 IV+ciphertext+tag\n */\n async function wrapVaultKeyForMember(myPrivatePkcs8, recipientPublicRaw, sharedDEK) {\n const wrapKey = await deriveSharedWrapKey(myPrivatePkcs8, recipientPublicRaw);\n const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));\n const encrypted = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, wrapKey, sharedDEK);\n const packed = new Uint8Array(iv.length + encrypted.byteLength);\n packed.set(iv, 0);\n packed.set(new Uint8Array(encrypted), iv.length);\n return VaultCrypto.bufToBase64(packed);\n }\n\n /**\n * Unwrap a shared vault DEK wrapped for me by a sender.\n * wrapKey = ECDH(myPriv, senderPub) \u2192 HKDF \u2192 AES-256-GCM.\n * @param {Uint8Array} myPrivatePkcs8 \u2014 my X25519 private key (PKCS#8)\n * @param {Uint8Array} senderPublicRaw \u2014 sender's raw 32-byte public key\n * @param {string} wrappedBase64 \u2014 blob from wrapVaultKeyForMember()\n * @returns {Promise<Uint8Array>} 32-byte shared vault DEK\n * Throws DOMException (OperationError) if the blob or sender key is tampered.\n */\n async function unwrapSharedVaultKey(myPrivatePkcs8, senderPublicRaw, wrappedBase64) {\n const wrapKey = await deriveSharedWrapKey(myPrivatePkcs8, senderPublicRaw);\n const packed = VaultCrypto.base64ToBuf(wrappedBase64);\n const iv = packed.slice(0, IV_BYTES);\n const ciphertext = packed.slice(IV_BYTES);\n const decrypted = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, wrapKey, ciphertext);\n return new Uint8Array(decrypted);\n }\n\n // \u2500\u2500\u2500 Fingerprint phrase \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Human-verifiable hash of a public key (Bitwarden trust model, O2). Two\n // members compare the phrase out-of-band; a server that swaps a public key\n // (MITM) cannot reproduce the victim's phrase. Deterministic \u2014 the server\n // renders the identical phrase for the console.\n\n /** Map one byte (0\u2013255) to a fixed CVC syllable. Bijective. */\n function fpSyllable(byte) {\n const c1 = FP_CONS_INITIAL[(byte >> 4) & 0x0f];\n const v = FP_VOWELS[(byte >> 2) & 0x03];\n const c2 = FP_CONS_FINAL[byte & 0x03];\n return c1 + v + c2;\n }\n\n /**\n * Derive the deterministic fingerprint phrase for a public key.\n * @param {Uint8Array|string} publicKey \u2014 raw 32-byte public key or its base64\n * @returns {Promise<string>} e.g. \"bok-tas-...\" \u2014 FP_WORD_COUNT syllables, '-' joined\n */\n async function deriveFingerprintPhrase(publicKey) {\n const raw = typeof publicKey === 'string' ? VaultCrypto.base64ToBuf(publicKey) : publicKey;\n const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', raw));\n const words = [];\n for (let i = 0; i < FP_WORD_COUNT; i++) words.push(fpSyllable(digest[i]));\n return words.join('-');\n }\n\n /**\n * Wrap ECDH private key with master_key (KEK).\n * @param {CryptoKey} masterKey \u2014 KEK\n * @param {Uint8Array} privateKey \u2014 32-byte X25519 private key\n * @returns {Promise<string>} Base64 IV+ciphertext\n */\n async function wrapEcdhPrivateKey(masterKey, privateKey) {\n const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));\n const encrypted = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv },\n masterKey,\n privateKey\n );\n const packed = new Uint8Array(iv.length + encrypted.byteLength);\n packed.set(iv, 0);\n packed.set(new Uint8Array(encrypted), iv.length);\n return VaultCrypto.bufToBase64(packed);\n }\n\n // \u2500\u2500\u2500 Registration crypto bundle \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Orchestrates all crypto for cloud registration in one call.\n\n /**\n * Generate all crypto material needed for cloud registration.\n * @param {string} password \u2014 master password\n * @param {Uint8Array} encSalt \u2014 32-byte PBKDF2 salt (from VaultCrypto.generateSalt())\n * @returns {Promise<{\n * auth_hash: string,\n * enc_salt: string,\n * encrypted_vault_key: string,\n * encrypted_recovery_blob: string,\n * encrypted_ecdh_private_key: string,\n * ecdh_public_key: string,\n * recovery_key: Uint8Array,\n * vault_key: Uint8Array,\n * }>}\n */\n async function prepareRegistration(password, encSalt) {\n // 1. Derive master_key (KEK) from password\n const masterKey = await VaultCrypto.deriveMasterKey(password, encSalt);\n\n // 2. Derive auth_hash for server\n const authHash = await deriveAuthHash(masterKey, password);\n\n // 3. Generate vault_key (DEK)\n const vaultKey = generateVaultKey();\n\n // 4. Generate recovery key\n const recoveryKey = generateRecoveryKey();\n\n // 5. Wrap vault_key with master_key \u2192 encrypted_vault_key\n const encryptedVaultKey = await wrapVaultKey(masterKey, vaultKey);\n\n // 6. Generate real X25519 key pair and wrap private key with master_key\n const ecdh = await generateEcdhKeyPair();\n const encryptedEcdhPrivate = await wrapEcdhPrivateKey(masterKey, ecdh.privateKey);\n\n // 7. Wrap vault_key + ECDH private key with recovery_key \u2192 v2 recovery blob\n // (keypair-preserving recovery, O3). New accounts are born ecdh-real\n // (ecdh_key_version = 1) so they never need the placeholder migration.\n const encryptedRecoveryBlob = await wrapVaultKeyWithRecovery(recoveryKey, vaultKey, ecdh.privateKey);\n\n return {\n auth_hash: authHash,\n enc_salt: VaultCrypto.bufToBase64(encSalt),\n encrypted_vault_key: encryptedVaultKey,\n encrypted_recovery_blob: encryptedRecoveryBlob,\n encrypted_ecdh_private_key: encryptedEcdhPrivate,\n ecdh_public_key: VaultCrypto.bufToBase64(ecdh.publicKey),\n ecdh_key_version: 1, // real X25519 from the start\n recovery_key: recoveryKey, // Show to user ONCE as BIP39 mnemonic\n vault_key: vaultKey, // Keep in memory for immediate sync\n };\n }\n\n // \u2500\u2500\u2500 ECDH placeholder \u2192 real migration (T10) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Existing cloud users (v3.0.0) hold a cryptographically useless placeholder\n // ECDH key (random public key, not derived from the private key). On unlock,\n // if ecdh_key_version = 0, the client generates a REAL pair, re-wraps the\n // private key with master_key, and uploads the new public key (version \u2192 1).\n // Transparent \u2014 no UX interruption. We cannot rewrap the recovery blob here\n // (the one-time recovery key is not held in memory), so migrated users get a\n // fresh pair on a future recovery; that is acceptable since nothing has\n // wrapped a DEK to their public key yet (shared vaults arrive in T11).\n\n /**\n * Prepare migration material for a placeholder\u2192real ECDH upgrade.\n * @param {CryptoKey} masterKey \u2014 KEK (from unlock)\n * @returns {Promise<{ encrypted_ecdh_private_key: string, ecdh_public_key: string }>}\n */\n async function prepareEcdhMigration(masterKey) {\n const ecdh = await generateEcdhKeyPair();\n const encryptedEcdhPrivate = await wrapEcdhPrivateKey(masterKey, ecdh.privateKey);\n return {\n encrypted_ecdh_private_key: encryptedEcdhPrivate,\n ecdh_public_key: VaultCrypto.bufToBase64(ecdh.publicKey),\n };\n }\n\n // \u2500\u2500\u2500 Login crypto helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Derive auth_hash for login and prepare to unwrap vault_key.\n * @param {string} password \u2014 master password\n * @param {string} encSaltBase64 \u2014 enc_salt from server (login response)\n * @returns {Promise<{ auth_hash: string, masterKey: CryptoKey }>}\n */\n async function prepareLogin(password, encSaltBase64) {\n const encSalt = VaultCrypto.base64ToBuf(encSaltBase64);\n const masterKey = await VaultCrypto.deriveMasterKey(password, encSalt);\n const authHash = await deriveAuthHash(masterKey, password);\n return { auth_hash: authHash, masterKey };\n }\n\n /**\n * After successful login, unwrap vault_key from server response.\n * @param {CryptoKey} masterKey \u2014 from prepareLogin()\n * @param {string} encryptedVaultKey \u2014 from login response\n * @returns {Promise<Uint8Array>} 32-byte vault_key (DEK)\n */\n async function unlockVaultKey(masterKey, encryptedVaultKey) {\n return unwrapVaultKey(masterKey, encryptedVaultKey);\n }\n\n /**\n * Full client-side recovery: decrypt vault_key with recovery key,\n * prepare new credentials (new master password + new recovery key).\n * @param {string} recoveryKeyB64 \u2014 Base64 recovery key (as shown to user)\n * @param {string} recoveryBlobB64 \u2014 encrypted_recovery_blob from server\n * @param {string} newPassword \u2014 new master password chosen by user\n */\n async function prepareRecovery(recoveryKeyB64, recoveryBlobB64, newPassword) {\n const recoveryKey = VaultCrypto.base64ToBuf(recoveryKeyB64);\n\n // Throws DOMException if recovery key is wrong\n const { vaultKey, ecdhPrivateKey } = await unwrapRecoveryBlob(recoveryKey, recoveryBlobB64);\n\n const newEncSalt = VaultCrypto.generateSalt();\n const newMasterKey = await VaultCrypto.deriveMasterKey(newPassword, newEncSalt);\n const newAuthHash = await deriveAuthHash(newMasterKey, newPassword);\n const newEncryptedVaultKey = await wrapVaultKey(newMasterKey, vaultKey);\n\n // Keypair-preserving recovery (O3). Recovery changes master_key, which would\n // orphan the server's encrypted_ecdh_private_key (wrapped under the OLD key).\n // v2 blob \u2192 recover the SAME private key, re-wrap it under the new master_key\n // and re-derive the public key so existing shared-vault wraps stay valid.\n // v1 blob (legacy / migrated) \u2192 no key in blob, mint a fresh real pair.\n let ecdhPriv = ecdhPrivateKey;\n const preservedKeypair = !!ecdhPrivateKey;\n if (!ecdhPriv) {\n ecdhPriv = (await generateEcdhKeyPair()).privateKey;\n }\n const ecdhPublicRaw = await ecdhPublicFromPrivate(ecdhPriv);\n const newEncryptedEcdhPrivate = await wrapEcdhPrivateKey(newMasterKey, ecdhPriv);\n\n const newRecoveryKey = generateRecoveryKey();\n const newEncryptedRecoveryBlob = await wrapVaultKeyWithRecovery(newRecoveryKey, vaultKey, ecdhPriv);\n\n return {\n new_auth_hash: newAuthHash,\n new_enc_salt: VaultCrypto.bufToBase64(newEncSalt),\n new_encrypted_vault_key: newEncryptedVaultKey,\n new_encrypted_recovery_blob: newEncryptedRecoveryBlob,\n new_encrypted_ecdh_private_key: newEncryptedEcdhPrivate,\n new_ecdh_public_key: VaultCrypto.bufToBase64(ecdhPublicRaw),\n ecdh_keypair_preserved: preservedKeypair,\n new_recovery_key_b64: VaultCrypto.bufToBase64(newRecoveryKey),\n vault_key: vaultKey,\n };\n }\n\n // \u2500\u2500\u2500 Public API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n return {\n // Auth hash\n deriveAuthHash,\n\n // Vault key (DEK)\n generateVaultKey,\n wrapVaultKey,\n unwrapVaultKey,\n importVaultKey,\n\n // Per-entry encrypt/decrypt\n encryptEntry,\n decryptEntry,\n\n // Recovery\n generateRecoveryKey,\n wrapVaultKeyWithRecovery,\n unwrapVaultKeyWithRecovery,\n unwrapRecoveryBlob,\n\n // ECDH key pair\n generateEcdhKeyPair,\n wrapEcdhPrivateKey,\n importEcdhPrivateKey,\n importEcdhPublicKey,\n ecdhPublicFromPrivate,\n\n // Shared-vault key exchange (T10)\n deriveSharedWrapKey,\n wrapVaultKeyForMember,\n unwrapSharedVaultKey,\n deriveFingerprintPhrase,\n\n // ECDH migration\n prepareEcdhMigration,\n\n // Orchestrators\n prepareRegistration,\n prepareLogin,\n unlockVaultKey,\n prepareRecovery,\n };\n})();\n\nif (typeof module !== 'undefined') module.exports = VaultCloudCrypto;\n", "// \u2500\u2500\u2500 Geslar \u2014 Org Recovery Enrollment Crypto \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Client-side sealed-box for Family Recovery (#23 Faza 2).\n//\n// Protocol overview:\n// Enroll: ephemeralX25519 + ECDH(ephemeral, orgRecoveryPub) \u2192 HKDF \u2192 AES-256-GCM\n// payload = { vaultKey(32) \u2016 ecdhPriv(48) } encrypted with AAD\n// wire: ephemeralPub(32) \u2016 nonce(12) \u2016 ciphertext+tag\n//\n// Reset: admin decrypts using orgRecoveryPriv + ephemeralPub from wire, same AAD\n//\n// T1: client verifies org recovery pub FINGERPRINT before sealing\n//\n// AAD binding: TextEncoder(\"orgId:memberUserId:keyVersion\")\n// HKDF domain: salt = \"geslar-recovery-seal-salt-v1\"\n// info = \"geslar-org-recovery-seal-v1\"\n//\n// Requires Web Crypto (crypto.subtle). Uses the same fingerprint algorithm as\n// VaultCloudCrypto.deriveFingerprintPhrase and the server (ecdh-fingerprint.ts).\n\nconst OrgRecoveryCrypto = (() => {\n 'use strict';\n\n const EPHEMERAL_PUB_BYTES = 32;\n const IV_BYTES = 12;\n\n const HKDF_SALT = new TextEncoder().encode('geslar-recovery-seal-salt-v1');\n const HKDF_INFO = new TextEncoder().encode('geslar-org-recovery-seal-v1');\n\n // Fingerprint constants \u2014 MUST match VaultCloudCrypto and server (ecdh-fingerprint.ts).\n const FP_CONS_INITIAL = ['b','d','f','g','k','l','m','n','p','r','s','t','v','z','h','j'];\n const FP_VOWELS = ['a','e','i','o'];\n const FP_CONS_FINAL = ['k','n','s','t'];\n const FP_WORD_COUNT = 6;\n\n // \u2500\u2500 Helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n function fpSyllable(byte) {\n return FP_CONS_INITIAL[(byte >> 4) & 0x0f]\n + FP_VOWELS[(byte >> 2) & 0x03]\n + FP_CONS_FINAL[byte & 0x03];\n }\n\n async function fingerprintFromPub(publicRaw) {\n const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', publicRaw));\n const words = [];\n for (let i = 0; i < FP_WORD_COUNT; i++) words.push(fpSyllable(digest[i]));\n return words.join('-');\n }\n\n async function deriveWrapKey(sharedSecret, aad) {\n // HKDF-SHA256 over DH shared secret, with AAD mixed into info so a key\n // derived for one (orgId, memberUserId, keyVersion) triple cannot be reused.\n const combinedInfo = new Uint8Array([...HKDF_INFO, 0x00, ...aad]);\n const ikm = await crypto.subtle.importKey('raw', sharedSecret, 'HKDF', false, ['deriveBits']);\n const okm = await crypto.subtle.deriveBits(\n { name: 'HKDF', hash: 'SHA-256', salt: HKDF_SALT, info: combinedInfo },\n ikm, 256,\n );\n return crypto.subtle.importKey('raw', okm, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);\n }\n\n // F5: reject all-zero DH output (low-order point / small subgroup attack guard).\n function isAllZero(buf) {\n return new Uint8Array(buf).every(b => b === 0);\n }\n\n // \u2500\u2500 Public API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Build the Additional Authenticated Data for a recovery payload.\n * Byte format: UTF-8(\"orgId:memberUserId:keyVersion\")\n * @param {string} orgId\n * @param {string} memberUserId\n * @param {number} keyVersion \u2014 member's ECDH key version at enrollment time\n * @returns {Uint8Array}\n */\n function buildRecoveryAAD(orgId, memberUserId, keyVersion) {\n return new TextEncoder().encode(`${orgId}:${memberUserId}:${keyVersion}`);\n }\n\n /**\n * Verify an org recovery public key against a displayed fingerprint phrase.\n * Invoke before sealRecoveryPayload so the user can confirm the key out-of-band.\n * @param {Uint8Array} orgRecoveryPubRaw \u2014 raw 32-byte org recovery public key\n * @param {string} expectedFingerprint \u2014 e.g. \"bok-tas-\u2026\" (6 syllables)\n * @returns {Promise<boolean>}\n */\n async function verifyOrgRecoveryKeyFingerprint(orgRecoveryPubRaw, expectedFingerprint) {\n const computed = await fingerprintFromPub(orgRecoveryPubRaw);\n return computed === expectedFingerprint;\n }\n\n /**\n * Seal a recovery payload for the org recovery public key.\n *\n * Emits: ephemeralPub(32) \u2016 nonce(12) \u2016 ciphertext+tag\n *\n * @param {Uint8Array} orgRecoveryPubRaw \u2014 raw 32-byte org recovery public key\n * @param {Uint8Array} payload \u2014 plaintext payload (vaultKey \u2016 ecdhPriv)\n * @param {Uint8Array} aad \u2014 from buildRecoveryAAD()\n * @returns {Promise<Uint8Array>} sealedBlob\n */\n async function sealRecoveryPayload(orgRecoveryPubRaw, payload, aad) {\n // 1. Generate fresh ephemeral X25519 keypair.\n const ephemeralPair = await crypto.subtle.generateKey({ name: 'X25519' }, true, ['deriveBits']);\n const ephemeralPubRaw = new Uint8Array(\n await crypto.subtle.exportKey('raw', ephemeralPair.publicKey)\n );\n\n // 2. ECDH(ephemeralPriv, orgRecoveryPub) \u2192 256-bit shared secret.\n const orgPubKey = await crypto.subtle.importKey(\n 'raw', orgRecoveryPubRaw, { name: 'X25519' }, false, []\n );\n const sharedSecret = await crypto.subtle.deriveBits(\n { name: 'X25519', public: orgPubKey }, ephemeralPair.privateKey, 256\n );\n if (isAllZero(sharedSecret)) throw new Error('Low-order point: shared secret is all-zero');\n\n // 3. HKDF \u2192 AES-256-GCM wrap key (AAD-bound).\n const wrapKey = await deriveWrapKey(sharedSecret, aad);\n\n // 4. AES-256-GCM encrypt payload with AAD.\n const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));\n const ciphertext = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv, additionalData: aad },\n wrapKey,\n payload,\n );\n\n // 5. Pack: ephemeralPub(32) \u2016 iv(12) \u2016 ciphertext+tag.\n const blob = new Uint8Array(EPHEMERAL_PUB_BYTES + IV_BYTES + ciphertext.byteLength);\n blob.set(ephemeralPubRaw, 0);\n blob.set(iv, EPHEMERAL_PUB_BYTES);\n blob.set(new Uint8Array(ciphertext), EPHEMERAL_PUB_BYTES + IV_BYTES);\n return blob;\n }\n\n /**\n * Open (decrypt) a sealed recovery payload.\n * Throws DOMException (OperationError) if AAD or key is wrong \u2014 tamper-evident.\n *\n * @param {Uint8Array} orgRecoveryPrivPkcs8 \u2014 org recovery private key (PKCS#8 DER, 48 B)\n * @param {Uint8Array} sealedBlob \u2014 output of sealRecoveryPayload()\n * @param {Uint8Array} aad \u2014 MUST match the value used during seal\n * @returns {Promise<Uint8Array>} plaintext payload\n */\n async function openRecoveryPayload(orgRecoveryPrivPkcs8, sealedBlob, aad) {\n if (sealedBlob.length <= EPHEMERAL_PUB_BYTES + IV_BYTES) {\n throw new Error('Sealed blob is too short');\n }\n\n // 1. Unpack: ephemeralPub \u2016 iv \u2016 ciphertext+tag.\n const ephemeralPubRaw = sealedBlob.slice(0, EPHEMERAL_PUB_BYTES);\n const iv = sealedBlob.slice(EPHEMERAL_PUB_BYTES, EPHEMERAL_PUB_BYTES + IV_BYTES);\n const ciphertext = sealedBlob.slice(EPHEMERAL_PUB_BYTES + IV_BYTES);\n\n // 2. Import org recovery private key for ECDH.\n const orgPrivKey = await crypto.subtle.importKey(\n 'pkcs8', orgRecoveryPrivPkcs8, { name: 'X25519' }, false, ['deriveBits']\n );\n\n // 3. ECDH(orgPriv, ephemeralPub) \u2192 shared secret (reciprocal of seal).\n const ephemeralPubKey = await crypto.subtle.importKey(\n 'raw', ephemeralPubRaw, { name: 'X25519' }, false, []\n );\n const sharedSecret = await crypto.subtle.deriveBits(\n { name: 'X25519', public: ephemeralPubKey }, orgPrivKey, 256\n );\n if (isAllZero(sharedSecret)) throw new Error('Low-order point: shared secret is all-zero');\n\n // 4. HKDF \u2192 same wrap key.\n const wrapKey = await deriveWrapKey(sharedSecret, aad);\n\n // 5. AES-256-GCM decrypt \u2014 throws OperationError if AAD or ciphertext is wrong.\n const plaintext = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv, additionalData: aad },\n wrapKey,\n ciphertext,\n );\n return new Uint8Array(plaintext);\n }\n\n return {\n buildRecoveryAAD,\n verifyOrgRecoveryKeyFingerprint,\n sealRecoveryPayload,\n openRecoveryPayload,\n };\n})();\n\nif (typeof module !== 'undefined') module.exports = OrgRecoveryCrypto;\n", "#!/usr/bin/env -S node --\n// ^ DO NOT \"simplify\" this back to `#!/usr/bin/env node`. Node.js (>=20.6)\n// has its OWN native `--env-file` CLI flag, and it intercepts that exact\n// token ANYWHERE in argv \u2014 even after the script path, even past our own\n// `--` separator \u2014 before a single line of this file ever runs (confirmed:\n// `node script.js run --env-file .env -- echo hi` fails with Node's own\n// \"env-file not found\" error, never reaching our code). Since `geslar run\n// --env-file <f>` is the spec'd syntax (spec-agentic-access.md \u00A73.1/\u00A73.2),\n// we can't rename the flag away from the collision \u2014 instead the trailing\n// `--` in this shebang makes `env -S` split it into `node --`, so Node\n// starts with argv already past its own flag-scanning boundary. Verified\n// against BOTH npm's and pnpm's real bin-shim generators (they parse extra\n// shebang args and reproduce them in the generated .cmd/.ps1 and POSIX sh\n// wrapper) \u2014 see tests/bin-shim.test.ts, which installs the packed tarball\n// for real and executes the GENERATED shim, not `node dist/index.js`\n// directly. A standalone binary (M4, Node SEA/pkg) doesn't go through Node's\n// CLI argv-scanning at all, so this workaround is npm-distribution-only.\nimport { Command } from 'commander';\nimport { signinCommand, CLI_VERSION } from './commands/signin.js';\nimport { signoutCommand } from './commands/signout.js';\nimport { whoamiCommand } from './commands/whoami.js';\nimport { unlockCommand } from './commands/unlock.js';\nimport { lockCommand } from './commands/lock.js';\nimport { listCommand } from './commands/list.js';\nimport { readCommand } from './commands/read.js';\nimport { runCommand } from './commands/run.js';\nimport { injectCommand } from './commands/inject.js';\nimport { agentCreateCommand } from './commands/agent-create.js';\nimport { agentListCommand } from './commands/agent-list.js';\nimport { agentRevokeCommand } from './commands/agent-revoke.js';\nimport { printErr } from './lib/output.js';\nimport { EXIT } from './lib/errors.js';\n\nconst program = new Command();\n\nprogram\n .name('geslar')\n .description('Geslar Agentic Access CLI')\n .enablePositionalOptions()\n .option('--agent <name>', 'operate as this agent profile instead of your own account (spec-access-core.md \u00A74)')\n .version(CLI_VERSION);\n\n// Normalizes --agent into GESLAR_AGENT once, before any subcommand's action\n// runs \u2014 every command (and requireHumanContext/resolveApiContext) then only\n// ever has to check the one env var, regardless of how it was set. Runs for\n// EVERY subcommand invocation (root-level hook), so this is the single choke\n// point --agent flows through \u2014 no per-command wiring needed.\nprogram.hook('preAction', (thisCommand) => {\n const agentOpt = thisCommand.opts()['agent'] as string | undefined;\n if (agentOpt) process.env['GESLAR_AGENT'] = agentOpt;\n});\n\nprogram\n .command('signin')\n .description('Sign in via device-flow (opens a code to enter at the console)')\n .option('--api <url>', 'override the API base URL')\n .action(async (opts: { api?: string }) => {\n process.exitCode = await signinCommand(opts);\n });\n\nprogram\n .command('signout')\n .description('Revoke this session and clear the local token')\n .action(async () => {\n process.exitCode = await signoutCommand();\n });\n\nprogram\n .command('whoami')\n .description('Show the signed-in account, plan, and org context')\n .action(async () => {\n process.exitCode = await whoamiCommand();\n });\n\nprogram\n .command('unlock')\n .description('Unlock the vault for headless use (stores a TTL-bound grant, OS-wrapped)')\n .option('--ttl <duration>', 'grant lifetime, e.g. 30m, 1h (default 30m, max 8h)')\n .action(async (opts: { ttl?: string }) => {\n process.exitCode = await unlockCommand(opts);\n });\n\nprogram\n .command('lock')\n .description('Clear the unlock grant immediately')\n .action(async () => {\n process.exitCode = await lockCommand();\n });\n\nprogram\n .command('list')\n .argument('[vault]', 'only list this vault (by name)')\n .description('List vaults and item names (no values)')\n .action(async (vaultFilter: string | undefined) => {\n process.exitCode = await listCommand(vaultFilter);\n });\n\nprogram\n .command('read')\n .argument('<ref>', 'a geslar://<vault>/<item>[/<field>] reference')\n .option('-o, --output <file>', 'write the value to this file (mode 0600) instead of stdout')\n .description('Resolve a geslar:// reference and print (or write) its value')\n .action(async (ref: string, opts: { output?: string }) => {\n process.exitCode = await readCommand(ref, opts);\n });\n\nprogram\n .command('run')\n .description('Run a command with geslar:// references resolved into its environment (fail-closed)')\n .option('--env-file <file>', 'dotenv file \u2014 geslar:// values are resolved, everything else passed through literally')\n .option(\n '-e, --env <mapping>',\n 'KEY=ref (repeatable) \u2014 overrides the same key from --env-file',\n (val: string, prev: string[]) => [...prev, val],\n [] as string[],\n )\n .argument('<command>', 'command to run')\n .argument('[args...]', 'arguments for the command')\n .enablePositionalOptions()\n .passThroughOptions()\n .action(async (command: string, args: string[], opts: { envFile?: string; env: string[] }) => {\n process.exitCode = await runCommand(command, args, opts);\n });\n\nprogram\n .command('inject')\n .description('Substitute {{ geslar://... }} placeholders in a template file (fail-closed)')\n .requiredOption('-i, --input <file>', 'template file')\n .requiredOption('-o, --output <file>', 'output file (mode 0600)')\n .action(async (opts: { input: string; output: string }) => {\n process.exitCode = await injectCommand(opts);\n });\n\nconst agent = program\n .command('agent')\n .description('Manage agent profiles \u2014 scoped machine credentials (spec-access-core.md)');\n\nagent\n .command('create')\n .argument('<name>', 'profile name')\n .description('Create an agent profile scoped to one or more vaults (TTY required, fresh TOTP)')\n .option('--vault <name>', 'vault to grant access to (repeatable)', (val: string, prev: string[]) => [...prev, val], [] as string[])\n .option('--allow-read', 'opt-in: also grant the read capability (default is run+inject only)')\n .option('--expires <duration>', 'e.g. 90d, or \"never\" (default: 90d)')\n .option('--show-token', 'print the plaintext token once (otherwise it only goes to local storage)')\n .action(async (name: string, opts: { vault: string[]; allowRead?: boolean; expires?: string; showToken?: boolean }) => {\n process.exitCode = await agentCreateCommand(name, opts);\n });\n\nagent\n .command('list')\n .description('List your agent profiles')\n .action(async () => {\n process.exitCode = await agentListCommand({});\n });\n\nagent\n .command('revoke')\n .argument('<name>', 'profile name')\n .description('Revoke an agent profile and clear its local token')\n .action(async (name: string) => {\n process.exitCode = await agentRevokeCommand(name, {});\n });\n\n// An IIFE, not top-level await: the npm-published dist/index.js is ESM (fine\n// either way), but the standalone-binary build (scripts/build-binary.mjs)\n// bundles this same entry point to CJS for Node's SEA feature, which doesn't\n// support top-level await.\nvoid (async () => {\n try {\n await program.parseAsync(process.argv);\n } catch (err) {\n printErr((err as Error).message);\n process.exitCode = EXIT.GENERAL;\n }\n})();\n", "import { hostname, platform } from 'node:os';\nimport { loadOrInitConfig } from '../lib/config.js';\nimport { saveSession } from '../lib/session.js';\nimport { print, printErr } from '../lib/output.js';\nimport { CliError, EXIT } from '../lib/errors.js';\nimport { selectBackend, createCliTokenStore } from '../token-store/index.js';\nimport { startDeviceFlow, pollDeviceFlow } from '../device-flow.js';\n\nexport const CLI_VERSION = '0.2.0';\n\nexport async function signinCommand(opts: { api?: string }): Promise<number> {\n const config = await loadOrInitConfig();\n const baseUrl = opts.api ?? config.apiBase;\n\n try {\n const start = await startDeviceFlow(baseUrl, {\n device_fingerprint: config.deviceFingerprint,\n hostname: hostname(),\n os: platform(),\n cli_version: CLI_VERSION,\n });\n\n print('');\n print(` Your code: ${start.user_code}`);\n print('');\n print(` Open ${start.verification_uri} and enter the code above to sign in.`);\n print(' (Type the code yourself \u2014 never follow a link that already has it filled in.)');\n print('');\n print('Waiting for approval...');\n\n const result = await pollDeviceFlow(baseUrl, start);\n\n const backend = await selectBackend();\n const tokenStore = await createCliTokenStore(backend);\n tokenStore.set({ access_token: result.access_token, refresh_token: result.refresh_token });\n await tokenStore.flush();\n\n await saveSession({ email: result.email, userId: result.user_id, plan: result.plan, apiBase: baseUrl });\n\n print(`Signed in as ${result.email} (${result.plan} plan).`);\n return EXIT.OK;\n } catch (err) {\n if (err instanceof CliError) {\n printErr(err.message);\n return err.exitCode;\n }\n printErr((err as Error).message);\n return EXIT.GENERAL;\n }\n}\n", "import { randomUUID } from 'node:crypto';\nimport { readFile, writeFile } from 'node:fs/promises';\nimport { configFilePath, ensureConfigDir } from './paths.js';\n\nexport const DEFAULT_API_BASE = 'https://api.geslar.app';\n\nexport interface CliConfig {\n /** Stable per-install id sent as device_fingerprint on every `signin` \u2014 lets\n * the server recognize \"this CLI install\" across sign-ins instead of\n * minting a new device row every time (see resolveDeviceSlot). */\n deviceFingerprint: string;\n apiBase: string;\n}\n\nconst CONFIG_FILE = 'config.json';\n\n/** Load the persisted config, creating one (with a fresh device_fingerprint) on first run. */\nexport async function loadOrInitConfig(): Promise<CliConfig> {\n const path = configFilePath(CONFIG_FILE);\n try {\n const raw = await readFile(path, 'utf-8');\n const parsed = JSON.parse(raw) as Partial<CliConfig>;\n if (parsed.deviceFingerprint && parsed.apiBase) {\n return { deviceFingerprint: parsed.deviceFingerprint, apiBase: parsed.apiBase };\n }\n } catch {\n // Missing or corrupt \u2014 fall through to (re)initialize.\n }\n const config: CliConfig = { deviceFingerprint: `cli-${randomUUID()}`, apiBase: DEFAULT_API_BASE };\n await ensureConfigDir();\n await writeFile(path, JSON.stringify(config, null, 2), 'utf-8');\n return config;\n}\n", "import { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { mkdir } from 'node:fs/promises';\n\n/** ~/.geslar \u2014 everything the CLI persists locally lives under this one directory. */\nexport function configDir(): string {\n return join(homedir(), '.geslar');\n}\n\nexport async function ensureConfigDir(): Promise<string> {\n const dir = configDir();\n await mkdir(dir, { recursive: true });\n return dir;\n}\n\nexport function configFilePath(name: string): string {\n return join(configDir(), name);\n}\n", "import { readFile, writeFile, rm } from 'node:fs/promises';\nimport { configFilePath, ensureConfigDir } from './paths.js';\n\n/** Non-secret identity cache \u2014 set by `signin`, cleared by `signout`. Never\n * holds tokens (those live in the OS-backed token store, see ../token-store). */\nexport interface CliSession {\n email: string;\n userId: string;\n plan: string;\n apiBase: string;\n}\n\nconst SESSION_FILE = 'session.json';\n\nexport async function loadSession(): Promise<CliSession | null> {\n try {\n const raw = await readFile(configFilePath(SESSION_FILE), 'utf-8');\n return JSON.parse(raw) as CliSession;\n } catch {\n return null;\n }\n}\n\nexport async function saveSession(session: CliSession): Promise<void> {\n await ensureConfigDir();\n await writeFile(configFilePath(SESSION_FILE), JSON.stringify(session, null, 2), 'utf-8');\n}\n\nexport async function clearSession(): Promise<void> {\n await rm(configFilePath(SESSION_FILE), { force: true });\n}\n", "/**\n * Output scrubber (spec \u00A73.2/\u00A78.1) \u2014 every value the CLI resolves from a\n * vault gets registered here; every string the CLI itself writes (stdout,\n * stderr, error messages, crash output) is passed through `scrub()` first.\n * This is the last line of defense against a secret accidentally ending up\n * in a log line, an error message, or an uncaught-exception dump.\n *\n * Module-level singleton by design \u2014 one CLI invocation, one process, one\n * scrubber. Values are matched longest-first so a short value can't mask a\n * longer one that contains it as a substring.\n */\n\nconst registered = new Set<string>();\n\n/** Register a resolved secret value so every future print/error masks it. */\nexport function registerSecret(value: string): void {\n if (value.length === 0) return; // an empty registration would match everything\n registered.add(value);\n}\n\n/** Replace every registered value in `text` with `***`. No-op if nothing registered. */\nexport function scrub(text: string): string {\n if (registered.size === 0) return text;\n let out = text;\n const values = [...registered].sort((a, b) => b.length - a.length);\n for (const value of values) {\n out = out.split(value).join('***');\n }\n return out;\n}\n\n/** Test-only: reset registered values between test cases. */\nexport function _resetScrubberForTests(): void {\n registered.clear();\n}\n", "import { scrub } from './scrubber.js';\n\n/** Zero-dependency stdout/stderr helpers. No color library per spec \u00A71 (only\n * @geslar/core + commander). Every write goes through the scrubber (\u00A73.2/\u00A78.1)\n * \u2014 this is the single choke point ALL CLI output passes through. */\n\nexport function print(message: string): void {\n process.stdout.write(`${scrub(message)}\\n`);\n}\n\nexport function printErr(message: string): void {\n process.stderr.write(`geslar: ${scrub(message)}\\n`);\n}\n", "/** Exit codes \u2014 spec-agentic-access.md \u00A73.5. */\nexport const EXIT = {\n OK: 0,\n GENERAL: 1,\n AUTH: 2,\n ENTITLEMENT: 3,\n UNRESOLVABLE_REF: 4,\n GRANT_DENIED: 5,\n VAULT_LOCKED: 6,\n} as const;\n\nexport type ExitCode = (typeof EXIT)[keyof typeof EXIT];\n\n/** A CLI-level failure that maps directly to an exit code and a user-facing message. */\nexport class CliError extends Error {\n constructor(\n public readonly exitCode: ExitCode,\n message: string,\n ) {\n super(message);\n this.name = 'CliError';\n }\n}\n", "import { spawn } from 'node:child_process';\nimport { readFile, writeFile, rm } from 'node:fs/promises';\nimport { configFilePath, ensureConfigDir } from '../lib/paths.js';\nimport type { TokenStoreBackend } from './types.js';\n\n/**\n * Windows \u2014 DPAPI (spec \u00A73.4/R5). `cmdkey` cannot read back stored secrets\n * (write/list only), so it is NOT usable here; instead we shell out to the\n * PowerShell that ships with every Windows install and call\n * `System.Security.Cryptography.ProtectedData` (CurrentUser scope) directly.\n * No native Node addon required.\n *\n * The plaintext blob travels to/from PowerShell over STDIN/STDOUT only \u2014\n * never as a command-line argument or environment variable (spec \u00A78.2).\n */\n\nconst PROTECT_SCRIPT = `\n$ErrorActionPreference = 'Stop'\nAdd-Type -AssemblyName System.Security\n$b64 = [Console]::In.ReadToEnd()\n$bytes = [Convert]::FromBase64String($b64)\n$protected = [System.Security.Cryptography.ProtectedData]::Protect(\n $bytes, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)\n[Console]::Out.Write([Convert]::ToBase64String($protected))\n`;\n\nconst UNPROTECT_SCRIPT = `\n$ErrorActionPreference = 'Stop'\nAdd-Type -AssemblyName System.Security\n$b64 = [Console]::In.ReadToEnd()\n$bytes = [Convert]::FromBase64String($b64)\n$plain = [System.Security.Cryptography.ProtectedData]::Unprotect(\n $bytes, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)\n[Console]::Out.Write([Convert]::ToBase64String($plain))\n`;\n\nfunction runPowerShell(script: string, stdinData: string): Promise<string> {\n return new Promise((resolve, reject) => {\n const child = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], {\n stdio: ['pipe', 'pipe', 'pipe'],\n windowsHide: true,\n });\n let stdout = '';\n let stderr = '';\n child.stdout.on('data', (chunk: Buffer) => { stdout += chunk.toString('utf-8'); });\n child.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString('utf-8'); });\n child.on('error', reject);\n child.on('close', (code) => {\n if (code === 0) resolve(stdout.trim());\n else reject(new Error(`powershell exited ${code}: ${stderr.trim() || 'DPAPI operation failed'}`));\n });\n child.stdin.write(stdinData);\n child.stdin.end();\n });\n}\n\n/**\n * @param namespace Selects the on-disk file (`<namespace>.dpapi` under\n * ~/.geslar). `'tokens'` is the M1 auth-token store (do not rename \u2014 already\n * shipped); `'vault-grant'` (M2) is a separate file so revoking one never\n * touches the other.\n */\nexport function createWindowsDpapiBackend(namespace: string): TokenStoreBackend {\n const tokenFile = `${namespace}.dpapi`;\n\n return {\n name: 'windows-dpapi',\n\n async load(): Promise<string | null> {\n let protectedB64: string;\n try {\n protectedB64 = await readFile(configFilePath(tokenFile), 'utf-8');\n } catch {\n return null;\n }\n if (!protectedB64.trim()) return null;\n const plainB64 = await runPowerShell(UNPROTECT_SCRIPT, protectedB64);\n return Buffer.from(plainB64, 'base64').toString('utf-8');\n },\n\n async save(data: string): Promise<void> {\n const plainB64 = Buffer.from(data, 'utf-8').toString('base64');\n const protectedB64 = await runPowerShell(PROTECT_SCRIPT, plainB64);\n await ensureConfigDir();\n await writeFile(configFilePath(tokenFile), protectedB64, { encoding: 'utf-8', mode: 0o600 });\n },\n\n async clear(): Promise<void> {\n await rm(configFilePath(tokenFile), { force: true });\n },\n };\n}\n\nexport const windowsDpapiBackend: TokenStoreBackend = createWindowsDpapiBackend('tokens');\n", "import { spawn } from 'node:child_process';\nimport { userInfo } from 'node:os';\nimport type { TokenStoreBackend } from './types.js';\n\n/**\n * macOS \u2014 login keychain via the built-in `security` CLI (spec \u00A73.4). No\n * native dependency. `security add-generic-password` has no stdin mode for\n * the secret value (`-w`), so the value is briefly visible in `ps` output\n * during that one call \u2014 an accepted, documented platform limitation shared\n * by every keychain-backed CLI on macOS (e.g. `gh`, 1Password CLI). Lookup\n * (`-w` on `find-generic-password`) only prints to stdout, no exposure there.\n */\n\nfunction account(): string {\n return userInfo().username;\n}\n\nfunction run(args: string[], input?: string): Promise<{ code: number | null; stdout: string; stderr: string }> {\n return new Promise((resolve, reject) => {\n const child = spawn('security', args, { stdio: ['pipe', 'pipe', 'pipe'] });\n let stdout = '';\n let stderr = '';\n child.stdout.on('data', (c: Buffer) => { stdout += c.toString('utf-8'); });\n child.stderr.on('data', (c: Buffer) => { stderr += c.toString('utf-8'); });\n child.on('error', reject);\n child.on('close', (code) => resolve({ code, stdout, stderr }));\n if (input !== undefined) child.stdin.write(input);\n child.stdin.end();\n });\n}\n\n/**\n * @param namespace Selects the keychain service name. `'tokens'` maps to the\n * original M1 service name (`geslar-cli`, unchanged \u2014 already shipped, do\n * not rename or existing signins silently stop resolving); any other\n * namespace (e.g. `'vault-grant'`, M2) gets its own `geslar-cli-<namespace>`\n * item so revoking one never touches the other.\n */\nexport function createMacosKeychainBackend(namespace: string): TokenStoreBackend {\n const service = namespace === 'tokens' ? 'geslar-cli' : `geslar-cli-${namespace}`;\n\n return {\n name: 'macos-keychain',\n\n async load(): Promise<string | null> {\n const res = await run(['find-generic-password', '-a', account(), '-s', service, '-w']);\n if (res.code !== 0) return null; // not found \u2014 not an error\n return res.stdout.trim();\n },\n\n async save(data: string): Promise<void> {\n const res = await run(['add-generic-password', '-a', account(), '-s', service, '-w', data, '-U']);\n if (res.code !== 0) {\n throw new Error(`security add-generic-password failed: ${res.stderr.trim()}`);\n }\n },\n\n async clear(): Promise<void> {\n await run(['delete-generic-password', '-a', account(), '-s', service]);\n // Non-zero exit here just means \"nothing to delete\" \u2014 not an error.\n },\n };\n}\n\nexport const macosKeychainBackend: TokenStoreBackend = createMacosKeychainBackend('tokens');\n", "import { spawn } from 'node:child_process';\nimport { userInfo } from 'node:os';\nimport type { TokenStoreBackend } from './types.js';\n\n/**\n * Linux \u2014 libsecret via the `secret-tool` CLI (spec \u00A73.4), when present. No\n * native dependency. Both store and lookup pass the secret over stdin/stdout\n * only \u2014 never argv or env.\n */\n\nfunction account(): string {\n return userInfo().username;\n}\n\nfunction run(args: string[], input?: string): Promise<{ code: number | null; stdout: string; stderr: string }> {\n return new Promise((resolve, reject) => {\n const child = spawn('secret-tool', args, { stdio: ['pipe', 'pipe', 'pipe'] });\n let stdout = '';\n let stderr = '';\n child.stdout.on('data', (c: Buffer) => { stdout += c.toString('utf-8'); });\n child.stderr.on('data', (c: Buffer) => { stderr += c.toString('utf-8'); });\n child.on('error', reject);\n child.on('close', (code) => resolve({ code, stdout, stderr }));\n if (input !== undefined) child.stdin.write(input);\n child.stdin.end();\n });\n}\n\n/** Best-effort probe: is `secret-tool` on PATH and does a D-Bus secret service answer? */\nexport async function isSecretToolAvailable(): Promise<boolean> {\n try {\n const res = await run(['lookup', 'service', 'geslar-cli-probe', 'account', 'probe']);\n // Exit 1 (\"not found\") means secret-tool AND the secret service both work.\n // Anything that fails to spawn (ENOENT) rejects instead of resolving.\n return res.code === 0 || res.code === 1;\n } catch {\n return false;\n }\n}\n\n/**\n * @param namespace Selects the libsecret service name. `'tokens'` maps to\n * the original M1 service name (`geslar-cli`, unchanged \u2014 already shipped);\n * any other namespace (e.g. `'vault-grant'`, M2) gets its own\n * `geslar-cli-<namespace>` item.\n */\nexport function createLinuxSecretToolBackend(namespace: string): TokenStoreBackend {\n const service = namespace === 'tokens' ? 'geslar-cli' : `geslar-cli-${namespace}`;\n\n return {\n name: 'linux-secret-tool',\n\n async load(): Promise<string | null> {\n const res = await run(['lookup', 'service', service, 'account', account()]);\n if (res.code !== 0) return null;\n return res.stdout.trim() || null;\n },\n\n async save(data: string): Promise<void> {\n const res = await run(\n ['store', '--label', 'Geslar CLI token', 'service', service, 'account', account()],\n data,\n );\n if (res.code !== 0) {\n throw new Error(`secret-tool store failed: ${res.stderr.trim()}`);\n }\n },\n\n async clear(): Promise<void> {\n await run(['clear', 'service', service, 'account', account()]);\n },\n };\n}\n\nexport const linuxSecretToolBackend: TokenStoreBackend = createLinuxSecretToolBackend('tokens');\n", "import { hkdfSync, randomBytes, createCipheriv, createDecipheriv } from 'node:crypto';\nimport { userInfo } from 'node:os';\nimport { readFile, writeFile, rm } from 'node:fs/promises';\nimport { configFilePath, ensureConfigDir } from '../lib/paths.js';\nimport { getMachineId } from './machine-id.js';\nimport type { TokenStoreBackend } from './types.js';\n\n/**\n * Fallback backend (spec \u00A73.4) \u2014 used only when no OS-vaulted mechanism is\n * available (Linux without `secret-tool`/a running secret service). Weaker\n * than DPAPI/Keychain/libsecret: the key is derived from machine+user\n * identity rather than protected by the OS credential vault, so anyone who\n * can read this user's files on this machine can decrypt it. `weak: true`\n * makes the CLI print a loud warning on every use (R5).\n */\n\nconst HKDF_SALT = Buffer.from('geslar-cli-token-store-v1', 'utf-8');\nconst HKDF_INFO = Buffer.from('geslar-cli-token-store', 'utf-8');\nconst IV_LEN = 12;\n\nasync function deriveKey(): Promise<Buffer> {\n const machineId = await getMachineId();\n const ikm = Buffer.from(`${machineId}|${userInfo().username}`, 'utf-8');\n const key = hkdfSync('sha256', ikm, HKDF_SALT, HKDF_INFO, 32);\n return Buffer.from(key);\n}\n\n/**\n * @param namespace Selects the on-disk file (`<namespace>.enc` under\n * ~/.geslar). `'tokens'` is the M1 auth-token store (do not rename \u2014\n * already shipped); `'vault-grant'` (M2) is a separate file.\n */\nexport function createFallbackEncryptedFileBackend(namespace: string): TokenStoreBackend {\n const tokenFile = `${namespace}.enc`;\n\n return {\n name: 'fallback-hkdf-file',\n weak: true,\n\n async load(): Promise<string | null> {\n let blob: Buffer;\n try {\n blob = await readFile(configFilePath(tokenFile));\n } catch {\n return null;\n }\n if (blob.length < IV_LEN + 16) return null;\n const key = await deriveKey();\n const iv = blob.subarray(0, IV_LEN);\n const tag = blob.subarray(blob.length - 16);\n const ciphertext = blob.subarray(IV_LEN, blob.length - 16);\n const decipher = createDecipheriv('aes-256-gcm', key, iv);\n decipher.setAuthTag(tag);\n const plain = Buffer.concat([decipher.update(ciphertext), decipher.final()]);\n return plain.toString('utf-8');\n },\n\n async save(data: string): Promise<void> {\n const key = await deriveKey();\n const iv = randomBytes(IV_LEN);\n const cipher = createCipheriv('aes-256-gcm', key, iv);\n const ciphertext = Buffer.concat([cipher.update(data, 'utf-8'), cipher.final()]);\n const tag = cipher.getAuthTag();\n await ensureConfigDir();\n await writeFile(configFilePath(tokenFile), Buffer.concat([iv, ciphertext, tag]), { mode: 0o600 });\n },\n\n async clear(): Promise<void> {\n await rm(configFilePath(tokenFile), { force: true });\n },\n };\n}\n\nexport const fallbackEncryptedFileBackend: TokenStoreBackend = createFallbackEncryptedFileBackend('tokens');\n", "import { readFile, writeFile } from 'node:fs/promises';\nimport { randomBytes } from 'node:crypto';\nimport { configFilePath, ensureConfigDir } from '../lib/paths.js';\n\n/**\n * Best-effort stable machine identifier for the HKDF fallback backend (spec\n * \u00A73.4, weakest tier). Tries real OS machine ids first; if none is readable\n * (containers, locked-down systems), falls back to a random id generated\n * once and persisted locally \u2014 still stable per-machine-per-install, just\n * not tied to OS-level machine identity.\n */\nexport async function getMachineId(): Promise<string> {\n const fromOs = await readOsMachineId();\n if (fromOs) return fromOs;\n return getOrCreatePersistedId();\n}\n\nasync function readOsMachineId(): Promise<string | null> {\n if (process.platform === 'linux') {\n for (const path of ['/etc/machine-id', '/var/lib/dbus/machine-id']) {\n try {\n const id = (await readFile(path, 'utf-8')).trim();\n if (id) return id;\n } catch {\n // try next\n }\n }\n }\n return null;\n}\n\nconst ID_FILE = 'machine-salt';\n\nasync function getOrCreatePersistedId(): Promise<string> {\n const path = configFilePath(ID_FILE);\n try {\n const existing = (await readFile(path, 'utf-8')).trim();\n if (existing) return existing;\n } catch {\n // create below\n }\n const id = randomBytes(32).toString('hex');\n await ensureConfigDir();\n await writeFile(path, id, { encoding: 'utf-8', mode: 0o600 });\n return id;\n}\n", "import type { TokenStore, TokenPair } from '@geslar/core';\nimport { printErr } from '../lib/output.js';\nimport { createWindowsDpapiBackend } from './windows.js';\nimport { createMacosKeychainBackend } from './macos.js';\nimport { createLinuxSecretToolBackend, isSecretToolAvailable } from './linux.js';\nimport { createFallbackEncryptedFileBackend } from './fallback.js';\nimport type { TokenStoreBackend } from './types.js';\n\nexport type { TokenStoreBackend } from './types.js';\n\n/** Pick the right OS-backed mechanism for this platform (spec \u00A73.4 table).\n * `namespace` selects which secret this backend stores \u2014 `'tokens'` (M1\n * auth token pair, the default) and `'vault-grant'` (M2 `geslar unlock`\n * grant) are stored under separate OS items so revoking one never touches\n * the other. */\nexport async function selectBackend(namespace: string = 'tokens'): Promise<TokenStoreBackend> {\n if (process.platform === 'win32') return createWindowsDpapiBackend(namespace);\n if (process.platform === 'darwin') return createMacosKeychainBackend(namespace);\n if (await isSecretToolAvailable()) return createLinuxSecretToolBackend(namespace);\n return createFallbackEncryptedFileBackend(namespace);\n}\n\nexport interface CliTokenStore extends TokenStore {\n /** Await in-flight persist writes before the process exits. */\n flush(): Promise<void>;\n readonly backendName: string;\n}\n\n/**\n * ApiClient's TokenStore is synchronous (get/set), but every OS-backed\n * mechanism here is async (spawns a helper process or hits a keychain\n * daemon). We bridge the two the same way desktop apps bridge async secret\n * storage to a sync in-memory cache: load once up front, keep an in-memory\n * mirror for synchronous reads, and write-through asynchronously on every\n * `set()` \u2014 serialized so concurrent writes can't interleave and corrupt the\n * backend. Callers MUST `await flush()` before the process exits.\n */\nexport async function createCliTokenStore(backend: TokenStoreBackend): Promise<CliTokenStore> {\n if (backend.weak) {\n 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.');\n }\n\n let current: TokenPair | null = null;\n try {\n const raw = await backend.load();\n current = raw ? (JSON.parse(raw) as TokenPair) : null;\n } catch (err) {\n printErr(`could not read stored session (${(err as Error).message}) \u2014 treating as signed out`);\n current = null;\n }\n\n let pending: Promise<void> = Promise.resolve();\n\n return {\n backendName: backend.name,\n get: () => current,\n set: (tokens: TokenPair | null) => {\n current = tokens;\n pending = pending\n .then(() => (tokens ? backend.save(JSON.stringify(tokens)) : backend.clear()))\n .catch((err: unknown) => {\n printErr(`failed to persist session (${(err as Error).message})`);\n });\n },\n flush: () => pending,\n };\n}\n", "import { CliError, EXIT } from './lib/errors.js';\n\n/** RFC 8628 device authorization flow \u2014 client side (spec \u00A73.3). */\n\nexport interface DeviceStartResult {\n device_code: string;\n user_code: string;\n verification_uri: string;\n expires_in: number;\n interval: number;\n}\n\nexport interface DevicePollSuccess {\n access_token: string;\n refresh_token: string;\n token_type: string;\n expires_in: number;\n user_id: string;\n email: string;\n plan: string;\n}\n\nexport interface DeviceFlowClientInfo {\n device_fingerprint: string;\n hostname?: string;\n os?: string;\n cli_version?: string;\n}\n\ntype Fetch = typeof fetch;\n\nasync function readJson(res: Response): Promise<Record<string, unknown>> {\n const text = await res.text();\n return text ? (JSON.parse(text) as Record<string, unknown>) : {};\n}\n\nexport async function startDeviceFlow(\n baseUrl: string,\n info: DeviceFlowClientInfo,\n fetchImpl: Fetch = fetch,\n): Promise<DeviceStartResult> {\n const res = await fetchImpl(`${baseUrl}/v1/auth/device/start`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(info),\n });\n const body = await readJson(res);\n if (!res.ok) {\n throw new CliError(EXIT.GENERAL, (body['detail'] as string) ?? `Could not start sign-in (HTTP ${res.status})`);\n }\n return body as unknown as DeviceStartResult;\n}\n\nexport interface PollOptions {\n /** Called once per tick \u2014 lets the caller print progress (\".\"), stays silent by default. */\n onTick?: () => void;\n /** Injectable for tests \u2014 avoids real timers slowing down the suite. */\n sleep?: (ms: number) => Promise<void>;\n}\n\n/**\n * Poll until approved, denied, or expired. Client-side mirrors the server's\n * state machine 1:1 (spec \u00A73.3 exit codes): expired \u2192 2, denied \u2192 5.\n */\nexport async function pollDeviceFlow(\n baseUrl: string,\n start: DeviceStartResult,\n fetchImpl: Fetch = fetch,\n opts: PollOptions = {},\n): Promise<DevicePollSuccess> {\n const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));\n let interval = start.interval;\n const deadline = Date.now() + start.expires_in * 1000;\n\n for (;;) {\n if (Date.now() >= deadline) {\n throw new CliError(EXIT.AUTH, 'Device code expired \u2014 run `geslar signin` again');\n }\n await sleep(interval * 1000);\n opts.onTick?.();\n\n const res = await fetchImpl(`${baseUrl}/v1/auth/device/poll`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ device_code: start.device_code }),\n });\n const body = await readJson(res);\n\n if (res.ok) {\n return body as unknown as DevicePollSuccess;\n }\n\n switch (body['code']) {\n case 'device-flow/authorization-pending':\n continue;\n case 'device-flow/slow-down':\n interval = typeof body['interval'] === 'number' ? body['interval'] : interval + 5;\n continue;\n case 'device-flow/expired-token':\n throw new CliError(EXIT.AUTH, 'Device code expired \u2014 run `geslar signin` again');\n case 'device-flow/access-denied':\n throw new CliError(EXIT.GRANT_DENIED, 'Sign-in request was denied in the console');\n default:\n throw new CliError(EXIT.GENERAL, (body['detail'] as string) ?? `Sign-in failed (HTTP ${res.status})`);\n }\n }\n}\n", "import { selectBackend } from '../token-store/index.js';\nimport { CliError, EXIT } from '../lib/errors.js';\nimport type { UnlockedKeys } from './unlock.js';\n\n/** `geslar unlock` session grant (spec \u00A73.7, R2) \u2014 the OS-wrapped vault key\n * survives across headless CLI/MCP invocations without re-prompting for the\n * master password. Stored under its OWN OS item (`selectBackend('vault-grant')`,\n * distinct from the M1 auth-token item) so `geslar lock`/`signout` clearing\n * one never clears the other. */\n\nexport const DEFAULT_TTL_SEC = 30 * 60; // 30 min\nexport const MAX_TTL_SEC = 8 * 60 * 60; // 8 h\n\ninterface VaultGrant {\n dek: string; // base64 raw DEK bytes\n ecdhPrivRaw: string | null; // base64\n createdAt: number; // ms epoch\n ttlSec: number;\n}\n\n/** Parse `--ttl` values like `30m`, `1h`, `90s` (bare number = minutes). Clamps to MAX_TTL_SEC. */\nexport function parseTtl(input: string | undefined): number {\n if (!input) return DEFAULT_TTL_SEC;\n const m = /^(\\d+)\\s*(s|m|h)?$/.exec(input.trim());\n if (!m) {\n throw new CliError(EXIT.GENERAL, `Invalid --ttl value \"${input}\" \u2014 use e.g. 30m, 1h, 90s`);\n }\n const n = parseInt(m[1]!, 10);\n const unit = m[2] ?? 'm';\n const sec = unit === 's' ? n : unit === 'h' ? n * 3600 : n * 60;\n if (sec <= 0) {\n throw new CliError(EXIT.GENERAL, `--ttl must be positive, got \"${input}\"`);\n }\n return Math.min(sec, MAX_TTL_SEC);\n}\n\nexport async function saveVaultGrant(unlocked: UnlockedKeys, ttlSec: number): Promise<void> {\n const grant: VaultGrant = {\n dek: Buffer.from(unlocked.dekRaw).toString('base64'),\n ecdhPrivRaw: unlocked.ecdhPrivRaw ? Buffer.from(unlocked.ecdhPrivRaw).toString('base64') : null,\n createdAt: Date.now(),\n ttlSec,\n };\n const backend = await selectBackend('vault-grant');\n await backend.save(JSON.stringify(grant));\n}\n\n/** Returns null when there is no grant, it's malformed, or it has expired\n * (an expired grant is also actively cleared \u2014 self-healing, no stale file\n * lingering past its TTL). */\nexport async function loadVaultGrant(): Promise<UnlockedKeys | null> {\n const backend = await selectBackend('vault-grant');\n const raw = await backend.load();\n if (!raw) return null;\n\n let grant: VaultGrant;\n try {\n grant = JSON.parse(raw) as VaultGrant;\n } catch {\n return null;\n }\n\n if (Date.now() - grant.createdAt > grant.ttlSec * 1000) {\n await backend.clear();\n return null;\n }\n\n return {\n dekRaw: new Uint8Array(Buffer.from(grant.dek, 'base64')),\n ecdhPrivRaw: grant.ecdhPrivRaw ? new Uint8Array(Buffer.from(grant.ecdhPrivRaw, 'base64')) : null,\n };\n}\n\nexport async function clearVaultGrant(): Promise<void> {\n const backend = await selectBackend('vault-grant');\n await backend.clear();\n}\n", "import { loadSession, clearSession } from '../lib/session.js';\nimport { loadOrInitConfig } from '../lib/config.js';\nimport { print, printErr } from '../lib/output.js';\nimport { EXIT } from '../lib/errors.js';\nimport { selectBackend, createCliTokenStore } from '../token-store/index.js';\nimport { clearVaultGrant } from '../vault/grant.js';\n\n/**\n * Revoke server-side + wipe the local session. NOTE: intentionally does NOT\n * use ApiClient.serverLogout() \u2014 that method sends an empty body and relies\n * on the httpOnly refresh cookie (console-only path); Bearer clients like\n * this CLI must send `refresh_token` in the body for POST /v1/auth/logout to\n * actually find and delete the row server-side (src/plugins/auth/routes.ts).\n */\nexport async function signoutCommand(): Promise<number> {\n const backend = await selectBackend();\n const tokenStore = await createCliTokenStore(backend);\n const tokens = tokenStore.get();\n\n if (!tokens) {\n print('Not signed in.');\n return EXIT.OK;\n }\n\n const config = await loadOrInitConfig();\n const session = await loadSession();\n const baseUrl = session?.apiBase ?? config.apiBase;\n\n try {\n await fetch(`${baseUrl}/v1/auth/logout`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ refresh_token: tokens.refresh_token }),\n });\n } catch (err) {\n // Best-effort revoke \u2014 local session is cleared regardless (spec \u00A73.5: signout\n // must never leave a stale-but-unrevocable local session).\n printErr(`could not reach the server to revoke the session (${(err as Error).message}) \u2014 clearing local session anyway`);\n }\n\n tokenStore.set(null);\n await tokenStore.flush();\n await clearSession();\n // Spec \u00A73.7: signout is one of the automatic vault-lock triggers.\n await clearVaultGrant();\n\n print('Signed out.');\n return EXIT.OK;\n}\n", "// Geslar API client (shared). Fetch-based, bearer + refresh rotation.\n// E2EE invariant: this client never sends the master password or derived keys \u2014\n// only auth_hash and opaque wrapped blobs. All crypto happens in @geslar/core/crypto.\n\nimport type {\n LoginResponse,\n PreloginResponse,\n RegisterResponse,\n RefreshResponse,\n MfaRequiredResponse,\n MfaListResponse,\n MfaEnrollTotpResponse,\n RecoverInitResponse,\n RecoverCompleteResponse,\n Org,\n OrgBranding,\n OrgMember,\n EntitlementsBundle,\n TokenPair,\n MemberRole,\n InviteResult,\n CollectionSummary,\n CollectionMember,\n MemberKeyResult,\n VaultEntryWire,\n PutEntryResult,\n PublicPlan,\n CollectionRotationStage,\n CollectionRotationCommit,\n RemoveCollectionMemberResult,\n CredentialAction,\n PasswordKnownRow,\n CredentialAuditPage,\n ExposureSummary,\n AuditPage,\n DeviceRow,\n DeviceFlowContext,\n VaultKeyMaterial,\n DeletionStatus,\n ErasureResult,\n ChangePlanPreview,\n ChangePlanResult,\n OrgInvite,\n OffboardReview,\n OffboardSeenPage,\n OffboardAccessPage,\n OrgRole,\n OrgGroup,\n OrgGroupMember,\n OrgGroupCollection,\n OrgGrant,\n Capability,\n CollectionAccessEntry,\n CollectionDataCapability,\n CollectionGrant,\n CollectionWrappedKey,\n CreateCollectionGrantBody,\n RevokeCollectionGrantResult,\n CreateAgentBody,\n CreateAgentResponse,\n AgentProfileSummary,\n AgentWhoamiResponse,\n} from '../types/index.js';\n\n/** The exact confirmation string the server checks for GDPR erasure (back-compat, EN). */\nexport const ERASURE_CONFIRMATION = 'DELETE MY ACCOUNT';\n\n/** Localized confirmation phrases for GDPR erasure. Server accepts any after normalization. */\nexport const ERASURE_CONFIRMATIONS = { hr: 'OBRI\u0160I MOJ RA\u010CUN', en: 'DELETE MY ACCOUNT' } as const;\n\n// \u2500\u2500 Cross-tenant search (MSP scope) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface TenantSearchOrgHit { org_id: string; name: string; type: string; plan: string }\nexport interface TenantSearchCollectionHit {\n vault_id: string; org_id: string; org_name: string; name: string | null;\n is_default: boolean; org_type: string; org_plan: string;\n}\nexport interface TenantSearchResult {\n orgs: TenantSearchOrgHit[]; orgs_has_more: boolean;\n collections: TenantSearchCollectionHit[]; collections_has_more: boolean;\n}\n\n/** Pluggable token persistence (memory, sessionStorage, chrome.storage, \u2026). */\nexport interface TokenStore {\n get(): TokenPair | null;\n set(tokens: TokenPair | null): void;\n}\n\n/** In-memory token store (default; cleared on reload \u2014 fits an E2EE console). */\nexport function memoryTokenStore(): TokenStore {\n let tokens: TokenPair | null = null;\n return {\n get: () => tokens,\n set: (t) => {\n tokens = t;\n },\n };\n}\n\nexport interface ApiClientOptions {\n baseUrl?: string;\n tokenStore?: TokenStore;\n /** Injected for tests; defaults to global fetch. */\n fetchImpl?: typeof fetch;\n /**\n * fetch credentials mode. The console sets 'include' so the httpOnly refresh\n * cookie rides /v1/auth/refresh and /v1/auth/logout. Default (undefined) keeps\n * the Bearer/body behaviour for the extension/mobile unchanged.\n */\n credentials?: RequestCredentials;\n}\n\n/** ms before a refresh attempt is aborted (avoids a hung refresh blocking the app). */\nconst REFRESH_TIMEOUT_MS = 10_000;\n\nexport class ApiError extends Error {\n readonly status: number;\n readonly code: string | undefined;\n /** Full response body (parsed JSON). Populated for structured error responses. */\n readonly body: Record<string, unknown>;\n constructor(status: number, message: string, code?: string, body?: Record<string, unknown>) {\n super(message);\n this.name = 'ApiError';\n this.status = status;\n this.code = code;\n this.body = body ?? {};\n }\n}\n\n/** F4 Rez 1d-B Faza 3: poslani entry key_version nije aktivna verzija vaulta.\n * RAZLI\u010CITO od OCC conflicta \u2014 klijent mora refetchati klju\u010Deve, re-enkriptirati\n * najnovijim DEK-om i ponoviti (ne reload+merge). */\nexport const SYNC_KEY_VERSION_STALE = 'sync/key-version-stale';\n\n/** A 409 from a sync write is an optimistic-concurrency conflict, not an error \u2014\n * surface it as a conflict result the editor can show; rethrow anything else.\n * server_version is extracted from the structured 409 body (never hardcoded to 0).\n * key-version-stale se PROPU\u0160TA kao gre\u0161ka (retry sloj iznad radi refetch+re-encrypt). */\nfunction asConflict(e: unknown): PutEntryResult {\n if (e instanceof ApiError && e.status === 409 && e.code !== SYNC_KEY_VERSION_STALE) {\n const sv = typeof e.body['server_version'] === 'number' ? e.body['server_version'] : 0;\n return { conflict: true, server_version: sv, message: e.message };\n }\n throw e;\n}\n\nexport class ApiClient {\n private readonly baseUrl: string;\n private readonly tokens: TokenStore;\n private readonly doFetch: typeof fetch;\n private readonly credentials: RequestCredentials | undefined;\n /** Single-flight guard: concurrent 401s share one in-flight refresh. */\n private refreshing: Promise<boolean> | null = null;\n /** Dedup concurrent getVaultEntries calls for the same vaultId. */\n private readonly _inflightEntries = new Map<string, Promise<VaultEntryWire[]>>();\n\n constructor(opts: ApiClientOptions = {}) {\n this.baseUrl = opts.baseUrl ?? 'https://api.geslar.app';\n this.tokens = opts.tokenStore ?? memoryTokenStore();\n this.doFetch = opts.fetchImpl ?? globalThis.fetch.bind(globalThis);\n this.credentials = opts.credentials;\n }\n\n /** True when refresh can ride a cookie (no refresh token needs to be in store). */\n private get cookieMode(): boolean {\n return this.credentials === 'include';\n }\n\n isLoggedIn(): boolean {\n return !!this.tokens.get()?.access_token;\n }\n\n /** Force a refresh (e.g. on rehydrate): pulls a new access token via the cookie. */\n refreshSession(): Promise<boolean> {\n return this.tryRefresh();\n }\n\n /** Server-side logout: invalidate the refresh token + clear the cookie, then drop local tokens. */\n async serverLogout(): Promise<void> {\n try {\n await this.doFetch(`${this.baseUrl}/v1/auth/logout`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: '{}',\n ...(this.credentials ? { credentials: this.credentials } : {}),\n });\n } catch {\n /* best-effort \u2014 local state is cleared regardless */\n }\n this.tokens.set(null);\n }\n\n logout(): void {\n this.tokens.set(null);\n }\n\n // \u2500\u2500 Auth \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n prelogin(email: string): Promise<PreloginResponse> {\n return this.request<PreloginResponse>('/v1/auth/prelogin', {\n method: 'POST',\n body: JSON.stringify({ email }),\n });\n }\n\n /**\n * Prijava. Ra\u010Dun s aktivnim MFA dobiva `MfaRequiredResponse` (BEZ tokena) \u2014\n * klijent tada zove `loginMfa()` s challenge tokenom. Ra\u010Dun bez MFA dobiva\n * puni `LoginResponse` kao i dosad (tokeni se usvajaju).\n */\n async login(params: {\n email: string;\n auth_hash: string;\n device_name: string;\n device_fingerprint: string;\n }): Promise<LoginResponse | MfaRequiredResponse> {\n const body = await this.request<LoginResponse | MfaRequiredResponse>('/v1/auth/login', {\n method: 'POST',\n body: JSON.stringify(params),\n });\n if (!('mfa_required' in body)) {\n this.tokens.set({ access_token: body.access_token, refresh_token: body.refresh_token });\n }\n return body;\n }\n\n /** Korak 2 prijave: MFA dokaz \u2192 puni login response (tokeni se usvajaju). */\n async loginMfa(params: {\n challenge_token: string;\n method: string;\n payload: Record<string, unknown>;\n }): Promise<LoginResponse> {\n const body = await this.request<LoginResponse>('/v1/auth/login/mfa', {\n method: 'POST',\n body: JSON.stringify(params),\n });\n this.tokens.set({ access_token: body.access_token, refresh_token: body.refresh_token });\n return body;\n }\n\n // \u2500\u2500 Oporavak ra\u010Duna (zaboravljen glavni klju\u010D) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Korak 1 oporavka: e-mail \u2192 recovery session + \u0161ifrirani recovery blob.\n * Uvijek 200 (anti-enumeracija) \u2014 nepoznat ra\u010Dun dobiva la\u017Eni blob koji se\n * lokalno ne da otvoriti.\n */\n recoverInit(email: string): Promise<RecoverInitResponse> {\n return this.request('/v1/auth/recover/init', {\n method: 'POST',\n body: JSON.stringify({ email }),\n });\n }\n\n /**\n * Korak 2 oporavka: novi auth_hash + novi wrapani blobovi (sve izvedeno u\n * pregledniku \u2014 prepareRecovery). MFA-gated kad je MFA aktivan (mfa_code /\n * mfa_recovery_code). Server revoka sve ostale sesije; tokeni se usvajaju.\n */\n async recoverComplete(params: {\n recovery_session_token: string;\n new_auth_hash: string;\n new_enc_salt: string;\n new_encrypted_vault_key: string;\n new_encrypted_recovery_blob: string;\n new_encrypted_ecdh_private_key?: string;\n new_ecdh_public_key?: string;\n device_name: string;\n device_fingerprint: string;\n mfa_code?: string;\n mfa_recovery_code?: string;\n }): Promise<RecoverCompleteResponse> {\n const body = await this.request<RecoverCompleteResponse>('/v1/auth/recover/complete', {\n method: 'POST',\n body: JSON.stringify(params),\n });\n this.tokens.set({ access_token: body.access_token, refresh_token: body.refresh_token });\n return body;\n }\n\n // \u2500\u2500 MFA upravljanje (modularni auth-methods sustav) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Aktivne MFA metode + broj preostalih recovery kodova. */\n mfaList(): Promise<MfaListResponse> {\n return this.request('/v1/account/mfa', { method: 'GET' });\n }\n\n /**\n * Korak 1 enrollmenta \u2014 step-up lozinkom (auth_hash deriviran u pregledniku).\n * TOTP vra\u0107a secret + otpauth URI (QR renderira klijent); budu\u0107i provideri\n * vra\u0107aju svoj clientPayload.\n */\n mfaEnroll(method: string, authHash: string): Promise<MfaEnrollTotpResponse> {\n return this.request(`/v1/account/mfa/${encodeURIComponent(method)}/enroll`, {\n method: 'POST',\n body: JSON.stringify({ auth_hash: authHash }),\n });\n }\n\n /**\n * Korak 2 enrollmenta \u2014 dokaz (TOTP: prvi kod). Prva metoda vra\u0107a recovery\n * kodove (plaintext JEDINI PUT).\n */\n mfaVerifyEnroll(method: string, proof: Record<string, unknown>): Promise<{\n method: string;\n enabled: true;\n recovery_codes?: string[];\n }> {\n return this.request(`/v1/account/mfa/${encodeURIComponent(method)}/verify-enroll`, {\n method: 'POST',\n body: JSON.stringify({ proof }),\n });\n }\n\n /** Isklju\u010Di metodu: lozinka OBAVEZNA + (kod aktivne metode ILI recovery kod). */\n mfaDisable(method: string, params: {\n auth_hash: string;\n code?: string;\n recovery_code?: string;\n method_id?: string;\n }): Promise<{ ok: true; methods_remaining: number }> {\n return this.request(`/v1/account/mfa/${encodeURIComponent(method)}/disable`, {\n method: 'POST',\n body: JSON.stringify(params),\n });\n }\n\n /** Novih 10 recovery kodova (stari prestaju vrijediti) \u2014 plaintext JEDINI PUT. */\n mfaRegenerateRecoveryCodes(params: {\n auth_hash: string;\n code?: string;\n recovery_code?: string;\n }): Promise<{ recovery_codes: string[] }> {\n return this.request('/v1/account/mfa/recovery-codes/regenerate', {\n method: 'POST',\n body: JSON.stringify(params),\n });\n }\n\n /** F2 \u2014 dismiss the \"set up 2FA again\" nudge after an admin reset (\"Not now\").\n * Clears the caller's own mfa_reenroll_prompt flag. No body. */\n dismissReenroll(): Promise<{ ok: boolean }> {\n return this.request('/v1/account/mfa/dismiss-reenroll', { method: 'POST' });\n }\n\n // \u2500\u2500 Agentic Access \u2014 CLI device-flow approval (M1) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Console /device page: request context to show BEFORE approve/deny. */\n getDeviceContext(userCode: string): Promise<DeviceFlowContext> {\n return this.request('/v1/auth/device/lookup', {\n method: 'POST',\n body: JSON.stringify({ user_code: userCode }),\n });\n }\n\n /** Approve a pending `geslar signin` request. Always requires a FRESH 2FA\n * proof \u2014 no session-freshness cache, same step-up model as mfaDisable. */\n approveDevice(params: { user_code: string; code?: string; recovery_code?: string }): Promise<{ ok: true; hostname: string | null }> {\n return this.request('/v1/auth/device/approve', {\n method: 'POST',\n body: JSON.stringify(params),\n });\n }\n\n /** Deny a pending request \u2014 the safe path, no 2FA gate. */\n denyDevice(userCode: string): Promise<{ ok: true }> {\n return this.request('/v1/auth/device/deny', {\n method: 'POST',\n body: JSON.stringify({ user_code: userCode }),\n });\n }\n\n /** M2 \u2014 caller's own wrapped vault-key material (enc_salt + encrypted_vault_key\n * + ECDH blobs), for `geslar unlock`'s local KDF chain. See VaultKeyMaterial. */\n getVaultKeyMaterial(): Promise<VaultKeyMaterial> {\n return this.request('/v1/account/vault-key-material', { method: 'GET' });\n }\n\n // \u2500\u2500 Access core (M4.5) \u2014 agent principals \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // spec-access-core.md REV 1.2 \u00A73. Human-session-only except getAgentWhoami,\n // which is the one route an agent bearer token may itself call.\n\n /** Human session + fresh TOTP required server-side. Returns the plaintext\n * token exactly once \u2014 the caller must persist it immediately. */\n createAgent(body: CreateAgentBody): Promise<CreateAgentResponse> {\n return this.request<CreateAgentResponse>('/v1/agents', {\n method: 'POST',\n body: JSON.stringify(body),\n });\n }\n\n listAgents(): Promise<{ agents: AgentProfileSummary[] }> {\n return this.request<{ agents: AgentProfileSummary[] }>('/v1/agents', { method: 'GET' });\n }\n\n revokeAgent(id: string): Promise<{ ok: boolean; revoked: boolean }> {\n return this.request<{ ok: boolean; revoked: boolean }>(`/v1/agents/${encodeURIComponent(id)}`, { method: 'DELETE' });\n }\n\n /** Reachable by both a human session AND an agent bearer token \u2014 the CLI\n * uses this under GESLAR_AGENT context to read live capabilities (never\n * guessed/cached locally, spec \u00A74). */\n getAgentWhoami(): Promise<AgentWhoamiResponse> {\n return this.request<AgentWhoamiResponse>('/v1/agents/whoami', { method: 'GET' });\n }\n\n /**\n * Create an account. All crypto happens in @geslar/core/crypto\n * (prepareRegistration) \u2014 this only ships auth_hash + opaque wrapped blobs.\n * Adopts the issued token pair so the fresh session is live immediately.\n */\n async register(params: {\n email: string;\n auth_hash: string;\n enc_salt: string;\n encrypted_vault_key: string;\n encrypted_recovery_blob: string;\n encrypted_ecdh_private_key: string;\n ecdh_public_key: string;\n device_name: string;\n device_fingerprint: string;\n locale?: string;\n }): Promise<RegisterResponse> {\n const body = await this.request<RegisterResponse>('/v1/auth/register', {\n method: 'POST',\n body: JSON.stringify(params),\n });\n this.tokens.set({ access_token: body.access_token, refresh_token: body.refresh_token });\n return body;\n }\n\n /** Consume an email-verification token (from the verification link). */\n verifyEmail(token: string): Promise<{ success: true; user_id: string; email_verified_at: string }> {\n return this.request('/v1/auth/verify-email', {\n method: 'POST',\n body: JSON.stringify({ token }),\n });\n }\n\n /** Re-send the verification email. Server rate-limits (3/h per email); always 200. */\n resendVerification(email: string): Promise<{ success: true }> {\n return this.request('/v1/auth/resend-verification', {\n method: 'POST',\n body: JSON.stringify({ email }),\n });\n }\n\n /** Mark the recovery key as stored by the user (onboarding ack). */\n acknowledgeRecoveryKey(): Promise<{ success: true }> {\n return this.request('/v1/account/acknowledge-recovery-key', {\n method: 'POST',\n body: JSON.stringify({ acknowledged: true }),\n });\n }\n\n /**\n * Replace the recovery blob with one wrapped under a FRESH recovery key (#44).\n * The new key + blob are generated in the browser; the server only stores the\n * opaque blob and resets the acknowledge flag.\n */\n regenerateRecoveryKey(encryptedRecoveryBlob: string): Promise<{ success: true }> {\n return this.request('/v1/account/regenerate-recovery-key', {\n method: 'POST',\n body: JSON.stringify({ encrypted_recovery_blob: encryptedRecoveryBlob }),\n });\n }\n\n // \u2500\u2500 Orgs / members (read-only, T13) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n getOrgs(): Promise<Org[]> {\n return this.request<Org[]>('/v1/orgs', { method: 'GET' });\n }\n\n /** Fire-and-forget audit trail for \"who switched into which org, when\" \u2014\n * MSP compliance groundwork. Caller must belong to orgId; server 403s otherwise. */\n logContextSwitch(orgId: string): Promise<{ ok: true }> {\n return this.request('/v1/context-switch', {\n method: 'POST',\n body: JSON.stringify({ org_id: orgId }),\n });\n }\n\n patchOrgBranding(\n orgId: string,\n body: { accent?: string | null; logo_light?: string | null; logo_dark?: string | null; locked?: boolean; brand_name?: string | null },\n ): Promise<{ ok: boolean; branding: OrgBranding }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/branding`, {\n method: 'PATCH',\n body: JSON.stringify(body),\n });\n }\n\n getOrgMembers(orgId: string): Promise<OrgMember[]> {\n return this.request<OrgMember[]>(`/v1/orgs/${encodeURIComponent(orgId)}/members`, {\n method: 'GET',\n });\n }\n\n getEntitlements(orgId?: string): Promise<EntitlementsBundle> {\n const url = orgId ? `/v1/account/entitlements?org=${encodeURIComponent(orgId)}` : '/v1/account/entitlements';\n return this.request<EntitlementsBundle>(url, { method: 'GET' });\n }\n\n /** Public plan catalogue (single source of truth for pricing). No auth needed. */\n async getPlans(): Promise<PublicPlan[]> {\n const res = await this.request<{ plans: PublicPlan[] }>('/v1/plans', { method: 'GET' });\n return res.plans;\n }\n\n /** Provider-agnostic checkout. Server attaches custom_data; returns the URL. */\n async createCheckout(plan: 'premium' | 'family', interval: 'monthly' | 'annual'): Promise<{ url: string }> {\n return this.request<{ url: string }>('/v1/billing/checkout', {\n method: 'POST',\n body: JSON.stringify({ plan, interval }),\n });\n }\n\n /** Faza 2 \u2014 \u0161to bi change-plan napravio (za ISTINIT copy prije potvrde):\n * interval_update (Lemon proration) / upgrade_checkout (Premium\u2192Family:\n * checkout + auto-otkaz + proration refund starog suba) / checkout / noop. */\n async changePlanPreview(plan: 'premium' | 'family', interval: 'monthly' | 'annual'): Promise<ChangePlanPreview> {\n return this.request<ChangePlanPreview>(\n `/v1/billing/change-plan/preview?plan=${plan}&interval=${interval}`,\n { method: 'GET' },\n );\n }\n\n /** Faza 3 (#11) \u2014 native otkaz iz konzole: sub vrijedi do kraja pla\u0107enog\n * perioda (bez daljnjih naplata), zatim grace (D-010). 404 bez aktivnog suba. */\n async cancelPlan(plan: 'premium' | 'family'): Promise<{ ok: boolean; valid_until: string | null }> {\n return this.request<{ ok: boolean; valid_until: string | null }>('/v1/billing/cancel', {\n method: 'POST',\n body: JSON.stringify({ plan }),\n });\n }\n\n /** Faza 2 \u2014 THE change-plan ulaz. Server odlu\u010Duje (autoritativno):\n * 'updated' = interval promijenjen u mjestu (bez checkouta); 'checkout' =\n * otvori vra\u0107eni URL. 409 kad je korisnik ve\u0107 na tra\u017Eenom planu/intervalu. */\n async changePlan(plan: 'premium' | 'family', interval: 'monthly' | 'annual'): Promise<ChangePlanResult> {\n return this.request<ChangePlanResult>('/v1/billing/change-plan', {\n method: 'POST',\n body: JSON.stringify({ plan, interval }),\n });\n }\n\n /** Authenticated deep-link to the provider's hosted customer/billing portal\n * (manage payment method, cancel a plan, view invoices). 404 when the caller\n * has no subscription to manage; 503 when the portal is not configured. */\n async getCustomerPortalUrl(): Promise<{ url: string }> {\n return this.request<{ url: string }>('/v1/billing/portal', { method: 'GET' });\n }\n\n // \u2500\u2500 Sharing (T11) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n // \"admin = razina\" Track A Faza 3/4b: optional role_id assigns a management\n // role via PDP grant (parallel to the legacy `role` enum \u2014 see BE accept flow).\n createInvite(orgId: string, email: string, role: MemberRole, roleId?: string): Promise<InviteResult> {\n return this.request<InviteResult>(`/v1/orgs/${encodeURIComponent(orgId)}/invites`, {\n method: 'POST',\n body: JSON.stringify({ email, role, ...(roleId ? { role_id: roleId } : {}) }),\n });\n }\n\n listInvites(orgId: string): Promise<{ invites: OrgInvite[] }> {\n return this.request<{ invites: OrgInvite[] }>(`/v1/orgs/${encodeURIComponent(orgId)}/invites`, { method: 'GET' });\n }\n\n revokeInvite(orgId: string, inviteId: string): Promise<{ ok: boolean }> {\n return this.request<{ ok: boolean }>(`/v1/orgs/${encodeURIComponent(orgId)}/invites/${encodeURIComponent(inviteId)}`, { method: 'DELETE' });\n }\n\n async resendInvite(orgId: string, inviteId: string, email: string, role: MemberRole): Promise<InviteResult> {\n // Server has no dedicated resend endpoint \u2014 revoke then recreate so a new email is sent.\n await this.revokeInvite(orgId, inviteId);\n return this.createInvite(orgId, email, role);\n }\n\n acceptInvite(token: string): Promise<{ member_id: string; org_id: string; role: MemberRole; status: string }> {\n return this.request(`/v1/invites/${encodeURIComponent(token)}/accept`, { method: 'POST' });\n }\n\n /** Upsert the caller's OWN wrapped DEK (bootstrapping a team_collection). */\n putOwnMemberKey(vaultId: string, encryptedKeyB64: string): Promise<{ ok: true }> {\n return this.request(`/v1/vaults/${encodeURIComponent(vaultId)}/member-keys`, {\n method: 'POST',\n body: JSON.stringify({ encrypted_key: encryptedKeyB64 }),\n });\n }\n\n /** Fetch the caller's wrapped DEK + the wrapper's public key (for unwrap). */\n getMemberKey(vaultId: string): Promise<MemberKeyResult> {\n return this.request<MemberKeyResult>(`/v1/vaults/${encodeURIComponent(vaultId)}/member-keys`, { method: 'GET' });\n }\n\n\n /** Cross-org: all team_collection vaults the caller holds a DEK for. */\n getCollections(): Promise<{ collections: CollectionSummary[] }> {\n return this.request<{ collections: CollectionSummary[] }>('/v1/collections', { method: 'GET' });\n }\n\n // \u2500\u2500 Collection management (D-053) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** idempotencyKey (B1): caller generates ONE UUID per logical submit and reuses\n * it on automatic retry of the SAME request (e.g. the 401-refresh retry in\n * request() below reuses this same init). Optional \u2014 server does not require\n * it yet (B2 lands after clients ship this).\n * isDefault (business-default-vault plan, 2026-07-14): creates the org's\n * singleton \"Op\u0107a \u0161krinja\" instead of a regular collection. A second\n * is_default=true create 409s with code 'vault/default-collection-exists'\n * and body.existing_vault_id \u2014 the caller should open that vault instead. */\n createCollection(orgId: string, name: string, idempotencyKey?: string, isDefault?: boolean): Promise<{ vault_id: string; name: string }> {\n return this.request<{ vault_id: string; name: string }>(`/v1/orgs/${encodeURIComponent(orgId)}/collections`, {\n method: 'POST',\n body: JSON.stringify({ name, is_default: isDefault ?? false }),\n ...(idempotencyKey ? { headers: { 'Idempotency-Key': idempotencyKey } } : {}),\n });\n }\n\n /** F4 B3: promote a folder subtree from a business vault into a NEW collection.\n * Enterprise-gated server-side (403 without the promote_folder module). The\n * server only creates the collection + (optionally) replicates the source's\n * access state; the ZK entry move + folder recreation happen client-side.\n * idempotencyKey (B1): see createCollection above. */\n promoteFolder(\n orgId: string,\n body: { name: string; source_vault_id: string; copy_permissions: boolean },\n idempotencyKey?: string,\n ): Promise<{ vault_id: string; name: string }> {\n return this.request<{ vault_id: string; name: string }>(`/v1/orgs/${encodeURIComponent(orgId)}/collections/promote-folder`, {\n method: 'POST',\n body: JSON.stringify(body),\n ...(idempotencyKey ? { headers: { 'Idempotency-Key': idempotencyKey } } : {}),\n });\n }\n\n renameCollection(orgId: string, cid: string, name: string): Promise<{ ok: boolean; name: string }> {\n return this.request<{ ok: boolean; name: string }>(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}`, {\n method: 'PATCH',\n body: JSON.stringify({ name }),\n });\n }\n\n deleteCollection(orgId: string, cid: string): Promise<{ ok: boolean }> {\n return this.request<{ ok: boolean }>(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}`, {\n method: 'DELETE',\n });\n }\n\n listCollectionMembers(orgId: string, cid: string): Promise<{ members: CollectionMember[] }> {\n return this.request<{ members: CollectionMember[] }>(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/members`, {\n method: 'GET',\n });\n }\n\n /** keyVersion: version of the DEK encryptedKeyB64 was wrapped with. Optional for\n * back-compat; omitting it keeps the server's pre-existing grace behavior\n * (tags the row as whatever version is current at insert time). Sending it lets\n * the server reject a stale wrap (409 sync/key-version-stale) instead of\n * silently tagging a rotation-raced wrap with the wrong version \u2014 same\n * contract as CollectionWrappedKey.key_version in the grants fan-out. */\n addCollectionMember(orgId: string, cid: string, userId: string, encryptedKeyB64: string, keyVersion?: number): Promise<{ ok: boolean }> {\n return this.request<{ ok: boolean }>(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/members`, {\n method: 'POST',\n body: JSON.stringify({ user_id: userId, encrypted_key: encryptedKeyB64, ...(keyVersion !== undefined ? { key_version: keyVersion } : {}) }),\n });\n }\n\n /** Remove a collection member (F4 Rez 1d-B Faza 4). Severs the removed member's\n * access immediately and flags rotation_required if they held the DEK; the\n * actual re-encryption runs staged (stage/commit/complete). No payload. */\n removeCollectionMember(orgId: string, cid: string, uid: string): Promise<RemoveCollectionMemberResult> {\n return this.request<RemoveCollectionMemberResult>(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/members/${encodeURIComponent(uid)}/remove`, {\n method: 'POST',\n });\n }\n\n /** Faza 4 stage: insert the target-version key for every remaining holder. */\n stageCollectionRotation(orgId: string, cid: string, body: CollectionRotationStage): Promise<{ ok: boolean; staged: boolean; target_key_version: number }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/rotate/stage`, {\n method: 'POST', body: JSON.stringify(body),\n });\n }\n\n /** Faza 4 commit: apply one chunk (\u2264500) of re-encrypted entries. */\n commitCollectionRotation(orgId: string, cid: string, body: CollectionRotationCommit): Promise<{ ok: boolean; committed: number; target_key_version: number }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/rotate/commit`, {\n method: 'POST', body: JSON.stringify(body),\n });\n }\n\n /** Faza 4 complete: sweep old key versions once all entries are on target.\n * `completed:false` means NOT actually done \u2014 `already` = this rotation was a\n * prior no-op retry, `stale` = a NEWER rotation debt appeared meanwhile (caller\n * must re-fetch + re-derive rotation_required from the server, never assume done). */\n completeCollectionRotation(orgId: string, cid: string, keyVersion: number): Promise<{ ok: boolean; completed: boolean; already?: boolean; stale?: boolean }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/rotate/complete`, {\n method: 'POST', body: JSON.stringify({ key_version: keyVersion }),\n });\n }\n\n /** Owner-override: clear the collection's rotation_required flag WITHOUT\n * rotating the key (residual exposure explicitly accepted; audited). */\n resetCollectionRotation(orgId: string, cid: string): Promise<{ ok: boolean; rotation_required: boolean }> {\n return this.request<{ ok: boolean; rotation_required: boolean }>(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/rotation-reset`, {\n method: 'POST',\n });\n }\n\n updateCollectionMemberPermissions(\n orgId: string,\n cid: string,\n uid: string,\n perms: { can_view?: boolean; can_edit?: boolean; can_share?: boolean; can_reveal?: boolean },\n ): Promise<{ ok: boolean }> {\n return this.request<{ ok: boolean }>(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/members/${encodeURIComponent(uid)}/permissions`, {\n method: 'PATCH',\n body: JSON.stringify(perms),\n });\n }\n\n // \u2500\u2500 Collection-scope data grants (F4 Rez 1d B2) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Effective access for the \"Pristup\" tab: grant subjects + key-holders. */\n getCollectionAccess(orgId: string, cid: string): Promise<{ access: CollectionAccessEntry[] }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/access`, { method: 'GET' });\n }\n\n /** List collection-scope grants (one row per subject \u00D7 capability). */\n getCollectionGrants(orgId: string, cid: string): Promise<{ grants: CollectionGrant[] }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/grants`, { method: 'GET' });\n }\n\n /** Create a collection-scope data grant + eager key-wrap fan-out (ZK: keys are\n * wrapped in the browser and delivered as wrapped_keys). */\n createCollectionGrant(orgId: string, cid: string, body: CreateCollectionGrantBody): Promise<{ ok: boolean; wrapped: number; pending: number }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/grants`, {\n method: 'POST', body: JSON.stringify(body),\n });\n }\n\n /** Revoke a grant; server severs orphaned keys + flags rotation as needed. */\n deleteCollectionGrant(orgId: string, cid: string, grantId: string): Promise<RevokeCollectionGrantResult> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/grants/${encodeURIComponent(grantId)}`, {\n method: 'DELETE',\n });\n }\n\n /** Key-holder-driven pending \u2192 active: wrap the DEK for pending members. */\n reconcileCollectionKeys(orgId: string, cid: string, wrappedKeys: CollectionWrappedKey[]): Promise<{ ok: boolean; reconciled: number }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/reconcile-keys`, {\n method: 'POST', body: JSON.stringify({ wrapped_keys: wrappedKeys }),\n });\n }\n\n /** F4 Rez 1d C-B: set (REPLACE) per-member deny override on a collection.\n * Enterprise-gated server-side (403 without the per_member_override module).\n * Server severs the key + flags rotation only when 'view' is actually lost. */\n setCollectionMemberOverride(orgId: string, cid: string, uid: string, deniedCapabilities: CollectionDataCapability[]): Promise<{ ok: true; denied_capabilities: CollectionDataCapability[]; rotation_required: boolean }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/members/${encodeURIComponent(uid)}/overrides`, {\n method: 'PUT', body: JSON.stringify({ denied_capabilities: deniedCapabilities }),\n });\n }\n\n /** Clear a member's deny override (un-override). NOT entitlement-gated \u2014\n * removing restrictions must stay available after a downgrade. */\n clearCollectionMemberOverride(orgId: string, cid: string, uid: string): Promise<{ ok: true }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/members/${encodeURIComponent(uid)}/overrides`, {\n method: 'DELETE',\n });\n }\n\n /** Confirm a pending member \u2014 unconditional for every org type (no DEK-wrap\n * ceremony): flips the member active and joins them to \"Svi \u010Dlanovi\". Access\n * to the org's default collection is grant + reconcile-keys driven, same as\n * any other team_collection. `vault_id` in the response is always `null`. */\n confirmMember(orgId: string, memberId: string): Promise<{ ok: true; vault_id: string | null }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/members/${encodeURIComponent(memberId)}/confirm`, {\n method: 'POST',\n body: JSON.stringify({}),\n });\n }\n\n // \u2500\u2500 Offboarding + audit (T12) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** All encrypted entries in a vault. Follows next_cursor pages until exhausted.\n * Concurrent calls for the same vaultId share one in-flight request so a\n * parallel listPersonalEntries + loadFolders pair only hits the network once.\n * Safety cap: aborts after 100 000 total entries to prevent unbounded loops. */\n async getVaultEntries(vaultId: string): Promise<VaultEntryWire[]> {\n const cached = this._inflightEntries.get(vaultId);\n if (cached) return cached;\n const promise = this._paginateEntries(vaultId);\n this._inflightEntries.set(vaultId, promise);\n promise.finally(() => this._inflightEntries.delete(vaultId));\n return promise;\n }\n\n private async _paginateEntries(vaultId: string): Promise<VaultEntryWire[]> {\n const PAGE_LIMIT = 1000;\n const MAX_ENTRIES = 100_000;\n const all: VaultEntryWire[] = [];\n let cursor: string | undefined;\n\n while (all.length < MAX_ENTRIES) {\n const params = new URLSearchParams({ vault_id: vaultId, limit: String(PAGE_LIMIT) });\n if (cursor) params.set('cursor', cursor);\n const res = await this.request<{ entries: VaultEntryWire[]; next_cursor: string | null }>(\n `/v1/sync/entries?${params.toString()}`,\n { method: 'GET' },\n );\n all.push(...res.entries);\n if (!res.next_cursor) break;\n cursor = res.next_cursor;\n }\n\n return all;\n }\n\n // \u2500\u2500 Vault entry write (T14 \u2014 full editor; reuses existing sync endpoints) \u2500\u2500\u2500\u2500\n\n /** Ensure the caller's personal vault exists; returns id + whether it was just created\n * (is_new=true means first-ever or revival after erasure). */\n async ensurePersonalVault(): Promise<{ vault_id: string; is_new: boolean }> {\n return this.request<{ vault_id: string; is_new: boolean }>('/v1/sync/vault', {\n method: 'POST',\n body: JSON.stringify({}),\n });\n }\n\n /** Tombstone a collection or shared vault (DELETE /v1/sync/vault/:id).\n * Server sets vault.deleted_at + cascades to all entries. 400 if vault_type=personal. */\n deleteVault(vaultId: string): Promise<{ ok: boolean }> {\n return this.request<{ ok: boolean }>(`/v1/sync/vault/${encodeURIComponent(vaultId)}`, {\n method: 'DELETE',\n });\n }\n\n /** Soft-delete all entries in a vault without touching the vault row itself.\n * Use for personal vault \"wipe cloud, keep local\" \u2014 vault_id stays stable.\n * auth_hash: re-derived master-password hash for server-side re-auth (same as purgeCloudData). */\n clearVaultEntries(vaultId: string, authHash?: string): Promise<{ entries_deleted: number }> {\n return this.request<{ entries_deleted: number }>(\n `/v1/sync/vault/${encodeURIComponent(vaultId)}/clear-entries`,\n {\n method: 'POST',\n body: authHash ? JSON.stringify({ auth_hash: authHash }) : JSON.stringify({}),\n },\n );\n }\n\n /** Pull vault tombstones (vaults deleted since `since`). Suite uses this to evict\n * deleted collections/shared vaults from the UI without requiring re-login. */\n getVaultTombstones(since?: string): Promise<{ deleted_vaults: Array<{ vault_id: string; deleted_at: string }> }> {\n const q = since ? `?since=${encodeURIComponent(since)}` : '';\n return this.request<{ deleted_vaults: Array<{ vault_id: string; deleted_at: string }> }>(\n `/v1/sync/vault-tombstones${q}`,\n { method: 'GET' },\n );\n }\n\n /**\n * Upsert a single encrypted entry (create when expected_version=0, else update\n * with optimistic concurrency). The server stores opaque blobs only \u2014 all crypto\n * happens in the browser. Returns the new server version, or a conflict.\n */\n async putEntry(\n entryId: string,\n args: { vaultId: string; entryType: string; encryptedBlob: string; blobHash: string; expectedVersion: number; keyVersion?: number },\n ): Promise<PutEntryResult> {\n try {\n return await this.request<PutEntryResult>(`/v1/sync/entries/${encodeURIComponent(entryId)}`, {\n method: 'PUT',\n body: JSON.stringify({\n vault_id: args.vaultId,\n entry_type: args.entryType,\n encrypted_blob: args.encryptedBlob,\n blob_hash: args.blobHash,\n expected_version: args.expectedVersion,\n // F4 Rez 1d-B Faza 3: envelope-tag DEK-a kojim je blob enkriptiran.\n // Izostavljeno = server grace-taga (stari klijenti).\n ...(args.keyVersion !== undefined ? { key_version: args.keyVersion } : {}),\n }),\n });\n } catch (e) {\n return asConflict(e);\n }\n }\n\n /** Soft-delete a single entry (optimistic concurrency on expected_version). */\n async deleteEntry(entryId: string, args: { vaultId: string; expectedVersion: number }): Promise<PutEntryResult> {\n try {\n return await this.request<PutEntryResult>(`/v1/sync/entries/${encodeURIComponent(entryId)}`, {\n method: 'DELETE',\n body: JSON.stringify({ vault_id: args.vaultId, expected_version: args.expectedVersion }),\n });\n } catch (e) {\n return asConflict(e);\n }\n }\n\n /**\n * Batch push (up to 500 ops). 200 = all OK, 207 = partial (some conflicts).\n * For delete ops: { op: 'delete', id, expected_version }.\n * For upsert ops: { op: 'upsert', id, entry_type, encrypted_blob, blob_hash, expected_version }.\n */\n async batchEntries(\n vaultId: string,\n operations: Array<{ op: 'delete' | 'upsert'; id: string; expected_version: number; entry_type?: string; encrypted_blob?: string; blob_hash?: string; key_version?: number }>,\n ): Promise<{ results: Array<{ id: string; status: 'ok' | 'conflict'; version: number; server_version?: number; server_updated_at?: string }>; server_time: string }> {\n return this.request('/v1/sync/entries/batch', {\n method: 'POST',\n body: JSON.stringify({ vault_id: vaultId, operations }),\n });\n }\n\n /** Remove a member. \"\u0160krinja je \u0160krinja\" unification: no client-side DEK\n * rotation anymore \u2014 the server flags any team_collection the member held a\n * key on (rotation_required); an existing key-holder rotates it later via\n * the staged /collections/:cid/rotate flow. */\n removeMember(orgId: string, memberId: string): Promise<{ ok: true; removed_member_id: string; collections_flagged_for_rotation: number }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/members/${encodeURIComponent(memberId)}/remove`, {\n method: 'POST',\n body: JSON.stringify({}),\n });\n }\n\n /** Leave an org. 'delete' starts the grace\u2192purge on the caller's personal cloud. */\n leaveOrg(orgId: string, memberId: string, choice: 'keep' | 'delete'): Promise<{ ok: true; choice: string; collections_flagged_for_rotation: number }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/members/${encodeURIComponent(memberId)}/leave`, {\n method: 'POST',\n body: JSON.stringify({ choice }),\n });\n }\n\n /** Owner cancels a shared plan WITH members (danger zone). */\n cancelOrg(orgId: string): Promise<{ ok: true; members_notified: number }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/cancel`, {\n method: 'POST',\n body: JSON.stringify({ confirm: true }),\n });\n }\n\n setOrgRequire2fa(orgId: string, enabled: boolean): Promise<{ ok: boolean; require_member_2fa: boolean }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/settings/require-member-2fa`, {\n method: 'PATCH',\n body: JSON.stringify({ enabled }),\n });\n }\n setOrgClipboardClearPolicy(orgId: string, enabled: boolean, seconds: 20 | 60 | 120): Promise<{ ok: boolean; clipboard_clear_policy: { enabled: boolean; seconds: number } | null }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/settings/clipboard-clear-policy`, {\n method: 'PUT',\n body: JSON.stringify({ enabled, seconds }),\n });\n }\n\n unsetOrgClipboardClearPolicy(orgId: string): Promise<{ ok: boolean; clipboard_clear_policy: null }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/settings/clipboard-clear-policy`, {\n method: 'DELETE',\n });\n }\n\n /** F2 \u2014 owner/admin resets a member's 2FA (login-factor only; server enforces the\n * manage_member_2fa capability + escalation guard). No body. */\n resetMemberMfa(orgId: string, memberId: string): Promise<{ ok: boolean }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/members/${encodeURIComponent(memberId)}/mfa`, {\n method: 'DELETE',\n });\n }\n\n /** F3b \u2014 owner/admin sets (exempt=true \u2192 PUT) or clears (exempt=false \u2192 DELETE) a\n * member's exemption from the org's require_member_2fa policy. Server enforces the\n * manage_org capability + self-block + owner-rank guard. */\n setMemberMfaExemption(orgId: string, memberId: string, exempt: boolean): Promise<{ ok: boolean; mfa_exempt: boolean }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/members/${encodeURIComponent(memberId)}/mfa-exemption`, {\n method: exempt ? 'PUT' : 'DELETE',\n });\n }\n\n /** Append an access record (reference only \u2014 never the plaintext). */\n logCredentialAccess(args: { orgId: string; entryId: string; vaultId: string; action: CredentialAction }): Promise<{ ok: true }> {\n return this.request('/v1/credential-access', {\n method: 'POST',\n body: JSON.stringify({ org_id: args.orgId, entry_id: args.entryId, vault_id: args.vaultId, action: args.action }),\n });\n }\n\n /** Entries a member has revealed/copied/autofilled \u2014 drives guided rotation. */\n getPasswordsKnownBy(orgId: string, userId: string): Promise<PasswordKnownRow[]> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/audit/passwords-known-by/${encodeURIComponent(userId)}`, { method: 'GET' });\n }\n\n /** Per-active-member count of entries they revealed/copied/autofilled. Business+ only. */\n getExposureSummary(orgId: string): Promise<ExposureSummary> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/audit/exposure-summary`, { method: 'GET' });\n }\n\n /** Who touched a given entry (access feed). Cursor-paginated (Faza A). */\n getCredentialAudit(\n orgId: string,\n entryId: string,\n cursor?: { before_ts: string; before_id: number },\n ): Promise<CredentialAuditPage> {\n const q = new URLSearchParams();\n if (cursor) { q.set('before_ts', cursor.before_ts); q.set('before_id', String(cursor.before_id)); }\n const qs = q.toString();\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/audit/credential/${encodeURIComponent(entryId)}${qs ? `?${qs}` : ''}`, { method: 'GET' });\n }\n\n /** The caller's own general audit log (GET /v1/audit). Per-user, not org-wide \u2014\n * surfaces the signed-in admin's security-relevant events (DEK rotations,\n * failed logins, membership changes) for the dashboard. */\n getAudit(params?: { limit?: number; action?: string; since?: string }): Promise<AuditPage> {\n const q = new URLSearchParams();\n if (params?.limit) q.set('limit', String(params.limit));\n if (params?.action) q.set('action', params.action);\n if (params?.since) q.set('since', params.since);\n const qs = q.toString();\n return this.request<AuditPage>(`/v1/audit${qs ? `?${qs}` : ''}`, { method: 'GET' });\n }\n\n /** Cross-tenant search: orgs and collections matching the query. MSP use case. */\n searchTenants(q: string): Promise<TenantSearchResult> {\n const params = new URLSearchParams({ q });\n return this.request<TenantSearchResult>(`/v1/search/tenants?${params.toString()}`, { method: 'GET' });\n }\n\n // \u2500\u2500 Devices / sessions (K4) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Registered devices/sessions for the signed-in user. */\n async getDevices(): Promise<DeviceRow[]> {\n const res = await this.request<{ devices: DeviceRow[] }>('/v1/devices', { method: 'GET' });\n return res.devices;\n }\n\n /** Revoke a single device (deletes its refresh tokens). */\n revokeDevice(deviceId: string): Promise<{ revoked: true; self_revoked: boolean }> {\n return this.request(`/v1/devices/${encodeURIComponent(deviceId)}`, { method: 'DELETE' });\n }\n\n /** Panic button \u2014 revoke every device except the current one. */\n revokeOtherDevices(): Promise<{ revoked_all: true; kept_device_id: string }> {\n return this.request('/v1/devices', { method: 'DELETE' });\n }\n\n // \u2500\u2500 Account erasure (K4 \u2014 GDPR art. 17) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Current scheduled-deletion state (none \u2192 all-null shape). */\n getDeletionStatus(): Promise<DeletionStatus> {\n return this.request<DeletionStatus>('/v1/account/deletion-status', { method: 'GET' });\n }\n\n /**\n * Request erasure of the account (30-day grace). `masterPasswordHash` is the\n * SAME auth_hash sent at login (re-derived in the browser from the master\n * password the user re-enters) \u2014 the server verifies it before scheduling.\n */\n requestAccountErasure(masterPasswordHash: string): Promise<ErasureResult> {\n return this.request<ErasureResult>('/v1/account/data-erasure-confirm', {\n method: 'POST',\n body: JSON.stringify({ confirmation: ERASURE_CONFIRMATION, master_password_hash: masterPasswordHash }),\n });\n }\n\n /** Cancel a scheduled deletion during the grace period. */\n cancelAccountDeletion(): Promise<{ status: string; message: string }> {\n return this.request('/v1/auth/account/cancel-deletion', { method: 'POST' });\n }\n\n /** GDPR Art. 20 \u2014 request full account data export. Backend queues a ZIP\n * and sends a download link via email when ready. Rate-limited to 1\u00D7/24h\n * (429 with Retry-After if called again within the window). */\n requestDataExport(): Promise<{ job_id: string; estimated_seconds: number }> {\n return this.request('/v1/account/data-export', { method: 'GET' });\n }\n\n /**\n * Self-serve \"wipe cloud data only\" \u2014 purges the cloud copy of the caller's\n * PERSONAL org (local vault untouched). Re-auth: auth_hash re-derived in the\n * browser, the master password never leaves the device.\n */\n purgeCloudData(authHash: string): Promise<{ entries_deleted: number; vaults_deleted: number }> {\n return this.request('/v1/account/purge-cloud-data', {\n method: 'POST',\n body: JSON.stringify({ auth_hash: authHash }),\n });\n }\n\n /** Rename an organization (owner-only server-side). Returns the saved name. */\n renameOrg(orgId: string, name: string): Promise<{ ok: boolean; name: string }> {\n return this.request(`/v1/orgs/${orgId}`, {\n method: 'PATCH',\n body: JSON.stringify({ name }),\n });\n }\n\n // \u2500\u2500 ECDH migration (T10/K5 \u2014 placeholder v0 \u2192 real X25519 v1) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Upload a real X25519 public key + its master-key-wrapped private key during\n * the placeholder\u2192real migration; the server sets ecdh_key_version = 1. SAME\n * route the extension's T10 migration uses (PUT /v1/account/ecdh-public-key) \u2014\n * identical envelope \u21D2 cross-client parity.\n */\n updateEcdhPublicKey(ecdhPublicKey: string, encryptedEcdhPrivateKey: string): Promise<{ success: true; ecdh_key_version: number }> {\n return this.request('/v1/account/ecdh-public-key', {\n method: 'PUT',\n body: JSON.stringify({ ecdh_public_key: ecdhPublicKey, encrypted_ecdh_private_key: encryptedEcdhPrivateKey }),\n });\n }\n\n // \u2500\u2500 Master password change (K4b) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Rotate the master password (user knows the current one). All crypto happens\n * in the browser: the caller re-wraps the unchanged vault_key + ECDH private key\n * under the new master_key and passes the opaque blobs here. The server re-checks\n * `current_auth_hash`, rotates the credentials, revokes every other session and\n * re-issues this device's tokens \u2014 which we adopt so the session stays live.\n */\n async changeMasterPassword(params: {\n current_auth_hash: string;\n new_auth_hash: string;\n new_enc_salt: string;\n new_encrypted_vault_key: string;\n new_encrypted_ecdh_private_key: string;\n device_name: string;\n device_fingerprint: string;\n }): Promise<{ success: true; enc_salt: string }> {\n const body = await this.request<{ success: true; access_token: string; refresh_token: string; enc_salt: string }>(\n '/v1/account/change-master-password',\n { method: 'POST', body: JSON.stringify(params) },\n );\n // Adopt the freshly-issued tokens (the old ones were just revoked server-side).\n this.tokens.set({ access_token: body.access_token, refresh_token: body.refresh_token });\n return { success: body.success, enc_salt: body.enc_salt };\n }\n\n // \u2500\u2500 Account profile + email change (#34) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Set or clear the optional display name. Returns the stored value. */\n updateProfile(displayName: string | null): Promise<{ display_name: string | null }> {\n return this.request('/v1/account/profile', {\n method: 'PATCH',\n body: JSON.stringify({ display_name: displayName }),\n });\n }\n\n /**\n * Begin an email change: step-up re-verifies the current master password\n * (`current_auth_hash`, re-derived in the browser), then the server mails a\n * 6-digit code to the NEW address and an alert to the OLD one. enc_salt/auth_hash\n * are untouched \u2014 the email is not part of the KDF.\n */\n changeEmailInit(newEmail: string, currentAuthHash: string): Promise<{ ok: true }> {\n return this.request('/v1/account/change-email/init', {\n method: 'POST',\n body: JSON.stringify({ new_email: newEmail, current_auth_hash: currentAuthHash }),\n });\n }\n\n /** Confirm the email change with the 6-digit code; returns the new email. */\n changeEmailConfirm(code: string): Promise<{ ok: true; email: string }> {\n return this.request('/v1/account/change-email/confirm', {\n method: 'POST',\n body: JSON.stringify({ code }),\n });\n }\n\n // \u2500\u2500 UI preferences \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Fetch user's stored UI preferences (e.g. dashboard_layout). */\n getUserPreferences(): Promise<{ dashboard_layout: Record<string, unknown[]> | null }> {\n return this.request('/v1/account/preferences', { method: 'GET' });\n }\n\n /** Persist UI preferences (merged server-side). */\n updateUserPreferences(prefs: { dashboard_layout?: Record<string, unknown[]> | null }): Promise<{ dashboard_layout: Record<string, unknown[]> | null }> {\n return this.request('/v1/account/preferences', {\n method: 'PUT',\n body: JSON.stringify(prefs),\n });\n }\n\n /** Patch site-icon display preferences. */\n updateSiteIconPrefs(patch: { show_site_icons?: boolean; site_icons_prompt_seen?: boolean }): Promise<{ show_site_icons: boolean; site_icons_prompt_seen: boolean }> {\n return this.request('/v1/users/me/preferences', {\n method: 'PATCH',\n body: JSON.stringify(patch),\n });\n }\n /** Patch clipboard-auto-clear personal preferences. No-op fields are omitted from the body. */\n updateClipboardClearPrefs(patch: { clipboard_clear_enabled?: boolean; clipboard_clear_seconds?: 20 | 60 | 120 }): Promise<{ clipboard_clear_enabled: boolean; clipboard_clear_seconds: 20 | 60 | 120 }> {\n return this.request('/v1/users/me/preferences', {\n method: 'PATCH',\n body: JSON.stringify(patch),\n });\n }\n\n // \u2500\u2500 Offboarding reviews (#20) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Open offboarding reviews for the org (one header per departed member). */\n getOffboardReviews(orgId: string): Promise<OffboardReview[]> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/offboard-reviews`, { method: 'GET' });\n }\n\n /** Cursor-paginated entries the departed member had revealed/copied. */\n getOffboardSeen(\n orgId: string,\n userId: string,\n params?: { limit?: number; sort?: 'recency' | 'risk'; before_ts?: string; before_entry_id?: string; before_high_risk?: boolean },\n ): Promise<OffboardSeenPage> {\n const q = new URLSearchParams();\n if (params?.limit) q.set('limit', String(params.limit));\n if (params?.sort) q.set('sort', params.sort);\n if (params?.before_ts) q.set('before_ts', params.before_ts);\n if (params?.before_entry_id) q.set('before_entry_id', params.before_entry_id);\n if (params?.before_high_risk !== undefined) q.set('before_high_risk', String(params.before_high_risk));\n const qs = q.toString();\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/offboard-reviews/${encodeURIComponent(userId)}/seen${qs ? `?${qs}` : ''}`, { method: 'GET' });\n }\n\n /** Shared vault entries the departed member had access to. */\n getOffboardAccess(\n orgId: string,\n userId: string,\n params?: { limit?: number; before_ts?: string; before_entry_id?: string },\n ): Promise<OffboardAccessPage> {\n const q = new URLSearchParams();\n if (params?.limit) q.set('limit', String(params.limit));\n if (params?.before_ts) q.set('before_ts', params.before_ts);\n if (params?.before_entry_id) q.set('before_entry_id', params.before_entry_id);\n const qs = q.toString();\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/offboard-reviews/${encodeURIComponent(userId)}/access${qs ? `?${qs}` : ''}`, { method: 'GET' });\n }\n\n /** Upsert a review item status (rotated | reviewed). */\n patchOffboardItem(\n orgId: string,\n userId: string,\n entryId: string,\n status: 'rotated' | 'reviewed',\n ): Promise<{ ok: boolean; entry_id: string; status: string }> {\n return this.request(\n `/v1/orgs/${encodeURIComponent(orgId)}/offboard-reviews/${encodeURIComponent(userId)}/items/${encodeURIComponent(entryId)}`,\n { method: 'PATCH', body: JSON.stringify({ status }) },\n );\n }\n\n /** Close the offboarding review for a departed member. */\n closeOffboardReview(orgId: string, userId: string): Promise<{ ok: boolean; closed: number }> {\n return this.request(\n `/v1/orgs/${encodeURIComponent(orgId)}/offboard-reviews/${encodeURIComponent(userId)}/close`,\n { method: 'POST' },\n );\n }\n\n // \u2500\u2500 RBAC: Permission Levels, Security Groups, Grants (Rez 1c) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n getRoles(orgId: string): Promise<{ roles: OrgRole[] }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/roles`, { method: 'GET' });\n }\n\n createRole(orgId: string, body: { name: string; capabilities: string[] }): Promise<OrgRole> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/roles`, {\n method: 'POST',\n body: JSON.stringify(body),\n });\n }\n\n updateRole(orgId: string, roleId: string, body: { name?: string; capabilities?: string[] }): Promise<OrgRole> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/roles/${encodeURIComponent(roleId)}`, {\n method: 'PATCH',\n body: JSON.stringify(body),\n });\n }\n\n deleteRole(orgId: string, roleId: string): Promise<{ ok: boolean }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/roles/${encodeURIComponent(roleId)}`, { method: 'DELETE' });\n }\n\n getGroups(orgId: string): Promise<{ groups: OrgGroup[] }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/groups`, { method: 'GET' });\n }\n\n createGroup(orgId: string, body: { name: string }): Promise<OrgGroup> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/groups`, {\n method: 'POST',\n body: JSON.stringify(body),\n });\n }\n\n updateGroup(orgId: string, gid: string, body: { name: string }): Promise<OrgGroup> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/groups/${encodeURIComponent(gid)}`, {\n method: 'PATCH',\n body: JSON.stringify(body),\n });\n }\n\n deleteGroup(orgId: string, gid: string): Promise<{ ok: boolean }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/groups/${encodeURIComponent(gid)}`, { method: 'DELETE' });\n }\n\n getGroupMembers(orgId: string, gid: string): Promise<{ members: OrgGroupMember[] }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/groups/${encodeURIComponent(gid)}/members`, { method: 'GET' });\n }\n\n /** F4 Rez 2 Faza 1: collections a group holds a grant on (group-inheritance fan-out). */\n getGroupCollections(orgId: string, gid: string): Promise<{ collections: OrgGroupCollection[] }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/groups/${encodeURIComponent(gid)}/collections`, { method: 'GET' });\n }\n\n addGroupMember(orgId: string, gid: string, userId: string): Promise<{ ok: boolean }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/groups/${encodeURIComponent(gid)}/members`, {\n method: 'POST',\n body: JSON.stringify({ user_id: userId }),\n });\n }\n\n removeGroupMember(orgId: string, gid: string, userId: string): Promise<{ ok: boolean }> {\n return this.request(\n `/v1/orgs/${encodeURIComponent(orgId)}/groups/${encodeURIComponent(gid)}/members/${encodeURIComponent(userId)}`,\n { method: 'DELETE' },\n );\n }\n\n getGrants(orgId: string): Promise<{ grants: OrgGrant[] }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/grants`, { method: 'GET' });\n }\n\n createGrant(\n orgId: string,\n body: { subject_type: 'user' | 'group'; subject_id: string; role_id?: string; capability?: string; effect?: 'allow' | 'deny' },\n ): Promise<OrgGrant> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/grants`, {\n method: 'POST',\n body: JSON.stringify(body),\n });\n }\n\n deleteGrant(orgId: string, grantId: string): Promise<{ ok: boolean }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/grants/${encodeURIComponent(grantId)}`, { method: 'DELETE' });\n }\n\n getCapabilities(orgId: string): Promise<{ capabilities: Capability[] }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/capabilities`, { method: 'GET' });\n }\n\n // \u2500\u2500 Internals \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private async request<T>(path: string, init: RequestInit, isRetry = false): Promise<T> {\n const headers = new Headers(init.headers);\n if (init.body) headers.set('Content-Type', 'application/json');\n const access = this.tokens.get()?.access_token;\n if (access) headers.set('Authorization', `Bearer ${access}`);\n\n const res = await this.doFetch(`${this.baseUrl}${path}`, {\n ...init,\n headers,\n ...(this.credentials ? { credentials: this.credentials } : {}),\n });\n\n // Refresh on 401 when we have a stored refresh token (Bearer clients) OR we're\n // in cookie mode (console: the refresh token lives in the httpOnly cookie).\n if (res.status === 401 && !isRetry && (this.tokens.get()?.refresh_token || this.cookieMode)) {\n if (await this.tryRefresh()) return this.request<T>(path, init, true);\n this.tokens.set(null);\n }\n\n const text = await res.text();\n const data = text ? (JSON.parse(text) as unknown) : null;\n if (!res.ok) {\n const body = (data ?? {}) as { detail?: string; title?: string; message?: string; code?: string; [key: string]: unknown };\n throw new ApiError(res.status, body.detail ?? body.title ?? body.message ?? `API error ${res.status}`, body.code, body);\n }\n return data as T;\n }\n\n private tryRefresh(): Promise<boolean> {\n // Single-flight: a burst of 401s triggers exactly one /refresh.\n if (this.refreshing) return this.refreshing;\n this.refreshing = this.doRefresh().finally(() => { this.refreshing = null; });\n return this.refreshing;\n }\n\n // \u2500\u2500 Token refresh (internal) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private async doRefresh(): Promise<boolean> {\n const current = this.tokens.get();\n // Bearer clients send the refresh token in the body; the console relies on the\n // httpOnly cookie (credentials:'include'), so an empty body is valid there.\n if (!current?.refresh_token && !this.cookieMode) return false;\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), REFRESH_TIMEOUT_MS);\n try {\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (current?.access_token) headers['Authorization'] = `Bearer ${current.access_token}`;\n const res = await this.doFetch(`${this.baseUrl}/v1/auth/refresh`, {\n method: 'POST',\n headers,\n body: JSON.stringify(current?.refresh_token ? { refresh_token: current.refresh_token } : {}),\n signal: controller.signal,\n ...(this.credentials ? { credentials: this.credentials } : {}),\n });\n if (!res.ok) {\n if (typeof console !== 'undefined') console.warn(`[auth] refresh failed: ${res.status}`);\n return false;\n }\n const data = (await res.json()) as RefreshResponse;\n // access token kept in memory; refresh (also returned) stays in memory only \u2014\n // never persisted (console persists no tokens; the cookie is the source of truth).\n this.tokens.set({ access_token: data.access_token, refresh_token: data.refresh_token });\n return true;\n } catch (e) {\n if (typeof console !== 'undefined') console.warn('[auth] refresh error', e);\n return false;\n } finally {\n clearTimeout(timer);\n }\n }\n}\n", "// Tier-aware entitlement helpers. Pure derivations over the server-authoritative\n// bundle (GET /v1/account/entitlements). The console's visible surface is now\n// derived from the module registry (see platform/), so the old ConsoleSection list\n// + visibleSections() were removed (#53 PR6) to kill the registry\u2194list double truth.\n\nimport type { EntitlementsBundle, FeatureEntitlement, PlanSlug } from '../types/index.js';\n\n/** Effective plan FOR GATING. Normalizes trial\u2192premium and trial_expired\u2192free \u2014\n * the same mapping the API applies when computing features \u2014 so plan gates agree\n * with feature gates during a trial. For DISPLAY (trial badge/days remaining)\n * read the raw `bundle.primary_org.plan_slug` directly. */\nexport function planOf(bundle: EntitlementsBundle | null): PlanSlug {\n const raw = bundle?.primary_org?.plan_slug ?? 'free';\n if (raw === 'trial') return 'premium';\n if (raw === 'trial_expired') return 'free';\n return raw;\n}\n\n/** True when a named server feature is enabled. The API sends `{ enabled, tier, ... }`\n * per slug (#20); a flat boolean is tolerated as a legacy/test shape. Anything\n * else \u2014 missing key, malformed value, null bundle \u2014 is fail-closed. */\nexport function hasFeature(bundle: EntitlementsBundle | null, key: string): boolean {\n const f: unknown = bundle?.features?.[key];\n if (f === true) return true; // legacy flat-boolean shape\n if (f && typeof f === 'object') return (f as FeatureEntitlement).enabled === true;\n return false;\n}\n", "// PDP reason codes \u2014 mirrored from geslar-api/src/core/pdp/reason-codes.ts.\n// The API returns these strings in ApiError.code on 403/402 responses from\n// PDP-gated routes. Kept in sync with the server dictionary; extend here\n// when the server adds a new code.\n\nexport const PDP_REASON = {\n FORBIDDEN: 'pdp/forbidden',\n ACCOUNT_INACTIVE: 'pdp/account-inactive',\n EMAIL_UNVERIFIED: 'pdp/email-unverified',\n MFA_SETUP_REQUIRED: 'pdp/mfa-setup-required',\n SCOPE_INSUFFICIENT: 'pdp/scope-insufficient',\n PLAN_REQUIRED: 'pdp/plan-required',\n CAPABILITY_DENIED: 'pdp/capability-denied',\n ORG_TYPE_RESTRICTION: 'pdp/org-type-restriction',\n} as const;\n\nexport type PdpReason = (typeof PDP_REASON)[keyof typeof PDP_REASON];\n\nconst _PDP_CODES = new Set<string>(Object.values(PDP_REASON));\n\n/** True when `code` is a known PDP denial reason (type-guard). */\nexport function isPdpReason(code: string | undefined): code is PdpReason {\n return !!code && _PDP_CODES.has(code);\n}\n\n/** Extract a PdpReason from an unknown thrown value, or null if it isn't one.\n * Checks ApiError duck-type (status 402/403 + .code) so callers don't need\n * to import ApiError. Only org-scope denials are surfaced as walls; generic\n * 403 without a PDP code falls through to existing error handling. */\nexport function extractPdpReason(e: unknown): PdpReason | null {\n if (typeof e !== 'object' || e === null) return null;\n const err = e as { status?: unknown; code?: unknown };\n if (err.status !== 403 && err.status !== 402) return null;\n return isPdpReason(err.code as string | undefined) ? (err.code as PdpReason) : null;\n}\n", "// Vault health analysis \u2014 pure, no DOM, no transport.\n//\n// DRIFT NOTE: geslar-skrinjar/vault/vault-health.js must stay in sync with this\n// module (same ENTROPY_WEAK_THRESHOLD constant, same scoring algorithm, same\n// category definitions, same HEALTH_CATEGORY_SEV map) until vault-health.js is\n// replaced by this shared package.\n\n/** bits \u2014 mirrors vault-health.js ENTROPY_WEAK_THRESHOLD */\nexport const ENTROPY_WEAK_THRESHOLD = 40;\n\n// \u2500\u2500\u2500 Per-entry health badge types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport type HealthSeverity = 'crit' | 'warn' | 'mid' | 'info';\n\nexport interface HealthStatusResult {\n status: 'breached' | 'weak' | 'reused' | 'old' | 'empty';\n sev: HealthSeverity;\n}\n\nconst _SEV_RANK: Record<HealthSeverity, number> = { crit: 4, warn: 3, mid: 2, info: 1 };\n\n/** Shared severity map \u2014 badge and report reference the same source of truth. */\nexport const HEALTH_CATEGORY_SEV: Readonly<Record<HealthStatusResult['status'], HealthSeverity>> = {\n breached: 'crit',\n weak: 'warn',\n reused: 'mid',\n old: 'info',\n empty: 'info',\n};\n\nconst OLD_THRESHOLD_MS = 365 * 24 * 60 * 60 * 1000;\n\nfunction calcEntropy(password: string): number {\n if (!password) return 0;\n const len = password.length;\n let charsetSize = 0;\n if (/[a-z]/.test(password)) charsetSize += 26;\n if (/[A-Z]/.test(password)) charsetSize += 26;\n if (/[0-9]/.test(password)) charsetSize += 10;\n if (/[^a-zA-Z0-9]/.test(password)) charsetSize += 32;\n return len * Math.log2(charsetSize || 1);\n}\n\n/** Minimal entry shape required by the analyzer. Matches the decrypted VaultEntry. */\nexport interface HealthEntry {\n id: string;\n type?: string;\n label?: string;\n password?: string;\n username?: string;\n updated?: string;\n created?: string;\n}\n\nexport interface WeakEntry { id: string; label?: string; entropy: number }\nexport interface OldEntry { id: string; label?: string; days: number }\nexport interface EmptyEntry { id: string; label?: string; missing: string[] }\nexport interface BreachedEntry { id: string; label?: string; count: number }\n\nexport interface VaultHealthResult {\n score: number;\n weak: WeakEntry[];\n reused: { id: string; label?: string }[][];\n old: OldEntry[];\n empty: EmptyEntry[];\n breached: BreachedEntry[];\n total: number;\n}\n\n/** Injected dep: receives plaintext passwords, returns breach status keyed by password.\n * SHA-1 hashing and HTTP transport are the caller's concern \u2014 analyzer stays clean. */\nexport type CheckBreachesFn = (\n passwords: string[],\n) => Promise<Map<string, { breached: boolean; count: number }>>;\n\nexport interface HealthDeps {\n checkBreaches: CheckBreachesFn;\n /** Epoch ms \"now\" \u2014 injectable for deterministic tests (default: Date.now()). */\n nowMs?: number;\n}\n\n/** Analyze vault health. Mirrors vault-health.js VaultHealth.analyze() 1:1. */\nexport async function analyzeVaultHealth(\n entries: HealthEntry[],\n deps: HealthDeps,\n): Promise<VaultHealthResult> {\n const loginEntries = entries.filter((e) => e.type !== 'card');\n const now = deps.nowMs ?? Date.now();\n\n // 1. Weak\n const weak: WeakEntry[] = [];\n for (const e of loginEntries) {\n if (!e.password) continue;\n const entropy = calcEntropy(e.password);\n if (entropy < ENTROPY_WEAK_THRESHOLD) {\n weak.push({ id: e.id, label: e.label, entropy: Math.round(entropy) });\n }\n }\n\n // 2. Reused\n const pwMap = new Map<string, { id: string; label?: string }[]>();\n for (const e of loginEntries) {\n if (!e.password) continue;\n const list = pwMap.get(e.password) ?? [];\n list.push({ id: e.id, label: e.label });\n pwMap.set(e.password, list);\n }\n const reused: { id: string; label?: string }[][] = [];\n for (const [, group] of pwMap) {\n if (group.length > 1) reused.push(group);\n }\n\n // 3. Old \u2014 skip entries with no date (no date \u2260 old; mirrors vault-health.js)\n const old: OldEntry[] = [];\n for (const e of loginEntries) {\n if (!e.password) continue;\n const dateStr = e.updated ?? e.created;\n if (!dateStr) continue;\n const ts = new Date(dateStr).getTime();\n if (now - ts > OLD_THRESHOLD_MS) {\n const days = Math.floor((now - ts) / 86_400_000);\n old.push({ id: e.id, label: e.label, days });\n }\n }\n\n // 4. Empty\n const empty: EmptyEntry[] = [];\n for (const e of loginEntries) {\n const missing: string[] = [];\n if (!e.password) missing.push('lozinka');\n if (!e.username) missing.push('korisnik');\n if (missing.length) empty.push({ id: e.id, label: e.label, missing });\n }\n\n // 5. Breached\n const totalLogin = loginEntries.length;\n if (totalLogin === 0) {\n return { score: 100, weak: [], reused: [], old: [], empty: [], breached: [], total: 0 };\n }\n\n const uniquePasswords = [\n ...new Set(loginEntries.map((e) => e.password).filter((p): p is string => !!p)),\n ];\n const breachMap = uniquePasswords.length > 0\n ? await deps.checkBreaches(uniquePasswords)\n : new Map<string, { breached: boolean; count: number }>();\n\n const breached: BreachedEntry[] = [];\n for (const e of loginEntries) {\n if (!e.password) continue;\n const result = breachMap.get(e.password);\n if (result?.breached) {\n breached.push({ id: e.id, label: e.label, count: result.count });\n }\n }\n\n // Score (0-100)\n const issueEntries = new Set<string>();\n weak.forEach((e) => issueEntries.add(e.id));\n reused.forEach((g) => g.forEach((e) => issueEntries.add(e.id)));\n old.forEach((e) => issueEntries.add(e.id));\n breached.forEach((e) => issueEntries.add(e.id));\n empty.filter((e) => e.missing.includes('lozinka')).forEach((e) => issueEntries.add(e.id));\n\n const score = Math.round((1 - issueEntries.size / totalLogin) * 100);\n return { score, weak, reused, old, empty, breached, total: totalLogin };\n}\n\n/**\n * Worst-wins badge status for a single entry.\n * Returns null when entry has no health issues.\n * Severity rank: crit > warn > mid > info.\n */\nexport function entryHealthStatus(\n entryId: string,\n result: VaultHealthResult,\n): HealthStatusResult | null {\n let best: HealthStatusResult | null = null;\n\n function consider(status: HealthStatusResult['status']): void {\n const sev = HEALTH_CATEGORY_SEV[status];\n if (!best || _SEV_RANK[sev] > _SEV_RANK[best.sev]) {\n best = { status, sev };\n }\n }\n\n if (result.breached.some((e) => e.id === entryId)) consider('breached');\n if (result.weak.some((e) => e.id === entryId)) consider('weak');\n if (result.reused.some((g) => g.some((e) => e.id === entryId))) consider('reused');\n if (result.old.some((e) => e.id === entryId)) consider('old');\n if (result.empty.some((e) => e.id === entryId && e.missing.includes('lozinka'))) consider('empty');\n\n return best;\n}\n", "import { ApiClient, type TokenStore } from '@geslar/core';\n\n/** Single wiring point for ApiClient \u2014 mirrors apps/admin/src/lib/core.ts, but\n * Bearer-mode (no cookies) and a caller-supplied OS-backed TokenStore instead\n * of memoryTokenStore(). */\nexport function buildApiClient(baseUrl: string, tokenStore: TokenStore): ApiClient {\n return new ApiClient({ baseUrl, tokenStore });\n}\n", "import { ApiError, planOf } from '@geslar/core';\nimport { loadSession } from '../lib/session.js';\nimport { loadOrInitConfig } from '../lib/config.js';\nimport { buildApiClient } from '../lib/core.js';\nimport { print, printErr } from '../lib/output.js';\nimport { EXIT } from '../lib/errors.js';\nimport { selectBackend, createCliTokenStore } from '../token-store/index.js';\n\nexport async function whoamiCommand(): Promise<number> {\n const backend = await selectBackend();\n const tokenStore = await createCliTokenStore(backend);\n const tokens = tokenStore.get();\n\n if (!tokens) {\n printErr('not signed in \u2014 run `geslar signin`');\n return EXIT.AUTH;\n }\n\n const session = await loadSession();\n const config = await loadOrInitConfig();\n const baseUrl = session?.apiBase ?? config.apiBase;\n const api = buildApiClient(baseUrl, tokenStore);\n\n try {\n const entitlements = await api.getEntitlements();\n await tokenStore.flush(); // a silent refresh may have rotated tokens\n const plan = planOf(entitlements);\n const org = entitlements.primary_org;\n\n print(`Account: ${session?.email ?? '(unknown \u2014 re-run `geslar signin`)'}`);\n print(`Plan: ${plan}`);\n if (org?.id) {\n print(`Org: ${org.id}${org.role ? ` (${org.role})` : ''}`);\n }\n print(`API: ${baseUrl}`);\n print(`Storage: ${backend.name}`);\n return EXIT.OK;\n } catch (err) {\n await tokenStore.flush();\n if (err instanceof ApiError && (err.status === 401 || err.status === 403)) {\n printErr('session expired \u2014 run `geslar signin` again');\n return EXIT.AUTH;\n }\n printErr((err as Error).message);\n return EXIT.GENERAL;\n }\n}\n", "import { CliError, EXIT } from './errors.js';\n\nconst TOTP_CTRL_C = '\u0003';\nconst TOTP_CTRL_D = '\u0004';\nconst TOTP_BACKSPACE = '\u007F';\n\n/** TTY no-echo TOTP-code prompt (`geslar agent create`, spec-access-core.md\n * \u00A74) \u2014 same no-echo skeleton as promptPassword, kept as its own function\n * (not a shared refactor of promptPassword) so that function's existing\n * behavior/message/exit-code stay byte-identical for the master-password\n * flow. `ttyError` lets the caller choose the exit code/message for \"no\n * TTY\" \u2014 agent create's TTY gate is a distinct condition from a locked vault. */\nexport function promptTotpCode(promptText: string, ttyError: CliError): Promise<string> {\n return new Promise((resolve, reject) => {\n if (!process.stdin.isTTY) {\n reject(ttyError);\n return;\n }\n\n process.stdout.write(promptText);\n const stdin = process.stdin;\n stdin.setRawMode(true);\n stdin.resume();\n stdin.setEncoding('utf8');\n\n let input = '';\n const onData = (chunk: string) => {\n const char = chunk.toString();\n if (char === '\\n' || char === '\\r' || char === TOTP_CTRL_D) {\n cleanup();\n process.stdout.write('\\n');\n resolve(input.trim());\n return;\n }\n if (char === TOTP_CTRL_C) {\n cleanup();\n process.stdout.write('\\n');\n reject(new CliError(EXIT.GENERAL, 'Aborted'));\n return;\n }\n if (char === TOTP_BACKSPACE || char === '\\b') {\n input = input.slice(0, -1);\n return;\n }\n input += char;\n };\n function cleanup() {\n stdin.setRawMode(false);\n stdin.pause();\n stdin.removeListener('data', onData);\n }\n stdin.on('data', onData);\n });\n}\n\nconst CTRL_C = '\u0003';\nconst CTRL_D = '\u0004';\nconst BACKSPACE = '\u007F';\n\n/** TTY no-echo master-password prompt (spec \u00A73.7/\u00A78.2) \u2014 nothing is echoed\n * back, not even asterisks; the password never touches argv or env, and\n * never leaves this process. Rejects immediately if stdin isn't a TTY (the\n * caller decides what to do \u2014 e.g. fall back to a `geslar unlock` grant, or\n * fail closed with exit 6). */\nexport function promptPassword(promptText: string): Promise<string> {\n return new Promise((resolve, reject) => {\n if (!process.stdin.isTTY) {\n reject(new CliError(EXIT.VAULT_LOCKED, 'No TTY available for a master-password prompt \u2014 run `geslar unlock` first'));\n return;\n }\n\n process.stdout.write(promptText);\n const stdin = process.stdin;\n stdin.setRawMode(true);\n stdin.resume();\n stdin.setEncoding('utf8');\n\n let input = '';\n const onData = (chunk: string) => {\n const char = chunk.toString();\n if (char === '\\n' || char === '\\r' || char === CTRL_D) {\n cleanup();\n process.stdout.write('\\n');\n resolve(input);\n return;\n }\n if (char === CTRL_C) {\n cleanup();\n process.stdout.write('\\n');\n reject(new CliError(EXIT.GENERAL, 'Aborted'));\n return;\n }\n if (char === BACKSPACE || char === '\\b') {\n input = input.slice(0, -1);\n return;\n }\n input += char;\n };\n function cleanup() {\n stdin.setRawMode(false);\n stdin.pause();\n stdin.removeListener('data', onData);\n }\n stdin.on('data', onData);\n });\n}\n", "// @geslar/core \u2014 crypto entry for TS/ESM consumers (admin console, web).\n//\n// The two crypto modules (`vault-crypto.js`, `vault-cloud-crypto.js`) are the\n// single source of truth, authored as classic scripts so the browser extension\n// can vendor and importScripts() them verbatim (see scripts/vendor-core.mjs).\n// `vault-cloud-crypto.js` reads `VaultCrypto` from the global scope (as it does\n// inside the extension's service worker), so we publish it on globalThis before\n// re-exporting. The crypto itself uses only Web Crypto (`crypto.subtle`) \u2014 no\n// eval/Function \u2014 so it stays MV3 CSP-safe in every consumer.\n//\n// Default imports resolve to each module's `module.exports` (CommonJS via the\n// sibling package.json), which works under Node ESM and Vite/esbuild alike.\n\nimport VaultCrypto from './vault-crypto.js';\n\n// Must exist before any VaultCloudCrypto.* call; module init is well before use.\nglobalThis.VaultCrypto = VaultCrypto;\n\nimport VaultCloudCrypto from './vault-cloud-crypto.js';\nimport OrgRecoveryCrypto from './recovery-enrollment.js';\n\nexport { VaultCrypto, VaultCloudCrypto, OrgRecoveryCrypto };\n", "import { VaultCrypto, VaultCloudCrypto } from '@geslar/core/crypto';\nimport type { VaultKeyMaterial } from '@geslar/core';\n\n/** Wrong master password (AES-GCM tag verification failure on unwrap) \u2014\n * distinct from \"no vault key material at all\" so callers can give the\n * right message (spec \u00A78.2: master password never leaves the process). */\nexport class WrongMasterPasswordError extends Error {\n constructor() {\n super('Incorrect master password');\n this.name = 'WrongMasterPasswordError';\n }\n}\n\nexport interface UnlockedKeys {\n /** Raw DEK bytes \u2014 kept raw (not imported to a CryptoKey) so `geslar unlock`\n * can persist them into the OS-wrapped grant; `importVaultKey` produces a\n * NON-extractable key, so importing early would make that impossible. */\n dekRaw: Uint8Array;\n /** Raw (PKCS8) ECDH private key bytes \u2014 present only if the account has one\n * wrapped server-side (needed to unwrap team_collection DEKs). */\n ecdhPrivRaw: Uint8Array | null;\n}\n\n/**\n * The local KDF chain (spec \u00A73.3/\u00A73.7): master password NEVER leaves this\n * process. `material` comes from GET /v1/account/vault-key-material (M2\n * dependency, geslar-api#97) \u2014 already-wrapped blobs only, no auth_hash.\n */\nexport async function deriveAndUnlock(password: string, material: VaultKeyMaterial): Promise<UnlockedKeys> {\n if (!material.encrypted_vault_key) {\n throw new Error('This account has no vault key yet \u2014 sign in via the console first to finish setup.');\n }\n\n const salt = VaultCrypto.base64ToBuf(material.enc_salt);\n const masterKey = await VaultCrypto.deriveMasterKey(password, salt);\n\n let dekRaw: Uint8Array;\n try {\n dekRaw = await VaultCloudCrypto.unwrapVaultKey(masterKey, material.encrypted_vault_key);\n } catch {\n throw new WrongMasterPasswordError();\n }\n\n let ecdhPrivRaw: Uint8Array | null = null;\n if (material.encrypted_ecdh_private_key) {\n // Master password already verified above (DEK unwrap succeeded) \u2014 a\n // failure here means corrupted/mismatched state, not a wrong password.\n ecdhPrivRaw = await VaultCloudCrypto.unwrapVaultKey(masterKey, material.encrypted_ecdh_private_key);\n }\n\n return { dekRaw, ecdhPrivRaw };\n}\n", "import { buildApiClient } from '../lib/core.js';\nimport { loadSession } from '../lib/session.js';\nimport { loadOrInitConfig } from '../lib/config.js';\nimport { selectBackend, createCliTokenStore } from '../token-store/index.js';\nimport { promptPassword } from '../lib/prompt.js';\nimport { print, printErr } from '../lib/output.js';\nimport { CliError, EXIT } from '../lib/errors.js';\nimport { deriveAndUnlock } from '../vault/unlock.js';\nimport { saveVaultGrant, parseTtl } from '../vault/grant.js';\n\nexport async function unlockCommand(opts: { ttl?: string }): Promise<number> {\n try {\n const ttlSec = parseTtl(opts.ttl);\n\n const config = await loadOrInitConfig();\n const session = await loadSession();\n const baseUrl = session?.apiBase ?? config.apiBase;\n const backend = await selectBackend();\n const tokenStore = await createCliTokenStore(backend);\n if (!tokenStore.get()) {\n printErr('not signed in \u2014 run `geslar signin`');\n return EXIT.AUTH;\n }\n const api = buildApiClient(baseUrl, tokenStore);\n\n const material = await api.getVaultKeyMaterial();\n await tokenStore.flush(); // a silent refresh during that call may have rotated tokens\n\n const password = await promptPassword('Master password: ');\n const unlocked = await deriveAndUnlock(password, material);\n await saveVaultGrant(unlocked, ttlSec);\n\n const mins = Math.round(ttlSec / 60);\n print(`Vault unlocked for ${mins} minute${mins === 1 ? '' : 's'}.`);\n return EXIT.OK;\n } catch (err) {\n if (err instanceof CliError) {\n printErr(err.message);\n return err.exitCode;\n }\n printErr((err as Error).message);\n return EXIT.GENERAL;\n }\n}\n", "import { print } from '../lib/output.js';\nimport { clearVaultGrant } from '../vault/grant.js';\nimport { EXIT } from '../lib/errors.js';\n\nexport async function lockCommand(): Promise<number> {\n await clearVaultGrant();\n print('Vault locked.');\n return EXIT.OK;\n}\n", "import type { ApiClient } from '@geslar/core';\nimport { promptPassword } from '../lib/prompt.js';\nimport { CliError, EXIT } from '../lib/errors.js';\nimport { loadVaultGrant } from './grant.js';\nimport { deriveAndUnlock, type UnlockedKeys } from './unlock.js';\n\n/**\n * Obtain the DEK (+ ECDH key) needed to decrypt entries: prefer an existing\n * `geslar unlock` grant (headless-friendly); otherwise, in a TTY, prompt for\n * the master password once WITHOUT persisting anything (spec \u00A73.7: \"geslar\n * run u TTY-ju bez granta pita lozinku po pozivu \u2014 ni\u0161ta se ne sprema\").\n * No grant + no TTY \u2192 fail closed, exit 6.\n */\nexport async function obtainUnlockedKeys(api: ApiClient): Promise<UnlockedKeys> {\n const grant = await loadVaultGrant();\n if (grant) return grant;\n\n if (!process.stdin.isTTY) {\n throw new CliError(EXIT.VAULT_LOCKED, 'Vault is locked and no TTY is available \u2014 run `geslar unlock` first');\n }\n\n const material = await api.getVaultKeyMaterial();\n const password = await promptPassword('Master password: ');\n return deriveAndUnlock(password, material);\n}\n", "import type { ApiClient, CollectionSummary, MemberKeyEntry, Org, OrgType } from '@geslar/core';\nimport { VaultCrypto, VaultCloudCrypto } from '@geslar/core/crypto';\nimport type { UnlockedKeys } from './unlock.js';\n\nexport const PERSONAL_VAULT_NAME = 'Osobno';\n\nexport interface VaultHandle {\n id: string;\n /** Effective display/match name \u2014 for an org's default collection this is\n * the ORG's name, never the stored placeholder (\"Obiteljska \u0161krinja\" /\n * \"Op\u0107a \u0161krinja\", spec REV 2.4.1 \u00A72's \"kontrakt zadanih kolekcija\": that\n * stored name is never shown or matched, `list` and the resolver both use\n * the org name instead). */\n name: string;\n kind: 'personal' | 'collection';\n /** Owning org \u2014 null only for the personal vault (kept as its own `kind`\n * case, same as before REV 2.4; a personal org's own name/type is never\n * part of the semantic-token or org-name addressing scheme). */\n orgId: string | null;\n orgType: OrgType | null;\n /** True for the org's singleton auto-created collection (personal vault\n * counts as its \"org\"'s only vault, so also true). Needed to find \"the\n * default vault of org X\" for `family`/`company`/`work` token resolution. */\n isDefault: boolean;\n /** key_version \u2192 CryptoKey. Personal vaults only ever have version 1\n * (server sends no key_version for entries there \u2014 treat as 1, same\n * convention apps/admin uses). Collections may have several during a\n * key rotation window. */\n dekMap: Map<number, CryptoKey>;\n}\n\n/** Mirrors apps/admin/src/lib/dek-map.ts's buildDekMap \u2014 kept as a small local\n * copy rather than a cross-app import (that file isn't part of @geslar/core). */\nasync function buildCollectionDekMap(\n keys: MemberKeyEntry[] | undefined,\n fallback: { key_version: number; encrypted_key: string | null; wrapper_ecdh_pub: string | null } | null,\n ecdhPrivRaw: Uint8Array,\n): Promise<Map<number, CryptoKey>> {\n const source: Array<{ key_version: number; encrypted_key: string | null; ecdh_public_key: string | null }> =\n keys && keys.length > 0\n ? keys.map(k => ({ key_version: k.key_version, encrypted_key: k.encrypted_key, ecdh_public_key: k.wrapped_by?.ecdh_public_key ?? null }))\n : fallback\n ? [{ key_version: fallback.key_version, encrypted_key: fallback.encrypted_key, ecdh_public_key: fallback.wrapper_ecdh_pub }]\n : [];\n\n const map = new Map<number, CryptoKey>();\n for (const k of source) {\n if (!k.encrypted_key || !k.ecdh_public_key) continue; // no usable key material for this version \u2014 skip, not fatal\n const wrapperPub = VaultCrypto.base64ToBuf(k.ecdh_public_key);\n const dekRaw = await VaultCloudCrypto.unwrapSharedVaultKey(ecdhPrivRaw, wrapperPub, k.encrypted_key);\n map.set(k.key_version, await VaultCloudCrypto.importVaultKey(dekRaw));\n }\n return map;\n}\n\n/**\n * All vaults the caller can currently read: the personal vault (always) plus\n * any team_collection \u0161krinje visible via GET /v1/collections. A collection\n * the caller can't unwrap (no ECDH key on this account yet, or missing key\n * material) is silently omitted from the list rather than erroring the whole\n * command \u2014 it simply won't resolve as a `geslar://` target.\n */\nexport async function listVaultHandles(api: ApiClient, unlocked: UnlockedKeys): Promise<VaultHandle[]> {\n const handles: VaultHandle[] = [];\n\n const personal = await api.ensurePersonalVault();\n handles.push({\n id: personal.vault_id,\n name: PERSONAL_VAULT_NAME,\n kind: 'personal',\n orgId: null,\n orgType: null,\n isDefault: true,\n dekMap: new Map([[1, await VaultCloudCrypto.importVaultKey(unlocked.dekRaw)]]),\n });\n\n if (unlocked.ecdhPrivRaw) {\n // GET /v1/collections doesn't carry org type (only org_id/org_name) \u2014\n // GET /v1/orgs is the one surface that does, so both are fetched and\n // joined by org_id.\n const [{ collections }, orgs] = await Promise.all([api.getCollections(), api.getOrgs()]);\n const orgTypeById = new Map<string, OrgType>((orgs as Org[]).map(o => [o.id, o.type]));\n\n for (const c of collections as CollectionSummary[]) {\n if (!c.can_view || !c.name) continue;\n const isDefault = c.is_default === true;\n // Spec REV 2.4.1 \u00A72 \"kontrakt zadanih kolekcija\": the stored name of a\n // default collection is never shown or matched \u2014 the org's name is\n // used instead everywhere.\n const name = isDefault ? (c.org_name ?? c.name) : c.name;\n const dekMap = await buildCollectionDekMap(\n c.keys,\n { key_version: c.key_version, encrypted_key: c.encrypted_key, wrapper_ecdh_pub: c.wrapper_ecdh_pub },\n unlocked.ecdhPrivRaw,\n );\n if (dekMap.size === 0) continue; // couldn't unwrap any version \u2014 omit\n handles.push({\n id: c.vault_id,\n name,\n kind: 'collection',\n orgId: c.org_id,\n orgType: c.org_id ? (orgTypeById.get(c.org_id) ?? null) : null,\n isDefault,\n dekMap,\n });\n }\n }\n\n return handles;\n}\n", "import type { ApiClient, CollectionSummary } from '@geslar/core';\nimport { VaultCrypto, VaultCloudCrypto } from '@geslar/core/crypto';\nimport type { UnlockedKeys } from './unlock.js';\nimport type { VaultHandle } from './vaults.js';\nimport { PERSONAL_VAULT_NAME } from './vaults.js';\nimport type { AgentTokenVaultRef } from '../agent/token-store.js';\n\n/**\n * Agent-context counterpart to listVaultHandles (spec-access-core.md REV 1.2\n * \u00A74) \u2014 deliberately does NOT call ensurePersonalVault() or getOrgs(): neither\n * is on the agent bearer allowlist (POST /v1/sync/vault is a write; GET\n * /v1/orgs isn't listed at all). GET /v1/collections IS allowlisted and\n * already server-filters to this agent's granted team_collections, so that\n * half works unmodified. The personal vault (if granted) has no allowlisted\n * discovery route at all \u2014 its id/name come from `grantedVaults`, the\n * locally-cached snapshot captured at `agent create` time (safe: scope is\n * immutable, see agent/token-store.ts's doc comment).\n *\n * A granted vault the server no longer serves (owner lost access, profile\n * revoked mid-flight) simply won't appear in GET /v1/collections \u2014 same\n * fail-closed-by-omission behavior as the human path, no special-casing\n * needed here.\n */\nexport async function listAgentVaultHandles(\n api: ApiClient,\n unlocked: UnlockedKeys,\n grantedVaults: AgentTokenVaultRef[],\n): Promise<VaultHandle[]> {\n const handles: VaultHandle[] = [];\n\n const personalGrant = grantedVaults.find(v => v.kind === 'personal');\n if (personalGrant) {\n handles.push({\n id: personalGrant.id,\n name: PERSONAL_VAULT_NAME,\n kind: 'personal',\n orgId: null,\n orgType: null,\n isDefault: true,\n dekMap: new Map([[1, await VaultCloudCrypto.importVaultKey(unlocked.dekRaw)]]),\n });\n }\n\n const hasCollectionGrant = grantedVaults.some(v => v.kind === 'collection');\n if (hasCollectionGrant && unlocked.ecdhPrivRaw) {\n const { collections } = await api.getCollections();\n for (const c of collections as CollectionSummary[]) {\n if (!c.can_view || !c.name) continue;\n const isDefault = c.is_default === true;\n const name = isDefault ? (c.org_name ?? c.name) : c.name;\n const dekMap = await buildCollectionDekMap(c, unlocked.ecdhPrivRaw);\n if (dekMap.size === 0) continue;\n handles.push({\n id: c.vault_id,\n name,\n kind: 'collection',\n orgId: c.org_id,\n // getOrgs() isn't on the agent allowlist \u2014 org type (needed only for\n // the family/company/work semantic tokens) is unavailable under\n // agent context; direct vault-name addressing is unaffected.\n orgType: null,\n isDefault,\n dekMap,\n });\n }\n }\n\n return handles;\n}\n\n// Mirrors vault/vaults.ts's buildCollectionDekMap exactly (not exported from\n// there) \u2014 same small local-copy precedent that file's own doc comment notes\n// for apps/admin's version.\nasync function buildCollectionDekMap(c: CollectionSummary, ecdhPrivRaw: Uint8Array): Promise<Map<number, CryptoKey>> {\n const source = c.keys && c.keys.length > 0\n ? c.keys.map(k => ({ key_version: k.key_version, encrypted_key: k.encrypted_key, ecdh_public_key: k.wrapped_by?.ecdh_public_key ?? null }))\n : c.encrypted_key\n ? [{ key_version: c.key_version, encrypted_key: c.encrypted_key, ecdh_public_key: c.wrapper_ecdh_pub }]\n : [];\n\n const map = new Map<number, CryptoKey>();\n for (const k of source) {\n if (!k.encrypted_key || !k.ecdh_public_key) continue;\n const wrapperPub = VaultCrypto.base64ToBuf(k.ecdh_public_key);\n const dekRaw = await VaultCloudCrypto.unwrapSharedVaultKey(ecdhPrivRaw, wrapperPub, k.encrypted_key);\n map.set(k.key_version, await VaultCloudCrypto.importVaultKey(dekRaw));\n }\n return map;\n}\n", "// RFC 6238 TOTP via Web Crypto HMAC \u2014 copied from packages/ui/src/logic/totp.ts\n// (generateTotp/base32Decode only \u2014 the ring/color helpers there are pure UI\n// concerns). Kept as a local copy rather than a @geslar/ui dependency: the UI\n// package pulls in React, which a Node CLI has no business depending on for\n// ~30 lines of crypto logic. Keep in sync manually if the RFC 6238 core ever\n// changes (unlikely \u2014 it hasn't since it was written).\n\nexport interface TotpParams {\n secret: string; // base32\n digits?: number; // default 6\n period?: number; // default 30\n algorithm?: 'SHA-1' | 'SHA-256' | 'SHA-512'; // default SHA-1\n}\n\nconst B32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';\n\n/** Decode an RFC 4648 base32 string (case-insensitive, padding/space tolerant). */\nexport function base32Decode(input: string): Uint8Array {\n const clean = input.replace(/[\\s=]/g, '').toUpperCase();\n let bits = 0;\n let value = 0;\n const out: number[] = [];\n for (const ch of clean) {\n const idx = B32.indexOf(ch);\n if (idx === -1) continue; // skip stray chars rather than throw\n value = (value << 5) | idx;\n bits += 5;\n if (bits >= 8) {\n bits -= 8;\n out.push((value >>> bits) & 0xff);\n }\n }\n return new Uint8Array(out);\n}\n\nfunction counterBytes(counter: number): Uint8Array {\n const buf = new Uint8Array(8);\n let hi = Math.floor(counter / 0x100000000);\n let lo = counter >>> 0;\n for (let i = 7; i >= 4; i--) { buf[i] = lo & 0xff; lo = Math.floor(lo / 256); }\n for (let i = 3; i >= 0; i--) { buf[i] = hi & 0xff; hi = Math.floor(hi / 256); }\n return buf;\n}\n\n/** Generate the TOTP code for `nowMs` (defaults to current time). */\nexport async function generateTotp(params: TotpParams, nowMs?: number): Promise<{ code: string; remaining: number }> {\n const digits = params.digits ?? 6;\n const period = params.period ?? 30;\n const algorithm = params.algorithm ?? 'SHA-1';\n const now = Math.floor((nowMs ?? Date.now()) / 1000);\n const counter = Math.floor(now / period);\n const remaining = period - (now % period);\n\n const keyRaw = base32Decode(params.secret) as BufferSource;\n const key = await crypto.subtle.importKey('raw', keyRaw, { name: 'HMAC', hash: algorithm }, false, ['sign']);\n const mac = new Uint8Array(await crypto.subtle.sign('HMAC', key, counterBytes(counter) as BufferSource));\n\n const offset = mac[mac.length - 1]! & 0x0f;\n const bin =\n ((mac[offset]! & 0x7f) << 24) |\n ((mac[offset + 1]! & 0xff) << 16) |\n ((mac[offset + 2]! & 0xff) << 8) |\n (mac[offset + 3]! & 0xff);\n const code = (bin % 10 ** digits).toString().padStart(digits, '0');\n return { code, remaining };\n}\n", "import type { ApiClient } from '@geslar/core';\nimport { VaultCloudCrypto } from '@geslar/core/crypto';\nimport type { VaultHandle } from './vaults.js';\nimport { generateTotp, type TotpParams } from './totp.js';\n\nexport interface DecryptedEntry {\n id: string;\n type: string;\n label: string;\n username?: string;\n password?: string;\n url?: string;\n notes?: string;\n totp?: TotpParams;\n customFields?: { label: string; value: string }[];\n}\n\n// Decrypted blob shape is intentionally untyped upstream (apps/admin/src/lib/vault.ts's\n// VaultEntry is `{ id, type, label?, version, [key: string]: unknown }`) \u2014 this repo has\n// no formal schema for the `login` type. Field names below match EntryEditor.tsx's saved shape.\ninterface RawEntry {\n id?: string;\n type?: string;\n label?: string;\n name?: string;\n username?: string;\n password?: string;\n url?: string;\n uris?: { uri: string }[];\n notes?: string;\n totp?: TotpParams;\n customFields?: { label: string; value: string; type?: string }[];\n deleted_at?: string | null;\n}\n\n/** Decrypt every non-deleted, non-internal entry in a vault. */\nexport async function listDecryptedEntries(api: ApiClient, vault: VaultHandle): Promise<DecryptedEntry[]> {\n const wire = await api.getVaultEntries(vault.id);\n const out: DecryptedEntry[] = [];\n\n for (const w of wire) {\n if (w.deleted_at) continue; // tombstone\n\n const keyVersion = w.key_version ?? 1;\n const key = vault.dekMap.get(keyVersion);\n if (!key) {\n // Rotation in progress and this entry's version isn't available yet \u2014\n // skip rather than fail the whole list/read (spec: fail-closed only on\n // the SPECIFIC ref being resolved, not on unrelated sibling entries).\n continue;\n }\n\n const raw = await VaultCloudCrypto.decryptEntry(key, w.encrypted_blob) as RawEntry;\n if (raw.deleted_at) continue;\n if ((raw.type ?? w.entry_type) === '_folders') continue; // internal folder-structure entry\n\n out.push({\n id: raw.id ?? w.id,\n type: raw.type ?? w.entry_type,\n label: raw.label ?? raw.name ?? '(untitled)',\n username: raw.username,\n password: raw.password,\n url: raw.url ?? raw.uris?.[0]?.uri,\n notes: raw.notes,\n totp: raw.totp,\n customFields: raw.customFields?.map(f => ({ label: f.label, value: f.value })),\n });\n }\n\n return out;\n}\n\n/** Resolve the `totp` field to the current computed code (spec \u00A72 \u2014 `totp`\n * means the computed code, never the raw secret). */\nexport async function resolveTotpCode(entry: DecryptedEntry): Promise<string> {\n if (!entry.totp) {\n throw new Error(`Item \"${entry.label}\" has no TOTP configured`);\n }\n const { code } = await generateTotp(entry.totp);\n return code;\n}\n", "import type { OrgType } from '@geslar/core';\nimport { CliError, EXIT } from './lib/errors.js';\nimport type { VaultHandle } from './vault/vaults.js';\nimport type { DecryptedEntry } from './vault/entries.js';\nimport { resolveTotpCode } from './vault/entries.js';\n\n/** `geslar://` grammar errors (spec \u00A72) \u2014 never carries a value, only names/ids\n * (names/ids aren't secrets; only entry field VALUES are). Maps to exit 4. */\nexport class UnresolvableRefError extends CliError {\n constructor(message: string) {\n super(EXIT.UNRESOLVABLE_REF, message);\n this.name = 'UnresolvableRefError';\n }\n}\n\nexport interface ParsedRef {\n vaultQuery: string;\n /** Empty when `itemId` is set (an `id:` qualifier was used instead). */\n itemQuery: string;\n itemId: string | null;\n field: string;\n}\n\nconst PREFIX = 'geslar://';\n\nfunction decodeSegment(seg: string): string {\n try {\n return decodeURIComponent(seg);\n } catch {\n throw new UnresolvableRefError(`Malformed percent-encoding in \"${seg}\"`);\n }\n}\n\n/** Pure, synchronous grammar parse (spec \u00A72) \u2014 no vault/entry lookups here. */\nexport function parseRef(ref: string): ParsedRef {\n if (!ref.startsWith(PREFIX)) {\n throw new UnresolvableRefError(`Not a geslar:// reference: \"${ref}\"`);\n }\n const rest = ref.slice(PREFIX.length);\n if (rest.length === 0) {\n throw new UnresolvableRefError('Empty geslar:// reference');\n }\n\n // Escaping (\u00A72): a literal \"/\" inside a name is %2F, which contains no raw\n // \"/\" byte \u2014 splitting on the raw character is therefore always correct;\n // decodeURIComponent per-segment turns %2F back into \"/\" afterwards.\n const segments = rest.split('/');\n if (segments.length < 2) {\n throw new UnresolvableRefError(`geslar:// reference needs at least <vault>/<item> \u2014 got \"${ref}\"`);\n }\n if (segments.length > 3) {\n throw new UnresolvableRefError(`Too many \"/\"-separated parts in \"${ref}\" \u2014 escape a literal \"/\" as %2F`);\n }\n\n const vaultQuery = decodeSegment(segments[0]!);\n if (vaultQuery.toLowerCase().startsWith('org:')) {\n throw new UnresolvableRefError('The org: qualifier is not implemented yet (v1) \u2014 use a unique collection name instead');\n }\n\n const itemRaw = decodeSegment(segments[1]!);\n let itemId: string | null = null;\n let itemQuery = itemRaw;\n if (itemRaw.startsWith('id:')) {\n itemId = itemRaw.slice(3);\n itemQuery = '';\n if (itemId.length === 0) throw new UnresolvableRefError('Empty id: qualifier');\n }\n\n const field = segments[2] !== undefined ? decodeSegment(segments[2]!) : 'password';\n if (field.length === 0) {\n throw new UnresolvableRefError('Empty field name after the last \"/\"');\n }\n\n return { vaultQuery, itemQuery, itemId, field };\n}\n\n// \u2500\u2500 \"Did you mean\" \u2014 simple Levenshtein nearest-match \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction levenshtein(a: string, b: string): number {\n const al = a.length;\n const bl = b.length;\n if (al === 0) return bl;\n if (bl === 0) return al;\n const dp: number[][] = Array.from({ length: al + 1 }, () => new Array<number>(bl + 1).fill(0));\n for (let i = 0; i <= al; i++) dp[i]![0] = i;\n for (let j = 0; j <= bl; j++) dp[0]![j] = j;\n for (let i = 1; i <= al; i++) {\n for (let j = 1; j <= bl; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n dp[i]![j] = Math.min(dp[i - 1]![j]! + 1, dp[i]![j - 1]! + 1, dp[i - 1]![j - 1]! + cost);\n }\n }\n return dp[al]![bl]!;\n}\n\nfunction closestMatch(query: string, candidates: string[]): string | null {\n if (candidates.length === 0 || query.length === 0) return null;\n const q = query.toLowerCase();\n let best: { name: string; dist: number } | null = null;\n for (const c of candidates) {\n const dist = levenshtein(q, c.toLowerCase());\n if (!best || dist < best.dist) best = { name: c, dist };\n }\n const threshold = Math.max(2, Math.ceil(query.length * 0.4));\n return best && best.dist <= threshold ? best.name : null;\n}\n\n// \u2500\u2500 Resolution against a live vault/entry set \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface ResolveContext {\n vaults: VaultHandle[];\n getEntries(vault: VaultHandle): Promise<DecryptedEntry[]>;\n}\n\nexport interface ResolvedRef {\n vault: VaultHandle;\n entry: DecryptedEntry;\n field: string;\n value: string;\n}\n\nfunction requireNonEmpty(value: string | undefined, label: string, field: string): string {\n if (!value) throw new UnresolvableRefError(`Field \"${field}\" on item \"${label}\" is empty`);\n return value;\n}\n\nasync function resolveField(entry: DecryptedEntry, field: string): Promise<string> {\n switch (field.toLowerCase()) {\n case 'username': return requireNonEmpty(entry.username, entry.label, field);\n case 'password': return requireNonEmpty(entry.password, entry.label, field);\n case 'url': return requireNonEmpty(entry.url, entry.label, field);\n case 'notes': return requireNonEmpty(entry.notes, entry.label, field);\n case 'totp': return resolveTotpCode(entry);\n default: {\n const custom = entry.customFields?.find(f => f.label.toLowerCase() === field.toLowerCase());\n if (!custom) {\n const known = ['username', 'password', 'url', 'notes', 'totp', ...(entry.customFields?.map(f => f.label) ?? [])];\n const suggestion = closestMatch(field, known);\n throw new UnresolvableRefError(\n `Item \"${entry.label}\" has no field \"${field}\"${suggestion ? ` \u2014 did you mean \"${suggestion}\"?` : ''}. `\n + `Available fields: ${known.join(', ')}`,\n );\n }\n return requireNonEmpty(custom.value, entry.label, field);\n }\n }\n}\n\n/** Canonical personal-vault token (spec REV 2.3 \u00A72, EN docs) \u2014 `Osobno` (the\n * handle's literal `name`, see PERSONAL_VAULT_NAME in vault/vaults.ts) keeps\n * matching via the plain name comparison below, so it stays a working alias\n * without needing its own entry here. */\nconst PERSONAL_VAULT_ALIAS = 'personal';\n\n/** True when `query` names the vault `v` \u2014 either its literal display name\n * (an org's default vault already carries its ORG's name here, never the\n * stored placeholder \u2014 see vault/vaults.ts), or (for the personal vault\n * only) the canonical `personal` alias. A real collection named \"Personal\"\n * is deliberately NOT special-cased against the personal vault: both\n * entries land in the filter result and the existing multiple-matches\n * branch below throws its normal ambiguity error, same as any other two\n * vaults sharing a name (see resolver.test.ts). */\nfunction matchesVaultQuery(v: VaultHandle, query: string): boolean {\n const q = query.toLowerCase();\n if (v.name.toLowerCase() === q) return true;\n return v.kind === 'personal' && q === PERSONAL_VAULT_ALIAS;\n}\n\n// spec REV 2.4.1 \u00A72 \u2014 `company` and its synonym `work` both mean \"poslovni\"\n// (business or enterprise); `team` is a legacy org type value the server\n// no longer produces (organizations.type is only personal/family/business/\n// enterprise) and is deliberately not included here.\nconst ORG_TYPE_TOKENS: Record<string, OrgType[]> = {\n family: ['family'],\n company: ['business', 'enterprise'],\n work: ['business', 'enterprise'],\n};\n\n/** Resolves `family`/`company`/`work` to the single default vault of a\n * matching-type org \u2014 deterministic only when the caller has EXACTLY ONE\n * qualifying org (spec REV 2.4.1 \u00A72); 2+ throws immediately, listing the\n * org names (a distinct, more specific error than the generic ambiguous-\n * vault-name one in resolveRef) and pointing at the exact-name workaround.\n * Counts only orgs whose default vault is actually present in `vaults`\n * (i.e. its key could be unwrapped) \u2014 an org the caller can't currently\n * read isn't a usable resolution target. Returns null for a query that\n * isn't one of these tokens at all, or that is but matches zero orgs. */\nfunction resolveOrgTypeToken(query: string, vaults: VaultHandle[]): VaultHandle | null {\n const types = ORG_TYPE_TOKENS[query.toLowerCase()];\n if (!types) return null;\n const matches = vaults.filter(v => v.isDefault && v.orgType !== null && types.includes(v.orgType));\n if (matches.length > 1) {\n throw new UnresolvableRefError(\n `Multiple \"${query}\" orgs \u2014 ${matches.map(v => v.name).join(', ')} \u2014 use the exact org name instead of \"${query}\"`,\n );\n }\n return matches[0] ?? null;\n}\n\n/**\n * Resolves a vault-address query \u2014 `personal`/`Osobno`, `family`,\n * `company`/`work`, an org's name, or a vault's own display name \u2014 against\n * a live vault set. Shared by `resolveRef` and `geslar list [vault]` so the\n * two never drift into matching different address spaces (spec REV 2.4.1\n * \u00A72). Throws UnresolvableRefError (never returns a value) on no match or\n * on ambiguity \u2014 a semantic token spanning 2+ orgs throws its own specific\n * message (see resolveOrgTypeToken); a query matching 2+ distinct vaults\n * (by literal name, or a token colliding with a real name) throws the\n * generic \"rename one\" ambiguity error, same treatment for every case \u2014\n * the resolver never silently prefers one match over another.\n */\nexport function resolveVaultByQuery(query: string, vaults: VaultHandle[]): VaultHandle {\n const vaultMatches = vaults.filter(v => matchesVaultQuery(v, query));\n const orgTokenVault = resolveOrgTypeToken(query, vaults);\n if (orgTokenVault && !vaultMatches.includes(orgTokenVault)) {\n vaultMatches.push(orgTokenVault);\n }\n if (vaultMatches.length === 0) {\n const suggestion = closestMatch(query, vaults.map(v => v.name));\n const available = vaults.map(v => v.name).join(', ') || '(none)';\n throw new UnresolvableRefError(\n `No vault named \"${query}\"${suggestion ? ` \u2014 did you mean \"${suggestion}\"?` : ''}. Available: ${available}`,\n );\n }\n if (vaultMatches.length > 1) {\n throw new UnresolvableRefError(`Multiple vaults named \"${query}\" \u2014 rename one, this isn't disambiguated yet`);\n }\n return vaultMatches[0]!;\n}\n\n/** Full `geslar://` resolution: parse \u2192 match vault (case-insensitive) \u2192\n * match item (name or id: qualifier) \u2192 extract field. Every failure mode\n * throws UnresolvableRefError with a \"did you mean\" hint \u2014 never a value. */\nexport async function resolveRef(ref: string, ctx: ResolveContext): Promise<ResolvedRef> {\n const parsed = parseRef(ref);\n\n const vault = resolveVaultByQuery(parsed.vaultQuery, ctx.vaults);\n\n const entries = await ctx.getEntries(vault);\n\n let entry: DecryptedEntry;\n if (parsed.itemId) {\n const found = entries.find(e => e.id.toLowerCase() === parsed.itemId!.toLowerCase());\n if (!found) throw new UnresolvableRefError(`No item with id \"${parsed.itemId}\" in \"${vault.name}\"`);\n entry = found;\n } else {\n const matches = entries.filter(e => e.label.toLowerCase() === parsed.itemQuery.toLowerCase());\n if (matches.length === 0) {\n const suggestion = closestMatch(parsed.itemQuery, entries.map(e => e.label));\n throw new UnresolvableRefError(\n `No item named \"${parsed.itemQuery}\" in \"${vault.name}\"${suggestion ? ` \u2014 did you mean \"${suggestion}\"?` : ''}`,\n );\n }\n if (matches.length > 1) {\n const ids = matches.map(e => e.id).join(', ');\n throw new UnresolvableRefError(\n `Multiple items named \"${parsed.itemQuery}\" in \"${vault.name}\" \u2014 use an id: qualifier `\n + `(e.g. geslar://${vault.name}/id:${matches[0]!.id}/${parsed.field}). Matching ids: ${ids}`,\n );\n }\n entry = matches[0]!;\n }\n\n const value = await resolveField(entry, parsed.field);\n return { vault, entry, field: parsed.field, value };\n}\n", "import { selectBackend } from '../token-store/index.js';\nimport type { AgentCapability } from '@geslar/core';\n\n/**\n * Local storage for agent-profile tokens (spec-access-core.md REV 1.2 \u00A74) \u2014\n * its OWN OS item (`selectBackend('agent-token')`), distinct from the M1 auth\n * token ('tokens') and the M2 unlock grant ('vault-grant') namespaces, so\n * revoking/clearing one never touches the others.\n *\n * Unlike those two (one secret per namespace), a machine can hold MULTIPLE\n * named agent profiles at once \u2014 so this namespace's single OS blob holds a\n * JSON map keyed by profile name, not a single value. `key = ime profila`\n * (spec wording) means \"key into this map,\" not \"one OS item per profile.\"\n *\n * `vaults` is cached here ONLY because it's the sole way the CLI can address\n * a personal-vault grant later: GET /v1/collections never returns personal\n * vaults (team_collection only) and the route that would normally resolve\n * the personal vault id (ensurePersonalVault, POST /v1/sync/vault) is not on\n * the agent allowlist. Caching is safe because scope is an immutable\n * snapshot at create time (spec \u00A70 decision 2) \u2014 it can only ever go stale\n * in the direction of \"no longer active,\" which the live server calls\n * (GET /v1/collections, GET /v1/sync/entries, GET /v1/agents/whoami) already\n * fail closed on. Capabilities are NEVER cached here \u2014 the read-block check\n * always re-fetches GET /v1/agents/whoami live (spec \u00A74: \"ne poga\u0111aj lokalno\").\n */\n\nexport interface AgentTokenVaultRef {\n id: string;\n name: string;\n kind: 'personal' | 'collection';\n}\n\nexport interface AgentTokenRecord {\n token: string;\n createdAt: string; // ISO\n vaults: AgentTokenVaultRef[];\n allowRead: boolean;\n}\n\ntype AgentTokenMap = Record<string, AgentTokenRecord>;\n\nasync function loadAll(): Promise<AgentTokenMap> {\n const backend = await selectBackend('agent-token');\n const raw = await backend.load();\n if (!raw) return {};\n try {\n return JSON.parse(raw) as AgentTokenMap;\n } catch {\n return {};\n }\n}\n\nexport async function saveAgentToken(name: string, record: AgentTokenRecord): Promise<void> {\n const backend = await selectBackend('agent-token');\n const map = await loadAll();\n map[name] = record;\n await backend.save(JSON.stringify(map));\n}\n\nexport async function loadAgentToken(name: string): Promise<AgentTokenRecord | null> {\n const map = await loadAll();\n return map[name] ?? null;\n}\n\nexport async function listAgentTokenNames(): Promise<string[]> {\n return Object.keys(await loadAll());\n}\n\n/** Deletes just this profile's local record \u2014 clears the whole OS item only\n * when it was the last one, so an untouched sibling profile's token never\n * gets an empty-but-present item vs. a genuinely-cleared one. */\nexport async function clearAgentToken(name: string): Promise<void> {\n const backend = await selectBackend('agent-token');\n const map = await loadAll();\n if (!(name in map)) return;\n delete map[name];\n if (Object.keys(map).length === 0) {\n await backend.clear();\n } else {\n await backend.save(JSON.stringify(map));\n }\n}\n\n// Re-export for callers that only need the capability type, avoids a second\n// import line for something this module already needs.\nexport type { AgentCapability };\n", "import type { ApiClient, TokenStore } from '@geslar/core';\nimport { buildApiClient } from './core.js';\nimport { selectBackend, createCliTokenStore } from '../token-store/index.js';\nimport { CliError, EXIT } from './errors.js';\nimport { loadAgentToken, type AgentTokenRecord } from '../agent/token-store.js';\n\n/** GESLAR_AGENT env var wins if BOTH are set with different values? No \u2014\n * --agent (explicit, per-invocation) takes precedence over the ambient env\n * var, same precedence rule as every other CLI-flag-vs-env-var pair. */\nexport function resolveAgentName(cliAgentOpt?: string): string | null {\n return cliAgentOpt || process.env['GESLAR_AGENT'] || null;\n}\n\n/** Agent tokens don't rotate (no refresh mechanism exists for them, spec \u00A79\n * reserves rotation for a future `/v1/agents/:id/rotate`) \u2014 `set()` is a\n * no-op so ApiClient's 401-triggered refresh attempt (which would target\n * /v1/auth/refresh, meaningless for an agent bearer) just quietly clears\n * in-memory and lets the caller's own error handling take over. */\nfunction agentTokenStore(token: string): TokenStore {\n const current = { access_token: token, refresh_token: '' };\n return {\n get: () => current,\n set: () => { /* no-op \u2014 see above */ },\n };\n}\n\nexport interface CliApiContext {\n api: ApiClient;\n isAgent: boolean;\n agentName: string | null;\n /** Human path: awaits any in-flight OS-store write. Agent path: no-op\n * (agentTokenStore never persists). Call this uniformly regardless of\n * context, same as every command already does today. */\n flush(): Promise<void>;\n}\n\n/**\n * Single choke point read/run/inject/list all go through instead of their\n * own inline selectBackend()+createCliTokenStore()+buildApiClient() block \u2014\n * resolves GESLAR_AGENT/--agent once and returns the right ApiClient. Every\n * downstream call (obtainUnlockedKeys, listVaultHandles, resolveRef, \u2026)\n * receives this same `api` and needs no agent-awareness of its own; the\n * server enforces the agent route allowlist regardless.\n */\nexport async function resolveApiContext(baseUrl: string, agentOpt?: string): Promise<CliApiContext> {\n const agentName = resolveAgentName(agentOpt);\n if (agentName) {\n const record = await loadAgentToken(agentName);\n if (!record) {\n throw new CliError(\n EXIT.AUTH,\n `No local token for agent profile \"${agentName}\" \u2014 run \\`geslar agent create ${agentName} ...\\` on this machine, or check the name with \\`geslar agent list\\``,\n );\n }\n const api = buildApiClient(baseUrl, agentTokenStore(record.token));\n return { api, isAgent: true, agentName, flush: async () => undefined };\n }\n\n const backend = await selectBackend();\n const tokenStore = await createCliTokenStore(backend);\n if (!tokenStore.get()) {\n throw new CliError(EXIT.AUTH, 'not signed in \u2014 run `geslar signin`');\n }\n const api = buildApiClient(baseUrl, tokenStore);\n return { api, isAgent: false, agentName: null, flush: () => tokenStore.flush() };\n}\n\n/** `agent create/list/revoke` are human-session-only actions (spec \u00A74) \u2014\n * refuse up front with a clear message instead of letting the server's own\n * 403 (route not in the agent allowlist) surface confusingly. */\nexport function requireHumanContext(agentOpt: string | undefined, action: string): void {\n const agentName = resolveAgentName(agentOpt);\n if (agentName) {\n throw new CliError(\n EXIT.GENERAL,\n `\\`geslar agent ${action}\\` is a human action \u2014 cannot run under agent context (GESLAR_AGENT=${agentName})`,\n );\n }\n}\n\nexport type { AgentTokenRecord };\n", "import { loadSession } from '../lib/session.js';\nimport { loadOrInitConfig } from '../lib/config.js';\nimport { print, printErr } from '../lib/output.js';\nimport { CliError, EXIT } from '../lib/errors.js';\nimport { obtainUnlockedKeys } from '../vault/session.js';\nimport { listVaultHandles } from '../vault/vaults.js';\nimport { listAgentVaultHandles } from '../vault/agent-vaults.js';\nimport { listDecryptedEntries } from '../vault/entries.js';\nimport { resolveVaultByQuery } from '../resolver.js';\nimport { resolveApiContext } from '../lib/agent-context.js';\nimport { loadAgentToken } from '../agent/token-store.js';\n\n/** `geslar list [vault]` \u2014 names + ids only (spec \u00A73.1). Item names are\n * themselves E2EE (server never sees them), so listing them locally still\n * requires the vault to be unlocked \u2014 same gate as `read`. */\nexport async function listCommand(vaultFilter?: string): Promise<number> {\n try {\n const config = await loadOrInitConfig();\n const session = await loadSession();\n const baseUrl = session?.apiBase ?? config.apiBase;\n const apiCtx = await resolveApiContext(baseUrl);\n const api = apiCtx.api;\n\n const unlocked = await obtainUnlockedKeys(api);\n await apiCtx.flush();\n const vaults = apiCtx.isAgent\n ? await listAgentVaultHandles(api, unlocked, (await loadAgentToken(apiCtx.agentName!))?.vaults ?? [])\n : await listVaultHandles(api, unlocked);\n\n // Same address space as geslar:// references (spec REV 2.4.1 \u00A72):\n // personal/Osobno, family, company/work, an org's name, or a vault's\n // own display name \u2014 resolveVaultByQuery is the single source of truth\n // for this so `list` and the resolver never drift apart.\n const targets = vaultFilter ? [resolveVaultByQuery(vaultFilter, vaults)] : vaults;\n\n for (const vault of targets) {\n print(`${vault.name} (${vault.id})`);\n const entries = await listDecryptedEntries(api, vault);\n for (const entry of entries) {\n print(` ${entry.label} (${entry.id})`);\n }\n }\n return EXIT.OK;\n } catch (err) {\n if (err instanceof CliError) {\n printErr(err.message);\n return err.exitCode;\n }\n printErr((err as Error).message);\n return EXIT.GENERAL;\n }\n}\n", "import { writeFile } from 'node:fs/promises';\nimport { loadSession } from '../lib/session.js';\nimport { loadOrInitConfig } from '../lib/config.js';\nimport { print, printErr } from '../lib/output.js';\nimport { registerSecret } from '../lib/scrubber.js';\nimport { CliError, EXIT } from '../lib/errors.js';\nimport { obtainUnlockedKeys } from '../vault/session.js';\nimport { listVaultHandles } from '../vault/vaults.js';\nimport { listAgentVaultHandles } from '../vault/agent-vaults.js';\nimport { createResolveContext } from '../vault/resolve-context.js';\nimport { resolveRef } from '../resolver.js';\nimport { requireAgenticCli } from '../lib/entitlements.js';\nimport { resolveApiContext } from '../lib/agent-context.js';\nimport { loadAgentToken } from '../agent/token-store.js';\n\n/** `geslar read <ref> [-o file]` \u2014 value to stdout/file (0600), NEVER through\n * the scrubbed print()/printErr() log channel (spec \u00A73.1: \"NIKAD u log\"). */\nexport async function readCommand(ref: string, opts: { output?: string }): Promise<number> {\n try {\n const config = await loadOrInitConfig();\n const session = await loadSession();\n const baseUrl = session?.apiBase ?? config.apiBase;\n const ctx = await resolveApiContext(baseUrl);\n const { api } = ctx;\n\n if (ctx.isAgent) {\n // Capability read LIVE from the server (spec \u00A74: \"ne poga\u0111aj lokalno\")\n // \u2014 never trust a locally cached value for this check.\n const whoami = await api.getAgentWhoami();\n if (whoami.type === 'agent' && !whoami.capabilities.includes('read')) {\n throw new CliError(\n EXIT.GRANT_DENIED,\n \"This agent profile doesn't have the 'read' capability \u2014 recreate it with \"\n + '`geslar agent create ... --allow-read` to permit printing secret values '\n + '(default profiles are run+inject only, by design).',\n );\n }\n } else {\n await requireAgenticCli(api);\n }\n\n const unlocked = await obtainUnlockedKeys(api);\n await ctx.flush();\n const vaults = ctx.isAgent\n ? await listAgentVaultHandles(api, unlocked, (await loadAgentToken(ctx.agentName!))?.vaults ?? [])\n : await listVaultHandles(api, unlocked);\n\n const resolved = await resolveRef(ref, createResolveContext(api, vaults));\n\n // Register BEFORE emitting \u2014 any error/log line printed after this point\n // (e.g. a failure writing the -o file) must mask the value too.\n registerSecret(resolved.value);\n\n if (opts.output) {\n await writeFile(opts.output, resolved.value, { mode: 0o600 });\n print(`Written to ${opts.output}`);\n } else {\n // Deliberately raw stdout, not print(): this IS the designated value\n // channel (spec \u00A73.1) \u2014 print() would scrub it right back out since\n // registerSecret() just made it a scrub target for every OTHER call.\n process.stdout.write(`${resolved.value}\\n`);\n }\n return EXIT.OK;\n } catch (err) {\n if (err instanceof CliError) {\n printErr(err.message);\n return err.exitCode;\n }\n printErr((err as Error).message);\n return EXIT.GENERAL;\n }\n}\n", "import type { ApiClient } from '@geslar/core';\nimport type { ResolveContext } from '../resolver.js';\nimport type { VaultHandle } from './vaults.js';\nimport { listDecryptedEntries, type DecryptedEntry } from './entries.js';\n\n/** Shared `ResolveContext` builder \u2014 one per command invocation, entries\n * decrypted once per vault and cached for every subsequent `resolveRef`\n * call against the same vault (used by `read`, and now `run`/`inject`\n * which may resolve many refs across one or two vaults). */\nexport function createResolveContext(api: ApiClient, vaults: VaultHandle[]): ResolveContext {\n const entryCache = new Map<string, DecryptedEntry[]>();\n return {\n vaults,\n getEntries: async (vault: VaultHandle) => {\n const cached = entryCache.get(vault.id);\n if (cached) return cached;\n const entries = await listDecryptedEntries(api, vault);\n entryCache.set(vault.id, entries);\n return entries;\n },\n };\n}\n", "import { hasFeature, planOf, type ApiClient } from '@geslar/core';\nimport { CliError, EXIT } from './errors.js';\n\n// Matches the ToS pricing reference (geslar-docs/legal/live/en/terms-of-service.md)\n// \u2014 no PRICING_URL constant exists anywhere else in the codebase yet.\nconst UPGRADE_URL = 'https://geslar.app/pricing';\n\n// spec \u00A77 \u2014 plans agentic_cli is meant to be enabled for. Mirrors\n// geslar-api's registry defaultPlans for the agentic_cli feature exactly\n// (registry.ts) \u2014 keep the two in sync if that list ever changes.\nconst QUALIFYING_PLANS = new Set(['premium', 'family', 'business', 'enterprise']);\n\n/**\n * spec-agentic-access.md \u00A73.6/\u00A77: `read`/`run`/`inject` require the\n * `agentic_cli` feature (Premium/Family/Business/Enterprise). The server\n * gates the same feature fail-closed on GET /v1/account/vault-key-material\n * (M4) \u2014 this check just fails fast and friendly, before any vault/session\n * work (or a master-password prompt) even starts.\n *\n * `hasFeature` returns false both when the plan genuinely doesn't qualify\n * AND when `agentic_cli` is simply absent from the bundle (e.g. the api\n * side of M4 hasn't deployed the slug yet, or a per-org grant lagging) \u2014 a\n * real incident (2026-07-18): a Family/Enterprise account got a plain\n * \"requires Premium\" upsell purely because prod hadn't deployed the slug.\n * `planOf()` is populated independently of `agentic_cli` (it's just the\n * account's plan_slug), so a paying plan + a false gate is distinguishable\n * from an actually-unqualified plan \u2014 give the two cases different messages.\n */\nexport async function requireAgenticCli(api: ApiClient): Promise<void> {\n const entitlements = await api.getEntitlements();\n if (hasFeature(entitlements, 'agentic_cli')) return;\n\n const plan = planOf(entitlements);\n if (QUALIFYING_PLANS.has(plan)) {\n throw new CliError(\n EXIT.ENTITLEMENT,\n `Your plan (${plan}) should include this feature but the server isn't reporting it yet. `\n + 'Run `geslar whoami` to confirm your plan, or contact support if this persists.',\n );\n }\n\n throw new CliError(\n EXIT.ENTITLEMENT,\n `This command requires a Premium plan or higher (your plan: ${plan}). Upgrade at ${UPGRADE_URL}`,\n );\n}\n", "import { spawn } from 'node:child_process';\nimport { readFile } from 'node:fs/promises';\nimport { loadSession } from '../lib/session.js';\nimport { loadOrInitConfig } from '../lib/config.js';\nimport { printErr } from '../lib/output.js';\nimport { CliError, EXIT } from '../lib/errors.js';\nimport { obtainUnlockedKeys } from '../vault/session.js';\nimport { listVaultHandles } from '../vault/vaults.js';\nimport { listAgentVaultHandles } from '../vault/agent-vaults.js';\nimport { createResolveContext } from '../vault/resolve-context.js';\nimport { resolveRefsOrLiteral } from '../vault/resolve-many.js';\nimport { parseDotenv } from '../lib/dotenv.js';\nimport { requireAgenticCli } from '../lib/entitlements.js';\nimport { resolveApiContext } from '../lib/agent-context.js';\nimport { loadAgentToken } from '../agent/token-store.js';\n\nexport interface RunOptions {\n envFile?: string;\n /** Repeated `-e KEY=ref` occurrences. */\n env?: string[];\n}\n\n// Shell exit-code convention (matches spec \u00A73.5's \"126/127 spawn (konvencija\n// shella)\"): a signal-terminated child reports 128+signal number.\nconst SIGNAL_NUMBERS: Partial<Record<NodeJS.Signals, number>> = {\n SIGHUP: 1, SIGINT: 2, SIGQUIT: 3, SIGILL: 4, SIGTRAP: 5, SIGABRT: 6,\n SIGBUS: 7, SIGFPE: 8, SIGKILL: 9, SIGUSR1: 10, SIGSEGV: 11, SIGUSR2: 12,\n SIGPIPE: 13, SIGALRM: 14, SIGTERM: 15,\n};\nfunction exitCodeForSignal(signal: NodeJS.Signals): number {\n return 128 + (SIGNAL_NUMBERS[signal] ?? 1);\n}\n\n/** `geslar run --env-file <f> [-e K=ref]... -- <cmd> [args...]` (spec \u00A73.2).\n * Every reference is resolved BEFORE anything spawns (fail-closed, exit 4);\n * the child's own stdio is inherited untouched \u2014 nothing captured, nothing\n * written to disk, no telemetry of values. */\nexport async function runCommand(command: string, args: string[], opts: RunOptions): Promise<number> {\n try {\n const values = await buildEnvValues(opts);\n\n const config = await loadOrInitConfig();\n const session = await loadSession();\n const baseUrl = session?.apiBase ?? config.apiBase;\n const apiCtx = await resolveApiContext(baseUrl);\n const api = apiCtx.api;\n if (!apiCtx.isAgent) await requireAgenticCli(api);\n\n const unlocked = await obtainUnlockedKeys(api);\n await apiCtx.flush();\n const vaults = apiCtx.isAgent\n ? await listAgentVaultHandles(api, unlocked, (await loadAgentToken(apiCtx.agentName!))?.vaults ?? [])\n : await listVaultHandles(api, unlocked);\n const resolveCtx = createResolveContext(api, vaults);\n\n // Fail-closed: every value resolved (and registered with the scrubber)\n // before spawnChild is ever called.\n const resolvedEnv = await resolveRefsOrLiteral(values, resolveCtx);\n\n return await spawnChild(command, args, resolvedEnv);\n } catch (err) {\n if (err instanceof CliError) {\n printErr(err.message);\n return err.exitCode;\n }\n printErr((err as Error).message);\n return EXIT.GENERAL;\n }\n}\n\nasync function buildEnvValues(opts: RunOptions): Promise<Record<string, string>> {\n const values: Record<string, string> = {};\n\n if (opts.envFile) {\n let content: string;\n try {\n content = await readFile(opts.envFile, 'utf-8');\n } catch (err) {\n throw new CliError(EXIT.GENERAL, `Could not read --env-file \"${opts.envFile}\": ${(err as Error).message}`);\n }\n Object.assign(values, parseDotenv(content));\n }\n\n for (const mapping of opts.env ?? []) {\n const eq = mapping.indexOf('=');\n if (eq === -1) {\n throw new CliError(EXIT.GENERAL, `Invalid -e value \"${mapping}\" \u2014 expected KEY=ref`);\n }\n const key = mapping.slice(0, eq);\n const value = mapping.slice(eq + 1);\n if (key in values) {\n printErr(`-e ${key} overrides the same key from --env-file`);\n }\n values[key] = value;\n }\n\n if (Object.keys(values).length === 0) {\n throw new CliError(EXIT.GENERAL, 'No environment variables to set \u2014 pass --env-file and/or -e');\n }\n\n return values;\n}\n\nfunction spawnChild(command: string, args: string[], resolvedEnv: Record<string, string>): Promise<number> {\n return new Promise((resolve) => {\n const child = spawn(command, args, {\n env: { ...process.env, ...resolvedEnv },\n stdio: 'inherit',\n });\n\n const forward = (signal: NodeJS.Signals) => child.kill(signal);\n process.on('SIGINT', forward);\n process.on('SIGTERM', forward);\n function cleanup(): void {\n process.removeListener('SIGINT', forward);\n process.removeListener('SIGTERM', forward);\n }\n\n child.on('error', (err: NodeJS.ErrnoException) => {\n cleanup();\n if (err.code === 'ENOENT') {\n printErr(`command not found: ${command}`);\n resolve(127);\n } else {\n printErr(`failed to run ${command}: ${err.message}`);\n resolve(EXIT.GENERAL);\n }\n });\n\n child.on('exit', (code, signal) => {\n cleanup();\n resolve(signal ? exitCodeForSignal(signal) : (code ?? EXIT.GENERAL));\n });\n });\n}\n", "import { registerSecret } from '../lib/scrubber.js';\nimport { CliError, EXIT } from '../lib/errors.js';\nimport { resolveRef, type ResolveContext } from '../resolver.js';\n\n/**\n * Resolve every `geslar://` value in `values` against `ctx`; anything that\n * doesn't start with `geslar://` passes through literally, unregistered\n * (spec \u00A72 only calls resolved-from-reference values secrets). Fail-closed\n * (spec \u00A73.2): every entry is attempted, and if ANY fails, nothing is\n * returned and nothing gets registered for the successful ones either \u2014\n * the caller must not spawn/write with a partially-resolved set.\n */\nexport async function resolveRefsOrLiteral(\n values: Record<string, string>,\n ctx: ResolveContext,\n): Promise<Record<string, string>> {\n const resolved: Record<string, string> = {};\n const fromRef = new Set<string>();\n const failures: string[] = [];\n\n for (const [key, value] of Object.entries(values)) {\n if (!value.startsWith('geslar://')) {\n resolved[key] = value;\n continue;\n }\n try {\n const result = await resolveRef(value, ctx);\n resolved[key] = result.value;\n fromRef.add(key);\n } catch (err) {\n failures.push(`${key}: ${(err as Error).message}`);\n }\n }\n\n if (failures.length > 0) {\n throw new CliError(\n EXIT.UNRESOLVABLE_REF,\n `${failures.length} reference${failures.length === 1 ? '' : 's'} could not be resolved \u2014 nothing was run:\\n ${failures.join('\\n ')}`,\n );\n }\n\n for (const key of fromRef) {\n registerSecret(resolved[key]!);\n }\n\n return resolved;\n}\n", "/**\n * Minimal dotenv-syntax parser (spec \u00A73.2) \u2014 no dependency, just the subset\n * `geslar run --env-file` actually needs: `KEY=value` lines, `#` comments,\n * blank lines, optional `export ` prefix, and single/double-quoted values\n * (double-quoted values unescape \\n \\\" \\\\). Values starting with\n * `geslar://` are resolved by the caller; everything else is passed through\n * literally \u2014 this parser doesn't know or care which is which.\n */\nexport function parseDotenv(content: string): Record<string, string> {\n const out: Record<string, string> = {};\n\n for (const rawLine of content.split(/\\r\\n|\\n|\\r/)) {\n const line = rawLine.trim();\n if (line.length === 0 || line.startsWith('#')) continue;\n\n const withoutExport = line.startsWith('export ') ? line.slice('export '.length).trim() : line;\n const eq = withoutExport.indexOf('=');\n if (eq === -1) continue; // not a KEY=VALUE line \u2014 skip rather than fail the whole file\n\n const key = withoutExport.slice(0, eq).trim();\n if (key.length === 0) continue;\n let value = withoutExport.slice(eq + 1).trim();\n\n if (value.length >= 2 && value.startsWith('\"') && value.endsWith('\"')) {\n value = value.slice(1, -1)\n .replace(/\\\\n/g, '\\n')\n .replace(/\\\\\"/g, '\"')\n .replace(/\\\\\\\\/g, '\\\\');\n } else if (value.length >= 2 && value.startsWith(\"'\") && value.endsWith(\"'\")) {\n value = value.slice(1, -1);\n }\n\n out[key] = value;\n }\n\n return out;\n}\n", "import { readFile, writeFile } from 'node:fs/promises';\nimport { loadSession } from '../lib/session.js';\nimport { loadOrInitConfig } from '../lib/config.js';\nimport { print, printErr } from '../lib/output.js';\nimport { CliError, EXIT } from '../lib/errors.js';\nimport { obtainUnlockedKeys } from '../vault/session.js';\nimport { listVaultHandles } from '../vault/vaults.js';\nimport { listAgentVaultHandles } from '../vault/agent-vaults.js';\nimport { createResolveContext } from '../vault/resolve-context.js';\nimport { resolveRefsOrLiteral } from '../vault/resolve-many.js';\nimport { requireAgenticCli } from '../lib/entitlements.js';\nimport { resolveApiContext } from '../lib/agent-context.js';\nimport { loadAgentToken } from '../agent/token-store.js';\n\n// Non-greedy up to the closing \"}}\" \u2014 vault/item names may contain literal\n// spaces (spec \u00A72), so this can't stop at the first whitespace character.\nconst PLACEHOLDER_RE = /\\{\\{\\s*(geslar:\\/\\/.+?)\\s*\\}\\}/g;\n\nexport interface InjectOptions {\n input: string;\n output: string;\n}\n\n/** `geslar inject -i <tpl> -o <out>` (spec \u00A73.1) \u2014 `{{ geslar://... }}`\n * placeholders resolved and substituted; output written with mode 0600.\n * Fail-closed like `run`: every placeholder is resolved before anything is\n * written \u2014 a single bad reference means the output file is never created. */\nexport async function injectCommand(opts: InjectOptions): Promise<number> {\n try {\n let template: string;\n try {\n template = await readFile(opts.input, 'utf-8');\n } catch (err) {\n throw new CliError(EXIT.GENERAL, `Could not read -i \"${opts.input}\": ${(err as Error).message}`);\n }\n\n const refByPlaceholder = new Map<string, string>(); // full \"{{ ... }}\" match -> ref text\n for (const m of template.matchAll(PLACEHOLDER_RE)) {\n refByPlaceholder.set(m[0], m[1]!);\n }\n\n if (refByPlaceholder.size === 0) {\n await writeFile(opts.output, template, { mode: 0o600 });\n print(`Written to ${opts.output} (no placeholders found)`);\n return EXIT.OK;\n }\n\n const config = await loadOrInitConfig();\n const session = await loadSession();\n const baseUrl = session?.apiBase ?? config.apiBase;\n const apiCtx = await resolveApiContext(baseUrl);\n const api = apiCtx.api;\n if (!apiCtx.isAgent) await requireAgenticCli(api);\n\n const unlocked = await obtainUnlockedKeys(api);\n await apiCtx.flush();\n const vaults = apiCtx.isAgent\n ? await listAgentVaultHandles(api, unlocked, (await loadAgentToken(apiCtx.agentName!))?.vaults ?? [])\n : await listVaultHandles(api, unlocked);\n const resolveCtx = createResolveContext(api, vaults);\n\n // Reuse resolveRefsOrLiteral keyed by the ref text itself (dedupes\n // identical placeholders automatically via the Set below) \u2014 fail-closed\n // across the WHOLE placeholder set before any substitution happens.\n const uniqueRefs: Record<string, string> = {};\n for (const ref of new Set(refByPlaceholder.values())) uniqueRefs[ref] = ref;\n const resolved = await resolveRefsOrLiteral(uniqueRefs, resolveCtx);\n\n let output = template;\n for (const [placeholder, ref] of refByPlaceholder) {\n output = output.split(placeholder).join(resolved[ref]!);\n }\n\n await writeFile(opts.output, output, { mode: 0o600 });\n print(`Written to ${opts.output}`);\n return EXIT.OK;\n } catch (err) {\n if (err instanceof CliError) {\n printErr(err.message);\n return err.exitCode;\n }\n printErr((err as Error).message);\n return EXIT.GENERAL;\n }\n}\n", "import { createInterface } from 'node:readline/promises';\nimport { ApiError, type AgentCapability } from '@geslar/core';\nimport { buildApiClient } from '../lib/core.js';\nimport { loadSession } from '../lib/session.js';\nimport { loadOrInitConfig } from '../lib/config.js';\nimport { selectBackend, createCliTokenStore } from '../token-store/index.js';\nimport { print, printErr } from '../lib/output.js';\nimport { CliError, EXIT } from '../lib/errors.js';\nimport { requireAgenticCli } from '../lib/entitlements.js';\nimport { obtainUnlockedKeys } from '../vault/session.js';\nimport { listVaultHandles } from '../vault/vaults.js';\nimport { resolveVaultByQuery } from '../resolver.js';\nimport { promptTotpCode } from '../lib/prompt.js';\nimport { requireHumanContext } from '../lib/agent-context.js';\nimport { saveAgentToken, type AgentTokenVaultRef } from '../agent/token-store.js';\n\nexport interface AgentCreateOptions {\n vault: string[];\n allowRead?: boolean;\n expires?: string;\n showToken?: boolean;\n agent?: string;\n}\n\nconst NO_TTY_ERROR = new CliError(\n EXIT.GENERAL,\n 'geslar agent create requires an interactive terminal (TTY) \u2014 TOTP entry cannot be scripted',\n);\n\nfunction validateExpires(expires: string | undefined): string | undefined {\n if (expires === undefined) return undefined;\n if (expires === 'never') return expires;\n if (/^[1-9]\\d{0,3}d$/.test(expires)) return expires;\n throw new CliError(EXIT.GENERAL, `Invalid --expires value \"${expires}\" \u2014 use e.g. 90d, or \"never\"`);\n}\n\nasync function confirmAllowRead(): Promise<boolean> {\n print(\n 'By default, agent profiles get run+inject only \u2014 they can USE a secret\\n'\n + '(spawn a process with it in env, substitute it into a template) but never\\n'\n + 'print it. --allow-read additionally grants the read capability, so\\n'\n + '`geslar read` under this profile WILL print the secret value to stdout.',\n );\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n try {\n const answer = await rl.question('Type \"yes\" to create this profile with read access: ');\n return answer.trim().toLowerCase() === 'yes';\n } finally {\n rl.close();\n }\n}\n\n/** `geslar agent create <name> --vault <name>... [--allow-read] [--expires 90d|never] [--show-token]`\n * (spec-access-core.md REV 1.2 \u00A74). Human session + fresh TOTP; the vault\n * resolver step reuses the SAME unlock chain as read/run/inject (existing\n * code, no agent-specific vault-discovery logic needed on the create path \u2014\n * that's only required later, for the resulting profile's OWN listing/reads). */\nexport async function agentCreateCommand(name: string, opts: AgentCreateOptions): Promise<number> {\n try {\n requireHumanContext(opts.agent, 'create');\n\n if (!process.stdin.isTTY) {\n throw NO_TTY_ERROR;\n }\n\n if (opts.vault.length === 0) {\n throw new CliError(EXIT.GENERAL, 'At least one --vault <name> is required');\n }\n const expires = validateExpires(opts.expires);\n\n if (opts.allowRead) {\n const confirmed = await confirmAllowRead();\n if (!confirmed) {\n printErr('Aborted \u2014 profile not created');\n return EXIT.GENERAL;\n }\n }\n\n const config = await loadOrInitConfig();\n const session = await loadSession();\n const baseUrl = session?.apiBase ?? config.apiBase;\n const backend = await selectBackend();\n const tokenStore = await createCliTokenStore(backend);\n if (!tokenStore.get()) {\n printErr('not signed in \u2014 run `geslar signin`');\n return EXIT.AUTH;\n }\n const api = buildApiClient(baseUrl, tokenStore);\n await requireAgenticCli(api);\n\n const unlocked = await obtainUnlockedKeys(api);\n await tokenStore.flush();\n const vaults = await listVaultHandles(api, unlocked);\n\n const resolvedVaults = opts.vault.map(v => resolveVaultByQuery(v, vaults));\n const vaultRefs: AgentTokenVaultRef[] = resolvedVaults.map(v => ({ id: v.id, name: v.name, kind: v.kind }));\n\n const capabilities: AgentCapability[] = opts.allowRead ? ['run', 'inject', 'read'] : ['run', 'inject'];\n\n print('Fresh TOTP code required to create an agent profile (recovery codes are not accepted).');\n const totpCode = await promptTotpCode('TOTP code: ', NO_TTY_ERROR);\n\n let created;\n try {\n created = await api.createAgent({\n name,\n vault_ids: resolvedVaults.map(v => v.id),\n capabilities,\n expires,\n totp_code: totpCode,\n });\n } catch (err) {\n throw mapCreateError(err);\n }\n\n await saveAgentToken(name, {\n token: created.token,\n createdAt: new Date().toISOString(),\n vaults: vaultRefs,\n allowRead: !!opts.allowRead,\n });\n\n print(`Agent profile \"${created.name}\" created (${created.capabilities.join('+')}).`);\n print(`Vaults: ${vaultRefs.map(v => v.name).join(', ')}`);\n print(`Expires: ${created.expires_at ?? 'never'}`);\n print(`Token stored locally (namespace: agent-token). Activate with GESLAR_AGENT=${created.name} or --agent ${created.name}.`);\n\n if (opts.showToken) {\n printErr('WARNING: printing the plaintext token \u2014 it will not be shown again. Treat it like a password.');\n // Deliberately raw stdout, not print() \u2014 same \"designated value channel,\n // don't scrub what we're about to display\" reasoning as read.ts.\n process.stdout.write(`${created.token}\\n`);\n }\n\n return EXIT.OK;\n } catch (err) {\n if (err instanceof CliError) {\n printErr(err.message);\n return err.exitCode;\n }\n printErr((err as Error).message);\n return EXIT.GENERAL;\n }\n}\n\nfunction mapCreateError(err: unknown): CliError {\n if (!(err instanceof ApiError)) {\n return new CliError(EXIT.GENERAL, (err as Error).message);\n }\n switch (err.code) {\n case 'licence/feature-locked':\n return new CliError(EXIT.ENTITLEMENT, err.message);\n case 'agent/name-exists':\n return new CliError(EXIT.GENERAL, err.message);\n case 'agent/limit-reached':\n return new CliError(EXIT.GENERAL, err.message);\n case 'mfa/setup-required':\n return new CliError(EXIT.AUTH, `${err.message} \u2014 enroll a TOTP authenticator first (console: Security settings)`);\n case 'auth/mfa-invalid':\n return new CliError(EXIT.AUTH, 'Invalid or expired TOTP code');\n case 'vault/not-found':\n return new CliError(EXIT.UNRESOLVABLE_REF, err.message);\n default:\n return new CliError(EXIT.GENERAL, err.message);\n }\n}\n", "import { buildApiClient } from '../lib/core.js';\nimport { loadSession } from '../lib/session.js';\nimport { loadOrInitConfig } from '../lib/config.js';\nimport { selectBackend, createCliTokenStore } from '../token-store/index.js';\nimport { print, printErr } from '../lib/output.js';\nimport { CliError, EXIT } from '../lib/errors.js';\nimport { requireHumanContext } from '../lib/agent-context.js';\nimport { loadAgentToken } from '../agent/token-store.js';\n\nexport interface AgentListOptions {\n agent?: string;\n}\n\n/** `geslar agent list` (spec-access-core.md REV 1.2 \u00A74) \u2014 GET /v1/agents\n * reports name/capabilities/status/expiry/last-used/scoped_vault_count, but\n * not vault NAMES (the server doesn't return them, by design \u2014 see\n * spec-access-core.md \u00A73). Vault names shown here come from this machine's\n * own create-time-cached record; a profile created on another machine (or\n * whose local token was already `geslar agent revoke`d/cleared) still shows\n * correctly, just without the vault-name line. */\nexport async function agentListCommand(opts: AgentListOptions): Promise<number> {\n try {\n requireHumanContext(opts.agent, 'list');\n\n const config = await loadOrInitConfig();\n const session = await loadSession();\n const baseUrl = session?.apiBase ?? config.apiBase;\n const backend = await selectBackend();\n const tokenStore = await createCliTokenStore(backend);\n if (!tokenStore.get()) {\n printErr('not signed in \u2014 run `geslar signin`');\n return EXIT.AUTH;\n }\n const api = buildApiClient(baseUrl, tokenStore);\n\n const { agents } = await api.listAgents();\n await tokenStore.flush();\n\n if (agents.length === 0) {\n print('No agent profiles. Create one with `geslar agent create <name> --vault <name>`.');\n return EXIT.OK;\n }\n\n for (const a of agents) {\n const local = await loadAgentToken(a.name);\n const vaultsText = local\n ? local.vaults.map(v => v.name).join(', ')\n : `${a.scoped_vault_count} vault(s) (not stored on this machine)`;\n const scopeNote = a.has_active_scope ? '' : ' [no active scope]';\n print(`${a.name} (${a.status})${scopeNote}`);\n print(` Vaults: ${vaultsText}`);\n print(` Capabilities: ${a.capabilities.join('+')}`);\n print(` Expires: ${a.expires_at ?? 'never'}`);\n print(` Last used: ${a.last_used_at ?? '(never)'}`);\n }\n return EXIT.OK;\n } catch (err) {\n if (err instanceof CliError) {\n printErr(err.message);\n return err.exitCode;\n }\n printErr((err as Error).message);\n return EXIT.GENERAL;\n }\n}\n", "import { buildApiClient } from '../lib/core.js';\nimport { loadSession } from '../lib/session.js';\nimport { loadOrInitConfig } from '../lib/config.js';\nimport { selectBackend, createCliTokenStore } from '../token-store/index.js';\nimport { print, printErr } from '../lib/output.js';\nimport { CliError, EXIT } from '../lib/errors.js';\nimport { requireHumanContext } from '../lib/agent-context.js';\nimport { clearAgentToken } from '../agent/token-store.js';\n\nexport interface AgentRevokeOptions {\n agent?: string;\n}\n\n/** `geslar agent revoke <name>` (spec-access-core.md REV 1.2 \u00A74) \u2014 DELETE\n * /v1/agents/:id then clears the local token unconditionally, even if the\n * server call fails (a token whose server-side profile is already gone or\n * already revoked is equally useless locally \u2014 no point leaving it behind). */\nexport async function agentRevokeCommand(name: string, opts: AgentRevokeOptions): Promise<number> {\n try {\n requireHumanContext(opts.agent, 'revoke');\n\n const config = await loadOrInitConfig();\n const session = await loadSession();\n const baseUrl = session?.apiBase ?? config.apiBase;\n const backend = await selectBackend();\n const tokenStore = await createCliTokenStore(backend);\n if (!tokenStore.get()) {\n printErr('not signed in \u2014 run `geslar signin`');\n return EXIT.AUTH;\n }\n const api = buildApiClient(baseUrl, tokenStore);\n\n const { agents } = await api.listAgents();\n await tokenStore.flush();\n const match = agents.find(a => a.name === name);\n if (!match) {\n throw new CliError(EXIT.GENERAL, `No agent profile named \"${name}\" \u2014 run \\`geslar agent list\\` to see your profiles`);\n }\n\n try {\n await api.revokeAgent(match.id);\n } finally {\n // Clear the local token regardless of the server call's outcome \u2014 see\n // doc comment above.\n await clearAgentToken(name);\n }\n\n print(`Agent profile \"${name}\" revoked. Local token cleared.`);\n return EXIT.OK;\n } catch (err) {\n if (err instanceof CliError) {\n printErr(err.message);\n return err.exitCode;\n }\n printErr((err as Error).message);\n return EXIT.GENERAL;\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAIA,QAAMA,gBAAe,MAAM;AACzB;AAEA,YAAM,oBAAoB;AAC1B,YAAM,aAAa;AACnB,YAAM,WAAW;AACjB,YAAM,WAAW;AAGjB,eAAS,eAAe;AACtB,eAAO,OAAO,gBAAgB,IAAI,WAAW,UAAU,CAAC;AAAA,MAC1D;AAGA,eAAS,aAAa;AACpB,eAAO,OAAO,gBAAgB,IAAI,WAAW,QAAQ,CAAC;AAAA,MACxD;AAGA,qBAAe,gBAAgB,UAAU,MAAM;AAC7C,cAAM,UAAU,IAAI,YAAY;AAChC,cAAM,cAAc,MAAM,OAAO,OAAO;AAAA,UACtC;AAAA,UAAO,QAAQ,OAAO,QAA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0F;AACrH,UAAQ,WAAW,MAAM,mBAAmB,MAAM,IAAI;AACxD,CAAC;AAEH,MACG,QAAQ,MAAM,EACd,YAAY,0BAA0B,EACtC,OAAO,YAAY;AAClB,UAAQ,WAAW,MAAM,iBAAiB,CAAC,CAAC;AAC9C,CAAC;AAEH,MACG,QAAQ,QAAQ,EAChB,SAAS,UAAU,cAAc,EACjC,YAAY,mDAAmD,EAC/D,OAAO,OAAO,SAAiB;AAC9B,UAAQ,WAAW,MAAM,mBAAmB,MAAM,CAAC,CAAC;AACtD,CAAC;AAMH,MAAM,YAAY;AAChB,MAAI;AACF,UAAM,QAAQ,WAAW,QAAQ,IAAI;AAAA,EACvC,SAAS,KAAK;AACZ,aAAU,IAAc,OAAO;AAC/B,YAAQ,WAAW,KAAK;AAAA,EAC1B;AACF,GAAG;",
6
- "names": ["VaultCrypto", "VaultCloudCrypto", "HKDF_SALT", "HKDF_INFO", "OrgRecoveryCrypto", "HKDF_SALT", "HKDF_INFO", "readFile", "writeFile", "readFile", "writeFile", "readFile", "writeFile", "rm", "readFile", "writeFile", "rm", "spawn", "spawn", "userInfo", "account", "run", "randomBytes", "userInfo", "readFile", "writeFile", "rm", "readFile", "writeFile", "readFile", "writeFile", "userInfo", "readFile", "randomBytes", "writeFile", "rm", "VaultCrypto", "VaultCrypto", "VaultCloudCrypto", "VaultCrypto", "VaultCloudCrypto", "VaultCloudCrypto", "buildCollectionDekMap", "VaultCrypto", "VaultCloudCrypto", "api", "writeFile", "writeFile", "spawn", "readFile", "readFile", "spawn", "readFile", "writeFile", "readFile", "writeFile"]
3
+ "sources": ["../../../packages/core/src/crypto/vault-crypto.js", "../../../packages/core/src/crypto/vault-cloud-crypto.js", "../../../packages/core/src/crypto/recovery-enrollment.js", "../src/index.ts", "../src/commands/signin.ts", "../src/lib/config.ts", "../src/lib/paths.ts", "../src/lib/session.ts", "../src/lib/scrubber.ts", "../src/lib/output.ts", "../src/lib/errors.ts", "../src/token-store/windows.ts", "../src/token-store/macos.ts", "../src/token-store/linux.ts", "../src/token-store/fallback.ts", "../src/token-store/machine-id.ts", "../src/token-store/index.ts", "../src/device-flow.ts", "../src/vault/grant.ts", "../src/commands/signout.ts", "../../../packages/core/src/api/client.ts", "../../../packages/core/src/entitlements/index.ts", "../../../packages/core/src/pdp.ts", "../../../packages/core/src/security/health.ts", "../src/lib/core.ts", "../src/commands/whoami.ts", "../src/lib/prompt.ts", "../../../packages/core/src/crypto/index.mjs", "../src/vault/unlock.ts", "../src/commands/unlock.ts", "../src/commands/lock.ts", "../src/vault/session.ts", "../src/vault/vaults.ts", "../src/vault/agent-vaults.ts", "../src/vault/totp.ts", "../src/vault/entries.ts", "../src/resolver.ts", "../src/agent/token-store.ts", "../src/lib/agent-context.ts", "../src/commands/list.ts", "../src/commands/read.ts", "../src/vault/resolve-context.ts", "../src/lib/entitlements.ts", "../src/commands/run.ts", "../src/vault/resolve-many.ts", "../src/lib/dotenv.ts", "../src/commands/inject.ts", "../src/commands/agent-create.ts", "../src/commands/agent-list.ts", "../src/commands/agent-revoke.ts", "../src/mcp/grant-store.ts", "../src/commands/mcp-allow.ts", "../src/commands/mcp-allow-cmd.ts", "../src/commands/mcp-grants.ts", "../src/commands/mcp-revoke.ts"],
4
+ "sourcesContent": ["// \u2500\u2500\u2500 Geslar Vault \u2014 Crypto Module \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Pure Web Crypto API \u2014 zero external dependencies\n// AES-256-GCM encryption with PBKDF2 key derivation\n\nconst VaultCrypto = (() => {\n 'use strict';\n\n const PBKDF2_ITERATIONS = 600000;\n const SALT_BYTES = 32;\n const IV_BYTES = 12;\n const KEY_BITS = 256;\n\n /** Generate a random salt (32 bytes) */\n function generateSalt() {\n return crypto.getRandomValues(new Uint8Array(SALT_BYTES));\n }\n\n /** Generate a random IV (12 bytes) */\n function generateIV() {\n return crypto.getRandomValues(new Uint8Array(IV_BYTES));\n }\n\n /** Derive a CryptoKey from master password + salt using PBKDF2 */\n async function deriveMasterKey(password, salt) {\n const encoder = new TextEncoder();\n const keyMaterial = await crypto.subtle.importKey(\n 'raw', encoder.encode(password), 'PBKDF2', false, ['deriveKey']\n );\n return crypto.subtle.deriveKey(\n { name: 'PBKDF2', salt, iterations: PBKDF2_ITERATIONS, hash: 'SHA-256' },\n keyMaterial,\n { name: 'AES-GCM', length: KEY_BITS },\n true, // extractable \u2014 needed to export/import via session storage\n ['encrypt', 'decrypt']\n );\n }\n\n /**\n * Derive a verification hash (separate from master key).\n * Uses a different salt to prevent key reuse.\n * Returns base64 string for quick master password verification.\n */\n async function deriveVerificationHash(password, salt) {\n const encoder = new TextEncoder();\n const keyMaterial = await crypto.subtle.importKey(\n 'raw', encoder.encode(password), 'PBKDF2', false, ['deriveBits']\n );\n const bits = await crypto.subtle.deriveBits(\n { name: 'PBKDF2', salt, iterations: PBKDF2_ITERATIONS, hash: 'SHA-256' },\n keyMaterial,\n 256\n );\n return bufToBase64(new Uint8Array(bits));\n }\n\n /** Encrypt plaintext string \u2192 { ciphertext: base64, iv: base64 } */\n async function encrypt(plaintext, key) {\n const encoder = new TextEncoder();\n const iv = generateIV();\n const encrypted = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv },\n key,\n encoder.encode(plaintext)\n );\n return {\n ciphertext: bufToBase64(new Uint8Array(encrypted)),\n iv: bufToBase64(iv)\n };\n }\n\n /** Decrypt { ciphertext: base64, iv: base64 } \u2192 plaintext string */\n async function decrypt(ciphertext, iv, key) {\n const decrypted = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv: base64ToBuf(iv) },\n key,\n base64ToBuf(ciphertext)\n );\n return new TextDecoder().decode(decrypted);\n }\n\n // \u2500\u2500\u2500 Key export/import (for session storage persistence) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Export CryptoKey to base64 string */\n async function exportKey(key) {\n const raw = await crypto.subtle.exportKey('raw', key);\n return bufToBase64(new Uint8Array(raw));\n }\n\n /** Import base64 string back to CryptoKey */\n async function importKey(b64) {\n const raw = base64ToBuf(b64);\n return crypto.subtle.importKey(\n 'raw', raw, { name: 'AES-GCM', length: KEY_BITS },\n true, ['encrypt', 'decrypt']\n );\n }\n\n // \u2500\u2500\u2500 Base64 helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n function bufToBase64(buf) {\n let binary = '';\n for (let i = 0; i < buf.length; i++) binary += String.fromCharCode(buf[i]);\n return btoa(binary);\n }\n\n function base64ToBuf(b64) {\n const binary = atob(b64);\n const buf = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) buf[i] = binary.charCodeAt(i);\n return buf;\n }\n\n // \u2500\u2500\u2500 UUID v4 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n function generateId() {\n return crypto.randomUUID ? crypto.randomUUID() : ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>\n (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16));\n }\n\n // \u2500\u2500\u2500 Public API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n return {\n generateSalt,\n generateIV,\n deriveMasterKey,\n deriveVerificationHash,\n encrypt,\n decrypt,\n exportKey,\n importKey,\n bufToBase64,\n base64ToBuf,\n generateId,\n PBKDF2_ITERATIONS\n };\n})();\n\nif (typeof module !== 'undefined') module.exports = VaultCrypto;\n", "// \u2500\u2500\u2500 Geslar Vault \u2014 Cloud Crypto \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Crypto operations specific to cloud sync: auth_hash derivation, vault_key\n// (DEK) management, per-entry encryption, and recovery key generation.\n// Uses existing VaultCrypto helpers. Never called directly from UI.\n\nconst VaultCloudCrypto = (() => {\n 'use strict';\n\n const AUTH_HASH_ITERATIONS = 1; // Intentionally 1 \u2014 see spec \"auth hash flow\"\n const VAULT_KEY_BYTES = 32; // AES-256\n const RECOVERY_KEY_BYTES = 32; // 256-bit recovery key\n const ECDH_PRIVATE_BYTES = 32; // X25519 private key (raw scalar)\n const IV_BYTES = 12; // AES-GCM nonce\n\n // \u2500\u2500\u2500 Shared-vault key exchange (T10) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Static-static X25519 ECDH \u2192 HKDF-SHA256 \u2192 AES-256-GCM wrap key.\n // Domain-separated salt/info so a shared secret can never be reused as a\n // different key by accident. MUST match server-side derivation.\n const HKDF_SALT = new TextEncoder().encode('geslar-ecdh-hkdf-salt-v1');\n const HKDF_INFO = new TextEncoder().encode('geslar-shared-vault-wrap-v1');\n\n // Recovery blob format marker. v1 (legacy) = raw 32-byte DEK wrapped by the\n // recovery key. v2 (O3, keypair-preserving) = MAGIC \u2016 DEK(32) \u2016 ECDH_priv.\n // The marker lets unwrap stay backward compatible with every blob already in\n // production (those have no prefix and decrypt to exactly 32 bytes).\n const RECOVERY_V2_MAGIC = Uint8Array.from([0x47, 0x52, 0x02]); // 'G','R',0x02\n\n // Fingerprint phrase: deterministic, bijective byte\u2192syllable mapping so the\n // exact same algorithm reproduces on the server with no shared word table to\n // drift. 16\u00D74\u00D74 = 256 distinct CVC syllables \u2194 one byte. MUST match server.\n const FP_CONS_INITIAL = ['b','d','f','g','k','l','m','n','p','r','s','t','v','z','h','j']; // 16\n const FP_VOWELS = ['a','e','i','o']; // 4\n const FP_CONS_FINAL = ['k','n','s','t']; // 4\n const FP_WORD_COUNT = 6; // 6 syllables \u2192 48 bits of the pubkey hash\n\n // \u2500\u2500\u2500 Auth hash derivation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // PBKDF2-SHA256(master_key_raw, password_bytes, 1 iteration) \u2192 auth_hash\n // This is NOT stretching (server does Argon2id for that).\n // It's a one-way derivation so server never sees master_key.\n\n /**\n * Derive auth_hash from master_key for server authentication.\n * @param {CryptoKey} masterKey \u2014 derived via VaultCrypto.deriveMasterKey()\n * @param {string} password \u2014 the user's master password (used as PBKDF2 salt)\n * @returns {Promise<string>} Base64-encoded 256-bit auth_hash\n */\n async function deriveAuthHash(masterKey, password) {\n // Export master_key to raw bytes (it's extractable)\n const masterKeyRaw = await crypto.subtle.exportKey('raw', masterKey);\n\n // Import raw master_key bytes as PBKDF2 key material\n const keyMaterial = await crypto.subtle.importKey(\n 'raw', masterKeyRaw, 'PBKDF2', false, ['deriveBits']\n );\n\n // Derive auth_hash: PBKDF2(master_key, password_as_salt, 1 iter)\n const encoder = new TextEncoder();\n const authHashBits = await crypto.subtle.deriveBits(\n {\n name: 'PBKDF2',\n salt: encoder.encode(password),\n iterations: AUTH_HASH_ITERATIONS,\n hash: 'SHA-256',\n },\n keyMaterial,\n 256\n );\n\n return VaultCrypto.bufToBase64(new Uint8Array(authHashBits));\n }\n\n // \u2500\u2500\u2500 Vault key (DEK) management \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // vault_key is a random AES-256 key that encrypts individual vault entries.\n // master_key (KEK) wraps vault_key \u2014 password change = re-wrap, not re-encrypt.\n\n /** Generate a fresh vault_key (DEK) \u2014 256-bit random. */\n function generateVaultKey() {\n return crypto.getRandomValues(new Uint8Array(VAULT_KEY_BYTES));\n }\n\n /**\n * Wrap (encrypt) vault_key with master_key (KEK).\n * @param {CryptoKey} masterKey \u2014 KEK derived from password\n * @param {Uint8Array} vaultKey \u2014 32-byte DEK\n * @returns {Promise<string>} Base64-encoded IV+ciphertext\n */\n async function wrapVaultKey(masterKey, vaultKey) {\n const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));\n const encrypted = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv },\n masterKey,\n vaultKey\n );\n // Pack: IV (12) + ciphertext (32 + 16 tag)\n const packed = new Uint8Array(iv.length + encrypted.byteLength);\n packed.set(iv, 0);\n packed.set(new Uint8Array(encrypted), iv.length);\n return VaultCrypto.bufToBase64(packed);\n }\n\n /**\n * Unwrap (decrypt) vault_key with master_key (KEK).\n * @param {CryptoKey} masterKey \u2014 KEK derived from password\n * @param {string} wrappedBase64 \u2014 Base64 IV+ciphertext from server\n * @returns {Promise<Uint8Array>} 32-byte vault_key (DEK)\n */\n async function unwrapVaultKey(masterKey, wrappedBase64) {\n const packed = VaultCrypto.base64ToBuf(wrappedBase64);\n const iv = packed.slice(0, IV_BYTES);\n const ciphertext = packed.slice(IV_BYTES);\n const decrypted = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv },\n masterKey,\n ciphertext\n );\n return new Uint8Array(decrypted);\n }\n\n /**\n * Import raw vault_key bytes as a CryptoKey for encrypt/decrypt operations.\n * @param {Uint8Array} vaultKeyRaw \u2014 32-byte DEK\n * @returns {Promise<CryptoKey>}\n */\n async function importVaultKey(vaultKeyRaw) {\n return crypto.subtle.importKey(\n 'raw', vaultKeyRaw, { name: 'AES-GCM', length: 256 },\n false, ['encrypt', 'decrypt']\n );\n }\n\n // \u2500\u2500\u2500 Per-entry encryption \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Each vault entry is individually encrypted with vault_key (DEK).\n // AES-256-GCM(vault_key, entry_json) \u2192 { encrypted_blob, blob_hash }\n\n /**\n * Encrypt a single vault entry for cloud push.\n * @param {CryptoKey} vaultKey \u2014 imported vault_key (DEK)\n * @param {object} entry \u2014 plaintext entry object\n * @returns {Promise<{ encrypted_blob: string, blob_hash: string }>}\n * encrypted_blob: Base64(IV + ciphertext+tag)\n * blob_hash: hex SHA-256 of the encrypted blob (for dedup/integrity)\n */\n async function encryptEntry(vaultKey, entry) {\n const encoder = new TextEncoder();\n const plaintext = encoder.encode(JSON.stringify(entry));\n\n const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));\n const encrypted = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv },\n vaultKey,\n plaintext\n );\n\n // Pack IV + ciphertext\n const packed = new Uint8Array(iv.length + encrypted.byteLength);\n packed.set(iv, 0);\n packed.set(new Uint8Array(encrypted), iv.length);\n\n const blob = VaultCrypto.bufToBase64(packed);\n\n // SHA-256 hash of the encrypted blob for integrity/dedup\n const hashBuffer = await crypto.subtle.digest('SHA-256', packed);\n const hashArray = new Uint8Array(hashBuffer);\n const blobHash = Array.from(hashArray).map(b => b.toString(16).padStart(2, '0')).join('');\n\n return { encrypted_blob: blob, blob_hash: blobHash };\n }\n\n /**\n * Decrypt a single vault entry from cloud pull.\n * @param {CryptoKey} vaultKey \u2014 imported vault_key (DEK)\n * @param {string} encryptedBlob \u2014 Base64(IV + ciphertext+tag)\n * @returns {Promise<object>} Plaintext entry object\n */\n async function decryptEntry(vaultKey, encryptedBlob) {\n const packed = VaultCrypto.base64ToBuf(encryptedBlob);\n const iv = packed.slice(0, IV_BYTES);\n const ciphertext = packed.slice(IV_BYTES);\n\n const decrypted = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv },\n vaultKey,\n ciphertext\n );\n\n return JSON.parse(new TextDecoder().decode(decrypted));\n }\n\n // \u2500\u2500\u2500 Recovery key \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // 256-bit random key that wraps the same vault_key (DEK).\n // Enables vault recovery without master password.\n\n /** Generate a 256-bit recovery key. */\n function generateRecoveryKey() {\n return crypto.getRandomValues(new Uint8Array(RECOVERY_KEY_BYTES));\n }\n\n /** True when a decrypted recovery payload carries the v2 (keypair) marker. */\n function isRecoveryV2(payload) {\n return payload.length > RECOVERY_V2_MAGIC.length + VAULT_KEY_BYTES &&\n payload[0] === RECOVERY_V2_MAGIC[0] &&\n payload[1] === RECOVERY_V2_MAGIC[1] &&\n payload[2] === RECOVERY_V2_MAGIC[2];\n }\n\n /**\n * Wrap vault_key (and optionally the ECDH private key) with recovery_key\n * \u2192 encrypted_recovery_blob.\n *\n * When `ecdhPrivateKey` is supplied the blob uses the v2 layout\n * (MAGIC \u2016 DEK \u2016 ECDH_priv) so recovery can preserve the user's key pair\n * (O3). Omitting it produces the legacy v1 layout (raw DEK) \u2014 byte-identical\n * to every blob already in production, so existing flows are untouched.\n *\n * @param {Uint8Array} recoveryKey \u2014 32-byte recovery key\n * @param {Uint8Array} vaultKey \u2014 32-byte DEK\n * @param {Uint8Array} [ecdhPrivateKey] \u2014 PKCS#8 X25519 private key (v2 only)\n * @returns {Promise<string>} Base64 IV+ciphertext\n */\n async function wrapVaultKeyWithRecovery(recoveryKey, vaultKey, ecdhPrivateKey) {\n const key = await crypto.subtle.importKey(\n 'raw', recoveryKey, { name: 'AES-GCM', length: 256 },\n false, ['encrypt']\n );\n\n let payload;\n if (ecdhPrivateKey) {\n payload = new Uint8Array(RECOVERY_V2_MAGIC.length + vaultKey.length + ecdhPrivateKey.length);\n payload.set(RECOVERY_V2_MAGIC, 0);\n payload.set(vaultKey, RECOVERY_V2_MAGIC.length);\n payload.set(ecdhPrivateKey, RECOVERY_V2_MAGIC.length + vaultKey.length);\n } else {\n payload = vaultKey;\n }\n\n const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));\n const encrypted = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, payload);\n const packed = new Uint8Array(iv.length + encrypted.byteLength);\n packed.set(iv, 0);\n packed.set(new Uint8Array(encrypted), iv.length);\n return VaultCrypto.bufToBase64(packed);\n }\n\n /**\n * Decrypt encrypted_recovery_blob and split it into its parts.\n * Handles both v1 (DEK only) and v2 (DEK + ECDH private key) layouts.\n * @param {Uint8Array} recoveryKey \u2014 32-byte recovery key\n * @param {string} recoveryBlob \u2014 Base64 IV+ciphertext\n * @returns {Promise<{ vaultKey: Uint8Array, ecdhPrivateKey: Uint8Array|null, version: number }>}\n * Throws DOMException (OperationError) if recovery key is wrong / blob tampered.\n */\n async function unwrapRecoveryBlob(recoveryKey, recoveryBlob) {\n const key = await crypto.subtle.importKey(\n 'raw', recoveryKey, { name: 'AES-GCM', length: 256 },\n false, ['decrypt']\n );\n const packed = VaultCrypto.base64ToBuf(recoveryBlob);\n const iv = packed.slice(0, IV_BYTES);\n const ciphertext = packed.slice(IV_BYTES);\n const decrypted = new Uint8Array(\n await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, key, ciphertext)\n );\n\n if (isRecoveryV2(decrypted)) {\n const off = RECOVERY_V2_MAGIC.length;\n return {\n vaultKey: decrypted.slice(off, off + VAULT_KEY_BYTES),\n ecdhPrivateKey: decrypted.slice(off + VAULT_KEY_BYTES),\n version: 2,\n };\n }\n return { vaultKey: decrypted, ecdhPrivateKey: null, version: 1 };\n }\n\n /**\n * Unwrap vault_key from encrypted_recovery_blob using recovery_key.\n * Backward-compatible accessor that always returns the DEK, regardless of\n * blob version. Existing callers keep working unchanged.\n * @param {Uint8Array} recoveryKey \u2014 32-byte recovery key\n * @param {string} recoveryBlob \u2014 Base64 IV+ciphertext\n * @returns {Promise<Uint8Array>} 32-byte vault_key (DEK)\n */\n async function unwrapVaultKeyWithRecovery(recoveryKey, recoveryBlob) {\n const { vaultKey } = await unwrapRecoveryBlob(recoveryKey, recoveryBlob);\n return vaultKey;\n }\n\n // \u2500\u2500\u2500 X25519 ECDH key pair \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Real X25519 (SubtleCrypto, Chrome 113+). Used for shared vaults (key\n // exchange) and trusted device transfer. Generated at registration, private\n // key wrapped by master_key. The public key is DERIVED from the private key.\n //\n // Storage convention:\n // privateKey \u2192 PKCS#8 DER bytes (48 B) \u2014 the only WebCrypto export format\n // that round-trips an X25519 private key via importKey().\n // publicKey \u2192 raw 32-byte u-coordinate.\n\n /**\n * Generate a real X25519 key pair.\n * @returns {Promise<{ privateKey: Uint8Array, publicKey: Uint8Array }>}\n * privateKey = PKCS#8 DER (48 B), publicKey = raw 32-byte u-coordinate.\n */\n async function generateEcdhKeyPair() {\n const pair = await crypto.subtle.generateKey({ name: 'X25519' }, true, ['deriveBits']);\n const publicKey = new Uint8Array(await crypto.subtle.exportKey('raw', pair.publicKey));\n const privateKey = new Uint8Array(await crypto.subtle.exportKey('pkcs8', pair.privateKey));\n return { privateKey, publicKey };\n }\n\n /** Import a PKCS#8 X25519 private key for ECDH deriveBits. */\n function importEcdhPrivateKey(privatePkcs8) {\n return crypto.subtle.importKey('pkcs8', privatePkcs8, { name: 'X25519' }, false, ['deriveBits']);\n }\n\n /** Import a raw 32-byte X25519 public key as an ECDH peer key. */\n function importEcdhPublicKey(publicRaw) {\n return crypto.subtle.importKey('raw', publicRaw, { name: 'X25519' }, false, []);\n }\n\n /**\n * Recover the raw 32-byte public key from a PKCS#8 X25519 private key.\n * WebCrypto cannot raw-export a public key from a private CryptoKey, but a\n * JWK export of the private key carries the public component in `x`.\n * @param {Uint8Array} privatePkcs8\n * @returns {Promise<Uint8Array>} raw 32-byte public key\n */\n async function ecdhPublicFromPrivate(privatePkcs8) {\n const key = await crypto.subtle.importKey('pkcs8', privatePkcs8, { name: 'X25519' }, true, ['deriveBits']);\n const jwk = await crypto.subtle.exportKey('jwk', key);\n const b64 = jwk.x.replace(/-/g, '+').replace(/_/g, '/');\n const padded = b64 + '='.repeat((4 - (b64.length % 4)) % 4);\n return VaultCrypto.base64ToBuf(padded);\n }\n\n /**\n * Derive the AES-256-GCM wrap key shared with a peer:\n * X25519(myPriv, peerPub) \u2192 HKDF-SHA256 \u2192 AES-256 key.\n * Static-static ECDH: identical key on both ends when the roles are swapped\n * (wrap uses myPriv+recipientPub, unwrap uses recipientPriv+myPub).\n * @param {Uint8Array} myPrivatePkcs8 \u2014 my X25519 private key (PKCS#8)\n * @param {Uint8Array} peerPublicRaw \u2014 peer's raw 32-byte public key\n * @returns {Promise<CryptoKey>} AES-256-GCM key (non-extractable)\n */\n async function deriveSharedWrapKey(myPrivatePkcs8, peerPublicRaw) {\n const privKey = await importEcdhPrivateKey(myPrivatePkcs8);\n const pubKey = await importEcdhPublicKey(peerPublicRaw);\n\n const sharedSecret = await crypto.subtle.deriveBits(\n { name: 'X25519', public: pubKey }, privKey, 256\n );\n\n // HKDF-extract+expand the raw DH secret into a clean 256-bit AES key.\n const ikm = await crypto.subtle.importKey('raw', sharedSecret, 'HKDF', false, ['deriveBits']);\n const okm = await crypto.subtle.deriveBits(\n { name: 'HKDF', hash: 'SHA-256', salt: HKDF_SALT, info: HKDF_INFO }, ikm, 256\n );\n return crypto.subtle.importKey('raw', okm, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);\n }\n\n /**\n * Wrap a shared vault DEK for a member.\n * wrapKey = ECDH(myPriv, recipientPub) \u2192 HKDF \u2192 AES-256-GCM.\n * @param {Uint8Array} myPrivatePkcs8 \u2014 sender's X25519 private key (PKCS#8)\n * @param {Uint8Array} recipientPublicRaw \u2014 recipient's raw 32-byte public key\n * @param {Uint8Array} sharedDEK \u2014 32-byte shared vault key to wrap\n * @returns {Promise<string>} Base64 IV+ciphertext+tag\n */\n async function wrapVaultKeyForMember(myPrivatePkcs8, recipientPublicRaw, sharedDEK) {\n const wrapKey = await deriveSharedWrapKey(myPrivatePkcs8, recipientPublicRaw);\n const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));\n const encrypted = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, wrapKey, sharedDEK);\n const packed = new Uint8Array(iv.length + encrypted.byteLength);\n packed.set(iv, 0);\n packed.set(new Uint8Array(encrypted), iv.length);\n return VaultCrypto.bufToBase64(packed);\n }\n\n /**\n * Unwrap a shared vault DEK wrapped for me by a sender.\n * wrapKey = ECDH(myPriv, senderPub) \u2192 HKDF \u2192 AES-256-GCM.\n * @param {Uint8Array} myPrivatePkcs8 \u2014 my X25519 private key (PKCS#8)\n * @param {Uint8Array} senderPublicRaw \u2014 sender's raw 32-byte public key\n * @param {string} wrappedBase64 \u2014 blob from wrapVaultKeyForMember()\n * @returns {Promise<Uint8Array>} 32-byte shared vault DEK\n * Throws DOMException (OperationError) if the blob or sender key is tampered.\n */\n async function unwrapSharedVaultKey(myPrivatePkcs8, senderPublicRaw, wrappedBase64) {\n const wrapKey = await deriveSharedWrapKey(myPrivatePkcs8, senderPublicRaw);\n const packed = VaultCrypto.base64ToBuf(wrappedBase64);\n const iv = packed.slice(0, IV_BYTES);\n const ciphertext = packed.slice(IV_BYTES);\n const decrypted = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, wrapKey, ciphertext);\n return new Uint8Array(decrypted);\n }\n\n // \u2500\u2500\u2500 Fingerprint phrase \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Human-verifiable hash of a public key (Bitwarden trust model, O2). Two\n // members compare the phrase out-of-band; a server that swaps a public key\n // (MITM) cannot reproduce the victim's phrase. Deterministic \u2014 the server\n // renders the identical phrase for the console.\n\n /** Map one byte (0\u2013255) to a fixed CVC syllable. Bijective. */\n function fpSyllable(byte) {\n const c1 = FP_CONS_INITIAL[(byte >> 4) & 0x0f];\n const v = FP_VOWELS[(byte >> 2) & 0x03];\n const c2 = FP_CONS_FINAL[byte & 0x03];\n return c1 + v + c2;\n }\n\n /**\n * Derive the deterministic fingerprint phrase for a public key.\n * @param {Uint8Array|string} publicKey \u2014 raw 32-byte public key or its base64\n * @returns {Promise<string>} e.g. \"bok-tas-...\" \u2014 FP_WORD_COUNT syllables, '-' joined\n */\n async function deriveFingerprintPhrase(publicKey) {\n const raw = typeof publicKey === 'string' ? VaultCrypto.base64ToBuf(publicKey) : publicKey;\n const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', raw));\n const words = [];\n for (let i = 0; i < FP_WORD_COUNT; i++) words.push(fpSyllable(digest[i]));\n return words.join('-');\n }\n\n /**\n * Wrap ECDH private key with master_key (KEK).\n * @param {CryptoKey} masterKey \u2014 KEK\n * @param {Uint8Array} privateKey \u2014 32-byte X25519 private key\n * @returns {Promise<string>} Base64 IV+ciphertext\n */\n async function wrapEcdhPrivateKey(masterKey, privateKey) {\n const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));\n const encrypted = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv },\n masterKey,\n privateKey\n );\n const packed = new Uint8Array(iv.length + encrypted.byteLength);\n packed.set(iv, 0);\n packed.set(new Uint8Array(encrypted), iv.length);\n return VaultCrypto.bufToBase64(packed);\n }\n\n // \u2500\u2500\u2500 Registration crypto bundle \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Orchestrates all crypto for cloud registration in one call.\n\n /**\n * Generate all crypto material needed for cloud registration.\n * @param {string} password \u2014 master password\n * @param {Uint8Array} encSalt \u2014 32-byte PBKDF2 salt (from VaultCrypto.generateSalt())\n * @returns {Promise<{\n * auth_hash: string,\n * enc_salt: string,\n * encrypted_vault_key: string,\n * encrypted_recovery_blob: string,\n * encrypted_ecdh_private_key: string,\n * ecdh_public_key: string,\n * recovery_key: Uint8Array,\n * vault_key: Uint8Array,\n * }>}\n */\n async function prepareRegistration(password, encSalt) {\n // 1. Derive master_key (KEK) from password\n const masterKey = await VaultCrypto.deriveMasterKey(password, encSalt);\n\n // 2. Derive auth_hash for server\n const authHash = await deriveAuthHash(masterKey, password);\n\n // 3. Generate vault_key (DEK)\n const vaultKey = generateVaultKey();\n\n // 4. Generate recovery key\n const recoveryKey = generateRecoveryKey();\n\n // 5. Wrap vault_key with master_key \u2192 encrypted_vault_key\n const encryptedVaultKey = await wrapVaultKey(masterKey, vaultKey);\n\n // 6. Generate real X25519 key pair and wrap private key with master_key\n const ecdh = await generateEcdhKeyPair();\n const encryptedEcdhPrivate = await wrapEcdhPrivateKey(masterKey, ecdh.privateKey);\n\n // 7. Wrap vault_key + ECDH private key with recovery_key \u2192 v2 recovery blob\n // (keypair-preserving recovery, O3). New accounts are born ecdh-real\n // (ecdh_key_version = 1) so they never need the placeholder migration.\n const encryptedRecoveryBlob = await wrapVaultKeyWithRecovery(recoveryKey, vaultKey, ecdh.privateKey);\n\n return {\n auth_hash: authHash,\n enc_salt: VaultCrypto.bufToBase64(encSalt),\n encrypted_vault_key: encryptedVaultKey,\n encrypted_recovery_blob: encryptedRecoveryBlob,\n encrypted_ecdh_private_key: encryptedEcdhPrivate,\n ecdh_public_key: VaultCrypto.bufToBase64(ecdh.publicKey),\n ecdh_key_version: 1, // real X25519 from the start\n recovery_key: recoveryKey, // Show to user ONCE as BIP39 mnemonic\n vault_key: vaultKey, // Keep in memory for immediate sync\n };\n }\n\n // \u2500\u2500\u2500 ECDH placeholder \u2192 real migration (T10) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // Existing cloud users (v3.0.0) hold a cryptographically useless placeholder\n // ECDH key (random public key, not derived from the private key). On unlock,\n // if ecdh_key_version = 0, the client generates a REAL pair, re-wraps the\n // private key with master_key, and uploads the new public key (version \u2192 1).\n // Transparent \u2014 no UX interruption. We cannot rewrap the recovery blob here\n // (the one-time recovery key is not held in memory), so migrated users get a\n // fresh pair on a future recovery; that is acceptable since nothing has\n // wrapped a DEK to their public key yet (shared vaults arrive in T11).\n\n /**\n * Prepare migration material for a placeholder\u2192real ECDH upgrade.\n * @param {CryptoKey} masterKey \u2014 KEK (from unlock)\n * @returns {Promise<{ encrypted_ecdh_private_key: string, ecdh_public_key: string }>}\n */\n async function prepareEcdhMigration(masterKey) {\n const ecdh = await generateEcdhKeyPair();\n const encryptedEcdhPrivate = await wrapEcdhPrivateKey(masterKey, ecdh.privateKey);\n return {\n encrypted_ecdh_private_key: encryptedEcdhPrivate,\n ecdh_public_key: VaultCrypto.bufToBase64(ecdh.publicKey),\n };\n }\n\n // \u2500\u2500\u2500 Login crypto helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Derive auth_hash for login and prepare to unwrap vault_key.\n * @param {string} password \u2014 master password\n * @param {string} encSaltBase64 \u2014 enc_salt from server (login response)\n * @returns {Promise<{ auth_hash: string, masterKey: CryptoKey }>}\n */\n async function prepareLogin(password, encSaltBase64) {\n const encSalt = VaultCrypto.base64ToBuf(encSaltBase64);\n const masterKey = await VaultCrypto.deriveMasterKey(password, encSalt);\n const authHash = await deriveAuthHash(masterKey, password);\n return { auth_hash: authHash, masterKey };\n }\n\n /**\n * After successful login, unwrap vault_key from server response.\n * @param {CryptoKey} masterKey \u2014 from prepareLogin()\n * @param {string} encryptedVaultKey \u2014 from login response\n * @returns {Promise<Uint8Array>} 32-byte vault_key (DEK)\n */\n async function unlockVaultKey(masterKey, encryptedVaultKey) {\n return unwrapVaultKey(masterKey, encryptedVaultKey);\n }\n\n /**\n * Full client-side recovery: decrypt vault_key with recovery key,\n * prepare new credentials (new master password + new recovery key).\n * @param {string} recoveryKeyB64 \u2014 Base64 recovery key (as shown to user)\n * @param {string} recoveryBlobB64 \u2014 encrypted_recovery_blob from server\n * @param {string} newPassword \u2014 new master password chosen by user\n */\n async function prepareRecovery(recoveryKeyB64, recoveryBlobB64, newPassword) {\n const recoveryKey = VaultCrypto.base64ToBuf(recoveryKeyB64);\n\n // Throws DOMException if recovery key is wrong\n const { vaultKey, ecdhPrivateKey } = await unwrapRecoveryBlob(recoveryKey, recoveryBlobB64);\n\n const newEncSalt = VaultCrypto.generateSalt();\n const newMasterKey = await VaultCrypto.deriveMasterKey(newPassword, newEncSalt);\n const newAuthHash = await deriveAuthHash(newMasterKey, newPassword);\n const newEncryptedVaultKey = await wrapVaultKey(newMasterKey, vaultKey);\n\n // Keypair-preserving recovery (O3). Recovery changes master_key, which would\n // orphan the server's encrypted_ecdh_private_key (wrapped under the OLD key).\n // v2 blob \u2192 recover the SAME private key, re-wrap it under the new master_key\n // and re-derive the public key so existing shared-vault wraps stay valid.\n // v1 blob (legacy / migrated) \u2192 no key in blob, mint a fresh real pair.\n let ecdhPriv = ecdhPrivateKey;\n const preservedKeypair = !!ecdhPrivateKey;\n if (!ecdhPriv) {\n ecdhPriv = (await generateEcdhKeyPair()).privateKey;\n }\n const ecdhPublicRaw = await ecdhPublicFromPrivate(ecdhPriv);\n const newEncryptedEcdhPrivate = await wrapEcdhPrivateKey(newMasterKey, ecdhPriv);\n\n const newRecoveryKey = generateRecoveryKey();\n const newEncryptedRecoveryBlob = await wrapVaultKeyWithRecovery(newRecoveryKey, vaultKey, ecdhPriv);\n\n return {\n new_auth_hash: newAuthHash,\n new_enc_salt: VaultCrypto.bufToBase64(newEncSalt),\n new_encrypted_vault_key: newEncryptedVaultKey,\n new_encrypted_recovery_blob: newEncryptedRecoveryBlob,\n new_encrypted_ecdh_private_key: newEncryptedEcdhPrivate,\n new_ecdh_public_key: VaultCrypto.bufToBase64(ecdhPublicRaw),\n ecdh_keypair_preserved: preservedKeypair,\n new_recovery_key_b64: VaultCrypto.bufToBase64(newRecoveryKey),\n vault_key: vaultKey,\n };\n }\n\n // \u2500\u2500\u2500 Public API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n return {\n // Auth hash\n deriveAuthHash,\n\n // Vault key (DEK)\n generateVaultKey,\n wrapVaultKey,\n unwrapVaultKey,\n importVaultKey,\n\n // Per-entry encrypt/decrypt\n encryptEntry,\n decryptEntry,\n\n // Recovery\n generateRecoveryKey,\n wrapVaultKeyWithRecovery,\n unwrapVaultKeyWithRecovery,\n unwrapRecoveryBlob,\n\n // ECDH key pair\n generateEcdhKeyPair,\n wrapEcdhPrivateKey,\n importEcdhPrivateKey,\n importEcdhPublicKey,\n ecdhPublicFromPrivate,\n\n // Shared-vault key exchange (T10)\n deriveSharedWrapKey,\n wrapVaultKeyForMember,\n unwrapSharedVaultKey,\n deriveFingerprintPhrase,\n\n // ECDH migration\n prepareEcdhMigration,\n\n // Orchestrators\n prepareRegistration,\n prepareLogin,\n unlockVaultKey,\n prepareRecovery,\n };\n})();\n\nif (typeof module !== 'undefined') module.exports = VaultCloudCrypto;\n", "// \u2500\u2500\u2500 Geslar \u2014 Org Recovery Enrollment Crypto \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n// Client-side sealed-box for Family Recovery (#23 Faza 2).\n//\n// Protocol overview:\n// Enroll: ephemeralX25519 + ECDH(ephemeral, orgRecoveryPub) \u2192 HKDF \u2192 AES-256-GCM\n// payload = { vaultKey(32) \u2016 ecdhPriv(48) } encrypted with AAD\n// wire: ephemeralPub(32) \u2016 nonce(12) \u2016 ciphertext+tag\n//\n// Reset: admin decrypts using orgRecoveryPriv + ephemeralPub from wire, same AAD\n//\n// T1: client verifies org recovery pub FINGERPRINT before sealing\n//\n// AAD binding: TextEncoder(\"orgId:memberUserId:keyVersion\")\n// HKDF domain: salt = \"geslar-recovery-seal-salt-v1\"\n// info = \"geslar-org-recovery-seal-v1\"\n//\n// Requires Web Crypto (crypto.subtle). Uses the same fingerprint algorithm as\n// VaultCloudCrypto.deriveFingerprintPhrase and the server (ecdh-fingerprint.ts).\n\nconst OrgRecoveryCrypto = (() => {\n 'use strict';\n\n const EPHEMERAL_PUB_BYTES = 32;\n const IV_BYTES = 12;\n\n const HKDF_SALT = new TextEncoder().encode('geslar-recovery-seal-salt-v1');\n const HKDF_INFO = new TextEncoder().encode('geslar-org-recovery-seal-v1');\n\n // Fingerprint constants \u2014 MUST match VaultCloudCrypto and server (ecdh-fingerprint.ts).\n const FP_CONS_INITIAL = ['b','d','f','g','k','l','m','n','p','r','s','t','v','z','h','j'];\n const FP_VOWELS = ['a','e','i','o'];\n const FP_CONS_FINAL = ['k','n','s','t'];\n const FP_WORD_COUNT = 6;\n\n // \u2500\u2500 Helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n function fpSyllable(byte) {\n return FP_CONS_INITIAL[(byte >> 4) & 0x0f]\n + FP_VOWELS[(byte >> 2) & 0x03]\n + FP_CONS_FINAL[byte & 0x03];\n }\n\n async function fingerprintFromPub(publicRaw) {\n const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', publicRaw));\n const words = [];\n for (let i = 0; i < FP_WORD_COUNT; i++) words.push(fpSyllable(digest[i]));\n return words.join('-');\n }\n\n async function deriveWrapKey(sharedSecret, aad) {\n // HKDF-SHA256 over DH shared secret, with AAD mixed into info so a key\n // derived for one (orgId, memberUserId, keyVersion) triple cannot be reused.\n const combinedInfo = new Uint8Array([...HKDF_INFO, 0x00, ...aad]);\n const ikm = await crypto.subtle.importKey('raw', sharedSecret, 'HKDF', false, ['deriveBits']);\n const okm = await crypto.subtle.deriveBits(\n { name: 'HKDF', hash: 'SHA-256', salt: HKDF_SALT, info: combinedInfo },\n ikm, 256,\n );\n return crypto.subtle.importKey('raw', okm, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);\n }\n\n // F5: reject all-zero DH output (low-order point / small subgroup attack guard).\n function isAllZero(buf) {\n return new Uint8Array(buf).every(b => b === 0);\n }\n\n // \u2500\u2500 Public API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Build the Additional Authenticated Data for a recovery payload.\n * Byte format: UTF-8(\"orgId:memberUserId:keyVersion\")\n * @param {string} orgId\n * @param {string} memberUserId\n * @param {number} keyVersion \u2014 member's ECDH key version at enrollment time\n * @returns {Uint8Array}\n */\n function buildRecoveryAAD(orgId, memberUserId, keyVersion) {\n return new TextEncoder().encode(`${orgId}:${memberUserId}:${keyVersion}`);\n }\n\n /**\n * Verify an org recovery public key against a displayed fingerprint phrase.\n * Invoke before sealRecoveryPayload so the user can confirm the key out-of-band.\n * @param {Uint8Array} orgRecoveryPubRaw \u2014 raw 32-byte org recovery public key\n * @param {string} expectedFingerprint \u2014 e.g. \"bok-tas-\u2026\" (6 syllables)\n * @returns {Promise<boolean>}\n */\n async function verifyOrgRecoveryKeyFingerprint(orgRecoveryPubRaw, expectedFingerprint) {\n const computed = await fingerprintFromPub(orgRecoveryPubRaw);\n return computed === expectedFingerprint;\n }\n\n /**\n * Seal a recovery payload for the org recovery public key.\n *\n * Emits: ephemeralPub(32) \u2016 nonce(12) \u2016 ciphertext+tag\n *\n * @param {Uint8Array} orgRecoveryPubRaw \u2014 raw 32-byte org recovery public key\n * @param {Uint8Array} payload \u2014 plaintext payload (vaultKey \u2016 ecdhPriv)\n * @param {Uint8Array} aad \u2014 from buildRecoveryAAD()\n * @returns {Promise<Uint8Array>} sealedBlob\n */\n async function sealRecoveryPayload(orgRecoveryPubRaw, payload, aad) {\n // 1. Generate fresh ephemeral X25519 keypair.\n const ephemeralPair = await crypto.subtle.generateKey({ name: 'X25519' }, true, ['deriveBits']);\n const ephemeralPubRaw = new Uint8Array(\n await crypto.subtle.exportKey('raw', ephemeralPair.publicKey)\n );\n\n // 2. ECDH(ephemeralPriv, orgRecoveryPub) \u2192 256-bit shared secret.\n const orgPubKey = await crypto.subtle.importKey(\n 'raw', orgRecoveryPubRaw, { name: 'X25519' }, false, []\n );\n const sharedSecret = await crypto.subtle.deriveBits(\n { name: 'X25519', public: orgPubKey }, ephemeralPair.privateKey, 256\n );\n if (isAllZero(sharedSecret)) throw new Error('Low-order point: shared secret is all-zero');\n\n // 3. HKDF \u2192 AES-256-GCM wrap key (AAD-bound).\n const wrapKey = await deriveWrapKey(sharedSecret, aad);\n\n // 4. AES-256-GCM encrypt payload with AAD.\n const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));\n const ciphertext = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv, additionalData: aad },\n wrapKey,\n payload,\n );\n\n // 5. Pack: ephemeralPub(32) \u2016 iv(12) \u2016 ciphertext+tag.\n const blob = new Uint8Array(EPHEMERAL_PUB_BYTES + IV_BYTES + ciphertext.byteLength);\n blob.set(ephemeralPubRaw, 0);\n blob.set(iv, EPHEMERAL_PUB_BYTES);\n blob.set(new Uint8Array(ciphertext), EPHEMERAL_PUB_BYTES + IV_BYTES);\n return blob;\n }\n\n /**\n * Open (decrypt) a sealed recovery payload.\n * Throws DOMException (OperationError) if AAD or key is wrong \u2014 tamper-evident.\n *\n * @param {Uint8Array} orgRecoveryPrivPkcs8 \u2014 org recovery private key (PKCS#8 DER, 48 B)\n * @param {Uint8Array} sealedBlob \u2014 output of sealRecoveryPayload()\n * @param {Uint8Array} aad \u2014 MUST match the value used during seal\n * @returns {Promise<Uint8Array>} plaintext payload\n */\n async function openRecoveryPayload(orgRecoveryPrivPkcs8, sealedBlob, aad) {\n if (sealedBlob.length <= EPHEMERAL_PUB_BYTES + IV_BYTES) {\n throw new Error('Sealed blob is too short');\n }\n\n // 1. Unpack: ephemeralPub \u2016 iv \u2016 ciphertext+tag.\n const ephemeralPubRaw = sealedBlob.slice(0, EPHEMERAL_PUB_BYTES);\n const iv = sealedBlob.slice(EPHEMERAL_PUB_BYTES, EPHEMERAL_PUB_BYTES + IV_BYTES);\n const ciphertext = sealedBlob.slice(EPHEMERAL_PUB_BYTES + IV_BYTES);\n\n // 2. Import org recovery private key for ECDH.\n const orgPrivKey = await crypto.subtle.importKey(\n 'pkcs8', orgRecoveryPrivPkcs8, { name: 'X25519' }, false, ['deriveBits']\n );\n\n // 3. ECDH(orgPriv, ephemeralPub) \u2192 shared secret (reciprocal of seal).\n const ephemeralPubKey = await crypto.subtle.importKey(\n 'raw', ephemeralPubRaw, { name: 'X25519' }, false, []\n );\n const sharedSecret = await crypto.subtle.deriveBits(\n { name: 'X25519', public: ephemeralPubKey }, orgPrivKey, 256\n );\n if (isAllZero(sharedSecret)) throw new Error('Low-order point: shared secret is all-zero');\n\n // 4. HKDF \u2192 same wrap key.\n const wrapKey = await deriveWrapKey(sharedSecret, aad);\n\n // 5. AES-256-GCM decrypt \u2014 throws OperationError if AAD or ciphertext is wrong.\n const plaintext = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv, additionalData: aad },\n wrapKey,\n ciphertext,\n );\n return new Uint8Array(plaintext);\n }\n\n return {\n buildRecoveryAAD,\n verifyOrgRecoveryKeyFingerprint,\n sealRecoveryPayload,\n openRecoveryPayload,\n };\n})();\n\nif (typeof module !== 'undefined') module.exports = OrgRecoveryCrypto;\n", "#!/usr/bin/env -S node --\n// ^ DO NOT \"simplify\" this back to `#!/usr/bin/env node`. Node.js (>=20.6)\n// has its OWN native `--env-file` CLI flag, and it intercepts that exact\n// token ANYWHERE in argv \u2014 even after the script path, even past our own\n// `--` separator \u2014 before a single line of this file ever runs (confirmed:\n// `node script.js run --env-file .env -- echo hi` fails with Node's own\n// \"env-file not found\" error, never reaching our code). Since `geslar run\n// --env-file <f>` is the spec'd syntax (spec-agentic-access.md \u00A73.1/\u00A73.2),\n// we can't rename the flag away from the collision \u2014 instead the trailing\n// `--` in this shebang makes `env -S` split it into `node --`, so Node\n// starts with argv already past its own flag-scanning boundary. Verified\n// against BOTH npm's and pnpm's real bin-shim generators (they parse extra\n// shebang args and reproduce them in the generated .cmd/.ps1 and POSIX sh\n// wrapper) \u2014 see tests/bin-shim.test.ts, which installs the packed tarball\n// for real and executes the GENERATED shim, not `node dist/index.js`\n// directly. A standalone binary (M4, Node SEA/pkg) doesn't go through Node's\n// CLI argv-scanning at all, so this workaround is npm-distribution-only.\nimport { Command } from 'commander';\nimport { signinCommand, CLI_VERSION } from './commands/signin.js';\nimport { signoutCommand } from './commands/signout.js';\nimport { whoamiCommand } from './commands/whoami.js';\nimport { unlockCommand } from './commands/unlock.js';\nimport { lockCommand } from './commands/lock.js';\nimport { listCommand } from './commands/list.js';\nimport { readCommand } from './commands/read.js';\nimport { runCommand } from './commands/run.js';\nimport { injectCommand } from './commands/inject.js';\nimport { agentCreateCommand } from './commands/agent-create.js';\nimport { agentListCommand } from './commands/agent-list.js';\nimport { agentRevokeCommand } from './commands/agent-revoke.js';\nimport { mcpAllowCommand } from './commands/mcp-allow.js';\nimport { mcpAllowCmdCommand } from './commands/mcp-allow-cmd.js';\nimport { mcpGrantsCommand } from './commands/mcp-grants.js';\nimport { mcpRevokeCommand } from './commands/mcp-revoke.js';\nimport { printErr } from './lib/output.js';\nimport { EXIT } from './lib/errors.js';\n\nconst program = new Command();\n\nprogram\n .name('geslar')\n .description('Geslar Agentic Access CLI')\n .enablePositionalOptions()\n .option('--agent <name>', 'operate as this agent profile instead of your own account (spec-access-core.md \u00A74)')\n .version(CLI_VERSION);\n\n// Normalizes --agent into GESLAR_AGENT once, before any subcommand's action\n// runs \u2014 every command (and requireHumanContext/resolveApiContext) then only\n// ever has to check the one env var, regardless of how it was set. Runs for\n// EVERY subcommand invocation (root-level hook), so this is the single choke\n// point --agent flows through \u2014 no per-command wiring needed.\nprogram.hook('preAction', (thisCommand) => {\n const agentOpt = thisCommand.opts()['agent'] as string | undefined;\n if (agentOpt) process.env['GESLAR_AGENT'] = agentOpt;\n});\n\nprogram\n .command('signin')\n .description('Sign in via device-flow (opens a code to enter at the console)')\n .option('--api <url>', 'override the API base URL')\n .action(async (opts: { api?: string }) => {\n process.exitCode = await signinCommand(opts);\n });\n\nprogram\n .command('signout')\n .description('Revoke this session and clear the local token')\n .action(async () => {\n process.exitCode = await signoutCommand();\n });\n\nprogram\n .command('whoami')\n .description('Show the signed-in account, plan, and org context')\n .action(async () => {\n process.exitCode = await whoamiCommand();\n });\n\nprogram\n .command('unlock')\n .description('Unlock the vault for headless use (stores a TTL-bound grant, OS-wrapped)')\n .option('--ttl <duration>', 'grant lifetime, e.g. 30m, 1h (default 30m, max 8h)')\n .action(async (opts: { ttl?: string }) => {\n process.exitCode = await unlockCommand(opts);\n });\n\nprogram\n .command('lock')\n .description('Clear the unlock grant immediately')\n .action(async () => {\n process.exitCode = await lockCommand();\n });\n\nprogram\n .command('list')\n .argument('[vault]', 'only list this vault (by name)')\n .description('List vaults and item names (no values)')\n .action(async (vaultFilter: string | undefined) => {\n process.exitCode = await listCommand(vaultFilter);\n });\n\nprogram\n .command('read')\n .argument('<ref>', 'a geslar://<vault>/<item>[/<field>] reference')\n .option('-o, --output <file>', 'write the value to this file (mode 0600) instead of stdout')\n .description('Resolve a geslar:// reference and print (or write) its value')\n .action(async (ref: string, opts: { output?: string }) => {\n process.exitCode = await readCommand(ref, opts);\n });\n\nprogram\n .command('run')\n .description('Run a command with geslar:// references resolved into its environment (fail-closed)')\n .option('--env-file <file>', 'dotenv file \u2014 geslar:// values are resolved, everything else passed through literally')\n .option(\n '-e, --env <mapping>',\n 'KEY=ref (repeatable) \u2014 overrides the same key from --env-file',\n (val: string, prev: string[]) => [...prev, val],\n [] as string[],\n )\n .argument('<command>', 'command to run')\n .argument('[args...]', 'arguments for the command')\n .enablePositionalOptions()\n .passThroughOptions()\n .action(async (command: string, args: string[], opts: { envFile?: string; env: string[] }) => {\n process.exitCode = await runCommand(command, args, opts);\n });\n\nprogram\n .command('inject')\n .description('Substitute {{ geslar://... }} placeholders in a template file (fail-closed)')\n .requiredOption('-i, --input <file>', 'template file')\n .requiredOption('-o, --output <file>', 'output file (mode 0600)')\n .action(async (opts: { input: string; output: string }) => {\n process.exitCode = await injectCommand(opts);\n });\n\nconst agent = program\n .command('agent')\n .description('Manage agent profiles \u2014 scoped machine credentials (spec-access-core.md)');\n\nagent\n .command('create')\n .argument('<name>', 'profile name')\n .description('Create an agent profile scoped to one or more vaults (TTY required, fresh TOTP)')\n .option('--vault <name>', 'vault to grant access to (repeatable)', (val: string, prev: string[]) => [...prev, val], [] as string[])\n .option('--allow-read', 'opt-in: also grant the read capability (default is run+inject only)')\n .option('--expires <duration>', 'e.g. 90d, or \"never\" (default: 90d)')\n .option('--show-token', 'print the plaintext token once (otherwise it only goes to local storage)')\n .action(async (name: string, opts: { vault: string[]; allowRead?: boolean; expires?: string; showToken?: boolean }) => {\n process.exitCode = await agentCreateCommand(name, opts);\n });\n\nagent\n .command('list')\n .description('List your agent profiles')\n .action(async () => {\n process.exitCode = await agentListCommand({});\n });\n\nagent\n .command('revoke')\n .argument('<name>', 'profile name')\n .description('Revoke an agent profile and clear its local token')\n .action(async (name: string) => {\n process.exitCode = await agentRevokeCommand(name, {});\n });\n\nconst mcp = program\n .command('mcp')\n .description('Model Context Protocol server + pre-grant management (spec-mcp.md)');\n\nmcp\n .command('allow')\n .argument('<scope>', 'vault (or vault/item) to pre-approve for MCP write/execute tools')\n .option('--ttl <duration>', 'grant lifetime, e.g. 1h (default 1h, max 8h)')\n .option('--max-uses <n>', 'limit the number of times this grant may be consumed', (v: string) => parseInt(v, 10))\n .action(async (scope: string, opts: { ttl?: string; maxUses?: number }) => {\n process.exitCode = await mcpAllowCommand(scope, opts);\n });\n\nmcp\n .command('allow-cmd')\n .argument('<pattern>', 'command pattern for geslar_run, e.g. \"npm test\" (supports * wildcard)')\n .option('--ttl <duration>', 'grant lifetime, e.g. 1h (default 1h, max 8h)')\n .option('--max-uses <n>', 'limit the number of times this grant may be consumed', (v: string) => parseInt(v, 10))\n .action(async (pattern: string, opts: { ttl?: string; maxUses?: number }) => {\n process.exitCode = await mcpAllowCmdCommand(pattern, opts);\n });\n\nmcp\n .command('grants')\n .description('List active MCP pre-grants')\n .action(async () => { process.exitCode = await mcpGrantsCommand(); });\n\nmcp\n .command('revoke')\n .argument('[id]', 'grant id to revoke')\n .option('--all', 'revoke every active grant')\n .action(async (id: string | undefined, opts: { all?: boolean }) => {\n process.exitCode = await mcpRevokeCommand(id, opts);\n });\n\n// An IIFE, not top-level await: the npm-published dist/index.js is ESM (fine\n// either way), but the standalone-binary build (scripts/build-binary.mjs)\n// bundles this same entry point to CJS for Node's SEA feature, which doesn't\n// support top-level await.\nvoid (async () => {\n try {\n await program.parseAsync(process.argv);\n } catch (err) {\n printErr((err as Error).message);\n process.exitCode = EXIT.GENERAL;\n }\n})();\n", "import { hostname, platform } from 'node:os';\nimport { loadOrInitConfig } from '../lib/config.js';\nimport { saveSession } from '../lib/session.js';\nimport { print, printErr } from '../lib/output.js';\nimport { CliError, EXIT } from '../lib/errors.js';\nimport { selectBackend, createCliTokenStore } from '../token-store/index.js';\nimport { startDeviceFlow, pollDeviceFlow } from '../device-flow.js';\n\nexport const CLI_VERSION = '0.2.0';\n\nexport async function signinCommand(opts: { api?: string }): Promise<number> {\n const config = await loadOrInitConfig();\n const baseUrl = opts.api ?? config.apiBase;\n\n try {\n const start = await startDeviceFlow(baseUrl, {\n device_fingerprint: config.deviceFingerprint,\n hostname: hostname(),\n os: platform(),\n cli_version: CLI_VERSION,\n });\n\n print('');\n print(` Your code: ${start.user_code}`);\n print('');\n print(` Open ${start.verification_uri} and enter the code above to sign in.`);\n print(' (Type the code yourself \u2014 never follow a link that already has it filled in.)');\n print('');\n print('Waiting for approval...');\n\n const result = await pollDeviceFlow(baseUrl, start);\n\n const backend = await selectBackend();\n const tokenStore = await createCliTokenStore(backend);\n tokenStore.set({ access_token: result.access_token, refresh_token: result.refresh_token });\n await tokenStore.flush();\n\n await saveSession({ email: result.email, userId: result.user_id, plan: result.plan, apiBase: baseUrl });\n\n print(`Signed in as ${result.email} (${result.plan} plan).`);\n return EXIT.OK;\n } catch (err) {\n if (err instanceof CliError) {\n printErr(err.message);\n return err.exitCode;\n }\n printErr((err as Error).message);\n return EXIT.GENERAL;\n }\n}\n", "import { randomUUID } from 'node:crypto';\nimport { readFile, writeFile } from 'node:fs/promises';\nimport { configFilePath, ensureConfigDir } from './paths.js';\n\nexport const DEFAULT_API_BASE = 'https://api.geslar.app';\n\nexport interface CliConfig {\n /** Stable per-install id sent as device_fingerprint on every `signin` \u2014 lets\n * the server recognize \"this CLI install\" across sign-ins instead of\n * minting a new device row every time (see resolveDeviceSlot). */\n deviceFingerprint: string;\n apiBase: string;\n}\n\nconst CONFIG_FILE = 'config.json';\n\n/** Load the persisted config, creating one (with a fresh device_fingerprint) on first run. */\nexport async function loadOrInitConfig(): Promise<CliConfig> {\n const path = configFilePath(CONFIG_FILE);\n try {\n const raw = await readFile(path, 'utf-8');\n const parsed = JSON.parse(raw) as Partial<CliConfig>;\n if (parsed.deviceFingerprint && parsed.apiBase) {\n return { deviceFingerprint: parsed.deviceFingerprint, apiBase: parsed.apiBase };\n }\n } catch {\n // Missing or corrupt \u2014 fall through to (re)initialize.\n }\n const config: CliConfig = { deviceFingerprint: `cli-${randomUUID()}`, apiBase: DEFAULT_API_BASE };\n await ensureConfigDir();\n await writeFile(path, JSON.stringify(config, null, 2), 'utf-8');\n return config;\n}\n", "import { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { mkdir } from 'node:fs/promises';\n\n/** ~/.geslar \u2014 everything the CLI persists locally lives under this one directory. */\nexport function configDir(): string {\n return join(homedir(), '.geslar');\n}\n\nexport async function ensureConfigDir(): Promise<string> {\n const dir = configDir();\n await mkdir(dir, { recursive: true });\n return dir;\n}\n\nexport function configFilePath(name: string): string {\n return join(configDir(), name);\n}\n", "import { readFile, writeFile, rm } from 'node:fs/promises';\nimport { configFilePath, ensureConfigDir } from './paths.js';\n\n/** Non-secret identity cache \u2014 set by `signin`, cleared by `signout`. Never\n * holds tokens (those live in the OS-backed token store, see ../token-store). */\nexport interface CliSession {\n email: string;\n userId: string;\n plan: string;\n apiBase: string;\n}\n\nconst SESSION_FILE = 'session.json';\n\nexport async function loadSession(): Promise<CliSession | null> {\n try {\n const raw = await readFile(configFilePath(SESSION_FILE), 'utf-8');\n return JSON.parse(raw) as CliSession;\n } catch {\n return null;\n }\n}\n\nexport async function saveSession(session: CliSession): Promise<void> {\n await ensureConfigDir();\n await writeFile(configFilePath(SESSION_FILE), JSON.stringify(session, null, 2), 'utf-8');\n}\n\nexport async function clearSession(): Promise<void> {\n await rm(configFilePath(SESSION_FILE), { force: true });\n}\n", "/**\n * Output scrubber (spec \u00A73.2/\u00A78.1) \u2014 every value the CLI resolves from a\n * vault gets registered here; every string the CLI itself writes (stdout,\n * stderr, error messages, crash output) is passed through `scrub()` first.\n * This is the last line of defense against a secret accidentally ending up\n * in a log line, an error message, or an uncaught-exception dump.\n *\n * Module-level singleton by design \u2014 one CLI invocation, one process, one\n * scrubber. Values are matched longest-first so a short value can't mask a\n * longer one that contains it as a substring.\n */\n\nconst registered = new Set<string>();\n\n/** Register a resolved secret value so every future print/error masks it. */\nexport function registerSecret(value: string): void {\n if (value.length === 0) return; // an empty registration would match everything\n registered.add(value);\n}\n\n/** Replace every registered value in `text` with `***`. No-op if nothing registered. */\nexport function scrub(text: string): string {\n if (registered.size === 0) return text;\n let out = text;\n const values = [...registered].sort((a, b) => b.length - a.length);\n for (const value of values) {\n out = out.split(value).join('***');\n }\n return out;\n}\n\n/** Test-only: reset registered values between test cases. */\nexport function _resetScrubberForTests(): void {\n registered.clear();\n}\n", "import { scrub } from './scrubber.js';\n\n/** Zero-dependency stdout/stderr helpers. No color library per spec \u00A71 (only\n * @geslar/core + commander). Every write goes through the scrubber (\u00A73.2/\u00A78.1)\n * \u2014 this is the single choke point ALL CLI output passes through. */\n\nexport function print(message: string): void {\n process.stdout.write(`${scrub(message)}\\n`);\n}\n\nexport function printErr(message: string): void {\n process.stderr.write(`geslar: ${scrub(message)}\\n`);\n}\n", "/** Exit codes \u2014 spec-agentic-access.md \u00A73.5. */\nexport const EXIT = {\n OK: 0,\n GENERAL: 1,\n AUTH: 2,\n ENTITLEMENT: 3,\n UNRESOLVABLE_REF: 4,\n GRANT_DENIED: 5,\n VAULT_LOCKED: 6,\n} as const;\n\nexport type ExitCode = (typeof EXIT)[keyof typeof EXIT];\n\n/** A CLI-level failure that maps directly to an exit code and a user-facing message. */\nexport class CliError extends Error {\n constructor(\n public readonly exitCode: ExitCode,\n message: string,\n ) {\n super(message);\n this.name = 'CliError';\n }\n}\n", "import { spawn } from 'node:child_process';\nimport { readFile, writeFile, rm } from 'node:fs/promises';\nimport { configFilePath, ensureConfigDir } from '../lib/paths.js';\nimport type { TokenStoreBackend } from './types.js';\n\n/**\n * Windows \u2014 DPAPI (spec \u00A73.4/R5). `cmdkey` cannot read back stored secrets\n * (write/list only), so it is NOT usable here; instead we shell out to the\n * PowerShell that ships with every Windows install and call\n * `System.Security.Cryptography.ProtectedData` (CurrentUser scope) directly.\n * No native Node addon required.\n *\n * The plaintext blob travels to/from PowerShell over STDIN/STDOUT only \u2014\n * never as a command-line argument or environment variable (spec \u00A78.2).\n */\n\nconst PROTECT_SCRIPT = `\n$ErrorActionPreference = 'Stop'\nAdd-Type -AssemblyName System.Security\n$b64 = [Console]::In.ReadToEnd()\n$bytes = [Convert]::FromBase64String($b64)\n$protected = [System.Security.Cryptography.ProtectedData]::Protect(\n $bytes, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)\n[Console]::Out.Write([Convert]::ToBase64String($protected))\n`;\n\nconst UNPROTECT_SCRIPT = `\n$ErrorActionPreference = 'Stop'\nAdd-Type -AssemblyName System.Security\n$b64 = [Console]::In.ReadToEnd()\n$bytes = [Convert]::FromBase64String($b64)\n$plain = [System.Security.Cryptography.ProtectedData]::Unprotect(\n $bytes, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)\n[Console]::Out.Write([Convert]::ToBase64String($plain))\n`;\n\nfunction runPowerShell(script: string, stdinData: string): Promise<string> {\n return new Promise((resolve, reject) => {\n const child = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], {\n stdio: ['pipe', 'pipe', 'pipe'],\n windowsHide: true,\n });\n let stdout = '';\n let stderr = '';\n child.stdout.on('data', (chunk: Buffer) => { stdout += chunk.toString('utf-8'); });\n child.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString('utf-8'); });\n child.on('error', reject);\n child.on('close', (code) => {\n if (code === 0) resolve(stdout.trim());\n else reject(new Error(`powershell exited ${code}: ${stderr.trim() || 'DPAPI operation failed'}`));\n });\n child.stdin.write(stdinData);\n child.stdin.end();\n });\n}\n\n/**\n * @param namespace Selects the on-disk file (`<namespace>.dpapi` under\n * ~/.geslar). `'tokens'` is the M1 auth-token store (do not rename \u2014 already\n * shipped); `'vault-grant'` (M2) is a separate file so revoking one never\n * touches the other.\n */\nexport function createWindowsDpapiBackend(namespace: string): TokenStoreBackend {\n const tokenFile = `${namespace}.dpapi`;\n\n return {\n name: 'windows-dpapi',\n\n async load(): Promise<string | null> {\n let protectedB64: string;\n try {\n protectedB64 = await readFile(configFilePath(tokenFile), 'utf-8');\n } catch {\n return null;\n }\n if (!protectedB64.trim()) return null;\n const plainB64 = await runPowerShell(UNPROTECT_SCRIPT, protectedB64);\n return Buffer.from(plainB64, 'base64').toString('utf-8');\n },\n\n async save(data: string): Promise<void> {\n const plainB64 = Buffer.from(data, 'utf-8').toString('base64');\n const protectedB64 = await runPowerShell(PROTECT_SCRIPT, plainB64);\n await ensureConfigDir();\n await writeFile(configFilePath(tokenFile), protectedB64, { encoding: 'utf-8', mode: 0o600 });\n },\n\n async clear(): Promise<void> {\n await rm(configFilePath(tokenFile), { force: true });\n },\n };\n}\n\nexport const windowsDpapiBackend: TokenStoreBackend = createWindowsDpapiBackend('tokens');\n", "import { spawn } from 'node:child_process';\nimport { userInfo } from 'node:os';\nimport type { TokenStoreBackend } from './types.js';\n\n/**\n * macOS \u2014 login keychain via the built-in `security` CLI (spec \u00A73.4). No\n * native dependency. `security add-generic-password` has no stdin mode for\n * the secret value (`-w`), so the value is briefly visible in `ps` output\n * during that one call \u2014 an accepted, documented platform limitation shared\n * by every keychain-backed CLI on macOS (e.g. `gh`, 1Password CLI). Lookup\n * (`-w` on `find-generic-password`) only prints to stdout, no exposure there.\n */\n\nfunction account(): string {\n return userInfo().username;\n}\n\nfunction run(args: string[], input?: string): Promise<{ code: number | null; stdout: string; stderr: string }> {\n return new Promise((resolve, reject) => {\n const child = spawn('security', args, { stdio: ['pipe', 'pipe', 'pipe'] });\n let stdout = '';\n let stderr = '';\n child.stdout.on('data', (c: Buffer) => { stdout += c.toString('utf-8'); });\n child.stderr.on('data', (c: Buffer) => { stderr += c.toString('utf-8'); });\n child.on('error', reject);\n child.on('close', (code) => resolve({ code, stdout, stderr }));\n if (input !== undefined) child.stdin.write(input);\n child.stdin.end();\n });\n}\n\n/**\n * @param namespace Selects the keychain service name. `'tokens'` maps to the\n * original M1 service name (`geslar-cli`, unchanged \u2014 already shipped, do\n * not rename or existing signins silently stop resolving); any other\n * namespace (e.g. `'vault-grant'`, M2) gets its own `geslar-cli-<namespace>`\n * item so revoking one never touches the other.\n */\nexport function createMacosKeychainBackend(namespace: string): TokenStoreBackend {\n const service = namespace === 'tokens' ? 'geslar-cli' : `geslar-cli-${namespace}`;\n\n return {\n name: 'macos-keychain',\n\n async load(): Promise<string | null> {\n const res = await run(['find-generic-password', '-a', account(), '-s', service, '-w']);\n if (res.code !== 0) return null; // not found \u2014 not an error\n return res.stdout.trim();\n },\n\n async save(data: string): Promise<void> {\n const res = await run(['add-generic-password', '-a', account(), '-s', service, '-w', data, '-U']);\n if (res.code !== 0) {\n throw new Error(`security add-generic-password failed: ${res.stderr.trim()}`);\n }\n },\n\n async clear(): Promise<void> {\n await run(['delete-generic-password', '-a', account(), '-s', service]);\n // Non-zero exit here just means \"nothing to delete\" \u2014 not an error.\n },\n };\n}\n\nexport const macosKeychainBackend: TokenStoreBackend = createMacosKeychainBackend('tokens');\n", "import { spawn } from 'node:child_process';\nimport { userInfo } from 'node:os';\nimport type { TokenStoreBackend } from './types.js';\n\n/**\n * Linux \u2014 libsecret via the `secret-tool` CLI (spec \u00A73.4), when present. No\n * native dependency. Both store and lookup pass the secret over stdin/stdout\n * only \u2014 never argv or env.\n */\n\nfunction account(): string {\n return userInfo().username;\n}\n\nfunction run(args: string[], input?: string): Promise<{ code: number | null; stdout: string; stderr: string }> {\n return new Promise((resolve, reject) => {\n const child = spawn('secret-tool', args, { stdio: ['pipe', 'pipe', 'pipe'] });\n let stdout = '';\n let stderr = '';\n child.stdout.on('data', (c: Buffer) => { stdout += c.toString('utf-8'); });\n child.stderr.on('data', (c: Buffer) => { stderr += c.toString('utf-8'); });\n child.on('error', reject);\n child.on('close', (code) => resolve({ code, stdout, stderr }));\n if (input !== undefined) child.stdin.write(input);\n child.stdin.end();\n });\n}\n\n/** Best-effort probe: is `secret-tool` on PATH and does a D-Bus secret service answer? */\nexport async function isSecretToolAvailable(): Promise<boolean> {\n try {\n const res = await run(['lookup', 'service', 'geslar-cli-probe', 'account', 'probe']);\n // Exit 1 (\"not found\") means secret-tool AND the secret service both work.\n // Anything that fails to spawn (ENOENT) rejects instead of resolving.\n return res.code === 0 || res.code === 1;\n } catch {\n return false;\n }\n}\n\n/**\n * @param namespace Selects the libsecret service name. `'tokens'` maps to\n * the original M1 service name (`geslar-cli`, unchanged \u2014 already shipped);\n * any other namespace (e.g. `'vault-grant'`, M2) gets its own\n * `geslar-cli-<namespace>` item.\n */\nexport function createLinuxSecretToolBackend(namespace: string): TokenStoreBackend {\n const service = namespace === 'tokens' ? 'geslar-cli' : `geslar-cli-${namespace}`;\n\n return {\n name: 'linux-secret-tool',\n\n async load(): Promise<string | null> {\n const res = await run(['lookup', 'service', service, 'account', account()]);\n if (res.code !== 0) return null;\n return res.stdout.trim() || null;\n },\n\n async save(data: string): Promise<void> {\n const res = await run(\n ['store', '--label', 'Geslar CLI token', 'service', service, 'account', account()],\n data,\n );\n if (res.code !== 0) {\n throw new Error(`secret-tool store failed: ${res.stderr.trim()}`);\n }\n },\n\n async clear(): Promise<void> {\n await run(['clear', 'service', service, 'account', account()]);\n },\n };\n}\n\nexport const linuxSecretToolBackend: TokenStoreBackend = createLinuxSecretToolBackend('tokens');\n", "import { hkdfSync, randomBytes, createCipheriv, createDecipheriv } from 'node:crypto';\nimport { userInfo } from 'node:os';\nimport { readFile, writeFile, rm } from 'node:fs/promises';\nimport { configFilePath, ensureConfigDir } from '../lib/paths.js';\nimport { getMachineId } from './machine-id.js';\nimport type { TokenStoreBackend } from './types.js';\n\n/**\n * Fallback backend (spec \u00A73.4) \u2014 used only when no OS-vaulted mechanism is\n * available (Linux without `secret-tool`/a running secret service). Weaker\n * than DPAPI/Keychain/libsecret: the key is derived from machine+user\n * identity rather than protected by the OS credential vault, so anyone who\n * can read this user's files on this machine can decrypt it. `weak: true`\n * makes the CLI print a loud warning on every use (R5).\n */\n\nconst HKDF_SALT = Buffer.from('geslar-cli-token-store-v1', 'utf-8');\nconst HKDF_INFO = Buffer.from('geslar-cli-token-store', 'utf-8');\nconst IV_LEN = 12;\n\nasync function deriveKey(): Promise<Buffer> {\n const machineId = await getMachineId();\n const ikm = Buffer.from(`${machineId}|${userInfo().username}`, 'utf-8');\n const key = hkdfSync('sha256', ikm, HKDF_SALT, HKDF_INFO, 32);\n return Buffer.from(key);\n}\n\n/**\n * @param namespace Selects the on-disk file (`<namespace>.enc` under\n * ~/.geslar). `'tokens'` is the M1 auth-token store (do not rename \u2014\n * already shipped); `'vault-grant'` (M2) is a separate file.\n */\nexport function createFallbackEncryptedFileBackend(namespace: string): TokenStoreBackend {\n const tokenFile = `${namespace}.enc`;\n\n return {\n name: 'fallback-hkdf-file',\n weak: true,\n\n async load(): Promise<string | null> {\n let blob: Buffer;\n try {\n blob = await readFile(configFilePath(tokenFile));\n } catch {\n return null;\n }\n if (blob.length < IV_LEN + 16) return null;\n const key = await deriveKey();\n const iv = blob.subarray(0, IV_LEN);\n const tag = blob.subarray(blob.length - 16);\n const ciphertext = blob.subarray(IV_LEN, blob.length - 16);\n const decipher = createDecipheriv('aes-256-gcm', key, iv);\n decipher.setAuthTag(tag);\n const plain = Buffer.concat([decipher.update(ciphertext), decipher.final()]);\n return plain.toString('utf-8');\n },\n\n async save(data: string): Promise<void> {\n const key = await deriveKey();\n const iv = randomBytes(IV_LEN);\n const cipher = createCipheriv('aes-256-gcm', key, iv);\n const ciphertext = Buffer.concat([cipher.update(data, 'utf-8'), cipher.final()]);\n const tag = cipher.getAuthTag();\n await ensureConfigDir();\n await writeFile(configFilePath(tokenFile), Buffer.concat([iv, ciphertext, tag]), { mode: 0o600 });\n },\n\n async clear(): Promise<void> {\n await rm(configFilePath(tokenFile), { force: true });\n },\n };\n}\n\nexport const fallbackEncryptedFileBackend: TokenStoreBackend = createFallbackEncryptedFileBackend('tokens');\n", "import { readFile, writeFile } from 'node:fs/promises';\nimport { randomBytes } from 'node:crypto';\nimport { configFilePath, ensureConfigDir } from '../lib/paths.js';\n\n/**\n * Best-effort stable machine identifier for the HKDF fallback backend (spec\n * \u00A73.4, weakest tier). Tries real OS machine ids first; if none is readable\n * (containers, locked-down systems), falls back to a random id generated\n * once and persisted locally \u2014 still stable per-machine-per-install, just\n * not tied to OS-level machine identity.\n */\nexport async function getMachineId(): Promise<string> {\n const fromOs = await readOsMachineId();\n if (fromOs) return fromOs;\n return getOrCreatePersistedId();\n}\n\nasync function readOsMachineId(): Promise<string | null> {\n if (process.platform === 'linux') {\n for (const path of ['/etc/machine-id', '/var/lib/dbus/machine-id']) {\n try {\n const id = (await readFile(path, 'utf-8')).trim();\n if (id) return id;\n } catch {\n // try next\n }\n }\n }\n return null;\n}\n\nconst ID_FILE = 'machine-salt';\n\nasync function getOrCreatePersistedId(): Promise<string> {\n const path = configFilePath(ID_FILE);\n try {\n const existing = (await readFile(path, 'utf-8')).trim();\n if (existing) return existing;\n } catch {\n // create below\n }\n const id = randomBytes(32).toString('hex');\n await ensureConfigDir();\n await writeFile(path, id, { encoding: 'utf-8', mode: 0o600 });\n return id;\n}\n", "import type { TokenStore, TokenPair } from '@geslar/core';\nimport { printErr } from '../lib/output.js';\nimport { createWindowsDpapiBackend } from './windows.js';\nimport { createMacosKeychainBackend } from './macos.js';\nimport { createLinuxSecretToolBackend, isSecretToolAvailable } from './linux.js';\nimport { createFallbackEncryptedFileBackend } from './fallback.js';\nimport type { TokenStoreBackend } from './types.js';\n\nexport type { TokenStoreBackend } from './types.js';\n\n/** Pick the right OS-backed mechanism for this platform (spec \u00A73.4 table).\n * `namespace` selects which secret this backend stores \u2014 `'tokens'` (M1\n * auth token pair, the default) and `'vault-grant'` (M2 `geslar unlock`\n * grant) are stored under separate OS items so revoking one never touches\n * the other. */\nexport async function selectBackend(namespace: string = 'tokens'): Promise<TokenStoreBackend> {\n if (process.platform === 'win32') return createWindowsDpapiBackend(namespace);\n if (process.platform === 'darwin') return createMacosKeychainBackend(namespace);\n if (await isSecretToolAvailable()) return createLinuxSecretToolBackend(namespace);\n return createFallbackEncryptedFileBackend(namespace);\n}\n\nexport interface CliTokenStore extends TokenStore {\n /** Await in-flight persist writes before the process exits. */\n flush(): Promise<void>;\n readonly backendName: string;\n}\n\n/**\n * ApiClient's TokenStore is synchronous (get/set), but every OS-backed\n * mechanism here is async (spawns a helper process or hits a keychain\n * daemon). We bridge the two the same way desktop apps bridge async secret\n * storage to a sync in-memory cache: load once up front, keep an in-memory\n * mirror for synchronous reads, and write-through asynchronously on every\n * `set()` \u2014 serialized so concurrent writes can't interleave and corrupt the\n * backend. Callers MUST `await flush()` before the process exits.\n */\nexport async function createCliTokenStore(backend: TokenStoreBackend): Promise<CliTokenStore> {\n if (backend.weak) {\n 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.');\n }\n\n let current: TokenPair | null = null;\n try {\n const raw = await backend.load();\n current = raw ? (JSON.parse(raw) as TokenPair) : null;\n } catch (err) {\n printErr(`could not read stored session (${(err as Error).message}) \u2014 treating as signed out`);\n current = null;\n }\n\n let pending: Promise<void> = Promise.resolve();\n\n return {\n backendName: backend.name,\n get: () => current,\n set: (tokens: TokenPair | null) => {\n current = tokens;\n pending = pending\n .then(() => (tokens ? backend.save(JSON.stringify(tokens)) : backend.clear()))\n .catch((err: unknown) => {\n printErr(`failed to persist session (${(err as Error).message})`);\n });\n },\n flush: () => pending,\n };\n}\n", "import { CliError, EXIT } from './lib/errors.js';\n\n/** RFC 8628 device authorization flow \u2014 client side (spec \u00A73.3). */\n\nexport interface DeviceStartResult {\n device_code: string;\n user_code: string;\n verification_uri: string;\n expires_in: number;\n interval: number;\n}\n\nexport interface DevicePollSuccess {\n access_token: string;\n refresh_token: string;\n token_type: string;\n expires_in: number;\n user_id: string;\n email: string;\n plan: string;\n}\n\nexport interface DeviceFlowClientInfo {\n device_fingerprint: string;\n hostname?: string;\n os?: string;\n cli_version?: string;\n}\n\ntype Fetch = typeof fetch;\n\nasync function readJson(res: Response): Promise<Record<string, unknown>> {\n const text = await res.text();\n return text ? (JSON.parse(text) as Record<string, unknown>) : {};\n}\n\nexport async function startDeviceFlow(\n baseUrl: string,\n info: DeviceFlowClientInfo,\n fetchImpl: Fetch = fetch,\n): Promise<DeviceStartResult> {\n const res = await fetchImpl(`${baseUrl}/v1/auth/device/start`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(info),\n });\n const body = await readJson(res);\n if (!res.ok) {\n throw new CliError(EXIT.GENERAL, (body['detail'] as string) ?? `Could not start sign-in (HTTP ${res.status})`);\n }\n return body as unknown as DeviceStartResult;\n}\n\nexport interface PollOptions {\n /** Called once per tick \u2014 lets the caller print progress (\".\"), stays silent by default. */\n onTick?: () => void;\n /** Injectable for tests \u2014 avoids real timers slowing down the suite. */\n sleep?: (ms: number) => Promise<void>;\n}\n\n/**\n * Poll until approved, denied, or expired. Client-side mirrors the server's\n * state machine 1:1 (spec \u00A73.3 exit codes): expired \u2192 2, denied \u2192 5.\n */\nexport async function pollDeviceFlow(\n baseUrl: string,\n start: DeviceStartResult,\n fetchImpl: Fetch = fetch,\n opts: PollOptions = {},\n): Promise<DevicePollSuccess> {\n const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));\n let interval = start.interval;\n const deadline = Date.now() + start.expires_in * 1000;\n\n for (;;) {\n if (Date.now() >= deadline) {\n throw new CliError(EXIT.AUTH, 'Device code expired \u2014 run `geslar signin` again');\n }\n await sleep(interval * 1000);\n opts.onTick?.();\n\n const res = await fetchImpl(`${baseUrl}/v1/auth/device/poll`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ device_code: start.device_code }),\n });\n const body = await readJson(res);\n\n if (res.ok) {\n return body as unknown as DevicePollSuccess;\n }\n\n switch (body['code']) {\n case 'device-flow/authorization-pending':\n continue;\n case 'device-flow/slow-down':\n interval = typeof body['interval'] === 'number' ? body['interval'] : interval + 5;\n continue;\n case 'device-flow/expired-token':\n throw new CliError(EXIT.AUTH, 'Device code expired \u2014 run `geslar signin` again');\n case 'device-flow/access-denied':\n throw new CliError(EXIT.GRANT_DENIED, 'Sign-in request was denied in the console');\n default:\n throw new CliError(EXIT.GENERAL, (body['detail'] as string) ?? `Sign-in failed (HTTP ${res.status})`);\n }\n }\n}\n", "import { selectBackend } from '../token-store/index.js';\nimport { CliError, EXIT } from '../lib/errors.js';\nimport type { UnlockedKeys } from './unlock.js';\n\n/** `geslar unlock` session grant (spec \u00A73.7, R2) \u2014 the OS-wrapped vault key\n * survives across headless CLI/MCP invocations without re-prompting for the\n * master password. Stored under its OWN OS item (`selectBackend('vault-grant')`,\n * distinct from the M1 auth-token item) so `geslar lock`/`signout` clearing\n * one never clears the other. */\n\nexport const DEFAULT_TTL_SEC = 30 * 60; // 30 min\nexport const MAX_TTL_SEC = 8 * 60 * 60; // 8 h\n\ninterface VaultGrant {\n dek: string; // base64 raw DEK bytes\n ecdhPrivRaw: string | null; // base64\n createdAt: number; // ms epoch\n ttlSec: number;\n}\n\n/** Parse `--ttl` values like `30m`, `1h`, `90s` (bare number = minutes). Clamps to MAX_TTL_SEC. */\nexport function parseTtl(input: string | undefined): number {\n if (!input) return DEFAULT_TTL_SEC;\n const m = /^(\\d+)\\s*(s|m|h)?$/.exec(input.trim());\n if (!m) {\n throw new CliError(EXIT.GENERAL, `Invalid --ttl value \"${input}\" \u2014 use e.g. 30m, 1h, 90s`);\n }\n const n = parseInt(m[1]!, 10);\n const unit = m[2] ?? 'm';\n const sec = unit === 's' ? n : unit === 'h' ? n * 3600 : n * 60;\n if (sec <= 0) {\n throw new CliError(EXIT.GENERAL, `--ttl must be positive, got \"${input}\"`);\n }\n return Math.min(sec, MAX_TTL_SEC);\n}\n\nexport async function saveVaultGrant(unlocked: UnlockedKeys, ttlSec: number): Promise<void> {\n const grant: VaultGrant = {\n dek: Buffer.from(unlocked.dekRaw).toString('base64'),\n ecdhPrivRaw: unlocked.ecdhPrivRaw ? Buffer.from(unlocked.ecdhPrivRaw).toString('base64') : null,\n createdAt: Date.now(),\n ttlSec,\n };\n const backend = await selectBackend('vault-grant');\n await backend.save(JSON.stringify(grant));\n}\n\n/** Returns null when there is no grant, it's malformed, or it has expired\n * (an expired grant is also actively cleared \u2014 self-healing, no stale file\n * lingering past its TTL). */\nexport async function loadVaultGrant(): Promise<UnlockedKeys | null> {\n const backend = await selectBackend('vault-grant');\n const raw = await backend.load();\n if (!raw) return null;\n\n let grant: VaultGrant;\n try {\n grant = JSON.parse(raw) as VaultGrant;\n } catch {\n return null;\n }\n\n if (Date.now() - grant.createdAt > grant.ttlSec * 1000) {\n await backend.clear();\n return null;\n }\n\n return {\n dekRaw: new Uint8Array(Buffer.from(grant.dek, 'base64')),\n ecdhPrivRaw: grant.ecdhPrivRaw ? new Uint8Array(Buffer.from(grant.ecdhPrivRaw, 'base64')) : null,\n };\n}\n\nexport async function clearVaultGrant(): Promise<void> {\n const backend = await selectBackend('vault-grant');\n await backend.clear();\n}\n", "import { loadSession, clearSession } from '../lib/session.js';\nimport { loadOrInitConfig } from '../lib/config.js';\nimport { print, printErr } from '../lib/output.js';\nimport { EXIT } from '../lib/errors.js';\nimport { selectBackend, createCliTokenStore } from '../token-store/index.js';\nimport { clearVaultGrant } from '../vault/grant.js';\n\n/**\n * Revoke server-side + wipe the local session. NOTE: intentionally does NOT\n * use ApiClient.serverLogout() \u2014 that method sends an empty body and relies\n * on the httpOnly refresh cookie (console-only path); Bearer clients like\n * this CLI must send `refresh_token` in the body for POST /v1/auth/logout to\n * actually find and delete the row server-side (src/plugins/auth/routes.ts).\n */\nexport async function signoutCommand(): Promise<number> {\n const backend = await selectBackend();\n const tokenStore = await createCliTokenStore(backend);\n const tokens = tokenStore.get();\n\n if (!tokens) {\n print('Not signed in.');\n return EXIT.OK;\n }\n\n const config = await loadOrInitConfig();\n const session = await loadSession();\n const baseUrl = session?.apiBase ?? config.apiBase;\n\n try {\n await fetch(`${baseUrl}/v1/auth/logout`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ refresh_token: tokens.refresh_token }),\n });\n } catch (err) {\n // Best-effort revoke \u2014 local session is cleared regardless (spec \u00A73.5: signout\n // must never leave a stale-but-unrevocable local session).\n printErr(`could not reach the server to revoke the session (${(err as Error).message}) \u2014 clearing local session anyway`);\n }\n\n tokenStore.set(null);\n await tokenStore.flush();\n await clearSession();\n // Spec \u00A73.7: signout is one of the automatic vault-lock triggers.\n await clearVaultGrant();\n\n print('Signed out.');\n return EXIT.OK;\n}\n", "// Geslar API client (shared). Fetch-based, bearer + refresh rotation.\n// E2EE invariant: this client never sends the master password or derived keys \u2014\n// only auth_hash and opaque wrapped blobs. All crypto happens in @geslar/core/crypto.\n\nimport type {\n LoginResponse,\n PreloginResponse,\n RegisterResponse,\n RefreshResponse,\n MfaRequiredResponse,\n MfaListResponse,\n MfaEnrollTotpResponse,\n RecoverInitResponse,\n RecoverCompleteResponse,\n Org,\n OrgBranding,\n OrgMember,\n EntitlementsBundle,\n TokenPair,\n MemberRole,\n InviteResult,\n CollectionSummary,\n CollectionMember,\n MemberKeyResult,\n VaultEntryWire,\n PutEntryResult,\n PublicPlan,\n CollectionRotationStage,\n CollectionRotationCommit,\n RemoveCollectionMemberResult,\n CredentialAction,\n PasswordKnownRow,\n CredentialAuditPage,\n ExposureSummary,\n AuditPage,\n DeviceRow,\n DeviceFlowContext,\n VaultKeyMaterial,\n DeletionStatus,\n ErasureResult,\n ChangePlanPreview,\n ChangePlanResult,\n OrgInvite,\n OffboardReview,\n OffboardSeenPage,\n OffboardAccessPage,\n OrgRole,\n OrgGroup,\n OrgGroupMember,\n OrgGroupCollection,\n OrgGrant,\n Capability,\n CollectionAccessEntry,\n CollectionDataCapability,\n CollectionGrant,\n CollectionWrappedKey,\n CreateCollectionGrantBody,\n RevokeCollectionGrantResult,\n CreateAgentBody,\n CreateAgentResponse,\n AgentProfileSummary,\n AgentWhoamiResponse,\n AuditRecentResponse,\n} from '../types/index.js';\n\n/** The exact confirmation string the server checks for GDPR erasure (back-compat, EN). */\nexport const ERASURE_CONFIRMATION = 'DELETE MY ACCOUNT';\n\n/** Localized confirmation phrases for GDPR erasure. Server accepts any after normalization. */\nexport const ERASURE_CONFIRMATIONS = { hr: 'OBRI\u0160I MOJ RA\u010CUN', en: 'DELETE MY ACCOUNT' } as const;\n\n// \u2500\u2500 Cross-tenant search (MSP scope) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface TenantSearchOrgHit { org_id: string; name: string; type: string; plan: string }\nexport interface TenantSearchCollectionHit {\n vault_id: string; org_id: string; org_name: string; name: string | null;\n is_default: boolean; org_type: string; org_plan: string;\n}\nexport interface TenantSearchResult {\n orgs: TenantSearchOrgHit[]; orgs_has_more: boolean;\n collections: TenantSearchCollectionHit[]; collections_has_more: boolean;\n}\n\n/** Pluggable token persistence (memory, sessionStorage, chrome.storage, \u2026). */\nexport interface TokenStore {\n get(): TokenPair | null;\n set(tokens: TokenPair | null): void;\n}\n\n/** In-memory token store (default; cleared on reload \u2014 fits an E2EE console). */\nexport function memoryTokenStore(): TokenStore {\n let tokens: TokenPair | null = null;\n return {\n get: () => tokens,\n set: (t) => {\n tokens = t;\n },\n };\n}\n\nexport interface ApiClientOptions {\n baseUrl?: string;\n tokenStore?: TokenStore;\n /** Injected for tests; defaults to global fetch. */\n fetchImpl?: typeof fetch;\n /**\n * fetch credentials mode. The console sets 'include' so the httpOnly refresh\n * cookie rides /v1/auth/refresh and /v1/auth/logout. Default (undefined) keeps\n * the Bearer/body behaviour for the extension/mobile unchanged.\n */\n credentials?: RequestCredentials;\n}\n\n/** ms before a refresh attempt is aborted (avoids a hung refresh blocking the app). */\nconst REFRESH_TIMEOUT_MS = 10_000;\n\nexport class ApiError extends Error {\n readonly status: number;\n readonly code: string | undefined;\n /** Full response body (parsed JSON). Populated for structured error responses. */\n readonly body: Record<string, unknown>;\n constructor(status: number, message: string, code?: string, body?: Record<string, unknown>) {\n super(message);\n this.name = 'ApiError';\n this.status = status;\n this.code = code;\n this.body = body ?? {};\n }\n}\n\n/** F4 Rez 1d-B Faza 3: poslani entry key_version nije aktivna verzija vaulta.\n * RAZLI\u010CITO od OCC conflicta \u2014 klijent mora refetchati klju\u010Deve, re-enkriptirati\n * najnovijim DEK-om i ponoviti (ne reload+merge). */\nexport const SYNC_KEY_VERSION_STALE = 'sync/key-version-stale';\n\n/** A 409 from a sync write is an optimistic-concurrency conflict, not an error \u2014\n * surface it as a conflict result the editor can show; rethrow anything else.\n * server_version is extracted from the structured 409 body (never hardcoded to 0).\n * key-version-stale se PROPU\u0160TA kao gre\u0161ka (retry sloj iznad radi refetch+re-encrypt). */\nfunction asConflict(e: unknown): PutEntryResult {\n if (e instanceof ApiError && e.status === 409 && e.code !== SYNC_KEY_VERSION_STALE) {\n const sv = typeof e.body['server_version'] === 'number' ? e.body['server_version'] : 0;\n return { conflict: true, server_version: sv, message: e.message };\n }\n throw e;\n}\n\nexport class ApiClient {\n private readonly baseUrl: string;\n private readonly tokens: TokenStore;\n private readonly doFetch: typeof fetch;\n private readonly credentials: RequestCredentials | undefined;\n /** Single-flight guard: concurrent 401s share one in-flight refresh. */\n private refreshing: Promise<boolean> | null = null;\n /** Dedup concurrent getVaultEntries calls for the same vaultId. */\n private readonly _inflightEntries = new Map<string, Promise<VaultEntryWire[]>>();\n\n constructor(opts: ApiClientOptions = {}) {\n this.baseUrl = opts.baseUrl ?? 'https://api.geslar.app';\n this.tokens = opts.tokenStore ?? memoryTokenStore();\n this.doFetch = opts.fetchImpl ?? globalThis.fetch.bind(globalThis);\n this.credentials = opts.credentials;\n }\n\n /** True when refresh can ride a cookie (no refresh token needs to be in store). */\n private get cookieMode(): boolean {\n return this.credentials === 'include';\n }\n\n isLoggedIn(): boolean {\n return !!this.tokens.get()?.access_token;\n }\n\n /** Force a refresh (e.g. on rehydrate): pulls a new access token via the cookie. */\n refreshSession(): Promise<boolean> {\n return this.tryRefresh();\n }\n\n /** Server-side logout: invalidate the refresh token + clear the cookie, then drop local tokens. */\n async serverLogout(): Promise<void> {\n try {\n await this.doFetch(`${this.baseUrl}/v1/auth/logout`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: '{}',\n ...(this.credentials ? { credentials: this.credentials } : {}),\n });\n } catch {\n /* best-effort \u2014 local state is cleared regardless */\n }\n this.tokens.set(null);\n }\n\n logout(): void {\n this.tokens.set(null);\n }\n\n // \u2500\u2500 Auth \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n prelogin(email: string): Promise<PreloginResponse> {\n return this.request<PreloginResponse>('/v1/auth/prelogin', {\n method: 'POST',\n body: JSON.stringify({ email }),\n });\n }\n\n /**\n * Prijava. Ra\u010Dun s aktivnim MFA dobiva `MfaRequiredResponse` (BEZ tokena) \u2014\n * klijent tada zove `loginMfa()` s challenge tokenom. Ra\u010Dun bez MFA dobiva\n * puni `LoginResponse` kao i dosad (tokeni se usvajaju).\n */\n async login(params: {\n email: string;\n auth_hash: string;\n device_name: string;\n device_fingerprint: string;\n }): Promise<LoginResponse | MfaRequiredResponse> {\n const body = await this.request<LoginResponse | MfaRequiredResponse>('/v1/auth/login', {\n method: 'POST',\n body: JSON.stringify(params),\n });\n if (!('mfa_required' in body)) {\n this.tokens.set({ access_token: body.access_token, refresh_token: body.refresh_token });\n }\n return body;\n }\n\n /** Korak 2 prijave: MFA dokaz \u2192 puni login response (tokeni se usvajaju). */\n async loginMfa(params: {\n challenge_token: string;\n method: string;\n payload: Record<string, unknown>;\n }): Promise<LoginResponse> {\n const body = await this.request<LoginResponse>('/v1/auth/login/mfa', {\n method: 'POST',\n body: JSON.stringify(params),\n });\n this.tokens.set({ access_token: body.access_token, refresh_token: body.refresh_token });\n return body;\n }\n\n // \u2500\u2500 Oporavak ra\u010Duna (zaboravljen glavni klju\u010D) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Korak 1 oporavka: e-mail \u2192 recovery session + \u0161ifrirani recovery blob.\n * Uvijek 200 (anti-enumeracija) \u2014 nepoznat ra\u010Dun dobiva la\u017Eni blob koji se\n * lokalno ne da otvoriti.\n */\n recoverInit(email: string): Promise<RecoverInitResponse> {\n return this.request('/v1/auth/recover/init', {\n method: 'POST',\n body: JSON.stringify({ email }),\n });\n }\n\n /**\n * Korak 2 oporavka: novi auth_hash + novi wrapani blobovi (sve izvedeno u\n * pregledniku \u2014 prepareRecovery). MFA-gated kad je MFA aktivan (mfa_code /\n * mfa_recovery_code). Server revoka sve ostale sesije; tokeni se usvajaju.\n */\n async recoverComplete(params: {\n recovery_session_token: string;\n new_auth_hash: string;\n new_enc_salt: string;\n new_encrypted_vault_key: string;\n new_encrypted_recovery_blob: string;\n new_encrypted_ecdh_private_key?: string;\n new_ecdh_public_key?: string;\n device_name: string;\n device_fingerprint: string;\n mfa_code?: string;\n mfa_recovery_code?: string;\n }): Promise<RecoverCompleteResponse> {\n const body = await this.request<RecoverCompleteResponse>('/v1/auth/recover/complete', {\n method: 'POST',\n body: JSON.stringify(params),\n });\n this.tokens.set({ access_token: body.access_token, refresh_token: body.refresh_token });\n return body;\n }\n\n // \u2500\u2500 MFA upravljanje (modularni auth-methods sustav) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Aktivne MFA metode + broj preostalih recovery kodova. */\n mfaList(): Promise<MfaListResponse> {\n return this.request('/v1/account/mfa', { method: 'GET' });\n }\n\n /**\n * Korak 1 enrollmenta \u2014 step-up lozinkom (auth_hash deriviran u pregledniku).\n * TOTP vra\u0107a secret + otpauth URI (QR renderira klijent); budu\u0107i provideri\n * vra\u0107aju svoj clientPayload.\n */\n mfaEnroll(method: string, authHash: string): Promise<MfaEnrollTotpResponse> {\n return this.request(`/v1/account/mfa/${encodeURIComponent(method)}/enroll`, {\n method: 'POST',\n body: JSON.stringify({ auth_hash: authHash }),\n });\n }\n\n /**\n * Korak 2 enrollmenta \u2014 dokaz (TOTP: prvi kod). Prva metoda vra\u0107a recovery\n * kodove (plaintext JEDINI PUT).\n */\n mfaVerifyEnroll(method: string, proof: Record<string, unknown>): Promise<{\n method: string;\n enabled: true;\n recovery_codes?: string[];\n }> {\n return this.request(`/v1/account/mfa/${encodeURIComponent(method)}/verify-enroll`, {\n method: 'POST',\n body: JSON.stringify({ proof }),\n });\n }\n\n /** Isklju\u010Di metodu: lozinka OBAVEZNA + (kod aktivne metode ILI recovery kod). */\n mfaDisable(method: string, params: {\n auth_hash: string;\n code?: string;\n recovery_code?: string;\n method_id?: string;\n }): Promise<{ ok: true; methods_remaining: number }> {\n return this.request(`/v1/account/mfa/${encodeURIComponent(method)}/disable`, {\n method: 'POST',\n body: JSON.stringify(params),\n });\n }\n\n /** Novih 10 recovery kodova (stari prestaju vrijediti) \u2014 plaintext JEDINI PUT. */\n mfaRegenerateRecoveryCodes(params: {\n auth_hash: string;\n code?: string;\n recovery_code?: string;\n }): Promise<{ recovery_codes: string[] }> {\n return this.request('/v1/account/mfa/recovery-codes/regenerate', {\n method: 'POST',\n body: JSON.stringify(params),\n });\n }\n\n /** F2 \u2014 dismiss the \"set up 2FA again\" nudge after an admin reset (\"Not now\").\n * Clears the caller's own mfa_reenroll_prompt flag. No body. */\n dismissReenroll(): Promise<{ ok: boolean }> {\n return this.request('/v1/account/mfa/dismiss-reenroll', { method: 'POST' });\n }\n\n // \u2500\u2500 Agentic Access \u2014 CLI device-flow approval (M1) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Console /device page: request context to show BEFORE approve/deny. */\n getDeviceContext(userCode: string): Promise<DeviceFlowContext> {\n return this.request('/v1/auth/device/lookup', {\n method: 'POST',\n body: JSON.stringify({ user_code: userCode }),\n });\n }\n\n /** Approve a pending `geslar signin` request. Always requires a FRESH 2FA\n * proof \u2014 no session-freshness cache, same step-up model as mfaDisable. */\n approveDevice(params: { user_code: string; code?: string; recovery_code?: string }): Promise<{ ok: true; hostname: string | null }> {\n return this.request('/v1/auth/device/approve', {\n method: 'POST',\n body: JSON.stringify(params),\n });\n }\n\n /** Deny a pending request \u2014 the safe path, no 2FA gate. */\n denyDevice(userCode: string): Promise<{ ok: true }> {\n return this.request('/v1/auth/device/deny', {\n method: 'POST',\n body: JSON.stringify({ user_code: userCode }),\n });\n }\n\n /** M2 \u2014 caller's own wrapped vault-key material (enc_salt + encrypted_vault_key\n * + ECDH blobs), for `geslar unlock`'s local KDF chain. See VaultKeyMaterial. */\n getVaultKeyMaterial(): Promise<VaultKeyMaterial> {\n return this.request('/v1/account/vault-key-material', { method: 'GET' });\n }\n\n // \u2500\u2500 Access core (M4.5) \u2014 agent principals \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // spec-access-core.md REV 1.2 \u00A73. Human-session-only except getAgentWhoami,\n // which is the one route an agent bearer token may itself call.\n\n /** Human session + fresh TOTP required server-side. Returns the plaintext\n * token exactly once \u2014 the caller must persist it immediately. */\n createAgent(body: CreateAgentBody): Promise<CreateAgentResponse> {\n return this.request<CreateAgentResponse>('/v1/agents', {\n method: 'POST',\n body: JSON.stringify(body),\n });\n }\n\n listAgents(): Promise<{ agents: AgentProfileSummary[] }> {\n return this.request<{ agents: AgentProfileSummary[] }>('/v1/agents', { method: 'GET' });\n }\n\n revokeAgent(id: string): Promise<{ ok: boolean; revoked: boolean }> {\n return this.request<{ ok: boolean; revoked: boolean }>(`/v1/agents/${encodeURIComponent(id)}`, { method: 'DELETE' });\n }\n\n /** Reachable by both a human session AND an agent bearer token \u2014 the CLI\n * uses this under GESLAR_AGENT context to read live capabilities (never\n * guessed/cached locally, spec \u00A74). */\n getAgentWhoami(): Promise<AgentWhoamiResponse> {\n return this.request<AgentWhoamiResponse>('/v1/agents/whoami', { method: 'GET' });\n }\n\n /** Reachable by an agent bearer (geslar-api Task 2) \u2014 scoped to this\n * principal's own agent.* events only. */\n getAuditRecent(params: { limit?: number } = {}): Promise<AuditRecentResponse> {\n const qs = params.limit ? `?limit=${encodeURIComponent(String(params.limit))}` : '';\n return this.request<AuditRecentResponse>(`/v1/audit${qs}`, { method: 'GET' });\n }\n\n /**\n * Create an account. All crypto happens in @geslar/core/crypto\n * (prepareRegistration) \u2014 this only ships auth_hash + opaque wrapped blobs.\n * Adopts the issued token pair so the fresh session is live immediately.\n */\n async register(params: {\n email: string;\n auth_hash: string;\n enc_salt: string;\n encrypted_vault_key: string;\n encrypted_recovery_blob: string;\n encrypted_ecdh_private_key: string;\n ecdh_public_key: string;\n device_name: string;\n device_fingerprint: string;\n locale?: string;\n }): Promise<RegisterResponse> {\n const body = await this.request<RegisterResponse>('/v1/auth/register', {\n method: 'POST',\n body: JSON.stringify(params),\n });\n this.tokens.set({ access_token: body.access_token, refresh_token: body.refresh_token });\n return body;\n }\n\n /** Consume an email-verification token (from the verification link). */\n verifyEmail(token: string): Promise<{ success: true; user_id: string; email_verified_at: string }> {\n return this.request('/v1/auth/verify-email', {\n method: 'POST',\n body: JSON.stringify({ token }),\n });\n }\n\n /** Re-send the verification email. Server rate-limits (3/h per email); always 200. */\n resendVerification(email: string): Promise<{ success: true }> {\n return this.request('/v1/auth/resend-verification', {\n method: 'POST',\n body: JSON.stringify({ email }),\n });\n }\n\n /** Mark the recovery key as stored by the user (onboarding ack). */\n acknowledgeRecoveryKey(): Promise<{ success: true }> {\n return this.request('/v1/account/acknowledge-recovery-key', {\n method: 'POST',\n body: JSON.stringify({ acknowledged: true }),\n });\n }\n\n /**\n * Replace the recovery blob with one wrapped under a FRESH recovery key (#44).\n * The new key + blob are generated in the browser; the server only stores the\n * opaque blob and resets the acknowledge flag.\n */\n regenerateRecoveryKey(encryptedRecoveryBlob: string): Promise<{ success: true }> {\n return this.request('/v1/account/regenerate-recovery-key', {\n method: 'POST',\n body: JSON.stringify({ encrypted_recovery_blob: encryptedRecoveryBlob }),\n });\n }\n\n // \u2500\u2500 Orgs / members (read-only, T13) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n getOrgs(): Promise<Org[]> {\n return this.request<Org[]>('/v1/orgs', { method: 'GET' });\n }\n\n /** Fire-and-forget audit trail for \"who switched into which org, when\" \u2014\n * MSP compliance groundwork. Caller must belong to orgId; server 403s otherwise. */\n logContextSwitch(orgId: string): Promise<{ ok: true }> {\n return this.request('/v1/context-switch', {\n method: 'POST',\n body: JSON.stringify({ org_id: orgId }),\n });\n }\n\n patchOrgBranding(\n orgId: string,\n body: { accent?: string | null; logo_light?: string | null; logo_dark?: string | null; locked?: boolean; brand_name?: string | null },\n ): Promise<{ ok: boolean; branding: OrgBranding }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/branding`, {\n method: 'PATCH',\n body: JSON.stringify(body),\n });\n }\n\n getOrgMembers(orgId: string): Promise<OrgMember[]> {\n return this.request<OrgMember[]>(`/v1/orgs/${encodeURIComponent(orgId)}/members`, {\n method: 'GET',\n });\n }\n\n getEntitlements(orgId?: string): Promise<EntitlementsBundle> {\n const url = orgId ? `/v1/account/entitlements?org=${encodeURIComponent(orgId)}` : '/v1/account/entitlements';\n return this.request<EntitlementsBundle>(url, { method: 'GET' });\n }\n\n /** Public plan catalogue (single source of truth for pricing). No auth needed. */\n async getPlans(): Promise<PublicPlan[]> {\n const res = await this.request<{ plans: PublicPlan[] }>('/v1/plans', { method: 'GET' });\n return res.plans;\n }\n\n /** Provider-agnostic checkout. Server attaches custom_data; returns the URL. */\n async createCheckout(plan: 'premium' | 'family', interval: 'monthly' | 'annual'): Promise<{ url: string }> {\n return this.request<{ url: string }>('/v1/billing/checkout', {\n method: 'POST',\n body: JSON.stringify({ plan, interval }),\n });\n }\n\n /** Faza 2 \u2014 \u0161to bi change-plan napravio (za ISTINIT copy prije potvrde):\n * interval_update (Lemon proration) / upgrade_checkout (Premium\u2192Family:\n * checkout + auto-otkaz + proration refund starog suba) / checkout / noop. */\n async changePlanPreview(plan: 'premium' | 'family', interval: 'monthly' | 'annual'): Promise<ChangePlanPreview> {\n return this.request<ChangePlanPreview>(\n `/v1/billing/change-plan/preview?plan=${plan}&interval=${interval}`,\n { method: 'GET' },\n );\n }\n\n /** Faza 3 (#11) \u2014 native otkaz iz konzole: sub vrijedi do kraja pla\u0107enog\n * perioda (bez daljnjih naplata), zatim grace (D-010). 404 bez aktivnog suba. */\n async cancelPlan(plan: 'premium' | 'family'): Promise<{ ok: boolean; valid_until: string | null }> {\n return this.request<{ ok: boolean; valid_until: string | null }>('/v1/billing/cancel', {\n method: 'POST',\n body: JSON.stringify({ plan }),\n });\n }\n\n /** Faza 2 \u2014 THE change-plan ulaz. Server odlu\u010Duje (autoritativno):\n * 'updated' = interval promijenjen u mjestu (bez checkouta); 'checkout' =\n * otvori vra\u0107eni URL. 409 kad je korisnik ve\u0107 na tra\u017Eenom planu/intervalu. */\n async changePlan(plan: 'premium' | 'family', interval: 'monthly' | 'annual'): Promise<ChangePlanResult> {\n return this.request<ChangePlanResult>('/v1/billing/change-plan', {\n method: 'POST',\n body: JSON.stringify({ plan, interval }),\n });\n }\n\n /** Authenticated deep-link to the provider's hosted customer/billing portal\n * (manage payment method, cancel a plan, view invoices). 404 when the caller\n * has no subscription to manage; 503 when the portal is not configured. */\n async getCustomerPortalUrl(): Promise<{ url: string }> {\n return this.request<{ url: string }>('/v1/billing/portal', { method: 'GET' });\n }\n\n // \u2500\u2500 Sharing (T11) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n // \"admin = razina\" Track A Faza 3/4b: optional role_id assigns a management\n // role via PDP grant (parallel to the legacy `role` enum \u2014 see BE accept flow).\n createInvite(orgId: string, email: string, role: MemberRole, roleId?: string): Promise<InviteResult> {\n return this.request<InviteResult>(`/v1/orgs/${encodeURIComponent(orgId)}/invites`, {\n method: 'POST',\n body: JSON.stringify({ email, role, ...(roleId ? { role_id: roleId } : {}) }),\n });\n }\n\n listInvites(orgId: string): Promise<{ invites: OrgInvite[] }> {\n return this.request<{ invites: OrgInvite[] }>(`/v1/orgs/${encodeURIComponent(orgId)}/invites`, { method: 'GET' });\n }\n\n revokeInvite(orgId: string, inviteId: string): Promise<{ ok: boolean }> {\n return this.request<{ ok: boolean }>(`/v1/orgs/${encodeURIComponent(orgId)}/invites/${encodeURIComponent(inviteId)}`, { method: 'DELETE' });\n }\n\n async resendInvite(orgId: string, inviteId: string, email: string, role: MemberRole): Promise<InviteResult> {\n // Server has no dedicated resend endpoint \u2014 revoke then recreate so a new email is sent.\n await this.revokeInvite(orgId, inviteId);\n return this.createInvite(orgId, email, role);\n }\n\n acceptInvite(token: string): Promise<{ member_id: string; org_id: string; role: MemberRole; status: string }> {\n return this.request(`/v1/invites/${encodeURIComponent(token)}/accept`, { method: 'POST' });\n }\n\n /** Upsert the caller's OWN wrapped DEK (bootstrapping a team_collection). */\n putOwnMemberKey(vaultId: string, encryptedKeyB64: string): Promise<{ ok: true }> {\n return this.request(`/v1/vaults/${encodeURIComponent(vaultId)}/member-keys`, {\n method: 'POST',\n body: JSON.stringify({ encrypted_key: encryptedKeyB64 }),\n });\n }\n\n /** Fetch the caller's wrapped DEK + the wrapper's public key (for unwrap). */\n getMemberKey(vaultId: string): Promise<MemberKeyResult> {\n return this.request<MemberKeyResult>(`/v1/vaults/${encodeURIComponent(vaultId)}/member-keys`, { method: 'GET' });\n }\n\n\n /** Cross-org: all team_collection vaults the caller holds a DEK for. */\n getCollections(): Promise<{ collections: CollectionSummary[] }> {\n return this.request<{ collections: CollectionSummary[] }>('/v1/collections', { method: 'GET' });\n }\n\n // \u2500\u2500 Collection management (D-053) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** idempotencyKey (B1): caller generates ONE UUID per logical submit and reuses\n * it on automatic retry of the SAME request (e.g. the 401-refresh retry in\n * request() below reuses this same init). Optional \u2014 server does not require\n * it yet (B2 lands after clients ship this).\n * isDefault (business-default-vault plan, 2026-07-14): creates the org's\n * singleton \"Op\u0107a \u0161krinja\" instead of a regular collection. A second\n * is_default=true create 409s with code 'vault/default-collection-exists'\n * and body.existing_vault_id \u2014 the caller should open that vault instead. */\n createCollection(orgId: string, name: string, idempotencyKey?: string, isDefault?: boolean): Promise<{ vault_id: string; name: string }> {\n return this.request<{ vault_id: string; name: string }>(`/v1/orgs/${encodeURIComponent(orgId)}/collections`, {\n method: 'POST',\n body: JSON.stringify({ name, is_default: isDefault ?? false }),\n ...(idempotencyKey ? { headers: { 'Idempotency-Key': idempotencyKey } } : {}),\n });\n }\n\n /** F4 B3: promote a folder subtree from a business vault into a NEW collection.\n * Enterprise-gated server-side (403 without the promote_folder module). The\n * server only creates the collection + (optionally) replicates the source's\n * access state; the ZK entry move + folder recreation happen client-side.\n * idempotencyKey (B1): see createCollection above. */\n promoteFolder(\n orgId: string,\n body: { name: string; source_vault_id: string; copy_permissions: boolean },\n idempotencyKey?: string,\n ): Promise<{ vault_id: string; name: string }> {\n return this.request<{ vault_id: string; name: string }>(`/v1/orgs/${encodeURIComponent(orgId)}/collections/promote-folder`, {\n method: 'POST',\n body: JSON.stringify(body),\n ...(idempotencyKey ? { headers: { 'Idempotency-Key': idempotencyKey } } : {}),\n });\n }\n\n renameCollection(orgId: string, cid: string, name: string): Promise<{ ok: boolean; name: string }> {\n return this.request<{ ok: boolean; name: string }>(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}`, {\n method: 'PATCH',\n body: JSON.stringify({ name }),\n });\n }\n\n deleteCollection(orgId: string, cid: string): Promise<{ ok: boolean }> {\n return this.request<{ ok: boolean }>(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}`, {\n method: 'DELETE',\n });\n }\n\n listCollectionMembers(orgId: string, cid: string): Promise<{ members: CollectionMember[] }> {\n return this.request<{ members: CollectionMember[] }>(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/members`, {\n method: 'GET',\n });\n }\n\n /** keyVersion: version of the DEK encryptedKeyB64 was wrapped with. Optional for\n * back-compat; omitting it keeps the server's pre-existing grace behavior\n * (tags the row as whatever version is current at insert time). Sending it lets\n * the server reject a stale wrap (409 sync/key-version-stale) instead of\n * silently tagging a rotation-raced wrap with the wrong version \u2014 same\n * contract as CollectionWrappedKey.key_version in the grants fan-out. */\n addCollectionMember(orgId: string, cid: string, userId: string, encryptedKeyB64: string, keyVersion?: number): Promise<{ ok: boolean }> {\n return this.request<{ ok: boolean }>(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/members`, {\n method: 'POST',\n body: JSON.stringify({ user_id: userId, encrypted_key: encryptedKeyB64, ...(keyVersion !== undefined ? { key_version: keyVersion } : {}) }),\n });\n }\n\n /** Remove a collection member (F4 Rez 1d-B Faza 4). Severs the removed member's\n * access immediately and flags rotation_required if they held the DEK; the\n * actual re-encryption runs staged (stage/commit/complete). No payload. */\n removeCollectionMember(orgId: string, cid: string, uid: string): Promise<RemoveCollectionMemberResult> {\n return this.request<RemoveCollectionMemberResult>(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/members/${encodeURIComponent(uid)}/remove`, {\n method: 'POST',\n });\n }\n\n /** Faza 4 stage: insert the target-version key for every remaining holder. */\n stageCollectionRotation(orgId: string, cid: string, body: CollectionRotationStage): Promise<{ ok: boolean; staged: boolean; target_key_version: number }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/rotate/stage`, {\n method: 'POST', body: JSON.stringify(body),\n });\n }\n\n /** Faza 4 commit: apply one chunk (\u2264500) of re-encrypted entries. */\n commitCollectionRotation(orgId: string, cid: string, body: CollectionRotationCommit): Promise<{ ok: boolean; committed: number; target_key_version: number }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/rotate/commit`, {\n method: 'POST', body: JSON.stringify(body),\n });\n }\n\n /** Faza 4 complete: sweep old key versions once all entries are on target.\n * `completed:false` means NOT actually done \u2014 `already` = this rotation was a\n * prior no-op retry, `stale` = a NEWER rotation debt appeared meanwhile (caller\n * must re-fetch + re-derive rotation_required from the server, never assume done). */\n completeCollectionRotation(orgId: string, cid: string, keyVersion: number): Promise<{ ok: boolean; completed: boolean; already?: boolean; stale?: boolean }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/rotate/complete`, {\n method: 'POST', body: JSON.stringify({ key_version: keyVersion }),\n });\n }\n\n /** Owner-override: clear the collection's rotation_required flag WITHOUT\n * rotating the key (residual exposure explicitly accepted; audited). */\n resetCollectionRotation(orgId: string, cid: string): Promise<{ ok: boolean; rotation_required: boolean }> {\n return this.request<{ ok: boolean; rotation_required: boolean }>(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/rotation-reset`, {\n method: 'POST',\n });\n }\n\n updateCollectionMemberPermissions(\n orgId: string,\n cid: string,\n uid: string,\n perms: { can_view?: boolean; can_edit?: boolean; can_share?: boolean; can_reveal?: boolean },\n ): Promise<{ ok: boolean }> {\n return this.request<{ ok: boolean }>(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/members/${encodeURIComponent(uid)}/permissions`, {\n method: 'PATCH',\n body: JSON.stringify(perms),\n });\n }\n\n // \u2500\u2500 Collection-scope data grants (F4 Rez 1d B2) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Effective access for the \"Pristup\" tab: grant subjects + key-holders. */\n getCollectionAccess(orgId: string, cid: string): Promise<{ access: CollectionAccessEntry[] }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/access`, { method: 'GET' });\n }\n\n /** List collection-scope grants (one row per subject \u00D7 capability). */\n getCollectionGrants(orgId: string, cid: string): Promise<{ grants: CollectionGrant[] }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/grants`, { method: 'GET' });\n }\n\n /** Create a collection-scope data grant + eager key-wrap fan-out (ZK: keys are\n * wrapped in the browser and delivered as wrapped_keys). */\n createCollectionGrant(orgId: string, cid: string, body: CreateCollectionGrantBody): Promise<{ ok: boolean; wrapped: number; pending: number }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/grants`, {\n method: 'POST', body: JSON.stringify(body),\n });\n }\n\n /** Revoke a grant; server severs orphaned keys + flags rotation as needed. */\n deleteCollectionGrant(orgId: string, cid: string, grantId: string): Promise<RevokeCollectionGrantResult> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/grants/${encodeURIComponent(grantId)}`, {\n method: 'DELETE',\n });\n }\n\n /** Key-holder-driven pending \u2192 active: wrap the DEK for pending members. */\n reconcileCollectionKeys(orgId: string, cid: string, wrappedKeys: CollectionWrappedKey[]): Promise<{ ok: boolean; reconciled: number }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/reconcile-keys`, {\n method: 'POST', body: JSON.stringify({ wrapped_keys: wrappedKeys }),\n });\n }\n\n /** F4 Rez 1d C-B: set (REPLACE) per-member deny override on a collection.\n * Enterprise-gated server-side (403 without the per_member_override module).\n * Server severs the key + flags rotation only when 'view' is actually lost. */\n setCollectionMemberOverride(orgId: string, cid: string, uid: string, deniedCapabilities: CollectionDataCapability[]): Promise<{ ok: true; denied_capabilities: CollectionDataCapability[]; rotation_required: boolean }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/members/${encodeURIComponent(uid)}/overrides`, {\n method: 'PUT', body: JSON.stringify({ denied_capabilities: deniedCapabilities }),\n });\n }\n\n /** Clear a member's deny override (un-override). NOT entitlement-gated \u2014\n * removing restrictions must stay available after a downgrade. */\n clearCollectionMemberOverride(orgId: string, cid: string, uid: string): Promise<{ ok: true }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections/${encodeURIComponent(cid)}/members/${encodeURIComponent(uid)}/overrides`, {\n method: 'DELETE',\n });\n }\n\n /** Confirm a pending member \u2014 unconditional for every org type (no DEK-wrap\n * ceremony): flips the member active and joins them to \"Svi \u010Dlanovi\". Access\n * to the org's default collection is grant + reconcile-keys driven, same as\n * any other team_collection. `vault_id` in the response is always `null`. */\n confirmMember(orgId: string, memberId: string): Promise<{ ok: true; vault_id: string | null }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/members/${encodeURIComponent(memberId)}/confirm`, {\n method: 'POST',\n body: JSON.stringify({}),\n });\n }\n\n // \u2500\u2500 Offboarding + audit (T12) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** All encrypted entries in a vault. Follows next_cursor pages until exhausted.\n * Concurrent calls for the same vaultId share one in-flight request so a\n * parallel listPersonalEntries + loadFolders pair only hits the network once.\n * Safety cap: aborts after 100 000 total entries to prevent unbounded loops. */\n async getVaultEntries(vaultId: string): Promise<VaultEntryWire[]> {\n const cached = this._inflightEntries.get(vaultId);\n if (cached) return cached;\n const promise = this._paginateEntries(vaultId);\n this._inflightEntries.set(vaultId, promise);\n promise.finally(() => this._inflightEntries.delete(vaultId));\n return promise;\n }\n\n private async _paginateEntries(vaultId: string): Promise<VaultEntryWire[]> {\n const PAGE_LIMIT = 1000;\n const MAX_ENTRIES = 100_000;\n const all: VaultEntryWire[] = [];\n let cursor: string | undefined;\n\n while (all.length < MAX_ENTRIES) {\n const params = new URLSearchParams({ vault_id: vaultId, limit: String(PAGE_LIMIT) });\n if (cursor) params.set('cursor', cursor);\n const res = await this.request<{ entries: VaultEntryWire[]; next_cursor: string | null }>(\n `/v1/sync/entries?${params.toString()}`,\n { method: 'GET' },\n );\n all.push(...res.entries);\n if (!res.next_cursor) break;\n cursor = res.next_cursor;\n }\n\n return all;\n }\n\n // \u2500\u2500 Vault entry write (T14 \u2014 full editor; reuses existing sync endpoints) \u2500\u2500\u2500\u2500\n\n /** Ensure the caller's personal vault exists; returns id + whether it was just created\n * (is_new=true means first-ever or revival after erasure). */\n async ensurePersonalVault(): Promise<{ vault_id: string; is_new: boolean }> {\n return this.request<{ vault_id: string; is_new: boolean }>('/v1/sync/vault', {\n method: 'POST',\n body: JSON.stringify({}),\n });\n }\n\n /** Tombstone a collection or shared vault (DELETE /v1/sync/vault/:id).\n * Server sets vault.deleted_at + cascades to all entries. 400 if vault_type=personal. */\n deleteVault(vaultId: string): Promise<{ ok: boolean }> {\n return this.request<{ ok: boolean }>(`/v1/sync/vault/${encodeURIComponent(vaultId)}`, {\n method: 'DELETE',\n });\n }\n\n /** Soft-delete all entries in a vault without touching the vault row itself.\n * Use for personal vault \"wipe cloud, keep local\" \u2014 vault_id stays stable.\n * auth_hash: re-derived master-password hash for server-side re-auth (same as purgeCloudData). */\n clearVaultEntries(vaultId: string, authHash?: string): Promise<{ entries_deleted: number }> {\n return this.request<{ entries_deleted: number }>(\n `/v1/sync/vault/${encodeURIComponent(vaultId)}/clear-entries`,\n {\n method: 'POST',\n body: authHash ? JSON.stringify({ auth_hash: authHash }) : JSON.stringify({}),\n },\n );\n }\n\n /** Pull vault tombstones (vaults deleted since `since`). Suite uses this to evict\n * deleted collections/shared vaults from the UI without requiring re-login. */\n getVaultTombstones(since?: string): Promise<{ deleted_vaults: Array<{ vault_id: string; deleted_at: string }> }> {\n const q = since ? `?since=${encodeURIComponent(since)}` : '';\n return this.request<{ deleted_vaults: Array<{ vault_id: string; deleted_at: string }> }>(\n `/v1/sync/vault-tombstones${q}`,\n { method: 'GET' },\n );\n }\n\n /**\n * Upsert a single encrypted entry (create when expected_version=0, else update\n * with optimistic concurrency). The server stores opaque blobs only \u2014 all crypto\n * happens in the browser. Returns the new server version, or a conflict.\n */\n async putEntry(\n entryId: string,\n args: { vaultId: string; entryType: string; encryptedBlob: string; blobHash: string; expectedVersion: number; keyVersion?: number },\n ): Promise<PutEntryResult> {\n try {\n return await this.request<PutEntryResult>(`/v1/sync/entries/${encodeURIComponent(entryId)}`, {\n method: 'PUT',\n body: JSON.stringify({\n vault_id: args.vaultId,\n entry_type: args.entryType,\n encrypted_blob: args.encryptedBlob,\n blob_hash: args.blobHash,\n expected_version: args.expectedVersion,\n // F4 Rez 1d-B Faza 3: envelope-tag DEK-a kojim je blob enkriptiran.\n // Izostavljeno = server grace-taga (stari klijenti).\n ...(args.keyVersion !== undefined ? { key_version: args.keyVersion } : {}),\n }),\n });\n } catch (e) {\n return asConflict(e);\n }\n }\n\n /** Soft-delete a single entry (optimistic concurrency on expected_version). */\n async deleteEntry(entryId: string, args: { vaultId: string; expectedVersion: number }): Promise<PutEntryResult> {\n try {\n return await this.request<PutEntryResult>(`/v1/sync/entries/${encodeURIComponent(entryId)}`, {\n method: 'DELETE',\n body: JSON.stringify({ vault_id: args.vaultId, expected_version: args.expectedVersion }),\n });\n } catch (e) {\n return asConflict(e);\n }\n }\n\n /**\n * Batch push (up to 500 ops). 200 = all OK, 207 = partial (some conflicts).\n * For delete ops: { op: 'delete', id, expected_version }.\n * For upsert ops: { op: 'upsert', id, entry_type, encrypted_blob, blob_hash, expected_version }.\n */\n async batchEntries(\n vaultId: string,\n operations: Array<{ op: 'delete' | 'upsert'; id: string; expected_version: number; entry_type?: string; encrypted_blob?: string; blob_hash?: string; key_version?: number }>,\n ): Promise<{ results: Array<{ id: string; status: 'ok' | 'conflict'; version: number; server_version?: number; server_updated_at?: string }>; server_time: string }> {\n return this.request('/v1/sync/entries/batch', {\n method: 'POST',\n body: JSON.stringify({ vault_id: vaultId, operations }),\n });\n }\n\n /** Remove a member. \"\u0160krinja je \u0160krinja\" unification: no client-side DEK\n * rotation anymore \u2014 the server flags any team_collection the member held a\n * key on (rotation_required); an existing key-holder rotates it later via\n * the staged /collections/:cid/rotate flow. */\n removeMember(orgId: string, memberId: string): Promise<{ ok: true; removed_member_id: string; collections_flagged_for_rotation: number }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/members/${encodeURIComponent(memberId)}/remove`, {\n method: 'POST',\n body: JSON.stringify({}),\n });\n }\n\n /** Leave an org. 'delete' starts the grace\u2192purge on the caller's personal cloud. */\n leaveOrg(orgId: string, memberId: string, choice: 'keep' | 'delete'): Promise<{ ok: true; choice: string; collections_flagged_for_rotation: number }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/members/${encodeURIComponent(memberId)}/leave`, {\n method: 'POST',\n body: JSON.stringify({ choice }),\n });\n }\n\n /** Owner cancels a shared plan WITH members (danger zone). */\n cancelOrg(orgId: string): Promise<{ ok: true; members_notified: number }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/cancel`, {\n method: 'POST',\n body: JSON.stringify({ confirm: true }),\n });\n }\n\n setOrgRequire2fa(orgId: string, enabled: boolean): Promise<{ ok: boolean; require_member_2fa: boolean }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/settings/require-member-2fa`, {\n method: 'PATCH',\n body: JSON.stringify({ enabled }),\n });\n }\n setOrgClipboardClearPolicy(orgId: string, enabled: boolean, seconds: 20 | 60 | 120): Promise<{ ok: boolean; clipboard_clear_policy: { enabled: boolean; seconds: number } | null }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/settings/clipboard-clear-policy`, {\n method: 'PUT',\n body: JSON.stringify({ enabled, seconds }),\n });\n }\n\n unsetOrgClipboardClearPolicy(orgId: string): Promise<{ ok: boolean; clipboard_clear_policy: null }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/settings/clipboard-clear-policy`, {\n method: 'DELETE',\n });\n }\n\n /** F2 \u2014 owner/admin resets a member's 2FA (login-factor only; server enforces the\n * manage_member_2fa capability + escalation guard). No body. */\n resetMemberMfa(orgId: string, memberId: string): Promise<{ ok: boolean }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/members/${encodeURIComponent(memberId)}/mfa`, {\n method: 'DELETE',\n });\n }\n\n /** F3b \u2014 owner/admin sets (exempt=true \u2192 PUT) or clears (exempt=false \u2192 DELETE) a\n * member's exemption from the org's require_member_2fa policy. Server enforces the\n * manage_org capability + self-block + owner-rank guard. */\n setMemberMfaExemption(orgId: string, memberId: string, exempt: boolean): Promise<{ ok: boolean; mfa_exempt: boolean }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/members/${encodeURIComponent(memberId)}/mfa-exemption`, {\n method: exempt ? 'PUT' : 'DELETE',\n });\n }\n\n /** Append an access record (reference only \u2014 never the plaintext). */\n logCredentialAccess(args: { orgId: string; entryId: string; vaultId: string; action: CredentialAction }): Promise<{ ok: true }> {\n return this.request('/v1/credential-access', {\n method: 'POST',\n body: JSON.stringify({ org_id: args.orgId, entry_id: args.entryId, vault_id: args.vaultId, action: args.action }),\n });\n }\n\n /** Entries a member has revealed/copied/autofilled \u2014 drives guided rotation. */\n getPasswordsKnownBy(orgId: string, userId: string): Promise<PasswordKnownRow[]> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/audit/passwords-known-by/${encodeURIComponent(userId)}`, { method: 'GET' });\n }\n\n /** Per-active-member count of entries they revealed/copied/autofilled. Business+ only. */\n getExposureSummary(orgId: string): Promise<ExposureSummary> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/audit/exposure-summary`, { method: 'GET' });\n }\n\n /** Who touched a given entry (access feed). Cursor-paginated (Faza A). */\n getCredentialAudit(\n orgId: string,\n entryId: string,\n cursor?: { before_ts: string; before_id: number },\n ): Promise<CredentialAuditPage> {\n const q = new URLSearchParams();\n if (cursor) { q.set('before_ts', cursor.before_ts); q.set('before_id', String(cursor.before_id)); }\n const qs = q.toString();\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/audit/credential/${encodeURIComponent(entryId)}${qs ? `?${qs}` : ''}`, { method: 'GET' });\n }\n\n /** The caller's own general audit log (GET /v1/audit). Per-user, not org-wide \u2014\n * surfaces the signed-in admin's security-relevant events (DEK rotations,\n * failed logins, membership changes) for the dashboard. */\n getAudit(params?: { limit?: number; action?: string; since?: string }): Promise<AuditPage> {\n const q = new URLSearchParams();\n if (params?.limit) q.set('limit', String(params.limit));\n if (params?.action) q.set('action', params.action);\n if (params?.since) q.set('since', params.since);\n const qs = q.toString();\n return this.request<AuditPage>(`/v1/audit${qs ? `?${qs}` : ''}`, { method: 'GET' });\n }\n\n /** Cross-tenant search: orgs and collections matching the query. MSP use case. */\n searchTenants(q: string): Promise<TenantSearchResult> {\n const params = new URLSearchParams({ q });\n return this.request<TenantSearchResult>(`/v1/search/tenants?${params.toString()}`, { method: 'GET' });\n }\n\n // \u2500\u2500 Devices / sessions (K4) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Registered devices/sessions for the signed-in user. */\n async getDevices(): Promise<DeviceRow[]> {\n const res = await this.request<{ devices: DeviceRow[] }>('/v1/devices', { method: 'GET' });\n return res.devices;\n }\n\n /** Revoke a single device (deletes its refresh tokens). */\n revokeDevice(deviceId: string): Promise<{ revoked: true; self_revoked: boolean }> {\n return this.request(`/v1/devices/${encodeURIComponent(deviceId)}`, { method: 'DELETE' });\n }\n\n /** Panic button \u2014 revoke every device except the current one. */\n revokeOtherDevices(): Promise<{ revoked_all: true; kept_device_id: string }> {\n return this.request('/v1/devices', { method: 'DELETE' });\n }\n\n // \u2500\u2500 Account erasure (K4 \u2014 GDPR art. 17) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Current scheduled-deletion state (none \u2192 all-null shape). */\n getDeletionStatus(): Promise<DeletionStatus> {\n return this.request<DeletionStatus>('/v1/account/deletion-status', { method: 'GET' });\n }\n\n /**\n * Request erasure of the account (30-day grace). `masterPasswordHash` is the\n * SAME auth_hash sent at login (re-derived in the browser from the master\n * password the user re-enters) \u2014 the server verifies it before scheduling.\n */\n requestAccountErasure(masterPasswordHash: string): Promise<ErasureResult> {\n return this.request<ErasureResult>('/v1/account/data-erasure-confirm', {\n method: 'POST',\n body: JSON.stringify({ confirmation: ERASURE_CONFIRMATION, master_password_hash: masterPasswordHash }),\n });\n }\n\n /** Cancel a scheduled deletion during the grace period. */\n cancelAccountDeletion(): Promise<{ status: string; message: string }> {\n return this.request('/v1/auth/account/cancel-deletion', { method: 'POST' });\n }\n\n /** GDPR Art. 20 \u2014 request full account data export. Backend queues a ZIP\n * and sends a download link via email when ready. Rate-limited to 1\u00D7/24h\n * (429 with Retry-After if called again within the window). */\n requestDataExport(): Promise<{ job_id: string; estimated_seconds: number }> {\n return this.request('/v1/account/data-export', { method: 'GET' });\n }\n\n /**\n * Self-serve \"wipe cloud data only\" \u2014 purges the cloud copy of the caller's\n * PERSONAL org (local vault untouched). Re-auth: auth_hash re-derived in the\n * browser, the master password never leaves the device.\n */\n purgeCloudData(authHash: string): Promise<{ entries_deleted: number; vaults_deleted: number }> {\n return this.request('/v1/account/purge-cloud-data', {\n method: 'POST',\n body: JSON.stringify({ auth_hash: authHash }),\n });\n }\n\n /** Rename an organization (owner-only server-side). Returns the saved name. */\n renameOrg(orgId: string, name: string): Promise<{ ok: boolean; name: string }> {\n return this.request(`/v1/orgs/${orgId}`, {\n method: 'PATCH',\n body: JSON.stringify({ name }),\n });\n }\n\n // \u2500\u2500 ECDH migration (T10/K5 \u2014 placeholder v0 \u2192 real X25519 v1) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Upload a real X25519 public key + its master-key-wrapped private key during\n * the placeholder\u2192real migration; the server sets ecdh_key_version = 1. SAME\n * route the extension's T10 migration uses (PUT /v1/account/ecdh-public-key) \u2014\n * identical envelope \u21D2 cross-client parity.\n */\n updateEcdhPublicKey(ecdhPublicKey: string, encryptedEcdhPrivateKey: string): Promise<{ success: true; ecdh_key_version: number }> {\n return this.request('/v1/account/ecdh-public-key', {\n method: 'PUT',\n body: JSON.stringify({ ecdh_public_key: ecdhPublicKey, encrypted_ecdh_private_key: encryptedEcdhPrivateKey }),\n });\n }\n\n // \u2500\u2500 Master password change (K4b) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /**\n * Rotate the master password (user knows the current one). All crypto happens\n * in the browser: the caller re-wraps the unchanged vault_key + ECDH private key\n * under the new master_key and passes the opaque blobs here. The server re-checks\n * `current_auth_hash`, rotates the credentials, revokes every other session and\n * re-issues this device's tokens \u2014 which we adopt so the session stays live.\n */\n async changeMasterPassword(params: {\n current_auth_hash: string;\n new_auth_hash: string;\n new_enc_salt: string;\n new_encrypted_vault_key: string;\n new_encrypted_ecdh_private_key: string;\n device_name: string;\n device_fingerprint: string;\n }): Promise<{ success: true; enc_salt: string }> {\n const body = await this.request<{ success: true; access_token: string; refresh_token: string; enc_salt: string }>(\n '/v1/account/change-master-password',\n { method: 'POST', body: JSON.stringify(params) },\n );\n // Adopt the freshly-issued tokens (the old ones were just revoked server-side).\n this.tokens.set({ access_token: body.access_token, refresh_token: body.refresh_token });\n return { success: body.success, enc_salt: body.enc_salt };\n }\n\n // \u2500\u2500 Account profile + email change (#34) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Set or clear the optional display name. Returns the stored value. */\n updateProfile(displayName: string | null): Promise<{ display_name: string | null }> {\n return this.request('/v1/account/profile', {\n method: 'PATCH',\n body: JSON.stringify({ display_name: displayName }),\n });\n }\n\n /**\n * Begin an email change: step-up re-verifies the current master password\n * (`current_auth_hash`, re-derived in the browser), then the server mails a\n * 6-digit code to the NEW address and an alert to the OLD one. enc_salt/auth_hash\n * are untouched \u2014 the email is not part of the KDF.\n */\n changeEmailInit(newEmail: string, currentAuthHash: string): Promise<{ ok: true }> {\n return this.request('/v1/account/change-email/init', {\n method: 'POST',\n body: JSON.stringify({ new_email: newEmail, current_auth_hash: currentAuthHash }),\n });\n }\n\n /** Confirm the email change with the 6-digit code; returns the new email. */\n changeEmailConfirm(code: string): Promise<{ ok: true; email: string }> {\n return this.request('/v1/account/change-email/confirm', {\n method: 'POST',\n body: JSON.stringify({ code }),\n });\n }\n\n // \u2500\u2500 UI preferences \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Fetch user's stored UI preferences (e.g. dashboard_layout). */\n getUserPreferences(): Promise<{ dashboard_layout: Record<string, unknown[]> | null }> {\n return this.request('/v1/account/preferences', { method: 'GET' });\n }\n\n /** Persist UI preferences (merged server-side). */\n updateUserPreferences(prefs: { dashboard_layout?: Record<string, unknown[]> | null }): Promise<{ dashboard_layout: Record<string, unknown[]> | null }> {\n return this.request('/v1/account/preferences', {\n method: 'PUT',\n body: JSON.stringify(prefs),\n });\n }\n\n /** Patch site-icon display preferences. */\n updateSiteIconPrefs(patch: { show_site_icons?: boolean; site_icons_prompt_seen?: boolean }): Promise<{ show_site_icons: boolean; site_icons_prompt_seen: boolean }> {\n return this.request('/v1/users/me/preferences', {\n method: 'PATCH',\n body: JSON.stringify(patch),\n });\n }\n /** Patch clipboard-auto-clear personal preferences. No-op fields are omitted from the body. */\n updateClipboardClearPrefs(patch: { clipboard_clear_enabled?: boolean; clipboard_clear_seconds?: 20 | 60 | 120 }): Promise<{ clipboard_clear_enabled: boolean; clipboard_clear_seconds: 20 | 60 | 120 }> {\n return this.request('/v1/users/me/preferences', {\n method: 'PATCH',\n body: JSON.stringify(patch),\n });\n }\n\n // \u2500\u2500 Offboarding reviews (#20) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n /** Open offboarding reviews for the org (one header per departed member). */\n getOffboardReviews(orgId: string): Promise<OffboardReview[]> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/offboard-reviews`, { method: 'GET' });\n }\n\n /** Cursor-paginated entries the departed member had revealed/copied. */\n getOffboardSeen(\n orgId: string,\n userId: string,\n params?: { limit?: number; sort?: 'recency' | 'risk'; before_ts?: string; before_entry_id?: string; before_high_risk?: boolean },\n ): Promise<OffboardSeenPage> {\n const q = new URLSearchParams();\n if (params?.limit) q.set('limit', String(params.limit));\n if (params?.sort) q.set('sort', params.sort);\n if (params?.before_ts) q.set('before_ts', params.before_ts);\n if (params?.before_entry_id) q.set('before_entry_id', params.before_entry_id);\n if (params?.before_high_risk !== undefined) q.set('before_high_risk', String(params.before_high_risk));\n const qs = q.toString();\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/offboard-reviews/${encodeURIComponent(userId)}/seen${qs ? `?${qs}` : ''}`, { method: 'GET' });\n }\n\n /** Shared vault entries the departed member had access to. */\n getOffboardAccess(\n orgId: string,\n userId: string,\n params?: { limit?: number; before_ts?: string; before_entry_id?: string },\n ): Promise<OffboardAccessPage> {\n const q = new URLSearchParams();\n if (params?.limit) q.set('limit', String(params.limit));\n if (params?.before_ts) q.set('before_ts', params.before_ts);\n if (params?.before_entry_id) q.set('before_entry_id', params.before_entry_id);\n const qs = q.toString();\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/offboard-reviews/${encodeURIComponent(userId)}/access${qs ? `?${qs}` : ''}`, { method: 'GET' });\n }\n\n /** Upsert a review item status (rotated | reviewed). */\n patchOffboardItem(\n orgId: string,\n userId: string,\n entryId: string,\n status: 'rotated' | 'reviewed',\n ): Promise<{ ok: boolean; entry_id: string; status: string }> {\n return this.request(\n `/v1/orgs/${encodeURIComponent(orgId)}/offboard-reviews/${encodeURIComponent(userId)}/items/${encodeURIComponent(entryId)}`,\n { method: 'PATCH', body: JSON.stringify({ status }) },\n );\n }\n\n /** Close the offboarding review for a departed member. */\n closeOffboardReview(orgId: string, userId: string): Promise<{ ok: boolean; closed: number }> {\n return this.request(\n `/v1/orgs/${encodeURIComponent(orgId)}/offboard-reviews/${encodeURIComponent(userId)}/close`,\n { method: 'POST' },\n );\n }\n\n // \u2500\u2500 RBAC: Permission Levels, Security Groups, Grants (Rez 1c) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n getRoles(orgId: string): Promise<{ roles: OrgRole[] }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/roles`, { method: 'GET' });\n }\n\n createRole(orgId: string, body: { name: string; capabilities: string[] }): Promise<OrgRole> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/roles`, {\n method: 'POST',\n body: JSON.stringify(body),\n });\n }\n\n updateRole(orgId: string, roleId: string, body: { name?: string; capabilities?: string[] }): Promise<OrgRole> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/roles/${encodeURIComponent(roleId)}`, {\n method: 'PATCH',\n body: JSON.stringify(body),\n });\n }\n\n deleteRole(orgId: string, roleId: string): Promise<{ ok: boolean }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/roles/${encodeURIComponent(roleId)}`, { method: 'DELETE' });\n }\n\n getGroups(orgId: string): Promise<{ groups: OrgGroup[] }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/groups`, { method: 'GET' });\n }\n\n createGroup(orgId: string, body: { name: string }): Promise<OrgGroup> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/groups`, {\n method: 'POST',\n body: JSON.stringify(body),\n });\n }\n\n updateGroup(orgId: string, gid: string, body: { name: string }): Promise<OrgGroup> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/groups/${encodeURIComponent(gid)}`, {\n method: 'PATCH',\n body: JSON.stringify(body),\n });\n }\n\n deleteGroup(orgId: string, gid: string): Promise<{ ok: boolean }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/groups/${encodeURIComponent(gid)}`, { method: 'DELETE' });\n }\n\n getGroupMembers(orgId: string, gid: string): Promise<{ members: OrgGroupMember[] }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/groups/${encodeURIComponent(gid)}/members`, { method: 'GET' });\n }\n\n /** F4 Rez 2 Faza 1: collections a group holds a grant on (group-inheritance fan-out).\n * F3b-2: response now also carries the group's current allow-capabilities per collection. */\n getGroupCollections(orgId: string, gid: string): Promise<{ collections: OrgGroupCollection[] }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/groups/${encodeURIComponent(gid)}/collections`, { method: 'GET' });\n }\n\n /** F3b-2: direct-member mirror of getGroupCollections \u2014 powers MemberDetailPage's \u0160krinje tab. */\n getMemberCollections(orgId: string, uid: string): Promise<{ collections: OrgGroupCollection[] }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/members/${encodeURIComponent(uid)}/collections`, { method: 'GET' });\n }\n\n /** F3b-2: wires the existing admin-listing GET /v1/orgs/:id/collections route\n * (previously had zero client callers) \u2014 used to pick a not-yet-granted\n * \u0160krinja when assigning new group/member access. */\n getOrgCollections(orgId: string): Promise<{ collections: {\n vault_id: string; name: string | null; has_key: boolean;\n can_view: boolean; can_edit: boolean; rotation_required: boolean; is_default: boolean;\n }[] }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/collections`, { method: 'GET' });\n }\n\n addGroupMember(orgId: string, gid: string, userId: string): Promise<{ ok: boolean }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/groups/${encodeURIComponent(gid)}/members`, {\n method: 'POST',\n body: JSON.stringify({ user_id: userId }),\n });\n }\n\n removeGroupMember(orgId: string, gid: string, userId: string): Promise<{ ok: boolean }> {\n return this.request(\n `/v1/orgs/${encodeURIComponent(orgId)}/groups/${encodeURIComponent(gid)}/members/${encodeURIComponent(userId)}`,\n { method: 'DELETE' },\n );\n }\n\n getGrants(orgId: string): Promise<{ grants: OrgGrant[] }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/grants`, { method: 'GET' });\n }\n\n createGrant(\n orgId: string,\n body: { subject_type: 'user' | 'group'; subject_id: string; role_id?: string; capability?: string; effect?: 'allow' | 'deny' },\n ): Promise<OrgGrant> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/grants`, {\n method: 'POST',\n body: JSON.stringify(body),\n });\n }\n\n deleteGrant(orgId: string, grantId: string): Promise<{ ok: boolean }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/grants/${encodeURIComponent(grantId)}`, { method: 'DELETE' });\n }\n\n getCapabilities(orgId: string): Promise<{ capabilities: Capability[] }> {\n return this.request(`/v1/orgs/${encodeURIComponent(orgId)}/capabilities`, { method: 'GET' });\n }\n\n // \u2500\u2500 Internals \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private async request<T>(path: string, init: RequestInit, isRetry = false): Promise<T> {\n const headers = new Headers(init.headers);\n if (init.body) headers.set('Content-Type', 'application/json');\n const access = this.tokens.get()?.access_token;\n if (access) headers.set('Authorization', `Bearer ${access}`);\n\n const res = await this.doFetch(`${this.baseUrl}${path}`, {\n ...init,\n headers,\n ...(this.credentials ? { credentials: this.credentials } : {}),\n });\n\n // Refresh on 401 when we have a stored refresh token (Bearer clients) OR we're\n // in cookie mode (console: the refresh token lives in the httpOnly cookie).\n if (res.status === 401 && !isRetry && (this.tokens.get()?.refresh_token || this.cookieMode)) {\n if (await this.tryRefresh()) return this.request<T>(path, init, true);\n this.tokens.set(null);\n }\n\n const text = await res.text();\n const data = text ? (JSON.parse(text) as unknown) : null;\n if (!res.ok) {\n const body = (data ?? {}) as { detail?: string; title?: string; message?: string; code?: string; [key: string]: unknown };\n throw new ApiError(res.status, body.detail ?? body.title ?? body.message ?? `API error ${res.status}`, body.code, body);\n }\n return data as T;\n }\n\n private tryRefresh(): Promise<boolean> {\n // Single-flight: a burst of 401s triggers exactly one /refresh.\n if (this.refreshing) return this.refreshing;\n this.refreshing = this.doRefresh().finally(() => { this.refreshing = null; });\n return this.refreshing;\n }\n\n // \u2500\u2500 Token refresh (internal) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n private async doRefresh(): Promise<boolean> {\n const current = this.tokens.get();\n // Bearer clients send the refresh token in the body; the console relies on the\n // httpOnly cookie (credentials:'include'), so an empty body is valid there.\n if (!current?.refresh_token && !this.cookieMode) return false;\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), REFRESH_TIMEOUT_MS);\n try {\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (current?.access_token) headers['Authorization'] = `Bearer ${current.access_token}`;\n const res = await this.doFetch(`${this.baseUrl}/v1/auth/refresh`, {\n method: 'POST',\n headers,\n body: JSON.stringify(current?.refresh_token ? { refresh_token: current.refresh_token } : {}),\n signal: controller.signal,\n ...(this.credentials ? { credentials: this.credentials } : {}),\n });\n if (!res.ok) {\n if (typeof console !== 'undefined') console.warn(`[auth] refresh failed: ${res.status}`);\n return false;\n }\n const data = (await res.json()) as RefreshResponse;\n // access token kept in memory; refresh (also returned) stays in memory only \u2014\n // never persisted (console persists no tokens; the cookie is the source of truth).\n this.tokens.set({ access_token: data.access_token, refresh_token: data.refresh_token });\n return true;\n } catch (e) {\n if (typeof console !== 'undefined') console.warn('[auth] refresh error', e);\n return false;\n } finally {\n clearTimeout(timer);\n }\n }\n}\n", "// Tier-aware entitlement helpers. Pure derivations over the server-authoritative\n// bundle (GET /v1/account/entitlements). The console's visible surface is now\n// derived from the module registry (see platform/), so the old ConsoleSection list\n// + visibleSections() were removed (#53 PR6) to kill the registry\u2194list double truth.\n\nimport type { EntitlementsBundle, FeatureEntitlement, PlanSlug } from '../types/index.js';\n\n/** Effective plan FOR GATING. Normalizes trial\u2192premium and trial_expired\u2192free \u2014\n * the same mapping the API applies when computing features \u2014 so plan gates agree\n * with feature gates during a trial. For DISPLAY (trial badge/days remaining)\n * read the raw `bundle.primary_org.plan_slug` directly. */\nexport function planOf(bundle: EntitlementsBundle | null): PlanSlug {\n const raw = bundle?.primary_org?.plan_slug ?? 'free';\n if (raw === 'trial') return 'premium';\n if (raw === 'trial_expired') return 'free';\n return raw;\n}\n\n/** True when a named server feature is enabled. The API sends `{ enabled, tier, ... }`\n * per slug (#20); a flat boolean is tolerated as a legacy/test shape. Anything\n * else \u2014 missing key, malformed value, null bundle \u2014 is fail-closed. */\nexport function hasFeature(bundle: EntitlementsBundle | null, key: string): boolean {\n const f: unknown = bundle?.features?.[key];\n if (f === true) return true; // legacy flat-boolean shape\n if (f && typeof f === 'object') return (f as FeatureEntitlement).enabled === true;\n return false;\n}\n", "// PDP reason codes \u2014 mirrored from geslar-api/src/core/pdp/reason-codes.ts.\n// The API returns these strings in ApiError.code on 403/402 responses from\n// PDP-gated routes. Kept in sync with the server dictionary; extend here\n// when the server adds a new code.\n\nexport const PDP_REASON = {\n FORBIDDEN: 'pdp/forbidden',\n ACCOUNT_INACTIVE: 'pdp/account-inactive',\n EMAIL_UNVERIFIED: 'pdp/email-unverified',\n MFA_SETUP_REQUIRED: 'pdp/mfa-setup-required',\n SCOPE_INSUFFICIENT: 'pdp/scope-insufficient',\n PLAN_REQUIRED: 'pdp/plan-required',\n CAPABILITY_DENIED: 'pdp/capability-denied',\n ORG_TYPE_RESTRICTION: 'pdp/org-type-restriction',\n} as const;\n\nexport type PdpReason = (typeof PDP_REASON)[keyof typeof PDP_REASON];\n\nconst _PDP_CODES = new Set<string>(Object.values(PDP_REASON));\n\n/** True when `code` is a known PDP denial reason (type-guard). */\nexport function isPdpReason(code: string | undefined): code is PdpReason {\n return !!code && _PDP_CODES.has(code);\n}\n\n/** Extract a PdpReason from an unknown thrown value, or null if it isn't one.\n * Checks ApiError duck-type (status 402/403 + .code) so callers don't need\n * to import ApiError. Only org-scope denials are surfaced as walls; generic\n * 403 without a PDP code falls through to existing error handling. */\nexport function extractPdpReason(e: unknown): PdpReason | null {\n if (typeof e !== 'object' || e === null) return null;\n const err = e as { status?: unknown; code?: unknown };\n if (err.status !== 403 && err.status !== 402) return null;\n return isPdpReason(err.code as string | undefined) ? (err.code as PdpReason) : null;\n}\n", "// Vault health analysis \u2014 pure, no DOM, no transport.\n//\n// DRIFT NOTE: geslar-skrinjar/vault/vault-health.js must stay in sync with this\n// module (same ENTROPY_WEAK_THRESHOLD constant, same scoring algorithm, same\n// category definitions, same HEALTH_CATEGORY_SEV map) until vault-health.js is\n// replaced by this shared package.\n\n/** bits \u2014 mirrors vault-health.js ENTROPY_WEAK_THRESHOLD */\nexport const ENTROPY_WEAK_THRESHOLD = 40;\n\n// \u2500\u2500\u2500 Per-entry health badge types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport type HealthSeverity = 'crit' | 'warn' | 'mid' | 'info';\n\nexport interface HealthStatusResult {\n status: 'breached' | 'weak' | 'reused' | 'old' | 'empty';\n sev: HealthSeverity;\n}\n\nconst _SEV_RANK: Record<HealthSeverity, number> = { crit: 4, warn: 3, mid: 2, info: 1 };\n\n/** Shared severity map \u2014 badge and report reference the same source of truth. */\nexport const HEALTH_CATEGORY_SEV: Readonly<Record<HealthStatusResult['status'], HealthSeverity>> = {\n breached: 'crit',\n weak: 'warn',\n reused: 'mid',\n old: 'info',\n empty: 'info',\n};\n\nconst OLD_THRESHOLD_MS = 365 * 24 * 60 * 60 * 1000;\n\nfunction calcEntropy(password: string): number {\n if (!password) return 0;\n const len = password.length;\n let charsetSize = 0;\n if (/[a-z]/.test(password)) charsetSize += 26;\n if (/[A-Z]/.test(password)) charsetSize += 26;\n if (/[0-9]/.test(password)) charsetSize += 10;\n if (/[^a-zA-Z0-9]/.test(password)) charsetSize += 32;\n return len * Math.log2(charsetSize || 1);\n}\n\n/** Minimal entry shape required by the analyzer. Matches the decrypted VaultEntry. */\nexport interface HealthEntry {\n id: string;\n type?: string;\n label?: string;\n password?: string;\n username?: string;\n updated?: string;\n created?: string;\n}\n\nexport interface WeakEntry { id: string; label?: string; entropy: number }\nexport interface OldEntry { id: string; label?: string; days: number }\nexport interface EmptyEntry { id: string; label?: string; missing: string[] }\nexport interface BreachedEntry { id: string; label?: string; count: number }\n\nexport interface VaultHealthResult {\n score: number;\n weak: WeakEntry[];\n reused: { id: string; label?: string }[][];\n old: OldEntry[];\n empty: EmptyEntry[];\n breached: BreachedEntry[];\n total: number;\n}\n\n/** Injected dep: receives plaintext passwords, returns breach status keyed by password.\n * SHA-1 hashing and HTTP transport are the caller's concern \u2014 analyzer stays clean. */\nexport type CheckBreachesFn = (\n passwords: string[],\n) => Promise<Map<string, { breached: boolean; count: number }>>;\n\nexport interface HealthDeps {\n checkBreaches: CheckBreachesFn;\n /** Epoch ms \"now\" \u2014 injectable for deterministic tests (default: Date.now()). */\n nowMs?: number;\n}\n\n/** Analyze vault health. Mirrors vault-health.js VaultHealth.analyze() 1:1. */\nexport async function analyzeVaultHealth(\n entries: HealthEntry[],\n deps: HealthDeps,\n): Promise<VaultHealthResult> {\n const loginEntries = entries.filter((e) => e.type !== 'card');\n const now = deps.nowMs ?? Date.now();\n\n // 1. Weak\n const weak: WeakEntry[] = [];\n for (const e of loginEntries) {\n if (!e.password) continue;\n const entropy = calcEntropy(e.password);\n if (entropy < ENTROPY_WEAK_THRESHOLD) {\n weak.push({ id: e.id, label: e.label, entropy: Math.round(entropy) });\n }\n }\n\n // 2. Reused\n const pwMap = new Map<string, { id: string; label?: string }[]>();\n for (const e of loginEntries) {\n if (!e.password) continue;\n const list = pwMap.get(e.password) ?? [];\n list.push({ id: e.id, label: e.label });\n pwMap.set(e.password, list);\n }\n const reused: { id: string; label?: string }[][] = [];\n for (const [, group] of pwMap) {\n if (group.length > 1) reused.push(group);\n }\n\n // 3. Old \u2014 skip entries with no date (no date \u2260 old; mirrors vault-health.js)\n const old: OldEntry[] = [];\n for (const e of loginEntries) {\n if (!e.password) continue;\n const dateStr = e.updated ?? e.created;\n if (!dateStr) continue;\n const ts = new Date(dateStr).getTime();\n if (now - ts > OLD_THRESHOLD_MS) {\n const days = Math.floor((now - ts) / 86_400_000);\n old.push({ id: e.id, label: e.label, days });\n }\n }\n\n // 4. Empty\n const empty: EmptyEntry[] = [];\n for (const e of loginEntries) {\n const missing: string[] = [];\n if (!e.password) missing.push('lozinka');\n if (!e.username) missing.push('korisnik');\n if (missing.length) empty.push({ id: e.id, label: e.label, missing });\n }\n\n // 5. Breached\n const totalLogin = loginEntries.length;\n if (totalLogin === 0) {\n return { score: 100, weak: [], reused: [], old: [], empty: [], breached: [], total: 0 };\n }\n\n const uniquePasswords = [\n ...new Set(loginEntries.map((e) => e.password).filter((p): p is string => !!p)),\n ];\n const breachMap = uniquePasswords.length > 0\n ? await deps.checkBreaches(uniquePasswords)\n : new Map<string, { breached: boolean; count: number }>();\n\n const breached: BreachedEntry[] = [];\n for (const e of loginEntries) {\n if (!e.password) continue;\n const result = breachMap.get(e.password);\n if (result?.breached) {\n breached.push({ id: e.id, label: e.label, count: result.count });\n }\n }\n\n // Score (0-100)\n const issueEntries = new Set<string>();\n weak.forEach((e) => issueEntries.add(e.id));\n reused.forEach((g) => g.forEach((e) => issueEntries.add(e.id)));\n old.forEach((e) => issueEntries.add(e.id));\n breached.forEach((e) => issueEntries.add(e.id));\n empty.filter((e) => e.missing.includes('lozinka')).forEach((e) => issueEntries.add(e.id));\n\n const score = Math.round((1 - issueEntries.size / totalLogin) * 100);\n return { score, weak, reused, old, empty, breached, total: totalLogin };\n}\n\n/**\n * Worst-wins badge status for a single entry.\n * Returns null when entry has no health issues.\n * Severity rank: crit > warn > mid > info.\n */\nexport function entryHealthStatus(\n entryId: string,\n result: VaultHealthResult,\n): HealthStatusResult | null {\n let best: HealthStatusResult | null = null;\n\n function consider(status: HealthStatusResult['status']): void {\n const sev = HEALTH_CATEGORY_SEV[status];\n if (!best || _SEV_RANK[sev] > _SEV_RANK[best.sev]) {\n best = { status, sev };\n }\n }\n\n if (result.breached.some((e) => e.id === entryId)) consider('breached');\n if (result.weak.some((e) => e.id === entryId)) consider('weak');\n if (result.reused.some((g) => g.some((e) => e.id === entryId))) consider('reused');\n if (result.old.some((e) => e.id === entryId)) consider('old');\n if (result.empty.some((e) => e.id === entryId && e.missing.includes('lozinka'))) consider('empty');\n\n return best;\n}\n", "import { ApiClient, type TokenStore } from '@geslar/core';\n\n/** Single wiring point for ApiClient \u2014 mirrors apps/admin/src/lib/core.ts, but\n * Bearer-mode (no cookies) and a caller-supplied OS-backed TokenStore instead\n * of memoryTokenStore(). */\nexport function buildApiClient(baseUrl: string, tokenStore: TokenStore): ApiClient {\n return new ApiClient({ baseUrl, tokenStore });\n}\n", "import { ApiError, planOf } from '@geslar/core';\nimport { loadSession } from '../lib/session.js';\nimport { loadOrInitConfig } from '../lib/config.js';\nimport { buildApiClient } from '../lib/core.js';\nimport { print, printErr } from '../lib/output.js';\nimport { EXIT } from '../lib/errors.js';\nimport { selectBackend, createCliTokenStore } from '../token-store/index.js';\n\nexport async function whoamiCommand(): Promise<number> {\n const backend = await selectBackend();\n const tokenStore = await createCliTokenStore(backend);\n const tokens = tokenStore.get();\n\n if (!tokens) {\n printErr('not signed in \u2014 run `geslar signin`');\n return EXIT.AUTH;\n }\n\n const session = await loadSession();\n const config = await loadOrInitConfig();\n const baseUrl = session?.apiBase ?? config.apiBase;\n const api = buildApiClient(baseUrl, tokenStore);\n\n try {\n const entitlements = await api.getEntitlements();\n await tokenStore.flush(); // a silent refresh may have rotated tokens\n const plan = planOf(entitlements);\n const org = entitlements.primary_org;\n\n print(`Account: ${session?.email ?? '(unknown \u2014 re-run `geslar signin`)'}`);\n print(`Plan: ${plan}`);\n if (org?.id) {\n print(`Org: ${org.id}${org.role ? ` (${org.role})` : ''}`);\n }\n print(`API: ${baseUrl}`);\n print(`Storage: ${backend.name}`);\n return EXIT.OK;\n } catch (err) {\n await tokenStore.flush();\n if (err instanceof ApiError && (err.status === 401 || err.status === 403)) {\n printErr('session expired \u2014 run `geslar signin` again');\n return EXIT.AUTH;\n }\n printErr((err as Error).message);\n return EXIT.GENERAL;\n }\n}\n", "import { CliError, EXIT } from './errors.js';\n\nconst TOTP_CTRL_C = '\u0003';\nconst TOTP_CTRL_D = '\u0004';\nconst TOTP_BACKSPACE = '\u007F';\n\n/** TTY no-echo TOTP-code prompt (`geslar agent create`, spec-access-core.md\n * \u00A74) \u2014 same no-echo skeleton as promptPassword, kept as its own function\n * (not a shared refactor of promptPassword) so that function's existing\n * behavior/message/exit-code stay byte-identical for the master-password\n * flow. `ttyError` lets the caller choose the exit code/message for \"no\n * TTY\" \u2014 agent create's TTY gate is a distinct condition from a locked vault. */\nexport function promptTotpCode(promptText: string, ttyError: CliError): Promise<string> {\n return new Promise((resolve, reject) => {\n if (!process.stdin.isTTY) {\n reject(ttyError);\n return;\n }\n\n process.stdout.write(promptText);\n const stdin = process.stdin;\n stdin.setRawMode(true);\n stdin.resume();\n stdin.setEncoding('utf8');\n\n let input = '';\n const onData = (chunk: string) => {\n const char = chunk.toString();\n if (char === '\\n' || char === '\\r' || char === TOTP_CTRL_D) {\n cleanup();\n process.stdout.write('\\n');\n resolve(input.trim());\n return;\n }\n if (char === TOTP_CTRL_C) {\n cleanup();\n process.stdout.write('\\n');\n reject(new CliError(EXIT.GENERAL, 'Aborted'));\n return;\n }\n if (char === TOTP_BACKSPACE || char === '\\b') {\n input = input.slice(0, -1);\n return;\n }\n input += char;\n };\n function cleanup() {\n stdin.setRawMode(false);\n stdin.pause();\n stdin.removeListener('data', onData);\n }\n stdin.on('data', onData);\n });\n}\n\nconst CTRL_C = '\u0003';\nconst CTRL_D = '\u0004';\nconst BACKSPACE = '\u007F';\n\n/** TTY no-echo master-password prompt (spec \u00A73.7/\u00A78.2) \u2014 nothing is echoed\n * back, not even asterisks; the password never touches argv or env, and\n * never leaves this process. Rejects immediately if stdin isn't a TTY (the\n * caller decides what to do \u2014 e.g. fall back to a `geslar unlock` grant, or\n * fail closed with exit 6). */\nexport function promptPassword(promptText: string): Promise<string> {\n return new Promise((resolve, reject) => {\n if (!process.stdin.isTTY) {\n reject(new CliError(EXIT.VAULT_LOCKED, 'No TTY available for a master-password prompt \u2014 run `geslar unlock` first'));\n return;\n }\n\n process.stdout.write(promptText);\n const stdin = process.stdin;\n stdin.setRawMode(true);\n stdin.resume();\n stdin.setEncoding('utf8');\n\n let input = '';\n const onData = (chunk: string) => {\n const char = chunk.toString();\n if (char === '\\n' || char === '\\r' || char === CTRL_D) {\n cleanup();\n process.stdout.write('\\n');\n resolve(input);\n return;\n }\n if (char === CTRL_C) {\n cleanup();\n process.stdout.write('\\n');\n reject(new CliError(EXIT.GENERAL, 'Aborted'));\n return;\n }\n if (char === BACKSPACE || char === '\\b') {\n input = input.slice(0, -1);\n return;\n }\n input += char;\n };\n function cleanup() {\n stdin.setRawMode(false);\n stdin.pause();\n stdin.removeListener('data', onData);\n }\n stdin.on('data', onData);\n });\n}\n", "// @geslar/core \u2014 crypto entry for TS/ESM consumers (admin console, web).\n//\n// The two crypto modules (`vault-crypto.js`, `vault-cloud-crypto.js`) are the\n// single source of truth, authored as classic scripts so the browser extension\n// can vendor and importScripts() them verbatim (see scripts/vendor-core.mjs).\n// `vault-cloud-crypto.js` reads `VaultCrypto` from the global scope (as it does\n// inside the extension's service worker), so we publish it on globalThis before\n// re-exporting. The crypto itself uses only Web Crypto (`crypto.subtle`) \u2014 no\n// eval/Function \u2014 so it stays MV3 CSP-safe in every consumer.\n//\n// Default imports resolve to each module's `module.exports` (CommonJS via the\n// sibling package.json), which works under Node ESM and Vite/esbuild alike.\n\nimport VaultCrypto from './vault-crypto.js';\n\n// Must exist before any VaultCloudCrypto.* call; module init is well before use.\nglobalThis.VaultCrypto = VaultCrypto;\n\nimport VaultCloudCrypto from './vault-cloud-crypto.js';\nimport OrgRecoveryCrypto from './recovery-enrollment.js';\n\nexport { VaultCrypto, VaultCloudCrypto, OrgRecoveryCrypto };\n", "import { VaultCrypto, VaultCloudCrypto } from '@geslar/core/crypto';\nimport type { VaultKeyMaterial } from '@geslar/core';\n\n/** Wrong master password (AES-GCM tag verification failure on unwrap) \u2014\n * distinct from \"no vault key material at all\" so callers can give the\n * right message (spec \u00A78.2: master password never leaves the process). */\nexport class WrongMasterPasswordError extends Error {\n constructor() {\n super('Incorrect master password');\n this.name = 'WrongMasterPasswordError';\n }\n}\n\nexport interface UnlockedKeys {\n /** Raw DEK bytes \u2014 kept raw (not imported to a CryptoKey) so `geslar unlock`\n * can persist them into the OS-wrapped grant; `importVaultKey` produces a\n * NON-extractable key, so importing early would make that impossible. */\n dekRaw: Uint8Array;\n /** Raw (PKCS8) ECDH private key bytes \u2014 present only if the account has one\n * wrapped server-side (needed to unwrap team_collection DEKs). */\n ecdhPrivRaw: Uint8Array | null;\n}\n\n/**\n * The local KDF chain (spec \u00A73.3/\u00A73.7): master password NEVER leaves this\n * process. `material` comes from GET /v1/account/vault-key-material (M2\n * dependency, geslar-api#97) \u2014 already-wrapped blobs only, no auth_hash.\n */\nexport async function deriveAndUnlock(password: string, material: VaultKeyMaterial): Promise<UnlockedKeys> {\n if (!material.encrypted_vault_key) {\n throw new Error('This account has no vault key yet \u2014 sign in via the console first to finish setup.');\n }\n\n const salt = VaultCrypto.base64ToBuf(material.enc_salt);\n const masterKey = await VaultCrypto.deriveMasterKey(password, salt);\n\n let dekRaw: Uint8Array;\n try {\n dekRaw = await VaultCloudCrypto.unwrapVaultKey(masterKey, material.encrypted_vault_key);\n } catch {\n throw new WrongMasterPasswordError();\n }\n\n let ecdhPrivRaw: Uint8Array | null = null;\n if (material.encrypted_ecdh_private_key) {\n // Master password already verified above (DEK unwrap succeeded) \u2014 a\n // failure here means corrupted/mismatched state, not a wrong password.\n ecdhPrivRaw = await VaultCloudCrypto.unwrapVaultKey(masterKey, material.encrypted_ecdh_private_key);\n }\n\n return { dekRaw, ecdhPrivRaw };\n}\n", "import { buildApiClient } from '../lib/core.js';\nimport { loadSession } from '../lib/session.js';\nimport { loadOrInitConfig } from '../lib/config.js';\nimport { selectBackend, createCliTokenStore } from '../token-store/index.js';\nimport { promptPassword } from '../lib/prompt.js';\nimport { print, printErr } from '../lib/output.js';\nimport { CliError, EXIT } from '../lib/errors.js';\nimport { deriveAndUnlock } from '../vault/unlock.js';\nimport { saveVaultGrant, parseTtl } from '../vault/grant.js';\n\nexport async function unlockCommand(opts: { ttl?: string }): Promise<number> {\n try {\n const ttlSec = parseTtl(opts.ttl);\n\n const config = await loadOrInitConfig();\n const session = await loadSession();\n const baseUrl = session?.apiBase ?? config.apiBase;\n const backend = await selectBackend();\n const tokenStore = await createCliTokenStore(backend);\n if (!tokenStore.get()) {\n printErr('not signed in \u2014 run `geslar signin`');\n return EXIT.AUTH;\n }\n const api = buildApiClient(baseUrl, tokenStore);\n\n const material = await api.getVaultKeyMaterial();\n await tokenStore.flush(); // a silent refresh during that call may have rotated tokens\n\n const password = await promptPassword('Master password: ');\n const unlocked = await deriveAndUnlock(password, material);\n await saveVaultGrant(unlocked, ttlSec);\n\n const mins = Math.round(ttlSec / 60);\n print(`Vault unlocked for ${mins} minute${mins === 1 ? '' : 's'}.`);\n return EXIT.OK;\n } catch (err) {\n if (err instanceof CliError) {\n printErr(err.message);\n return err.exitCode;\n }\n printErr((err as Error).message);\n return EXIT.GENERAL;\n }\n}\n", "import { print } from '../lib/output.js';\nimport { clearVaultGrant } from '../vault/grant.js';\nimport { EXIT } from '../lib/errors.js';\n\nexport async function lockCommand(): Promise<number> {\n await clearVaultGrant();\n print('Vault locked.');\n return EXIT.OK;\n}\n", "import type { ApiClient } from '@geslar/core';\nimport { promptPassword } from '../lib/prompt.js';\nimport { CliError, EXIT } from '../lib/errors.js';\nimport { loadVaultGrant } from './grant.js';\nimport { deriveAndUnlock, type UnlockedKeys } from './unlock.js';\n\n/**\n * Obtain the DEK (+ ECDH key) needed to decrypt entries: prefer an existing\n * `geslar unlock` grant (headless-friendly); otherwise, in a TTY, prompt for\n * the master password once WITHOUT persisting anything (spec \u00A73.7: \"geslar\n * run u TTY-ju bez granta pita lozinku po pozivu \u2014 ni\u0161ta se ne sprema\").\n * No grant + no TTY \u2192 fail closed, exit 6.\n */\nexport async function obtainUnlockedKeys(api: ApiClient): Promise<UnlockedKeys> {\n const grant = await loadVaultGrant();\n if (grant) return grant;\n\n if (!process.stdin.isTTY) {\n throw new CliError(EXIT.VAULT_LOCKED, 'Vault is locked and no TTY is available \u2014 run `geslar unlock` first');\n }\n\n const material = await api.getVaultKeyMaterial();\n const password = await promptPassword('Master password: ');\n return deriveAndUnlock(password, material);\n}\n", "import type { ApiClient, CollectionSummary, MemberKeyEntry, Org, OrgType } from '@geslar/core';\nimport { VaultCrypto, VaultCloudCrypto } from '@geslar/core/crypto';\nimport type { UnlockedKeys } from './unlock.js';\n\nexport const PERSONAL_VAULT_NAME = 'Osobno';\n\nexport interface VaultHandle {\n id: string;\n /** Effective display/match name \u2014 for an org's default collection this is\n * the ORG's name, never the stored placeholder (\"Obiteljska \u0161krinja\" /\n * \"Op\u0107a \u0161krinja\", spec REV 2.4.1 \u00A72's \"kontrakt zadanih kolekcija\": that\n * stored name is never shown or matched, `list` and the resolver both use\n * the org name instead). */\n name: string;\n kind: 'personal' | 'collection';\n /** Owning org \u2014 null only for the personal vault (kept as its own `kind`\n * case, same as before REV 2.4; a personal org's own name/type is never\n * part of the semantic-token or org-name addressing scheme). */\n orgId: string | null;\n orgType: OrgType | null;\n /** True for the org's singleton auto-created collection (personal vault\n * counts as its \"org\"'s only vault, so also true). Needed to find \"the\n * default vault of org X\" for `family`/`company`/`work` token resolution. */\n isDefault: boolean;\n /** key_version \u2192 CryptoKey. Personal vaults only ever have version 1\n * (server sends no key_version for entries there \u2014 treat as 1, same\n * convention apps/admin uses). Collections may have several during a\n * key rotation window. */\n dekMap: Map<number, CryptoKey>;\n}\n\n/** Mirrors apps/admin/src/lib/dek-map.ts's buildDekMap \u2014 kept as a small local\n * copy rather than a cross-app import (that file isn't part of @geslar/core). */\nasync function buildCollectionDekMap(\n keys: MemberKeyEntry[] | undefined,\n fallback: { key_version: number; encrypted_key: string | null; wrapper_ecdh_pub: string | null } | null,\n ecdhPrivRaw: Uint8Array,\n): Promise<Map<number, CryptoKey>> {\n const source: Array<{ key_version: number; encrypted_key: string | null; ecdh_public_key: string | null }> =\n keys && keys.length > 0\n ? keys.map(k => ({ key_version: k.key_version, encrypted_key: k.encrypted_key, ecdh_public_key: k.wrapped_by?.ecdh_public_key ?? null }))\n : fallback\n ? [{ key_version: fallback.key_version, encrypted_key: fallback.encrypted_key, ecdh_public_key: fallback.wrapper_ecdh_pub }]\n : [];\n\n const map = new Map<number, CryptoKey>();\n for (const k of source) {\n if (!k.encrypted_key || !k.ecdh_public_key) continue; // no usable key material for this version \u2014 skip, not fatal\n const wrapperPub = VaultCrypto.base64ToBuf(k.ecdh_public_key);\n const dekRaw = await VaultCloudCrypto.unwrapSharedVaultKey(ecdhPrivRaw, wrapperPub, k.encrypted_key);\n map.set(k.key_version, await VaultCloudCrypto.importVaultKey(dekRaw));\n }\n return map;\n}\n\n/**\n * All vaults the caller can currently read: the personal vault (always) plus\n * any team_collection \u0161krinje visible via GET /v1/collections. A collection\n * the caller can't unwrap (no ECDH key on this account yet, or missing key\n * material) is silently omitted from the list rather than erroring the whole\n * command \u2014 it simply won't resolve as a `geslar://` target.\n */\nexport async function listVaultHandles(api: ApiClient, unlocked: UnlockedKeys): Promise<VaultHandle[]> {\n const handles: VaultHandle[] = [];\n\n const personal = await api.ensurePersonalVault();\n handles.push({\n id: personal.vault_id,\n name: PERSONAL_VAULT_NAME,\n kind: 'personal',\n orgId: null,\n orgType: null,\n isDefault: true,\n dekMap: new Map([[1, await VaultCloudCrypto.importVaultKey(unlocked.dekRaw)]]),\n });\n\n if (unlocked.ecdhPrivRaw) {\n // GET /v1/collections doesn't carry org type (only org_id/org_name) \u2014\n // GET /v1/orgs is the one surface that does, so both are fetched and\n // joined by org_id.\n const [{ collections }, orgs] = await Promise.all([api.getCollections(), api.getOrgs()]);\n const orgTypeById = new Map<string, OrgType>((orgs as Org[]).map(o => [o.id, o.type]));\n\n for (const c of collections as CollectionSummary[]) {\n if (!c.can_view || !c.name) continue;\n const isDefault = c.is_default === true;\n // Spec REV 2.4.1 \u00A72 \"kontrakt zadanih kolekcija\": the stored name of a\n // default collection is never shown or matched \u2014 the org's name is\n // used instead everywhere.\n const name = isDefault ? (c.org_name ?? c.name) : c.name;\n const dekMap = await buildCollectionDekMap(\n c.keys,\n { key_version: c.key_version, encrypted_key: c.encrypted_key, wrapper_ecdh_pub: c.wrapper_ecdh_pub },\n unlocked.ecdhPrivRaw,\n );\n if (dekMap.size === 0) continue; // couldn't unwrap any version \u2014 omit\n handles.push({\n id: c.vault_id,\n name,\n kind: 'collection',\n orgId: c.org_id,\n orgType: c.org_id ? (orgTypeById.get(c.org_id) ?? null) : null,\n isDefault,\n dekMap,\n });\n }\n }\n\n return handles;\n}\n", "import type { ApiClient, CollectionSummary } from '@geslar/core';\nimport { VaultCrypto, VaultCloudCrypto } from '@geslar/core/crypto';\nimport type { UnlockedKeys } from './unlock.js';\nimport type { VaultHandle } from './vaults.js';\nimport { PERSONAL_VAULT_NAME } from './vaults.js';\nimport type { AgentTokenVaultRef } from '../agent/token-store.js';\n\n/**\n * Agent-context counterpart to listVaultHandles (spec-access-core.md REV 1.2\n * \u00A74) \u2014 deliberately does NOT call ensurePersonalVault() or getOrgs(): neither\n * is on the agent bearer allowlist (POST /v1/sync/vault is a write; GET\n * /v1/orgs isn't listed at all). GET /v1/collections IS allowlisted and\n * already server-filters to this agent's granted team_collections, so that\n * half works unmodified. The personal vault (if granted) has no allowlisted\n * discovery route at all \u2014 its id/name come from `grantedVaults`, the\n * locally-cached snapshot captured at `agent create` time (safe: scope is\n * immutable, see agent/token-store.ts's doc comment).\n *\n * A granted vault the server no longer serves (owner lost access, profile\n * revoked mid-flight) simply won't appear in GET /v1/collections \u2014 same\n * fail-closed-by-omission behavior as the human path, no special-casing\n * needed here.\n */\nexport async function listAgentVaultHandles(\n api: ApiClient,\n unlocked: UnlockedKeys,\n grantedVaults: AgentTokenVaultRef[],\n): Promise<VaultHandle[]> {\n const handles: VaultHandle[] = [];\n\n const personalGrant = grantedVaults.find(v => v.kind === 'personal');\n if (personalGrant) {\n handles.push({\n id: personalGrant.id,\n name: PERSONAL_VAULT_NAME,\n kind: 'personal',\n orgId: null,\n orgType: null,\n isDefault: true,\n dekMap: new Map([[1, await VaultCloudCrypto.importVaultKey(unlocked.dekRaw)]]),\n });\n }\n\n const hasCollectionGrant = grantedVaults.some(v => v.kind === 'collection');\n if (hasCollectionGrant && unlocked.ecdhPrivRaw) {\n const { collections } = await api.getCollections();\n for (const c of collections as CollectionSummary[]) {\n if (!c.can_view || !c.name) continue;\n const isDefault = c.is_default === true;\n const name = isDefault ? (c.org_name ?? c.name) : c.name;\n const dekMap = await buildCollectionDekMap(c, unlocked.ecdhPrivRaw);\n if (dekMap.size === 0) continue;\n handles.push({\n id: c.vault_id,\n name,\n kind: 'collection',\n orgId: c.org_id,\n // getOrgs() isn't on the agent allowlist \u2014 org type (needed only for\n // the family/company/work semantic tokens) is unavailable under\n // agent context; direct vault-name addressing is unaffected.\n orgType: null,\n isDefault,\n dekMap,\n });\n }\n }\n\n return handles;\n}\n\n// Mirrors vault/vaults.ts's buildCollectionDekMap exactly (not exported from\n// there) \u2014 same small local-copy precedent that file's own doc comment notes\n// for apps/admin's version.\nasync function buildCollectionDekMap(c: CollectionSummary, ecdhPrivRaw: Uint8Array): Promise<Map<number, CryptoKey>> {\n const source = c.keys && c.keys.length > 0\n ? c.keys.map(k => ({ key_version: k.key_version, encrypted_key: k.encrypted_key, ecdh_public_key: k.wrapped_by?.ecdh_public_key ?? null }))\n : c.encrypted_key\n ? [{ key_version: c.key_version, encrypted_key: c.encrypted_key, ecdh_public_key: c.wrapper_ecdh_pub }]\n : [];\n\n const map = new Map<number, CryptoKey>();\n for (const k of source) {\n if (!k.encrypted_key || !k.ecdh_public_key) continue;\n const wrapperPub = VaultCrypto.base64ToBuf(k.ecdh_public_key);\n const dekRaw = await VaultCloudCrypto.unwrapSharedVaultKey(ecdhPrivRaw, wrapperPub, k.encrypted_key);\n map.set(k.key_version, await VaultCloudCrypto.importVaultKey(dekRaw));\n }\n return map;\n}\n", "// RFC 6238 TOTP via Web Crypto HMAC \u2014 copied from packages/ui/src/logic/totp.ts\n// (generateTotp/base32Decode only \u2014 the ring/color helpers there are pure UI\n// concerns). Kept as a local copy rather than a @geslar/ui dependency: the UI\n// package pulls in React, which a Node CLI has no business depending on for\n// ~30 lines of crypto logic. Keep in sync manually if the RFC 6238 core ever\n// changes (unlikely \u2014 it hasn't since it was written).\n\nexport interface TotpParams {\n secret: string; // base32\n digits?: number; // default 6\n period?: number; // default 30\n algorithm?: 'SHA-1' | 'SHA-256' | 'SHA-512'; // default SHA-1\n}\n\nconst B32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';\n\n/** Decode an RFC 4648 base32 string (case-insensitive, padding/space tolerant). */\nexport function base32Decode(input: string): Uint8Array {\n const clean = input.replace(/[\\s=]/g, '').toUpperCase();\n let bits = 0;\n let value = 0;\n const out: number[] = [];\n for (const ch of clean) {\n const idx = B32.indexOf(ch);\n if (idx === -1) continue; // skip stray chars rather than throw\n value = (value << 5) | idx;\n bits += 5;\n if (bits >= 8) {\n bits -= 8;\n out.push((value >>> bits) & 0xff);\n }\n }\n return new Uint8Array(out);\n}\n\nfunction counterBytes(counter: number): Uint8Array {\n const buf = new Uint8Array(8);\n let hi = Math.floor(counter / 0x100000000);\n let lo = counter >>> 0;\n for (let i = 7; i >= 4; i--) { buf[i] = lo & 0xff; lo = Math.floor(lo / 256); }\n for (let i = 3; i >= 0; i--) { buf[i] = hi & 0xff; hi = Math.floor(hi / 256); }\n return buf;\n}\n\n/** Generate the TOTP code for `nowMs` (defaults to current time). */\nexport async function generateTotp(params: TotpParams, nowMs?: number): Promise<{ code: string; remaining: number }> {\n const digits = params.digits ?? 6;\n const period = params.period ?? 30;\n const algorithm = params.algorithm ?? 'SHA-1';\n const now = Math.floor((nowMs ?? Date.now()) / 1000);\n const counter = Math.floor(now / period);\n const remaining = period - (now % period);\n\n const keyRaw = base32Decode(params.secret) as BufferSource;\n const key = await crypto.subtle.importKey('raw', keyRaw, { name: 'HMAC', hash: algorithm }, false, ['sign']);\n const mac = new Uint8Array(await crypto.subtle.sign('HMAC', key, counterBytes(counter) as BufferSource));\n\n const offset = mac[mac.length - 1]! & 0x0f;\n const bin =\n ((mac[offset]! & 0x7f) << 24) |\n ((mac[offset + 1]! & 0xff) << 16) |\n ((mac[offset + 2]! & 0xff) << 8) |\n (mac[offset + 3]! & 0xff);\n const code = (bin % 10 ** digits).toString().padStart(digits, '0');\n return { code, remaining };\n}\n", "import type { ApiClient } from '@geslar/core';\nimport { VaultCloudCrypto } from '@geslar/core/crypto';\nimport type { VaultHandle } from './vaults.js';\nimport { generateTotp, type TotpParams } from './totp.js';\n\nexport interface DecryptedEntry {\n id: string;\n type: string;\n label: string;\n username?: string;\n password?: string;\n url?: string;\n notes?: string;\n totp?: TotpParams;\n customFields?: { label: string; value: string }[];\n}\n\n// Decrypted blob shape is intentionally untyped upstream (apps/admin/src/lib/vault.ts's\n// VaultEntry is `{ id, type, label?, version, [key: string]: unknown }`) \u2014 this repo has\n// no formal schema for the `login` type. Field names below match EntryEditor.tsx's saved shape.\ninterface RawEntry {\n id?: string;\n type?: string;\n label?: string;\n name?: string;\n username?: string;\n password?: string;\n url?: string;\n uris?: { uri: string }[];\n notes?: string;\n totp?: TotpParams;\n customFields?: { label: string; value: string; type?: string }[];\n deleted_at?: string | null;\n}\n\n/** Decrypt every non-deleted, non-internal entry in a vault. */\nexport async function listDecryptedEntries(api: ApiClient, vault: VaultHandle): Promise<DecryptedEntry[]> {\n const wire = await api.getVaultEntries(vault.id);\n const out: DecryptedEntry[] = [];\n\n for (const w of wire) {\n if (w.deleted_at) continue; // tombstone\n\n const keyVersion = w.key_version ?? 1;\n const key = vault.dekMap.get(keyVersion);\n if (!key) {\n // Rotation in progress and this entry's version isn't available yet \u2014\n // skip rather than fail the whole list/read (spec: fail-closed only on\n // the SPECIFIC ref being resolved, not on unrelated sibling entries).\n continue;\n }\n\n const raw = await VaultCloudCrypto.decryptEntry(key, w.encrypted_blob) as RawEntry;\n if (raw.deleted_at) continue;\n if ((raw.type ?? w.entry_type) === '_folders') continue; // internal folder-structure entry\n\n out.push({\n id: raw.id ?? w.id,\n type: raw.type ?? w.entry_type,\n label: raw.label ?? raw.name ?? '(untitled)',\n username: raw.username,\n password: raw.password,\n url: raw.url ?? raw.uris?.[0]?.uri,\n notes: raw.notes,\n totp: raw.totp,\n customFields: raw.customFields?.map(f => ({ label: f.label, value: f.value })),\n });\n }\n\n return out;\n}\n\n/** Resolve the `totp` field to the current computed code (spec \u00A72 \u2014 `totp`\n * means the computed code, never the raw secret). */\nexport async function resolveTotpCode(entry: DecryptedEntry): Promise<string> {\n if (!entry.totp) {\n throw new Error(`Item \"${entry.label}\" has no TOTP configured`);\n }\n const { code } = await generateTotp(entry.totp);\n return code;\n}\n", "import type { OrgType } from '@geslar/core';\nimport { CliError, EXIT } from './lib/errors.js';\nimport type { VaultHandle } from './vault/vaults.js';\nimport type { DecryptedEntry } from './vault/entries.js';\nimport { resolveTotpCode } from './vault/entries.js';\n\n/** `geslar://` grammar errors (spec \u00A72) \u2014 never carries a value, only names/ids\n * (names/ids aren't secrets; only entry field VALUES are). Maps to exit 4. */\nexport class UnresolvableRefError extends CliError {\n constructor(message: string) {\n super(EXIT.UNRESOLVABLE_REF, message);\n this.name = 'UnresolvableRefError';\n }\n}\n\nexport interface ParsedRef {\n vaultQuery: string;\n /** Empty when `itemId` is set (an `id:` qualifier was used instead). */\n itemQuery: string;\n itemId: string | null;\n field: string;\n}\n\nconst PREFIX = 'geslar://';\n\nfunction decodeSegment(seg: string): string {\n try {\n return decodeURIComponent(seg);\n } catch {\n throw new UnresolvableRefError(`Malformed percent-encoding in \"${seg}\"`);\n }\n}\n\n/** Pure, synchronous grammar parse (spec \u00A72) \u2014 no vault/entry lookups here. */\nexport function parseRef(ref: string): ParsedRef {\n if (!ref.startsWith(PREFIX)) {\n throw new UnresolvableRefError(`Not a geslar:// reference: \"${ref}\"`);\n }\n const rest = ref.slice(PREFIX.length);\n if (rest.length === 0) {\n throw new UnresolvableRefError('Empty geslar:// reference');\n }\n\n // Escaping (\u00A72): a literal \"/\" inside a name is %2F, which contains no raw\n // \"/\" byte \u2014 splitting on the raw character is therefore always correct;\n // decodeURIComponent per-segment turns %2F back into \"/\" afterwards.\n const segments = rest.split('/');\n if (segments.length < 2) {\n throw new UnresolvableRefError(`geslar:// reference needs at least <vault>/<item> \u2014 got \"${ref}\"`);\n }\n if (segments.length > 3) {\n throw new UnresolvableRefError(`Too many \"/\"-separated parts in \"${ref}\" \u2014 escape a literal \"/\" as %2F`);\n }\n\n const vaultQuery = decodeSegment(segments[0]!);\n if (vaultQuery.toLowerCase().startsWith('org:')) {\n throw new UnresolvableRefError('The org: qualifier is not implemented yet (v1) \u2014 use a unique collection name instead');\n }\n\n const itemRaw = decodeSegment(segments[1]!);\n let itemId: string | null = null;\n let itemQuery = itemRaw;\n if (itemRaw.startsWith('id:')) {\n itemId = itemRaw.slice(3);\n itemQuery = '';\n if (itemId.length === 0) throw new UnresolvableRefError('Empty id: qualifier');\n }\n\n const field = segments[2] !== undefined ? decodeSegment(segments[2]!) : 'password';\n if (field.length === 0) {\n throw new UnresolvableRefError('Empty field name after the last \"/\"');\n }\n\n return { vaultQuery, itemQuery, itemId, field };\n}\n\n// \u2500\u2500 \"Did you mean\" \u2014 simple Levenshtein nearest-match \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction levenshtein(a: string, b: string): number {\n const al = a.length;\n const bl = b.length;\n if (al === 0) return bl;\n if (bl === 0) return al;\n const dp: number[][] = Array.from({ length: al + 1 }, () => new Array<number>(bl + 1).fill(0));\n for (let i = 0; i <= al; i++) dp[i]![0] = i;\n for (let j = 0; j <= bl; j++) dp[0]![j] = j;\n for (let i = 1; i <= al; i++) {\n for (let j = 1; j <= bl; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n dp[i]![j] = Math.min(dp[i - 1]![j]! + 1, dp[i]![j - 1]! + 1, dp[i - 1]![j - 1]! + cost);\n }\n }\n return dp[al]![bl]!;\n}\n\nfunction closestMatch(query: string, candidates: string[]): string | null {\n if (candidates.length === 0 || query.length === 0) return null;\n const q = query.toLowerCase();\n let best: { name: string; dist: number } | null = null;\n for (const c of candidates) {\n const dist = levenshtein(q, c.toLowerCase());\n if (!best || dist < best.dist) best = { name: c, dist };\n }\n const threshold = Math.max(2, Math.ceil(query.length * 0.4));\n return best && best.dist <= threshold ? best.name : null;\n}\n\n// \u2500\u2500 Resolution against a live vault/entry set \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface ResolveContext {\n vaults: VaultHandle[];\n getEntries(vault: VaultHandle): Promise<DecryptedEntry[]>;\n}\n\nexport interface ResolvedRef {\n vault: VaultHandle;\n entry: DecryptedEntry;\n field: string;\n value: string;\n}\n\nfunction requireNonEmpty(value: string | undefined, label: string, field: string): string {\n if (!value) throw new UnresolvableRefError(`Field \"${field}\" on item \"${label}\" is empty`);\n return value;\n}\n\nasync function resolveField(entry: DecryptedEntry, field: string): Promise<string> {\n switch (field.toLowerCase()) {\n case 'username': return requireNonEmpty(entry.username, entry.label, field);\n case 'password': return requireNonEmpty(entry.password, entry.label, field);\n case 'url': return requireNonEmpty(entry.url, entry.label, field);\n case 'notes': return requireNonEmpty(entry.notes, entry.label, field);\n case 'totp': return resolveTotpCode(entry);\n default: {\n const custom = entry.customFields?.find(f => f.label.toLowerCase() === field.toLowerCase());\n if (!custom) {\n const known = ['username', 'password', 'url', 'notes', 'totp', ...(entry.customFields?.map(f => f.label) ?? [])];\n const suggestion = closestMatch(field, known);\n throw new UnresolvableRefError(\n `Item \"${entry.label}\" has no field \"${field}\"${suggestion ? ` \u2014 did you mean \"${suggestion}\"?` : ''}. `\n + `Available fields: ${known.join(', ')}`,\n );\n }\n return requireNonEmpty(custom.value, entry.label, field);\n }\n }\n}\n\n/** Canonical personal-vault token (spec REV 2.3 \u00A72, EN docs) \u2014 `Osobno` (the\n * handle's literal `name`, see PERSONAL_VAULT_NAME in vault/vaults.ts) keeps\n * matching via the plain name comparison below, so it stays a working alias\n * without needing its own entry here. */\nconst PERSONAL_VAULT_ALIAS = 'personal';\n\n/** True when `query` names the vault `v` \u2014 either its literal display name\n * (an org's default vault already carries its ORG's name here, never the\n * stored placeholder \u2014 see vault/vaults.ts), or (for the personal vault\n * only) the canonical `personal` alias. A real collection named \"Personal\"\n * is deliberately NOT special-cased against the personal vault: both\n * entries land in the filter result and the existing multiple-matches\n * branch below throws its normal ambiguity error, same as any other two\n * vaults sharing a name (see resolver.test.ts). */\nfunction matchesVaultQuery(v: VaultHandle, query: string): boolean {\n const q = query.toLowerCase();\n if (v.name.toLowerCase() === q) return true;\n return v.kind === 'personal' && q === PERSONAL_VAULT_ALIAS;\n}\n\n// spec REV 2.4.1 \u00A72 \u2014 `company` and its synonym `work` both mean \"poslovni\"\n// (business or enterprise); `team` is a legacy org type value the server\n// no longer produces (organizations.type is only personal/family/business/\n// enterprise) and is deliberately not included here.\nconst ORG_TYPE_TOKENS: Record<string, OrgType[]> = {\n family: ['family'],\n company: ['business', 'enterprise'],\n work: ['business', 'enterprise'],\n};\n\n/** Resolves `family`/`company`/`work` to the single default vault of a\n * matching-type org \u2014 deterministic only when the caller has EXACTLY ONE\n * qualifying org (spec REV 2.4.1 \u00A72); 2+ throws immediately, listing the\n * org names (a distinct, more specific error than the generic ambiguous-\n * vault-name one in resolveRef) and pointing at the exact-name workaround.\n * Counts only orgs whose default vault is actually present in `vaults`\n * (i.e. its key could be unwrapped) \u2014 an org the caller can't currently\n * read isn't a usable resolution target. Returns null for a query that\n * isn't one of these tokens at all, or that is but matches zero orgs. */\nfunction resolveOrgTypeToken(query: string, vaults: VaultHandle[]): VaultHandle | null {\n const types = ORG_TYPE_TOKENS[query.toLowerCase()];\n if (!types) return null;\n const matches = vaults.filter(v => v.isDefault && v.orgType !== null && types.includes(v.orgType));\n if (matches.length > 1) {\n throw new UnresolvableRefError(\n `Multiple \"${query}\" orgs \u2014 ${matches.map(v => v.name).join(', ')} \u2014 use the exact org name instead of \"${query}\"`,\n );\n }\n return matches[0] ?? null;\n}\n\n/**\n * Resolves a vault-address query \u2014 `personal`/`Osobno`, `family`,\n * `company`/`work`, an org's name, or a vault's own display name \u2014 against\n * a live vault set. Shared by `resolveRef` and `geslar list [vault]` so the\n * two never drift into matching different address spaces (spec REV 2.4.1\n * \u00A72). Throws UnresolvableRefError (never returns a value) on no match or\n * on ambiguity \u2014 a semantic token spanning 2+ orgs throws its own specific\n * message (see resolveOrgTypeToken); a query matching 2+ distinct vaults\n * (by literal name, or a token colliding with a real name) throws the\n * generic \"rename one\" ambiguity error, same treatment for every case \u2014\n * the resolver never silently prefers one match over another.\n */\nexport function resolveVaultByQuery(query: string, vaults: VaultHandle[]): VaultHandle {\n const vaultMatches = vaults.filter(v => matchesVaultQuery(v, query));\n const orgTokenVault = resolveOrgTypeToken(query, vaults);\n if (orgTokenVault && !vaultMatches.includes(orgTokenVault)) {\n vaultMatches.push(orgTokenVault);\n }\n if (vaultMatches.length === 0) {\n const suggestion = closestMatch(query, vaults.map(v => v.name));\n const available = vaults.map(v => v.name).join(', ') || '(none)';\n throw new UnresolvableRefError(\n `No vault named \"${query}\"${suggestion ? ` \u2014 did you mean \"${suggestion}\"?` : ''}. Available: ${available}`,\n );\n }\n if (vaultMatches.length > 1) {\n throw new UnresolvableRefError(`Multiple vaults named \"${query}\" \u2014 rename one, this isn't disambiguated yet`);\n }\n return vaultMatches[0]!;\n}\n\n/** Full `geslar://` resolution: parse \u2192 match vault (case-insensitive) \u2192\n * match item (name or id: qualifier) \u2192 extract field. Every failure mode\n * throws UnresolvableRefError with a \"did you mean\" hint \u2014 never a value. */\nexport async function resolveRef(ref: string, ctx: ResolveContext): Promise<ResolvedRef> {\n const parsed = parseRef(ref);\n\n const vault = resolveVaultByQuery(parsed.vaultQuery, ctx.vaults);\n\n const entries = await ctx.getEntries(vault);\n\n let entry: DecryptedEntry;\n if (parsed.itemId) {\n const found = entries.find(e => e.id.toLowerCase() === parsed.itemId!.toLowerCase());\n if (!found) throw new UnresolvableRefError(`No item with id \"${parsed.itemId}\" in \"${vault.name}\"`);\n entry = found;\n } else {\n const matches = entries.filter(e => e.label.toLowerCase() === parsed.itemQuery.toLowerCase());\n if (matches.length === 0) {\n const suggestion = closestMatch(parsed.itemQuery, entries.map(e => e.label));\n throw new UnresolvableRefError(\n `No item named \"${parsed.itemQuery}\" in \"${vault.name}\"${suggestion ? ` \u2014 did you mean \"${suggestion}\"?` : ''}`,\n );\n }\n if (matches.length > 1) {\n const ids = matches.map(e => e.id).join(', ');\n throw new UnresolvableRefError(\n `Multiple items named \"${parsed.itemQuery}\" in \"${vault.name}\" \u2014 use an id: qualifier `\n + `(e.g. geslar://${vault.name}/id:${matches[0]!.id}/${parsed.field}). Matching ids: ${ids}`,\n );\n }\n entry = matches[0]!;\n }\n\n const value = await resolveField(entry, parsed.field);\n return { vault, entry, field: parsed.field, value };\n}\n", "import { selectBackend } from '../token-store/index.js';\nimport type { AgentCapability } from '@geslar/core';\n\n/**\n * Local storage for agent-profile tokens (spec-access-core.md REV 1.2 \u00A74) \u2014\n * its OWN OS item (`selectBackend('agent-token')`), distinct from the M1 auth\n * token ('tokens') and the M2 unlock grant ('vault-grant') namespaces, so\n * revoking/clearing one never touches the others.\n *\n * Unlike those two (one secret per namespace), a machine can hold MULTIPLE\n * named agent profiles at once \u2014 so this namespace's single OS blob holds a\n * JSON map keyed by profile name, not a single value. `key = ime profila`\n * (spec wording) means \"key into this map,\" not \"one OS item per profile.\"\n *\n * `vaults` is cached here ONLY because it's the sole way the CLI can address\n * a personal-vault grant later: GET /v1/collections never returns personal\n * vaults (team_collection only) and the route that would normally resolve\n * the personal vault id (ensurePersonalVault, POST /v1/sync/vault) is not on\n * the agent allowlist. Caching is safe because scope is an immutable\n * snapshot at create time (spec \u00A70 decision 2) \u2014 it can only ever go stale\n * in the direction of \"no longer active,\" which the live server calls\n * (GET /v1/collections, GET /v1/sync/entries, GET /v1/agents/whoami) already\n * fail closed on. Capabilities are NEVER cached here \u2014 the read-block check\n * always re-fetches GET /v1/agents/whoami live (spec \u00A74: \"ne poga\u0111aj lokalno\").\n */\n\nexport interface AgentTokenVaultRef {\n id: string;\n name: string;\n kind: 'personal' | 'collection';\n}\n\nexport interface AgentTokenRecord {\n token: string;\n createdAt: string; // ISO\n vaults: AgentTokenVaultRef[];\n allowRead: boolean;\n}\n\ntype AgentTokenMap = Record<string, AgentTokenRecord>;\n\nasync function loadAll(): Promise<AgentTokenMap> {\n const backend = await selectBackend('agent-token');\n const raw = await backend.load();\n if (!raw) return {};\n try {\n return JSON.parse(raw) as AgentTokenMap;\n } catch {\n return {};\n }\n}\n\nexport async function saveAgentToken(name: string, record: AgentTokenRecord): Promise<void> {\n const backend = await selectBackend('agent-token');\n const map = await loadAll();\n map[name] = record;\n await backend.save(JSON.stringify(map));\n}\n\nexport async function loadAgentToken(name: string): Promise<AgentTokenRecord | null> {\n const map = await loadAll();\n return map[name] ?? null;\n}\n\nexport async function listAgentTokenNames(): Promise<string[]> {\n return Object.keys(await loadAll());\n}\n\n/** Deletes just this profile's local record \u2014 clears the whole OS item only\n * when it was the last one, so an untouched sibling profile's token never\n * gets an empty-but-present item vs. a genuinely-cleared one. */\nexport async function clearAgentToken(name: string): Promise<void> {\n const backend = await selectBackend('agent-token');\n const map = await loadAll();\n if (!(name in map)) return;\n delete map[name];\n if (Object.keys(map).length === 0) {\n await backend.clear();\n } else {\n await backend.save(JSON.stringify(map));\n }\n}\n\n// Re-export for callers that only need the capability type, avoids a second\n// import line for something this module already needs.\nexport type { AgentCapability };\n", "import type { ApiClient, TokenStore } from '@geslar/core';\nimport { buildApiClient } from './core.js';\nimport { selectBackend, createCliTokenStore } from '../token-store/index.js';\nimport { CliError, EXIT } from './errors.js';\nimport { loadAgentToken, type AgentTokenRecord } from '../agent/token-store.js';\n\n/** GESLAR_AGENT env var wins if BOTH are set with different values? No \u2014\n * --agent (explicit, per-invocation) takes precedence over the ambient env\n * var, same precedence rule as every other CLI-flag-vs-env-var pair. */\nexport function resolveAgentName(cliAgentOpt?: string): string | null {\n return cliAgentOpt || process.env['GESLAR_AGENT'] || null;\n}\n\n/** Agent tokens don't rotate (no refresh mechanism exists for them, spec \u00A79\n * reserves rotation for a future `/v1/agents/:id/rotate`) \u2014 `set()` is a\n * no-op so ApiClient's 401-triggered refresh attempt (which would target\n * /v1/auth/refresh, meaningless for an agent bearer) just quietly clears\n * in-memory and lets the caller's own error handling take over. */\nfunction agentTokenStore(token: string): TokenStore {\n const current = { access_token: token, refresh_token: '' };\n return {\n get: () => current,\n set: () => { /* no-op \u2014 see above */ },\n };\n}\n\nexport interface CliApiContext {\n api: ApiClient;\n isAgent: boolean;\n agentName: string | null;\n /** Human path: awaits any in-flight OS-store write. Agent path: no-op\n * (agentTokenStore never persists). Call this uniformly regardless of\n * context, same as every command already does today. */\n flush(): Promise<void>;\n}\n\n/**\n * Single choke point read/run/inject/list all go through instead of their\n * own inline selectBackend()+createCliTokenStore()+buildApiClient() block \u2014\n * resolves GESLAR_AGENT/--agent once and returns the right ApiClient. Every\n * downstream call (obtainUnlockedKeys, listVaultHandles, resolveRef, \u2026)\n * receives this same `api` and needs no agent-awareness of its own; the\n * server enforces the agent route allowlist regardless.\n */\nexport async function resolveApiContext(baseUrl: string, agentOpt?: string): Promise<CliApiContext> {\n const agentName = resolveAgentName(agentOpt);\n if (agentName) {\n const record = await loadAgentToken(agentName);\n if (!record) {\n throw new CliError(\n EXIT.AUTH,\n `No local token for agent profile \"${agentName}\" \u2014 run \\`geslar agent create ${agentName} ...\\` on this machine, or check the name with \\`geslar agent list\\``,\n );\n }\n const api = buildApiClient(baseUrl, agentTokenStore(record.token));\n return { api, isAgent: true, agentName, flush: async () => undefined };\n }\n\n const backend = await selectBackend();\n const tokenStore = await createCliTokenStore(backend);\n if (!tokenStore.get()) {\n throw new CliError(EXIT.AUTH, 'not signed in \u2014 run `geslar signin`');\n }\n const api = buildApiClient(baseUrl, tokenStore);\n return { api, isAgent: false, agentName: null, flush: () => tokenStore.flush() };\n}\n\n/** `agent create/list/revoke` are human-session-only actions (spec \u00A74) \u2014\n * refuse up front with a clear message instead of letting the server's own\n * 403 (route not in the agent allowlist) surface confusingly. */\nexport function requireHumanContext(agentOpt: string | undefined, action: string): void {\n const agentName = resolveAgentName(agentOpt);\n if (agentName) {\n throw new CliError(\n EXIT.GENERAL,\n `\\`geslar agent ${action}\\` is a human action \u2014 cannot run under agent context (GESLAR_AGENT=${agentName})`,\n );\n }\n}\n\nexport type { AgentTokenRecord };\n", "import { loadSession } from '../lib/session.js';\nimport { loadOrInitConfig } from '../lib/config.js';\nimport { print, printErr } from '../lib/output.js';\nimport { CliError, EXIT } from '../lib/errors.js';\nimport { obtainUnlockedKeys } from '../vault/session.js';\nimport { listVaultHandles } from '../vault/vaults.js';\nimport { listAgentVaultHandles } from '../vault/agent-vaults.js';\nimport { listDecryptedEntries } from '../vault/entries.js';\nimport { resolveVaultByQuery } from '../resolver.js';\nimport { resolveApiContext } from '../lib/agent-context.js';\nimport { loadAgentToken } from '../agent/token-store.js';\n\n/** `geslar list [vault]` \u2014 names + ids only (spec \u00A73.1). Item names are\n * themselves E2EE (server never sees them), so listing them locally still\n * requires the vault to be unlocked \u2014 same gate as `read`. */\nexport async function listCommand(vaultFilter?: string): Promise<number> {\n try {\n const config = await loadOrInitConfig();\n const session = await loadSession();\n const baseUrl = session?.apiBase ?? config.apiBase;\n const apiCtx = await resolveApiContext(baseUrl);\n const api = apiCtx.api;\n\n const unlocked = await obtainUnlockedKeys(api);\n await apiCtx.flush();\n const vaults = apiCtx.isAgent\n ? await listAgentVaultHandles(api, unlocked, (await loadAgentToken(apiCtx.agentName!))?.vaults ?? [])\n : await listVaultHandles(api, unlocked);\n\n // Same address space as geslar:// references (spec REV 2.4.1 \u00A72):\n // personal/Osobno, family, company/work, an org's name, or a vault's\n // own display name \u2014 resolveVaultByQuery is the single source of truth\n // for this so `list` and the resolver never drift apart.\n const targets = vaultFilter ? [resolveVaultByQuery(vaultFilter, vaults)] : vaults;\n\n for (const vault of targets) {\n print(`${vault.name} (${vault.id})`);\n const entries = await listDecryptedEntries(api, vault);\n for (const entry of entries) {\n print(` ${entry.label} (${entry.id})`);\n }\n }\n return EXIT.OK;\n } catch (err) {\n if (err instanceof CliError) {\n printErr(err.message);\n return err.exitCode;\n }\n printErr((err as Error).message);\n return EXIT.GENERAL;\n }\n}\n", "import { writeFile } from 'node:fs/promises';\nimport { loadSession } from '../lib/session.js';\nimport { loadOrInitConfig } from '../lib/config.js';\nimport { print, printErr } from '../lib/output.js';\nimport { registerSecret } from '../lib/scrubber.js';\nimport { CliError, EXIT } from '../lib/errors.js';\nimport { obtainUnlockedKeys } from '../vault/session.js';\nimport { listVaultHandles } from '../vault/vaults.js';\nimport { listAgentVaultHandles } from '../vault/agent-vaults.js';\nimport { createResolveContext } from '../vault/resolve-context.js';\nimport { resolveRef } from '../resolver.js';\nimport { requireAgenticCli } from '../lib/entitlements.js';\nimport { resolveApiContext } from '../lib/agent-context.js';\nimport { loadAgentToken } from '../agent/token-store.js';\n\n/** `geslar read <ref> [-o file]` \u2014 value to stdout/file (0600), NEVER through\n * the scrubbed print()/printErr() log channel (spec \u00A73.1: \"NIKAD u log\"). */\nexport async function readCommand(ref: string, opts: { output?: string }): Promise<number> {\n try {\n const config = await loadOrInitConfig();\n const session = await loadSession();\n const baseUrl = session?.apiBase ?? config.apiBase;\n const ctx = await resolveApiContext(baseUrl);\n const { api } = ctx;\n\n if (ctx.isAgent) {\n // Capability read LIVE from the server (spec \u00A74: \"ne poga\u0111aj lokalno\")\n // \u2014 never trust a locally cached value for this check.\n const whoami = await api.getAgentWhoami();\n if (whoami.type === 'agent' && !whoami.capabilities.includes('read')) {\n throw new CliError(\n EXIT.GRANT_DENIED,\n \"This agent profile doesn't have the 'read' capability \u2014 recreate it with \"\n + '`geslar agent create ... --allow-read` to permit printing secret values '\n + '(default profiles are run+inject only, by design).',\n );\n }\n } else {\n await requireAgenticCli(api);\n }\n\n const unlocked = await obtainUnlockedKeys(api);\n await ctx.flush();\n const vaults = ctx.isAgent\n ? await listAgentVaultHandles(api, unlocked, (await loadAgentToken(ctx.agentName!))?.vaults ?? [])\n : await listVaultHandles(api, unlocked);\n\n const resolved = await resolveRef(ref, createResolveContext(api, vaults));\n\n // Register BEFORE emitting \u2014 any error/log line printed after this point\n // (e.g. a failure writing the -o file) must mask the value too.\n registerSecret(resolved.value);\n\n if (opts.output) {\n await writeFile(opts.output, resolved.value, { mode: 0o600 });\n print(`Written to ${opts.output}`);\n } else {\n // Deliberately raw stdout, not print(): this IS the designated value\n // channel (spec \u00A73.1) \u2014 print() would scrub it right back out since\n // registerSecret() just made it a scrub target for every OTHER call.\n process.stdout.write(`${resolved.value}\\n`);\n }\n return EXIT.OK;\n } catch (err) {\n if (err instanceof CliError) {\n printErr(err.message);\n return err.exitCode;\n }\n printErr((err as Error).message);\n return EXIT.GENERAL;\n }\n}\n", "import type { ApiClient } from '@geslar/core';\nimport type { ResolveContext } from '../resolver.js';\nimport type { VaultHandle } from './vaults.js';\nimport { listDecryptedEntries, type DecryptedEntry } from './entries.js';\n\n/** Shared `ResolveContext` builder \u2014 one per command invocation, entries\n * decrypted once per vault and cached for every subsequent `resolveRef`\n * call against the same vault (used by `read`, and now `run`/`inject`\n * which may resolve many refs across one or two vaults). */\nexport function createResolveContext(api: ApiClient, vaults: VaultHandle[]): ResolveContext {\n const entryCache = new Map<string, DecryptedEntry[]>();\n return {\n vaults,\n getEntries: async (vault: VaultHandle) => {\n const cached = entryCache.get(vault.id);\n if (cached) return cached;\n const entries = await listDecryptedEntries(api, vault);\n entryCache.set(vault.id, entries);\n return entries;\n },\n };\n}\n", "import { hasFeature, planOf, type ApiClient } from '@geslar/core';\nimport { CliError, EXIT } from './errors.js';\n\n// Matches the ToS pricing reference (geslar-docs/legal/live/en/terms-of-service.md)\n// \u2014 no PRICING_URL constant exists anywhere else in the codebase yet.\nconst UPGRADE_URL = 'https://geslar.app/pricing';\n\n// spec \u00A77 \u2014 plans agentic_cli is meant to be enabled for. Mirrors\n// geslar-api's registry defaultPlans for the agentic_cli feature exactly\n// (registry.ts) \u2014 keep the two in sync if that list ever changes.\nconst QUALIFYING_PLANS = new Set(['premium', 'family', 'business', 'enterprise']);\n\n/**\n * spec-agentic-access.md \u00A73.6/\u00A77: `read`/`run`/`inject` require the\n * `agentic_cli` feature (Premium/Family/Business/Enterprise). The server\n * gates the same feature fail-closed on GET /v1/account/vault-key-material\n * (M4) \u2014 this check just fails fast and friendly, before any vault/session\n * work (or a master-password prompt) even starts.\n *\n * `hasFeature` returns false both when the plan genuinely doesn't qualify\n * AND when `agentic_cli` is simply absent from the bundle (e.g. the api\n * side of M4 hasn't deployed the slug yet, or a per-org grant lagging) \u2014 a\n * real incident (2026-07-18): a Family/Enterprise account got a plain\n * \"requires Premium\" upsell purely because prod hadn't deployed the slug.\n * `planOf()` is populated independently of `agentic_cli` (it's just the\n * account's plan_slug), so a paying plan + a false gate is distinguishable\n * from an actually-unqualified plan \u2014 give the two cases different messages.\n */\nexport async function requireAgenticCli(api: ApiClient): Promise<void> {\n const entitlements = await api.getEntitlements();\n if (hasFeature(entitlements, 'agentic_cli')) return;\n\n const plan = planOf(entitlements);\n if (QUALIFYING_PLANS.has(plan)) {\n throw new CliError(\n EXIT.ENTITLEMENT,\n `Your plan (${plan}) should include this feature but the server isn't reporting it yet. `\n + 'Run `geslar whoami` to confirm your plan, or contact support if this persists.',\n );\n }\n\n throw new CliError(\n EXIT.ENTITLEMENT,\n `This command requires a Premium plan or higher (your plan: ${plan}). Upgrade at ${UPGRADE_URL}`,\n );\n}\n", "import { spawn } from 'node:child_process';\nimport { readFile } from 'node:fs/promises';\nimport { loadSession } from '../lib/session.js';\nimport { loadOrInitConfig } from '../lib/config.js';\nimport { printErr } from '../lib/output.js';\nimport { CliError, EXIT } from '../lib/errors.js';\nimport { obtainUnlockedKeys } from '../vault/session.js';\nimport { listVaultHandles } from '../vault/vaults.js';\nimport { listAgentVaultHandles } from '../vault/agent-vaults.js';\nimport { createResolveContext } from '../vault/resolve-context.js';\nimport { resolveRefsOrLiteral } from '../vault/resolve-many.js';\nimport { parseDotenv } from '../lib/dotenv.js';\nimport { requireAgenticCli } from '../lib/entitlements.js';\nimport { resolveApiContext } from '../lib/agent-context.js';\nimport { loadAgentToken } from '../agent/token-store.js';\n\nexport interface RunOptions {\n envFile?: string;\n /** Repeated `-e KEY=ref` occurrences. */\n env?: string[];\n}\n\n// Shell exit-code convention (matches spec \u00A73.5's \"126/127 spawn (konvencija\n// shella)\"): a signal-terminated child reports 128+signal number.\nconst SIGNAL_NUMBERS: Partial<Record<NodeJS.Signals, number>> = {\n SIGHUP: 1, SIGINT: 2, SIGQUIT: 3, SIGILL: 4, SIGTRAP: 5, SIGABRT: 6,\n SIGBUS: 7, SIGFPE: 8, SIGKILL: 9, SIGUSR1: 10, SIGSEGV: 11, SIGUSR2: 12,\n SIGPIPE: 13, SIGALRM: 14, SIGTERM: 15,\n};\nfunction exitCodeForSignal(signal: NodeJS.Signals): number {\n return 128 + (SIGNAL_NUMBERS[signal] ?? 1);\n}\n\n/** `geslar run --env-file <f> [-e K=ref]... -- <cmd> [args...]` (spec \u00A73.2).\n * Every reference is resolved BEFORE anything spawns (fail-closed, exit 4);\n * the child's own stdio is inherited untouched \u2014 nothing captured, nothing\n * written to disk, no telemetry of values. */\nexport async function runCommand(command: string, args: string[], opts: RunOptions): Promise<number> {\n try {\n const values = await buildEnvValues(opts);\n\n const config = await loadOrInitConfig();\n const session = await loadSession();\n const baseUrl = session?.apiBase ?? config.apiBase;\n const apiCtx = await resolveApiContext(baseUrl);\n const api = apiCtx.api;\n if (!apiCtx.isAgent) await requireAgenticCli(api);\n\n const unlocked = await obtainUnlockedKeys(api);\n await apiCtx.flush();\n const vaults = apiCtx.isAgent\n ? await listAgentVaultHandles(api, unlocked, (await loadAgentToken(apiCtx.agentName!))?.vaults ?? [])\n : await listVaultHandles(api, unlocked);\n const resolveCtx = createResolveContext(api, vaults);\n\n // Fail-closed: every value resolved (and registered with the scrubber)\n // before spawnChild is ever called.\n const resolvedEnv = await resolveRefsOrLiteral(values, resolveCtx);\n\n return await spawnChild(command, args, resolvedEnv);\n } catch (err) {\n if (err instanceof CliError) {\n printErr(err.message);\n return err.exitCode;\n }\n printErr((err as Error).message);\n return EXIT.GENERAL;\n }\n}\n\nasync function buildEnvValues(opts: RunOptions): Promise<Record<string, string>> {\n const values: Record<string, string> = {};\n\n if (opts.envFile) {\n let content: string;\n try {\n content = await readFile(opts.envFile, 'utf-8');\n } catch (err) {\n throw new CliError(EXIT.GENERAL, `Could not read --env-file \"${opts.envFile}\": ${(err as Error).message}`);\n }\n Object.assign(values, parseDotenv(content));\n }\n\n for (const mapping of opts.env ?? []) {\n const eq = mapping.indexOf('=');\n if (eq === -1) {\n throw new CliError(EXIT.GENERAL, `Invalid -e value \"${mapping}\" \u2014 expected KEY=ref`);\n }\n const key = mapping.slice(0, eq);\n const value = mapping.slice(eq + 1);\n if (key in values) {\n printErr(`-e ${key} overrides the same key from --env-file`);\n }\n values[key] = value;\n }\n\n if (Object.keys(values).length === 0) {\n throw new CliError(EXIT.GENERAL, 'No environment variables to set \u2014 pass --env-file and/or -e');\n }\n\n return values;\n}\n\nfunction spawnChild(command: string, args: string[], resolvedEnv: Record<string, string>): Promise<number> {\n return new Promise((resolve) => {\n const child = spawn(command, args, {\n env: { ...process.env, ...resolvedEnv },\n stdio: 'inherit',\n });\n\n const forward = (signal: NodeJS.Signals) => child.kill(signal);\n process.on('SIGINT', forward);\n process.on('SIGTERM', forward);\n function cleanup(): void {\n process.removeListener('SIGINT', forward);\n process.removeListener('SIGTERM', forward);\n }\n\n child.on('error', (err: NodeJS.ErrnoException) => {\n cleanup();\n if (err.code === 'ENOENT') {\n printErr(`command not found: ${command}`);\n resolve(127);\n } else {\n printErr(`failed to run ${command}: ${err.message}`);\n resolve(EXIT.GENERAL);\n }\n });\n\n child.on('exit', (code, signal) => {\n cleanup();\n resolve(signal ? exitCodeForSignal(signal) : (code ?? EXIT.GENERAL));\n });\n });\n}\n", "import { registerSecret } from '../lib/scrubber.js';\nimport { CliError, EXIT } from '../lib/errors.js';\nimport { resolveRef, type ResolveContext } from '../resolver.js';\n\n/**\n * Resolve every `geslar://` value in `values` against `ctx`; anything that\n * doesn't start with `geslar://` passes through literally, unregistered\n * (spec \u00A72 only calls resolved-from-reference values secrets). Fail-closed\n * (spec \u00A73.2): every entry is attempted, and if ANY fails, nothing is\n * returned and nothing gets registered for the successful ones either \u2014\n * the caller must not spawn/write with a partially-resolved set.\n */\nexport async function resolveRefsOrLiteral(\n values: Record<string, string>,\n ctx: ResolveContext,\n): Promise<Record<string, string>> {\n const resolved: Record<string, string> = {};\n const fromRef = new Set<string>();\n const failures: string[] = [];\n\n for (const [key, value] of Object.entries(values)) {\n if (!value.startsWith('geslar://')) {\n resolved[key] = value;\n continue;\n }\n try {\n const result = await resolveRef(value, ctx);\n resolved[key] = result.value;\n fromRef.add(key);\n } catch (err) {\n failures.push(`${key}: ${(err as Error).message}`);\n }\n }\n\n if (failures.length > 0) {\n throw new CliError(\n EXIT.UNRESOLVABLE_REF,\n `${failures.length} reference${failures.length === 1 ? '' : 's'} could not be resolved \u2014 nothing was run:\\n ${failures.join('\\n ')}`,\n );\n }\n\n for (const key of fromRef) {\n registerSecret(resolved[key]!);\n }\n\n return resolved;\n}\n", "/**\n * Minimal dotenv-syntax parser (spec \u00A73.2) \u2014 no dependency, just the subset\n * `geslar run --env-file` actually needs: `KEY=value` lines, `#` comments,\n * blank lines, optional `export ` prefix, and single/double-quoted values\n * (double-quoted values unescape \\n \\\" \\\\). Values starting with\n * `geslar://` are resolved by the caller; everything else is passed through\n * literally \u2014 this parser doesn't know or care which is which.\n */\nexport function parseDotenv(content: string): Record<string, string> {\n const out: Record<string, string> = {};\n\n for (const rawLine of content.split(/\\r\\n|\\n|\\r/)) {\n const line = rawLine.trim();\n if (line.length === 0 || line.startsWith('#')) continue;\n\n const withoutExport = line.startsWith('export ') ? line.slice('export '.length).trim() : line;\n const eq = withoutExport.indexOf('=');\n if (eq === -1) continue; // not a KEY=VALUE line \u2014 skip rather than fail the whole file\n\n const key = withoutExport.slice(0, eq).trim();\n if (key.length === 0) continue;\n let value = withoutExport.slice(eq + 1).trim();\n\n if (value.length >= 2 && value.startsWith('\"') && value.endsWith('\"')) {\n value = value.slice(1, -1)\n .replace(/\\\\n/g, '\\n')\n .replace(/\\\\\"/g, '\"')\n .replace(/\\\\\\\\/g, '\\\\');\n } else if (value.length >= 2 && value.startsWith(\"'\") && value.endsWith(\"'\")) {\n value = value.slice(1, -1);\n }\n\n out[key] = value;\n }\n\n return out;\n}\n", "import { readFile, writeFile } from 'node:fs/promises';\nimport { loadSession } from '../lib/session.js';\nimport { loadOrInitConfig } from '../lib/config.js';\nimport { print, printErr } from '../lib/output.js';\nimport { CliError, EXIT } from '../lib/errors.js';\nimport { obtainUnlockedKeys } from '../vault/session.js';\nimport { listVaultHandles } from '../vault/vaults.js';\nimport { listAgentVaultHandles } from '../vault/agent-vaults.js';\nimport { createResolveContext } from '../vault/resolve-context.js';\nimport { resolveRefsOrLiteral } from '../vault/resolve-many.js';\nimport { requireAgenticCli } from '../lib/entitlements.js';\nimport { resolveApiContext } from '../lib/agent-context.js';\nimport { loadAgentToken } from '../agent/token-store.js';\n\n// Non-greedy up to the closing \"}}\" \u2014 vault/item names may contain literal\n// spaces (spec \u00A72), so this can't stop at the first whitespace character.\nconst PLACEHOLDER_RE = /\\{\\{\\s*(geslar:\\/\\/.+?)\\s*\\}\\}/g;\n\nexport interface InjectOptions {\n input: string;\n output: string;\n}\n\n/** `geslar inject -i <tpl> -o <out>` (spec \u00A73.1) \u2014 `{{ geslar://... }}`\n * placeholders resolved and substituted; output written with mode 0600.\n * Fail-closed like `run`: every placeholder is resolved before anything is\n * written \u2014 a single bad reference means the output file is never created. */\nexport async function injectCommand(opts: InjectOptions): Promise<number> {\n try {\n let template: string;\n try {\n template = await readFile(opts.input, 'utf-8');\n } catch (err) {\n throw new CliError(EXIT.GENERAL, `Could not read -i \"${opts.input}\": ${(err as Error).message}`);\n }\n\n const refByPlaceholder = new Map<string, string>(); // full \"{{ ... }}\" match -> ref text\n for (const m of template.matchAll(PLACEHOLDER_RE)) {\n refByPlaceholder.set(m[0], m[1]!);\n }\n\n if (refByPlaceholder.size === 0) {\n await writeFile(opts.output, template, { mode: 0o600 });\n print(`Written to ${opts.output} (no placeholders found)`);\n return EXIT.OK;\n }\n\n const config = await loadOrInitConfig();\n const session = await loadSession();\n const baseUrl = session?.apiBase ?? config.apiBase;\n const apiCtx = await resolveApiContext(baseUrl);\n const api = apiCtx.api;\n if (!apiCtx.isAgent) await requireAgenticCli(api);\n\n const unlocked = await obtainUnlockedKeys(api);\n await apiCtx.flush();\n const vaults = apiCtx.isAgent\n ? await listAgentVaultHandles(api, unlocked, (await loadAgentToken(apiCtx.agentName!))?.vaults ?? [])\n : await listVaultHandles(api, unlocked);\n const resolveCtx = createResolveContext(api, vaults);\n\n // Reuse resolveRefsOrLiteral keyed by the ref text itself (dedupes\n // identical placeholders automatically via the Set below) \u2014 fail-closed\n // across the WHOLE placeholder set before any substitution happens.\n const uniqueRefs: Record<string, string> = {};\n for (const ref of new Set(refByPlaceholder.values())) uniqueRefs[ref] = ref;\n const resolved = await resolveRefsOrLiteral(uniqueRefs, resolveCtx);\n\n let output = template;\n for (const [placeholder, ref] of refByPlaceholder) {\n output = output.split(placeholder).join(resolved[ref]!);\n }\n\n await writeFile(opts.output, output, { mode: 0o600 });\n print(`Written to ${opts.output}`);\n return EXIT.OK;\n } catch (err) {\n if (err instanceof CliError) {\n printErr(err.message);\n return err.exitCode;\n }\n printErr((err as Error).message);\n return EXIT.GENERAL;\n }\n}\n", "import { createInterface } from 'node:readline/promises';\nimport { ApiError, type AgentCapability } from '@geslar/core';\nimport { buildApiClient } from '../lib/core.js';\nimport { loadSession } from '../lib/session.js';\nimport { loadOrInitConfig } from '../lib/config.js';\nimport { selectBackend, createCliTokenStore } from '../token-store/index.js';\nimport { print, printErr } from '../lib/output.js';\nimport { CliError, EXIT } from '../lib/errors.js';\nimport { requireAgenticCli } from '../lib/entitlements.js';\nimport { obtainUnlockedKeys } from '../vault/session.js';\nimport { listVaultHandles } from '../vault/vaults.js';\nimport { resolveVaultByQuery } from '../resolver.js';\nimport { promptTotpCode } from '../lib/prompt.js';\nimport { requireHumanContext } from '../lib/agent-context.js';\nimport { saveAgentToken, type AgentTokenVaultRef } from '../agent/token-store.js';\n\nexport interface AgentCreateOptions {\n vault: string[];\n allowRead?: boolean;\n expires?: string;\n showToken?: boolean;\n agent?: string;\n}\n\nconst NO_TTY_ERROR = new CliError(\n EXIT.GENERAL,\n 'geslar agent create requires an interactive terminal (TTY) \u2014 TOTP entry cannot be scripted',\n);\n\nfunction validateExpires(expires: string | undefined): string | undefined {\n if (expires === undefined) return undefined;\n if (expires === 'never') return expires;\n if (/^[1-9]\\d{0,3}d$/.test(expires)) return expires;\n throw new CliError(EXIT.GENERAL, `Invalid --expires value \"${expires}\" \u2014 use e.g. 90d, or \"never\"`);\n}\n\nasync function confirmAllowRead(): Promise<boolean> {\n print(\n 'By default, agent profiles get run+inject only \u2014 they can USE a secret\\n'\n + '(spawn a process with it in env, substitute it into a template) but never\\n'\n + 'print it. --allow-read additionally grants the read capability, so\\n'\n + '`geslar read` under this profile WILL print the secret value to stdout.',\n );\n const rl = createInterface({ input: process.stdin, output: process.stdout });\n try {\n const answer = await rl.question('Type \"yes\" to create this profile with read access: ');\n return answer.trim().toLowerCase() === 'yes';\n } finally {\n rl.close();\n }\n}\n\n/** `geslar agent create <name> --vault <name>... [--allow-read] [--expires 90d|never] [--show-token]`\n * (spec-access-core.md REV 1.2 \u00A74). Human session + fresh TOTP; the vault\n * resolver step reuses the SAME unlock chain as read/run/inject (existing\n * code, no agent-specific vault-discovery logic needed on the create path \u2014\n * that's only required later, for the resulting profile's OWN listing/reads). */\nexport async function agentCreateCommand(name: string, opts: AgentCreateOptions): Promise<number> {\n try {\n requireHumanContext(opts.agent, 'create');\n\n if (!process.stdin.isTTY) {\n throw NO_TTY_ERROR;\n }\n\n if (opts.vault.length === 0) {\n throw new CliError(EXIT.GENERAL, 'At least one --vault <name> is required');\n }\n const expires = validateExpires(opts.expires);\n\n if (opts.allowRead) {\n const confirmed = await confirmAllowRead();\n if (!confirmed) {\n printErr('Aborted \u2014 profile not created');\n return EXIT.GENERAL;\n }\n }\n\n const config = await loadOrInitConfig();\n const session = await loadSession();\n const baseUrl = session?.apiBase ?? config.apiBase;\n const backend = await selectBackend();\n const tokenStore = await createCliTokenStore(backend);\n if (!tokenStore.get()) {\n printErr('not signed in \u2014 run `geslar signin`');\n return EXIT.AUTH;\n }\n const api = buildApiClient(baseUrl, tokenStore);\n await requireAgenticCli(api);\n\n const unlocked = await obtainUnlockedKeys(api);\n await tokenStore.flush();\n const vaults = await listVaultHandles(api, unlocked);\n\n const resolvedVaults = opts.vault.map(v => resolveVaultByQuery(v, vaults));\n const vaultRefs: AgentTokenVaultRef[] = resolvedVaults.map(v => ({ id: v.id, name: v.name, kind: v.kind }));\n\n const capabilities: AgentCapability[] = opts.allowRead ? ['run', 'inject', 'read'] : ['run', 'inject'];\n\n print('Fresh TOTP code required to create an agent profile (recovery codes are not accepted).');\n const totpCode = await promptTotpCode('TOTP code: ', NO_TTY_ERROR);\n\n let created;\n try {\n created = await api.createAgent({\n name,\n vault_ids: resolvedVaults.map(v => v.id),\n capabilities,\n expires,\n totp_code: totpCode,\n });\n } catch (err) {\n throw mapCreateError(err);\n }\n\n await saveAgentToken(name, {\n token: created.token,\n createdAt: new Date().toISOString(),\n vaults: vaultRefs,\n allowRead: !!opts.allowRead,\n });\n\n print(`Agent profile \"${created.name}\" created (${created.capabilities.join('+')}).`);\n print(`Vaults: ${vaultRefs.map(v => v.name).join(', ')}`);\n print(`Expires: ${created.expires_at ?? 'never'}`);\n print(`Token stored locally (namespace: agent-token). Activate with GESLAR_AGENT=${created.name} or --agent ${created.name}.`);\n\n if (opts.showToken) {\n printErr('WARNING: printing the plaintext token \u2014 it will not be shown again. Treat it like a password.');\n // Deliberately raw stdout, not print() \u2014 same \"designated value channel,\n // don't scrub what we're about to display\" reasoning as read.ts.\n process.stdout.write(`${created.token}\\n`);\n }\n\n return EXIT.OK;\n } catch (err) {\n if (err instanceof CliError) {\n printErr(err.message);\n return err.exitCode;\n }\n printErr((err as Error).message);\n return EXIT.GENERAL;\n }\n}\n\nfunction mapCreateError(err: unknown): CliError {\n if (!(err instanceof ApiError)) {\n return new CliError(EXIT.GENERAL, (err as Error).message);\n }\n switch (err.code) {\n case 'licence/feature-locked':\n return new CliError(EXIT.ENTITLEMENT, err.message);\n case 'agent/name-exists':\n return new CliError(EXIT.GENERAL, err.message);\n case 'agent/limit-reached':\n return new CliError(EXIT.GENERAL, err.message);\n case 'mfa/setup-required':\n return new CliError(EXIT.AUTH, `${err.message} \u2014 enroll a TOTP authenticator first (console: Security settings)`);\n case 'auth/mfa-invalid':\n return new CliError(EXIT.AUTH, 'Invalid or expired TOTP code');\n case 'vault/not-found':\n return new CliError(EXIT.UNRESOLVABLE_REF, err.message);\n default:\n return new CliError(EXIT.GENERAL, err.message);\n }\n}\n", "import { buildApiClient } from '../lib/core.js';\nimport { loadSession } from '../lib/session.js';\nimport { loadOrInitConfig } from '../lib/config.js';\nimport { selectBackend, createCliTokenStore } from '../token-store/index.js';\nimport { print, printErr } from '../lib/output.js';\nimport { CliError, EXIT } from '../lib/errors.js';\nimport { requireHumanContext } from '../lib/agent-context.js';\nimport { loadAgentToken } from '../agent/token-store.js';\n\nexport interface AgentListOptions {\n agent?: string;\n}\n\n/** `geslar agent list` (spec-access-core.md REV 1.2 \u00A74) \u2014 GET /v1/agents\n * reports name/capabilities/status/expiry/last-used/scoped_vault_count, but\n * not vault NAMES (the server doesn't return them, by design \u2014 see\n * spec-access-core.md \u00A73). Vault names shown here come from this machine's\n * own create-time-cached record; a profile created on another machine (or\n * whose local token was already `geslar agent revoke`d/cleared) still shows\n * correctly, just without the vault-name line. */\nexport async function agentListCommand(opts: AgentListOptions): Promise<number> {\n try {\n requireHumanContext(opts.agent, 'list');\n\n const config = await loadOrInitConfig();\n const session = await loadSession();\n const baseUrl = session?.apiBase ?? config.apiBase;\n const backend = await selectBackend();\n const tokenStore = await createCliTokenStore(backend);\n if (!tokenStore.get()) {\n printErr('not signed in \u2014 run `geslar signin`');\n return EXIT.AUTH;\n }\n const api = buildApiClient(baseUrl, tokenStore);\n\n const { agents } = await api.listAgents();\n await tokenStore.flush();\n\n if (agents.length === 0) {\n print('No agent profiles. Create one with `geslar agent create <name> --vault <name>`.');\n return EXIT.OK;\n }\n\n for (const a of agents) {\n const local = await loadAgentToken(a.name);\n const vaultsText = local\n ? local.vaults.map(v => v.name).join(', ')\n : `${a.scoped_vault_count} vault(s) (not stored on this machine)`;\n const scopeNote = a.has_active_scope ? '' : ' [no active scope]';\n print(`${a.name} (${a.status})${scopeNote}`);\n print(` Vaults: ${vaultsText}`);\n print(` Capabilities: ${a.capabilities.join('+')}`);\n print(` Expires: ${a.expires_at ?? 'never'}`);\n print(` Last used: ${a.last_used_at ?? '(never)'}`);\n }\n return EXIT.OK;\n } catch (err) {\n if (err instanceof CliError) {\n printErr(err.message);\n return err.exitCode;\n }\n printErr((err as Error).message);\n return EXIT.GENERAL;\n }\n}\n", "import { buildApiClient } from '../lib/core.js';\nimport { loadSession } from '../lib/session.js';\nimport { loadOrInitConfig } from '../lib/config.js';\nimport { selectBackend, createCliTokenStore } from '../token-store/index.js';\nimport { print, printErr } from '../lib/output.js';\nimport { CliError, EXIT } from '../lib/errors.js';\nimport { requireHumanContext } from '../lib/agent-context.js';\nimport { clearAgentToken } from '../agent/token-store.js';\n\nexport interface AgentRevokeOptions {\n agent?: string;\n}\n\n/** `geslar agent revoke <name>` (spec-access-core.md REV 1.2 \u00A74) \u2014 DELETE\n * /v1/agents/:id then clears the local token unconditionally, even if the\n * server call fails (a token whose server-side profile is already gone or\n * already revoked is equally useless locally \u2014 no point leaving it behind). */\nexport async function agentRevokeCommand(name: string, opts: AgentRevokeOptions): Promise<number> {\n try {\n requireHumanContext(opts.agent, 'revoke');\n\n const config = await loadOrInitConfig();\n const session = await loadSession();\n const baseUrl = session?.apiBase ?? config.apiBase;\n const backend = await selectBackend();\n const tokenStore = await createCliTokenStore(backend);\n if (!tokenStore.get()) {\n printErr('not signed in \u2014 run `geslar signin`');\n return EXIT.AUTH;\n }\n const api = buildApiClient(baseUrl, tokenStore);\n\n const { agents } = await api.listAgents();\n await tokenStore.flush();\n const match = agents.find(a => a.name === name);\n if (!match) {\n throw new CliError(EXIT.GENERAL, `No agent profile named \"${name}\" \u2014 run \\`geslar agent list\\` to see your profiles`);\n }\n\n try {\n await api.revokeAgent(match.id);\n } finally {\n // Clear the local token regardless of the server call's outcome \u2014 see\n // doc comment above.\n await clearAgentToken(name);\n }\n\n print(`Agent profile \"${name}\" revoked. Local token cleared.`);\n return EXIT.OK;\n } catch (err) {\n if (err instanceof CliError) {\n printErr(err.message);\n return err.exitCode;\n }\n printErr((err as Error).message);\n return EXIT.GENERAL;\n }\n}\n", "import { randomUUID, randomBytes, createHmac, timingSafeEqual } from 'node:crypto';\nimport { selectBackend } from '../token-store/index.js';\n\n/** Pre-grant subsystem (spec-mcp \u00A70.1/R1) \u2014 grants are OS-wrapped (via the\n * existing selectBackend() mechanism, same DPAPI/Keychain/libsecret/fallback\n * as every other CLI secret) AND signed with a per-machine HMAC key, so a\n * weak-fallback-backend file that gets edited on disk is detected and\n * rejected rather than silently trusted (fail-closed on tamper, not just on\n * absence). The signing key itself lives in its own OS-wrapped namespace. */\n\nexport const DEFAULT_GRANT_TTL_SEC = 3600; // 1h\nexport const MAX_GRANT_TTL_SEC = 8 * 3600; // 8h\n\nexport interface McpGrant {\n id: string;\n kind: 'scope' | 'cmd';\n scope?: string;\n pattern?: string;\n createdAt: number;\n ttlSec: number;\n maxUses: number | null;\n usesRemaining: number | null;\n}\n\nconst GRANT_NAMESPACE = 'mcp-grant';\nconst SIGNING_KEY_NAMESPACE = 'mcp-grant-signing-key';\n\nasync function getOrCreateSigningKey(): Promise<Buffer> {\n const backend = await selectBackend(SIGNING_KEY_NAMESPACE);\n const existing = await backend.load();\n if (existing) return Buffer.from(existing, 'base64');\n const key = randomBytes(32);\n await backend.save(key.toString('base64'));\n return key;\n}\n\nfunction sign(key: Buffer, payload: string): string {\n return createHmac('sha256', key).update(payload).digest('base64');\n}\n\nfunction verifySignature(key: Buffer, payload: string, signature: string): boolean {\n const expected = sign(key, payload);\n const a = Buffer.from(expected);\n const b = Buffer.from(signature);\n return a.length === b.length && timingSafeEqual(a, b);\n}\n\nasync function loadAll(): Promise<McpGrant[]> {\n const backend = await selectBackend(GRANT_NAMESPACE);\n const raw = await backend.load();\n if (!raw) return [];\n let envelope: unknown;\n try {\n envelope = JSON.parse(raw);\n } catch {\n return [];\n }\n if (\n typeof envelope !== 'object' ||\n envelope === null ||\n typeof (envelope as { payload?: unknown }).payload !== 'string' ||\n typeof (envelope as { signature?: unknown }).signature !== 'string'\n ) {\n return [];\n }\n const { payload, signature } = envelope as { payload: string; signature: string };\n const key = await getOrCreateSigningKey();\n if (!verifySignature(key, payload, signature)) return [];\n let grants: McpGrant[];\n try {\n grants = JSON.parse(payload);\n } catch {\n return [];\n }\n const now = Date.now();\n return grants.filter(g => now - g.createdAt <= g.ttlSec * 1000);\n}\n\nasync function saveAll(grants: McpGrant[]): Promise<void> {\n const backend = await selectBackend(GRANT_NAMESPACE);\n const key = await getOrCreateSigningKey();\n const payload = JSON.stringify(grants);\n const signature = sign(key, payload);\n await backend.save(JSON.stringify({ payload, signature }));\n}\n\nfunction clampTtl(ttlSec: number | undefined): number {\n const v = ttlSec ?? DEFAULT_GRANT_TTL_SEC;\n return Math.min(Math.max(v, 1), MAX_GRANT_TTL_SEC);\n}\n\nasync function createGrant(partial: Omit<McpGrant, 'id' | 'createdAt' | 'usesRemaining'> & { maxUses: number | null }): Promise<McpGrant> {\n const grants = await loadAll();\n const grant: McpGrant = {\n ...partial,\n id: randomUUID(),\n createdAt: Date.now(),\n usesRemaining: partial.maxUses,\n };\n grants.push(grant);\n await saveAll(grants);\n return grant;\n}\n\nexport function createScopeGrant(scope: string, opts: { ttlSec?: number; maxUses?: number }): Promise<McpGrant> {\n return createGrant({ kind: 'scope', scope, ttlSec: clampTtl(opts.ttlSec), maxUses: opts.maxUses ?? null });\n}\n\nexport function createCmdGrant(pattern: string, opts: { ttlSec?: number; maxUses?: number }): Promise<McpGrant> {\n return createGrant({ kind: 'cmd', pattern, ttlSec: clampTtl(opts.ttlSec), maxUses: opts.maxUses ?? null });\n}\n\nexport function listGrants(): Promise<McpGrant[]> {\n return loadAll();\n}\n\nexport async function revokeGrant(id: string): Promise<boolean> {\n const grants = await loadAll();\n const next = grants.filter(g => g.id !== id);\n if (next.length === grants.length) return false;\n await saveAll(next);\n return true;\n}\n\nexport async function revokeAllGrants(): Promise<void> {\n await saveAll([]);\n}\n\n/** `*` = any run of characters, everything else literal; case-sensitive\n * (command patterns are typically exact-case binaries: \"npm\", not \"NPM\"). */\nfunction globToRegExp(pattern: string): RegExp {\n const escaped = pattern.replace(/[.+^${}()|[\\]\\\\?]/g, '\\\\$&').replace(/\\*/g, '.*');\n return new RegExp(`^${escaped}$`);\n}\n\nasync function consumeMatching(predicate: (g: McpGrant) => boolean): Promise<McpGrant | null> {\n const grants = await loadAll();\n const idx = grants.findIndex(predicate);\n if (idx === -1) return null;\n const grant = grants[idx]!;\n if (grant.usesRemaining !== null) {\n grant.usesRemaining -= 1;\n if (grant.usesRemaining <= 0) {\n grants.splice(idx, 1);\n await saveAll(grants);\n return grant;\n }\n }\n await saveAll(grants);\n return grant;\n}\n\nexport function consumeScopeGrant(scope: string): Promise<McpGrant | null> {\n const q = scope.toLowerCase();\n return consumeMatching(g => g.kind === 'scope' && g.scope!.toLowerCase() === q);\n}\n\nexport function consumeCmdGrant(command: string, args: string[]): Promise<McpGrant | null> {\n const full = [command, ...args].join(' ');\n return consumeMatching(g => g.kind === 'cmd' && globToRegExp(g.pattern!).test(full));\n}\n", "import { print, printErr } from '../lib/output.js';\nimport { EXIT } from '../lib/errors.js';\nimport { parseTtl } from '../vault/grant.js';\nimport { createScopeGrant } from '../mcp/grant-store.js';\n\nexport async function mcpAllowCommand(scope: string, opts: { ttl?: string; maxUses?: number }): Promise<number> {\n try {\n const ttlSec = opts.ttl ? parseTtl(opts.ttl) : undefined;\n const grant = await createScopeGrant(scope, { ttlSec, maxUses: opts.maxUses });\n print(`Granted MCP access to \"${scope}\" (grant ${grant.id}, ttl ${grant.ttlSec}s${grant.maxUses ? `, max ${grant.maxUses} uses` : ''}).`);\n return EXIT.OK;\n } catch (err) {\n printErr((err as Error).message);\n return EXIT.GENERAL;\n }\n}\n", "import { print, printErr } from '../lib/output.js';\nimport { EXIT } from '../lib/errors.js';\nimport { parseTtl } from '../vault/grant.js';\nimport { createCmdGrant } from '../mcp/grant-store.js';\n\nexport async function mcpAllowCmdCommand(pattern: string, opts: { ttl?: string; maxUses?: number }): Promise<number> {\n try {\n const ttlSec = opts.ttl ? parseTtl(opts.ttl) : undefined;\n const grant = await createCmdGrant(pattern, { ttlSec, maxUses: opts.maxUses });\n print(`Granted MCP run access to commands matching \"${pattern}\" (grant ${grant.id}, ttl ${grant.ttlSec}s).`);\n print('Reminder: this narrows ACCIDENTAL scope only \u2014 it is not a security boundary against an injected agent (spec-mcp \u00A71/\u00A72.1). Keep patterns as narrow as your workflow allows.');\n return EXIT.OK;\n } catch (err) {\n printErr((err as Error).message);\n return EXIT.GENERAL;\n }\n}\n", "import { print, printErr } from '../lib/output.js';\nimport { EXIT } from '../lib/errors.js';\nimport { listGrants } from '../mcp/grant-store.js';\n\nexport async function mcpGrantsCommand(): Promise<number> {\n try {\n const grants = await listGrants();\n if (grants.length === 0) {\n print('No active MCP grants.');\n return EXIT.OK;\n }\n for (const g of grants) {\n const target = g.kind === 'scope' ? `scope: ${g.scope}` : `cmd: ${g.pattern}`;\n const uses = g.usesRemaining !== null ? `, ${g.usesRemaining} uses left` : '';\n const ageSec = Math.floor((Date.now() - g.createdAt) / 1000);\n const remainingSec = Math.max(0, g.ttlSec - ageSec);\n print(`${g.id} ${target}${uses} (expires in ${remainingSec}s)`);\n }\n return EXIT.OK;\n } catch (err) {\n printErr((err as Error).message);\n return EXIT.GENERAL;\n }\n}\n", "import { print, printErr } from '../lib/output.js';\nimport { CliError, EXIT } from '../lib/errors.js';\nimport { revokeGrant, revokeAllGrants } from '../mcp/grant-store.js';\n\nexport async function mcpRevokeCommand(id: string | undefined, opts: { all?: boolean }): Promise<number> {\n try {\n if (opts.all) {\n await revokeAllGrants();\n print('All MCP grants revoked.');\n return EXIT.OK;\n }\n if (!id) throw new CliError(EXIT.GENERAL, 'Provide a grant id, or --all');\n const revoked = await revokeGrant(id);\n print(revoked ? `Grant ${id} revoked.` : `No grant found with id ${id} (already expired or never existed).`);\n return EXIT.OK;\n } catch (err) {\n if (err instanceof CliError) { printErr(err.message); return err.exitCode; }\n printErr((err as Error).message);\n return EXIT.GENERAL;\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAIA,QAAMA,gBAAe,MAAM;AACzB;AAEA,YAAM,oBAAoB;AAC1B,YAAM,aAAa;AACnB,YAAM,WAAW;AACjB,YAAM,WAAW;AAGjB,eAAS,eAAe;AACtB,eAAO,OAAO,gBAAgB,IAAI,WAAW,UAAU,CAAC;AAAA,MAC1D;AAGA,eAAS,aAAa;AACpB,eAAO,OAAO,gBAAgB,IAAI,WAAW,QAAQ,CAAC;AAAA,MACxD;AAGA,qBAAe,gBAAgB,UAAU,MAAM;AAC7C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AAO,SAAS,2BAA2B,EAC3C,OAAO,OAAO,IAAwB,SAA4B;AACjE,UAAQ,WAAW,MAAM,iBAAiB,IAAI,IAAI;AACpD,CAAC;AAMH,MAAM,YAAY;AAChB,MAAI;AACF,UAAM,QAAQ,WAAW,QAAQ,IAAI;AAAA,EACvC,SAAS,KAAK;AACZ,aAAU,IAAc,OAAO;AAC/B,YAAQ,WAAW,KAAK;AAAA,EAC1B;AACF,GAAG;",
6
+ "names": ["VaultCrypto", "VaultCloudCrypto", "HKDF_SALT", "HKDF_INFO", "OrgRecoveryCrypto", "HKDF_SALT", "HKDF_INFO", "readFile", "writeFile", "readFile", "writeFile", "readFile", "writeFile", "rm", "readFile", "writeFile", "rm", "spawn", "spawn", "userInfo", "account", "run", "randomBytes", "userInfo", "readFile", "writeFile", "rm", "readFile", "writeFile", "readFile", "writeFile", "userInfo", "readFile", "randomBytes", "writeFile", "rm", "VaultCrypto", "VaultCrypto", "VaultCloudCrypto", "VaultCrypto", "VaultCloudCrypto", "VaultCloudCrypto", "buildCollectionDekMap", "VaultCrypto", "VaultCloudCrypto", "api", "writeFile", "writeFile", "spawn", "readFile", "readFile", "spawn", "readFile", "writeFile", "readFile", "writeFile", "randomUUID", "randomBytes", "randomBytes", "loadAll", "randomUUID"]
7
7
  }