Skip to content
This repository was archived by the owner on Sep 14, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 64 additions & 1 deletion packages/cli/src/commands/vault.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,12 @@ export async function vault(args: string[], flags: Record<string, string>): 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`);
}
}

Expand Down Expand Up @@ -111,6 +113,67 @@ async function vaultStore(args: string[], flags: Record<string, string>): Promis
}
}

async function vaultUpdateAccess(args: string[], flags: Record<string, string>): Promise<void> {
const [path] = args;
if (!path)
error("Usage: orbitmem vault update-access <path> --allow-address <addr> | --min-score <n>");

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 <addr> or --min-score <n>");
}

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<string, string>): Promise<void> {
const [path] = args;
if (!path) error("Usage: orbitmem vault get <path>");
Expand Down
1 change: 1 addition & 0 deletions packages/cli/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ Commands:
vault store <path> <value> Store data in vault
vault get <path> Read data from vault
vault ls [prefix] List vault keys
vault update-access <path> Re-encrypt with new Lit access conditions
vault price set <path> <amount> Set per-read price (USDC)
vault price get <path> Show price for path
vault price ls List all priced paths
Expand Down
105 changes: 105 additions & 0 deletions packages/sdk/src/data/__tests__/vault-encryption.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
45 changes: 45 additions & 0 deletions packages/sdk/src/data/vault.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ import type {
EncryptionEngine,
IDataLayer,
IEncryptionLayer,
LitAccessCondition,
LitAuthSig,
LitEncryptedData,
VaultEntry,
VaultPath,
Visibility,
Expand Down Expand Up @@ -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<VaultEntry>;
}
> {
const db = await orbitdb.open(config.dbName ?? "orbitmem-vault", { type: "nested" });
Expand Down Expand Up @@ -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<VaultEntry>;
} = {
db,
metaDb,
Expand Down Expand Up @@ -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();
Expand Down
Loading