diff --git a/packages/cli/src/commands/vault.ts b/packages/cli/src/commands/vault.ts index c0d9224..443bb71 100644 --- a/packages/cli/src/commands/vault.ts +++ b/packages/cli/src/commands/vault.ts @@ -20,10 +20,12 @@ export async function vault(args: string[], flags: Record): Prom return vaultGet(args.slice(1), flags); case "ls": return vaultLs(args.slice(1), flags); + case "update-access": + return vaultUpdateAccess(args.slice(1), flags); case "price": return vaultPrice(args.slice(1), flags); default: - error(`Unknown vault command: ${sub ?? "(none)"}. Use: store, get, ls, price`); + error(`Unknown vault command: ${sub ?? "(none)"}. Use: store, get, ls, update-access, price`); } } @@ -111,6 +113,67 @@ async function vaultStore(args: string[], flags: Record): Promis } } +async function vaultUpdateAccess(args: string[], flags: Record): Promise { + const [path] = args; + if (!path) + error("Usage: orbitmem vault update-access --allow-address | --min-score "); + + const config = loadConfig(); + if (flags.relay) config.relay = flags.relay; + + const litNetwork = (flags["lit-network"] as LitNetwork) ?? "cayenne"; + const client = await createClient(config, loadKey(), { litNetwork }); + + try { + const accessConditions: LitAccessCondition[] = []; + const chain = (flags["access-chain"] ?? config.chain ?? "base-sepolia") as EvmChain; + + if (flags["allow-address"]) { + const condition: LitEvmCondition = { + conditionType: "evmBasic", + contractAddress: "" as EvmAddress, + standardContractType: "", + chain, + method: "", + parameters: [":userAddress"], + returnValueTest: { comparator: "=", value: flags["allow-address"] }, + }; + accessConditions.push(condition); + } + if (flags["min-score"]) { + const condition: LitEvmCondition = { + conditionType: "evmContract", + contractAddress: config.reputationAddress as EvmAddress, + standardContractType: "", + chain, + method: "getScore", + parameters: [":userAddress"], + returnValueTest: { comparator: ">=", value: flags["min-score"] }, + }; + accessConditions.push(condition); + } + if (accessConditions.length === 0) { + error("update-access requires --allow-address or --min-score "); + } + + const vault = client.vault as typeof client.vault & { + updateAccess: ( + path: string, + conditions: LitAccessCondition[], + opts?: { chain?: string }, + ) => Promise<{ timestamp: number }>; + }; + const entry = await vault.updateAccess(path, accessConditions, { chain }); + if (flags.json !== undefined) { + output({ path, updated: true, timestamp: entry.timestamp }, true); + } else { + process.stdout.write(`Updated access for "${path}"\n`); + } + } finally { + await client.destroy(); + } +} + async function vaultGet(args: string[], flags: Record): Promise { const [path] = args; if (!path) error("Usage: orbitmem vault get "); diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index c6f7ea6..f028f6a 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -41,6 +41,7 @@ Commands: vault store Store data in vault vault get Read data from vault vault ls [prefix] List vault keys + vault update-access Re-encrypt with new Lit access conditions vault price set Set per-read price (USDC) vault price get Show price for path vault price ls List all priced paths diff --git a/packages/sdk/src/data/__tests__/vault-encryption.test.ts b/packages/sdk/src/data/__tests__/vault-encryption.test.ts index d3ede88..5c23535 100644 --- a/packages/sdk/src/data/__tests__/vault-encryption.test.ts +++ b/packages/sdk/src/data/__tests__/vault-encryption.test.ts @@ -223,6 +223,111 @@ describe("Vault Encryption", () => { expect(entry!.value).toBe("decrypted-value"); }); + test("updateAccess: decrypt → re-encrypt → store with new conditions", async () => { + let lastEncryptConditions: any[] = []; + const mockEncryptionLayer = { + encrypt: async (_data: any, opts: any) => { + lastEncryptConditions = opts.accessConditions ?? []; + return { + engine: "lit" as const, + ciphertext: new TextEncoder().encode("encrypted"), + dataToEncryptHash: "hash-new", + accessControlConditions: opts.accessConditions ?? [], + chain: "base" as const, + }; + }, + decrypt: async (_encrypted: any, opts: any) => { + if (!opts?.authSig) throw new Error("No authSig"); + return new TextEncoder().encode(JSON.stringify("secret-data")); + }, + }; + + const vault = await createVault(createMockOrbitDB(), { + encryptionLayer: mockEncryptionLayer as any, + }); + + const authSig = { + sig: "0xsig", + derivedVia: "web3.eth.personal.sign", + signedMessage: "test", + address: "0xABCD", + }; + vault.setAuthSig(authSig); + + // Store with initial conditions + await vault.put("gated/data", "secret-data", { + visibility: "shared", + engine: "lit", + accessConditions: [ + { + conditionType: "evmBasic", + contractAddress: "", + standardContractType: "", + chain: "base-sepolia", + method: "", + parameters: [":userAddress"], + returnValueTest: { comparator: "=", value: "0xOLD" }, + }, + ], + }); + + // Update access to a new address + const newConditions = [ + { + conditionType: "evmBasic" as const, + contractAddress: "" as any, + standardContractType: "" as const, + chain: "base-sepolia" as const, + method: "", + parameters: [":userAddress"], + returnValueTest: { comparator: "=" as const, value: "0xNEW" }, + }, + ]; + + const entry = await vault.updateAccess("gated/data", newConditions); + expect(entry.value).toBe("secret-data"); + expect(entry.encrypted).toBe(true); + expect(entry.encryptionEngine).toBe("lit"); + + // Verify the re-encrypt call received the new conditions + expect(lastEncryptConditions).toEqual(newConditions); + }); + + test("updateAccess: throws for non-Lit entry", async () => { + const aes = new AESEngine({ kdf: "hkdf-sha256" }); + const key = await deriveTestKey(aes); + const mockEncLayer = { + encrypt: async () => ({}), + decrypt: async () => new Uint8Array(), + }; + const vault = await createVault(createMockOrbitDB(), { + aesEngine: aes, + encryptionLayer: mockEncLayer as any, + }); + vault.setDefaultKey(key); + vault.setAuthSig({ sig: "0x", derivedVia: "test", signedMessage: "t", address: "0x1" }); + + await vault.put("private/data", "hello", { visibility: "private" }); + await expect(vault.updateAccess("private/data", [])).rejects.toThrow(/not Lit-encrypted/); + }); + + test("updateAccess: throws for missing path", async () => { + const vault = await createVault(createMockOrbitDB(), { + encryptionLayer: { encrypt: async () => ({}), decrypt: async () => new Uint8Array() } as any, + }); + vault.setAuthSig({ sig: "0x", derivedVia: "test", signedMessage: "t", address: "0x1" }); + + await expect(vault.updateAccess("nonexistent", [])).rejects.toThrow(/Not found/); + }); + + test("updateAccess: throws without authSig", async () => { + const vault = await createVault(createMockOrbitDB(), { + encryptionLayer: { encrypt: async () => ({}), decrypt: async () => new Uint8Array() } as any, + }); + + await expect(vault.updateAccess("some/path", [])).rejects.toThrow(/authSig/); + }); + test("query auto-decrypts private entries", async () => { const aes = new AESEngine({ kdf: "hkdf-sha256" }); const key = await deriveTestKey(aes); diff --git a/packages/sdk/src/data/vault.ts b/packages/sdk/src/data/vault.ts index 1268bdf..f2ad244 100644 --- a/packages/sdk/src/data/vault.ts +++ b/packages/sdk/src/data/vault.ts @@ -11,7 +11,9 @@ import type { EncryptionEngine, IDataLayer, IEncryptionLayer, + LitAccessCondition, LitAuthSig, + LitEncryptedData, VaultEntry, VaultPath, Visibility, @@ -48,6 +50,11 @@ export async function createVault( metaDb: any; setDefaultKey: (key: CryptoKey) => void; setAuthSig: (authSig: LitAuthSig) => void; + updateAccess: ( + path: VaultPath, + newConditions: LitAccessCondition[], + opts?: { chain?: string }, + ) => Promise; } > { const db = await orbitdb.open(config.dbName ?? "orbitmem-vault", { type: "nested" }); @@ -159,6 +166,11 @@ export async function createVault( metaDb: any; setDefaultKey: (key: CryptoKey) => void; setAuthSig: (authSig: LitAuthSig) => void; + updateAccess: ( + path: VaultPath, + newConditions: LitAccessCondition[], + opts?: { chain?: string }, + ) => Promise; } = { db, metaDb, @@ -327,6 +339,39 @@ export async function createVault( return { merged: Object.keys(obj).length, conflicts: 0 }; }, + async updateAccess(path, newConditions, opts) { + if (!config.encryptionLayer) throw new Error("Encryption layer not configured for Lit"); + if (!litAuthSig) throw new Error("No authSig — call setAuthSig() first"); + + const key = normalizePath(path); + const rawValue = await db.get(key); + if (rawValue === undefined) throw new Error(`Not found: ${key}`); + + const meta = await metaDb.get(key); + if (meta?.encryptionEngine !== "lit") + throw new Error(`Entry "${key}" is not Lit-encrypted (engine: ${meta?.encryptionEngine})`); + if (!isSerializedEncrypted(rawValue)) throw new Error(`Entry "${key}" is not encrypted`); + + // Decrypt with current conditions + const encrypted = deserializeEncrypted(rawValue) as LitEncryptedData; + const plaintext = await config.encryptionLayer.decrypt(encrypted, { authSig: litAuthSig }); + + // Re-encrypt with new conditions + const reEncrypted = await config.encryptionLayer.encrypt(plaintext, { + engine: "lit", + accessConditions: newConditions, + chain: opts?.chain as any, + }); + const serialized = serializeEncrypted(reEncrypted); + + // Write back + await db.put(key, serialized); + await metaDb.put(key, { ...meta, timestamp: Date.now() }); + + const value = JSON.parse(new TextDecoder().decode(plaintext)); + return makeEntry(key, value, meta.visibility, true, "lit"); + }, + async close() { await db.close(); await metaDb.close();