mirror of
https://github.com/profullstack/logicsrc.git
synced 2026-10-05 06:05:28 +00:00
vault: autosync the personal vault to the logicsrc account (#226)
`logicsrc vault` (OpenCreds) lived only in ~/.config/logicsrc/opencreds. Lose the machine and the vault went with it, and a second machine had no way to get it. It now syncs to the logged-in account. Server (apps/pwa, /api/opencreds, session or lsk_ bearer): - opencreds_vaults: one per user. meta (key material already wrapped under the master password) + an encrypted folder list, each with a revision. - opencreds_items: one row per item, as the spec asks; envelope NULL is a tombstone so purges propagate; seq for incremental pulls. - Every write names its base revision; a stale one gets 409 with the current row. Writes are conditional and read back (each envelope's random IV identifies our write), so this needs nothing dialect-specific from SQLite or Postgres. - Stores ciphertext only. The server learns item count and type codes, as OpenCreds security.md already accepts. Client (@logicsrc/opencreds sync.ts, key-free except where noted): - Pull before every vault command, push after. Offline, the command still works and the change goes up next time. - Conflicts never lose data: the account's edit keeps the id and this machine's becomes "<name> (conflict copy)" (needs the unlocked key, so it waits otherwise). An edit beats a purge. Byte-identical envelopes are adopted, not split, so a lost sync.json is harmless. - Two different vaults (meta.createdAt differs) are never merged: refused, with `vault sync --use-remote` (backs this machine's up to .bak-NNN) or `--use-local`. - Remote item ids must be plain ids; anything else is ignored and never becomes a path. - Folder names are AES-GCM encrypted under the user key before upload. CLI (0.6.0): `logicsrc vault sync [--status|--use-remote|--use-local]`. Only the default vault syncs, and only when logged in; a --home or OPENCREDS_HOME vault stays local unless LOGICSRC_VAULT_SYNC=on; LOGICSRC_VAULT_SYNC=off disables it. The standalone `opencreds` binary gets no remote and never syncs. `init` on a machine that just downloaded the account's vault says to unlock it instead of suggesting --force. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
5bebc50beb
commit
d38db62e8b
14 changed files with 1293 additions and 7 deletions
|
|
@ -1,5 +1,6 @@
|
|||
import type { Command } from "commander";
|
||||
import { registerCredsCommands } from "@logicsrc/opencreds/commands";
|
||||
import { accountRemoteFor } from "./vault-sync.js";
|
||||
|
||||
/**
|
||||
* `logicsrc vault …`
|
||||
|
|
@ -45,6 +46,12 @@ Personal vault:
|
|||
logicsrc vault export --format csv --category db --out db.csv --yes
|
||||
logicsrc vault import bitwarden.csv
|
||||
|
||||
Your personal vault syncs to your account (after logicsrc login), end to end
|
||||
encrypted: every vault command pulls first and pushes after. A new machine
|
||||
gets it with: logicsrc login, then logicsrc vault sync.
|
||||
logicsrc vault sync --status what is synced, what is waiting
|
||||
LOGICSRC_VAULT_SYNC=off turn it off (a --home vault never syncs)
|
||||
|
||||
Help for any command: logicsrc vault <command> --help (or: logicsrc vault help <command>)
|
||||
`;
|
||||
|
||||
|
|
@ -59,5 +66,6 @@ export function registerOpenCredsCommands(program: Command): void {
|
|||
// under `teams`. Say so first, with commands they can paste.
|
||||
.addHelpText("after", VAULT_GUIDE);
|
||||
|
||||
registerCredsCommands(vault);
|
||||
// Logged in: the vault syncs to the account around every command.
|
||||
registerCredsCommands(vault, { remote: accountRemoteFor });
|
||||
}
|
||||
|
|
|
|||
94
packages/cli/src/vault-sync.ts
Normal file
94
packages/cli/src/vault-sync.ts
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
import { join, resolve } from "node:path";
|
||||
import { homedir } from "node:os";
|
||||
import type { Envelope, RemoteItem, RemoteVault, SyncRemote, VaultMeta, VaultStore } from "@logicsrc/opencreds";
|
||||
import { readIdentity, resolveApiUrl } from "@logicsrc/plugin-credential-sharing";
|
||||
|
||||
/**
|
||||
* `logicsrc vault` syncs to the logged-in account (apps/pwa /api/opencreds),
|
||||
* so the personal vault survives the machine and follows you to the next one.
|
||||
*
|
||||
* Only the default vault syncs. A vault opened with --home or OPENCREDS_HOME is
|
||||
* a second vault (a test, a scratch copy), and the account holds one; letting
|
||||
* it sync would replace the real one. LOGICSRC_VAULT_SYNC=on opts such a vault
|
||||
* in, =off turns sync off everywhere.
|
||||
*/
|
||||
export function defaultVaultDir(): string {
|
||||
const config = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
|
||||
return join(config, "logicsrc", "opencreds");
|
||||
}
|
||||
|
||||
export function accountRemoteFor(store: VaultStore): SyncRemote | undefined {
|
||||
const setting = (process.env.LOGICSRC_VAULT_SYNC || "").toLowerCase();
|
||||
if (setting === "off" || setting === "0" || setting === "false") return undefined;
|
||||
if (setting !== "on" && resolve(store.baseDir) !== resolve(defaultVaultDir())) return undefined;
|
||||
const identity = readIdentity();
|
||||
if (!identity?.apiToken) return undefined;
|
||||
return createAccountRemote(resolveApiUrl(identity), identity.apiToken, identity.email);
|
||||
}
|
||||
|
||||
class HttpError extends Error {
|
||||
constructor(message: string, readonly status: number, readonly body: Record<string, unknown>) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
export function createAccountRemote(apiUrl: string, token: string, email?: string): SyncRemote {
|
||||
const base = apiUrl.replace(/\/+$/, "");
|
||||
const host = (() => {
|
||||
try {
|
||||
return new URL(base).host;
|
||||
} catch {
|
||||
return base;
|
||||
}
|
||||
})();
|
||||
|
||||
async function call(method: string, path: string, body?: unknown, ok: number[] = []): Promise<{ status: number; body: Record<string, unknown> }> {
|
||||
const res = await fetch(`${base}${path}`, {
|
||||
method,
|
||||
headers: { authorization: `Bearer ${token}`, accept: "application/json", ...(body ? { "content-type": "application/json" } : {}) },
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
signal: AbortSignal.timeout(15_000),
|
||||
});
|
||||
const json = (await res.json().catch(() => ({}))) as Record<string, unknown>;
|
||||
if (!res.ok && !ok.includes(res.status)) {
|
||||
throw new HttpError(String(json.error || `${host} answered HTTP ${res.status}`), res.status, json);
|
||||
}
|
||||
return { status: res.status, body: json };
|
||||
}
|
||||
|
||||
return {
|
||||
label: email ? `${host} (${email})` : host,
|
||||
|
||||
async getVault() {
|
||||
const { status, body } = await call("GET", "/api/opencreds/vault", undefined, [404]);
|
||||
return status === 404 ? null : (body.vault as RemoteVault);
|
||||
},
|
||||
|
||||
async putMeta(meta: VaultMeta, baseRevision: number) {
|
||||
const { status, body } = await call("PUT", "/api/opencreds/vault/meta", { meta, baseRevision }, [409]);
|
||||
return status === 409 ? { ok: false, vault: (body.vault as RemoteVault) ?? null } : { ok: true, revision: Number(body.revision) };
|
||||
},
|
||||
|
||||
async putFolders(blob: { ciphertext: string; iv: string }, baseRevision: number) {
|
||||
const { status, body } = await call("PUT", "/api/opencreds/vault/folders", { ...blob, baseRevision }, [409]);
|
||||
return status === 409 ? { ok: false, vault: (body.vault as RemoteVault) ?? null } : { ok: true, revision: Number(body.revision) };
|
||||
},
|
||||
|
||||
async listItems(since: number) {
|
||||
const { body } = await call("GET", `/api/opencreds/items?since=${since}`);
|
||||
return { items: body.items as RemoteItem[], cursor: Number(body.cursor) };
|
||||
},
|
||||
|
||||
async putItems(changes: Array<{ id: string; envelope: Envelope | null; baseRevision: number }>) {
|
||||
const { body } = await call("PUT", "/api/opencreds/items", { changes });
|
||||
return {
|
||||
applied: body.applied as Array<{ id: string; revision: number; seq: number }>,
|
||||
conflicts: body.conflicts as RemoteItem[],
|
||||
};
|
||||
},
|
||||
|
||||
async reset() {
|
||||
await call("DELETE", "/api/opencreds/vault");
|
||||
},
|
||||
};
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue