feat(keyring): end-to-end encrypted keyring for SSH keys and key pairs, optional cloud sync (CLI 0.12.0)

`logicsrc keyring` (alias `kr`; `keys` is API keys): add/gen/list/show/restore/
rm/export --pub/sync/status. A keyring is an OpenCreds user-profile vault (same
PBKDF2-600k + HKDF + AES-256-GCM scheme as `logicsrc vault`, recovery key);
each private key is an OpenCreds `key` item envelope, public halves stay
readable. Works fully local under ~/.config/logicsrc/keyring; `keyring sync`
pushes ciphertext to the account. restore writes the default file name,
600/644, refuses a different existing key without --force and backs it up
first; private keys are printed only with --print-private.

- apps/pwa: /api/keyring (person Bearer key; session read-only; machine keys
  refused), additive migration 008_keyring, server refuses any upload that
  carries plaintext private key material (incl. base64'd PEM "ciphertext");
  /keyring page lists public halves and decrypts in the browser (WebCrypto,
  same derivation) for download.
- logicsrc-mcp: list/show/export_authorized_keys/add (sealed only)/remove/
  restore instructions; never returns a private key.
- docs/keyring.md served at /docs/keyring.
- Tests: crypto round trip, ssh-keygen fingerprint parity, AAD binding,
  restore perms + overwrite guard + backup, two-machine sync, server stores
  ciphertext only, browser decrypt opens CLI-sealed envelopes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Anthony Ettinger 2026-10-28 18:45:46 +00:00
parent ae4615e61d
commit 1bff3e975c
21 changed files with 2168 additions and 3 deletions

View file

@ -1,6 +1,6 @@
{
"name": "@logicsrc/cli",
"version": "0.11.0",
"version": "0.12.0",
"description": "LogicSRC CLI: every LogicSRC standard and tool as one command.",
"type": "module",
"main": "./dist/index.js",

View file

@ -34,6 +34,7 @@ import {
prepareApiKeyAuth
} from "./teams.js";
import { registerKeysCommands } from "./keys.js";
import { registerKeyringCommands } from "./keyring-cmd.js";
import { sshAgentAction, sshListAction, sshPullAction, sshPushAction } from "./ssh.js";
import { credentialsRotateAction } from "./rotate.js";
import { teamsRotateKeysAction, teamsRotationAction, teamsRotationSetAction } from "./rotate-keys.js";
@ -1381,6 +1382,7 @@ async function runYoloArcade(game: string, repo?: string) {
}
registerKeysCommands(program);
registerKeyringCommands(program);
// LOGICSRC_API_KEY: prepare the key's identity (first use registers a machine
// key's own public key) before any command that talks to the credentials app.

View file

@ -0,0 +1,360 @@
import { spawnSync } from "node:child_process";
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { homedir, hostname, userInfo } from "node:os";
import { basename, join, resolve } from "node:path";
import type { Command } from "commander";
import { promptNewSecret, promptSecret } from "@logicsrc/opencreds";
import {
KEYRING_TYPES,
KeyringStore,
agePublicFromIdentity,
authorizedKeysLines,
createKeyring,
detectType,
fileMode,
looksPrivate,
openEntry,
publicEntry,
restoreToDisk,
sealEntry,
unlockKeyring,
type KeyringEntry,
type KeyringType
} from "./keyring.js";
import { accountKeyringRemote, describeKeyringSync, syncKeyring, type KeyringRemote } from "./keyring-sync.js";
import { print, printColumns, type OutputFormat } from "./format.js";
/**
* `logicsrc keyring …` — SSH keys and other key pairs, end-to-end encrypted.
* (`logicsrc keys` was already taken by API keys.)
*/
export const PASSPHRASE_ENV = "LOGICSRC_KEYRING_PASSPHRASE";
let storeOverride: KeyringStore | undefined;
let remoteOverride: (() => KeyringRemote | undefined) | undefined;
/** Tests point the commands at a temp keyring and a fake account. */
export function setKeyringTestHooks(hooks: { store?: KeyringStore; remote?: () => KeyringRemote | undefined }): void {
storeOverride = hooks.store;
remoteOverride = hooks.remote;
}
const store = (): KeyringStore => storeOverride ?? new KeyringStore();
const remoteFor = (): KeyringRemote | undefined => (remoteOverride ? remoteOverride() : accountKeyringRemote());
const tilde = (p: string): string => {
const home = homedir();
return p === home || p.startsWith(`${home}/`) ? `~${p.slice(home.length)}` : p;
};
const expandHome = (p: string): string => (p === "~" ? homedir() : p.startsWith("~/") ? join(homedir(), p.slice(2)) : p);
async function newPassphrase(): Promise<string> {
const fromEnv = process.env[PASSPHRASE_ENV];
if (fromEnv) return fromEnv;
console.error("Choose a keyring passphrase. It never leaves this machine; without it (or the recovery key) the keys cannot be opened.");
return promptNewSecret("Keyring passphrase: ", "Repeat: ");
}
async function unlock(s: KeyringStore, recoveryKey?: string): Promise<Uint8Array> {
const meta = s.readMeta();
if (!meta) throw new Error("No keyring yet. Make one: logicsrc keyring init (or add a key: logicsrc keyring add ~/.ssh/id_ed25519)");
if (recoveryKey) return unlockKeyring(meta, { recoveryKey });
const passphrase = process.env[PASSPHRASE_ENV] || (await promptSecret("Keyring passphrase: "));
return unlockKeyring(meta, { passphrase });
}
async function initIfMissing(s: KeyringStore): Promise<Uint8Array | undefined> {
if (s.exists()) return undefined;
// A keyring may already exist in the account: take it rather than forking a second one.
const remote = remoteFor();
if (remote) {
try {
const { meta } = await remote.get();
if (meta) {
s.writeMeta(meta);
s.writeSync({ cloud: true });
console.error(`Using the keyring already in your account (${remote.label}).`);
return undefined;
}
} catch (e) {
console.error(`(Could not reach the account: ${(e as Error).message}. Making a local keyring.)`);
}
}
const { meta, userKey, recoveryKey } = await createKeyring(await newPassphrase());
s.writeMeta(meta);
s.writeSync({ cloud: false });
console.error(`Created the keyring at ${tilde(s.baseDir)}.`);
console.error(`RECOVERY KEY (shown once, store it offline; it opens the keyring if the passphrase is lost):\n ${recoveryKey}`);
return userKey;
}
/** Push after a change when cloud is on (or --sync). Sync never fails the command. */
async function maybeSync(s: KeyringStore, force?: boolean, quiet = false): Promise<void> {
if (!force && !s.readSync().cloud) return;
const remote = remoteFor();
if (!remote) {
if (force) console.error("Not logged in, so nothing was synced. Run: logicsrc login, then logicsrc keyring sync");
return;
}
try {
const report = await syncKeyring(s, remote);
if (!quiet) console.error(describeKeyringSync(report, remote.label));
} catch (e) {
console.error(`Keyring sync skipped: ${(e as Error).message}`);
}
}
function row(e: KeyringEntry): Record<string, unknown> {
return { name: e.name, type: e.type, fingerprint: e.fingerprint || "—", comment: e.comment || "—", file: e.filename, updated: e.updatedAt.slice(0, 10) };
}
function readKeyFile(file: string): { privateKey: string; publicKey: string; pubPath?: string } {
const path = resolve(expandHome(file));
if (!existsSync(path)) throw new Error(`No such file: ${file}`);
const privateKey = readFileSync(path, "utf8");
if (!looksPrivate(privateKey)) {
throw new Error(`${file} does not look like a private key. Pass the private half (e.g. ~/.ssh/id_ed25519); its .pub is read alongside.`);
}
return { privateKey, publicKey: "", pubPath: path };
}
function derivePublic(privatePath: string, privateKey: string, explicitPub?: string): string {
if (explicitPub) return readFileSync(resolve(expandHome(explicitPub)), "utf8").trim();
if (existsSync(`${privatePath}.pub`)) return readFileSync(`${privatePath}.pub`, "utf8").trim();
const age = agePublicFromIdentity(privateKey);
if (age) return age;
if (/OPENSSH PRIVATE KEY|RSA PRIVATE KEY|EC PRIVATE KEY/.test(privateKey)) {
const out = spawnSync("ssh-keygen", ["-y", "-f", privatePath], { stdio: ["inherit", "pipe", "inherit"], encoding: "utf8" });
if (out.status === 0 && out.stdout.trim()) return out.stdout.trim();
}
throw new Error(`No public key found for ${privatePath}. Pass one with --pub <file>.`);
}
export function registerKeyringCommands(program: Command): void {
const kr = program
.command("keyring")
.alias("kr")
.description(
"SSH keys and other public/private key pairs, end-to-end encrypted on this machine; optional sync of the ciphertext to your logicsrc account."
)
.addHelpText(
"after",
`
Private keys are encrypted here (OpenCreds: PBKDF2-SHA256 600k + AES-256-GCM) before
they touch disk or the network. The account only ever stores ciphertext + public keys.
logicsrc keyring add ~/.ssh/id_ed25519 import a key (+ its .pub)
logicsrc keyring sync turn on cloud sync and push/pull
logicsrc keyring restore id_ed25519 write it back to ~/.ssh (600/644)
logicsrc keyring export --pub >> ~/.ssh/authorized_keys
Non-interactive: ${PASSPHRASE_ENV}=… (or pipe the passphrase on stdin).`
);
kr.command("init")
.description("Create the keyring (asks for a passphrase, prints a one-time recovery key).")
.option("--cloud", "Also turn on sync to your logicsrc account and push")
.action(async (opts: { cloud?: boolean }) => {
const s = store();
if (s.exists()) {
console.error(`A keyring already exists at ${tilde(s.baseDir)}.`);
} else {
await initIfMissing(s);
}
if (opts.cloud) await maybeSync(s, true);
});
kr.command("add")
.description("Import a private key file and its .pub (e.g. ~/.ssh/id_ed25519).")
.argument("<file>", "The private key file")
.option("--name <name>", "Name in the keyring (default: the file name, e.g. id_ed25519)")
.option("--pub <file>", "The public key file (default: <file>.pub)")
.option("--type <type>", `One of ${KEYRING_TYPES.join(", ")} (default: detected)`)
.option("--comment <text>", "Comment (default: the public key's comment)")
.option("--force", "Replace an existing entry of the same name that holds a different key")
.option("--sync", "Push to your account after adding, even if cloud sync is off")
.action(async (file: string, opts: { name?: string; pub?: string; type?: string; comment?: string; force?: boolean; sync?: boolean }) => {
const s = store();
const { privateKey, pubPath } = readKeyFile(file);
const publicKey = derivePublic(pubPath!, privateKey, opts.pub);
if (opts.type && !KEYRING_TYPES.includes(opts.type as KeyringType)) throw new Error(`--type must be one of ${KEYRING_TYPES.join(", ")}`);
const name = opts.name ?? basename(pubPath!);
const fresh = await initIfMissing(s);
const existing = s.find(name);
const userKey = fresh ?? (await unlock(s));
const entry = await sealEntry(
userKey,
{ name, privateKey, publicKey, type: opts.type as KeyringType | undefined, filename: basename(pubPath!), comment: opts.comment },
existing
);
if (existing && existing.fingerprint === entry.fingerprint && !opts.force) {
console.error(`${name} is already in the keyring (${existing.fingerprint}).`);
} else {
if (existing && !opts.force) {
throw new Error(`The keyring already has a different key named ${name} (${existing.fingerprint}). Use --name, or --force to replace it.`);
}
s.write(entry);
console.error(`Added ${name} (${entry.type}, ${entry.fingerprint}) — encrypted at rest in ${tilde(s.baseDir)}.`);
}
await maybeSync(s, opts.sync);
});
kr.command("gen")
.description("Generate a new key pair straight into the keyring (ssh-keygen).")
.argument("<name>", "Name, and the file name it restores to (e.g. id_ed25519)")
.option("--type <type>", "ed25519 (default), rsa or ecdsa", "ed25519")
.option("--bits <n>", "RSA bits (default 4096)")
.option("--comment <text>", "Comment (default: user@host)")
.option("--sync", "Push to your account after generating")
.action(async (name: string, opts: { type: string; bits?: string; comment?: string; sync?: boolean }) => {
const s = store();
if (!["ed25519", "rsa", "ecdsa"].includes(opts.type)) throw new Error("--type must be ed25519, rsa or ecdsa");
if (s.find(name)) throw new Error(`The keyring already has ${name}. Pick another name or remove it first.`);
const fresh = await initIfMissing(s);
const userKey = fresh ?? (await unlock(s));
const tmp = mkdtempSync(join(s.baseDir, ".gen-"));
try {
const path = join(tmp, "key");
const comment = opts.comment ?? `${safeUser()}@${hostname()}`;
const args = ["-q", "-t", opts.type, "-N", "", "-C", comment, "-f", path];
if (opts.type === "rsa") args.push("-b", opts.bits ?? "4096");
const out = spawnSync("ssh-keygen", args, { stdio: ["ignore", "ignore", "pipe"], encoding: "utf8" });
if (out.status !== 0) throw new Error(`ssh-keygen failed: ${out.stderr || out.error?.message}`);
const entry = await sealEntry(userKey, {
name,
privateKey: readFileSync(path, "utf8"),
publicKey: readFileSync(`${path}.pub`, "utf8"),
filename: name,
comment
});
s.write(entry);
console.error(`Generated ${name} (${entry.type}, ${entry.fingerprint}). Nothing was written to ~/.ssh; restore it with: logicsrc keyring restore ${name}`);
console.log(entry.publicKey);
} finally {
rmSync(tmp, { recursive: true, force: true });
}
await maybeSync(s, opts.sync);
});
kr.command("list")
.alias("ls")
.description("List keys: name, type, fingerprint (no passphrase needed).")
.option("--format <format>", "table, json or markdown", "table")
.action(async (opts: { format: OutputFormat }) => {
const s = store();
// A machine with no keyring yet but a login: show what the account holds.
await maybeSync(s, !s.exists() && Boolean(remoteFor()), true);
const entries = s.entries();
if (opts.format === "json") return print(entries.map(publicEntry), "json");
if (!entries.length) return console.error("The keyring is empty. Add one: logicsrc keyring add ~/.ssh/id_ed25519");
printColumns(entries.map(row));
});
kr.command("show")
.description("Show one key's public half and fingerprint.")
.argument("<name>")
.option("--format <format>", "table or json", "table")
.option("--print-private", "Also print the PRIVATE key to stdout (asks for the passphrase)")
.option("--recovery-key <key>", "Unlock with the recovery key instead of the passphrase")
.action(async (name: string, opts: { format: OutputFormat; printPrivate?: boolean; recoveryKey?: string }) => {
const s = store();
const e = s.get(name);
if (opts.format === "json") print(publicEntry(e), "json");
else {
console.log(`name: ${e.name}\ntype: ${e.type}\nfingerprint: ${e.fingerprint}\ncomment: ${e.comment || "—"}\nfile: ${e.filename}\nupdated: ${e.updatedAt}\npublic key:\n${e.publicKey}`);
}
if (opts.printPrivate) {
const { privateKey } = await openEntry(await unlock(s, opts.recoveryKey), e);
process.stdout.write(privateKey.endsWith("\n") ? privateKey : `${privateKey}\n`);
}
});
kr.command("restore")
.description("Decrypt a key and write it under its default file name (private 600, public 644).")
.argument("<name>")
.option("--to <dir>", "Directory to write into", "~/.ssh")
.option("--force", "Replace a different key already at that path (the old file is backed up first)")
.option("--print-private", "Print the private key to stdout instead of writing files")
.option("--recovery-key <key>", "Unlock with the recovery key instead of the passphrase")
.action(async (name: string, opts: { to: string; force?: boolean; printPrivate?: boolean; recoveryKey?: string }) => {
const s = store();
if (!s.find(name)) await maybeSync(s, Boolean(remoteFor()), true);
const e = s.get(name);
const { privateKey } = await openEntry(await unlock(s, opts.recoveryKey), e);
if (opts.printPrivate) {
process.stdout.write(privateKey.endsWith("\n") ? privateKey : `${privateKey}\n`);
return;
}
const result = restoreToDisk(e, privateKey, { dir: expandHome(opts.to), force: opts.force });
const modes = `${fileMode(result.privatePath)}${result.publicPath ? `/${fileMode(result.publicPath)}` : ""}`;
console.error(`${tilde(result.privatePath)}${result.publicPath ? ` + .pub` : ""}: ${result.note} (mode ${modes}, ${e.fingerprint}).`);
});
kr.command("rm")
.alias("remove")
.description("Remove a key from the keyring (and from the account on the next sync).")
.argument("<name>")
.option("--sync", "Push the removal to your account now")
.action(async (name: string, opts: { sync?: boolean }) => {
const s = store();
const e = s.get(name);
const now = new Date().toISOString();
s.write({ ...e, envelope: null, deletedAt: now, updatedAt: now });
console.error(`Removed ${e.name} (${e.fingerprint}) from the keyring. Files already restored on disk are left alone.`);
await maybeSync(s, opts.sync);
});
kr.command("export")
.description("Print public keys as authorized_keys lines (public halves only).")
.argument("[names...]", "Only these keys (default: every SSH key)")
.option("--pub", "Public keys only (the only kind of export there is)", true)
.action((names: string[]) => {
const s = store();
const entries = names.length ? names.map((n) => s.get(n)) : s.entries();
for (const line of authorizedKeysLines(entries)) console.log(line);
});
kr.command("sync")
.description("Turn on cloud sync and exchange ciphertext with your logicsrc account.")
.option("--use-remote", "The account's keyring wins (this machine's is moved to a .bak dir)")
.option("--use-local", "This machine's keyring replaces the account's")
.option("--off", "Turn cloud sync off for this machine (the account copy is left as is)")
.action(async (opts: { useRemote?: boolean; useLocal?: boolean; off?: boolean }) => {
const s = store();
if (opts.off) {
s.writeSync({ ...s.readSync(), cloud: false });
return console.error("Keyring cloud sync is off on this machine.");
}
const remote = remoteFor();
if (!remote) throw new Error("Not logged in. Run: logicsrc login");
const report = await syncKeyring(s, remote, opts.useRemote ? "use-remote" : opts.useLocal ? "use-local" : undefined);
console.error(describeKeyringSync(report, remote.label));
});
kr.command("status")
.description("Where the keyring lives, how many keys, whether cloud sync is on.")
.action(() => {
const s = store();
const settings = s.readSync();
print(
{
path: tilde(s.baseDir),
exists: s.exists(),
keys: s.entries().length,
cloud: settings.cloud ? `on${remoteFor() ? "" : " (not logged in)"}` : "off",
lastSyncAt: settings.lastSyncAt ?? "never"
},
"markdown"
);
});
}
function safeUser(): string {
try {
return userInfo().username;
} catch {
return process.env.USER ?? "user";
}
}
// Re-exported for tests.
export { detectType };

View file

@ -0,0 +1,161 @@
import type { VaultMeta } from "@logicsrc/opencreds";
import { readIdentity, resolveApiUrl } from "@logicsrc/plugin-credential-sharing";
import type { KeyringEntry, KeyringStore } from "./keyring.js";
/**
* Optional cloud for the keyring: the account copy at app.logicsrc.com
* (/api/keyring). What goes up is exactly what is on disk: the wrapped meta and
* each entry's public half + envelope. Merging is last-writer-wins per entry on
* updatedAt/deletedAt, which is enough for a keyring (keys are added and
* removed, rarely edited, and an edit is a whole new envelope).
*/
export interface KeyringRemote {
label: string;
get(): Promise<{ meta: VaultMeta | null; entries: KeyringEntry[] }>;
putMeta(meta: VaultMeta): Promise<{ ok: true } | { ok: false; meta: VaultMeta }>;
putEntry(entry: KeyringEntry): Promise<{ ok: true } | { ok: false; current: KeyringEntry }>;
wipe(): Promise<void>;
}
export class KeyringDivergedError extends Error {}
export interface KeyringSyncReport {
pulled: string[];
pushed: string[];
deleted: string[];
createdRemote: boolean;
adoptedRemote: boolean;
backup?: string;
}
const stamp = (e: KeyringEntry): number => Math.max(Date.parse(e.updatedAt) || 0, e.deletedAt ? Date.parse(e.deletedAt) || 0 : 0);
const sameKeyring = (a: VaultMeta, b: VaultMeta): boolean => a.kdfSalt === b.kdfSalt && a.protectedUserKey === b.protectedUserKey;
export async function syncKeyring(
store: KeyringStore,
remote: KeyringRemote,
mode?: "use-remote" | "use-local"
): Promise<KeyringSyncReport> {
const report: KeyringSyncReport = { pulled: [], pushed: [], deleted: [], createdRemote: false, adoptedRemote: false };
let { meta: remoteMeta, entries: remoteEntries } = await remote.get();
let localMeta = store.readMeta();
if (!localMeta && !remoteMeta) {
throw new Error("There is no keyring here or in your account yet. Make one: logicsrc keyring init");
}
if (localMeta && remoteMeta && !sameKeyring(localMeta, remoteMeta)) {
if (mode === "use-remote") {
report.backup = store.backup();
localMeta = undefined;
} else if (mode === "use-local") {
await remote.wipe();
remoteMeta = null;
remoteEntries = [];
} else {
throw new KeyringDivergedError(
`This machine's keyring and the one in your account (${remote.label}) are different keyrings (different passphrase/salt). ` +
"Keep the account's with `logicsrc keyring sync --use-remote` (this one is moved to a .bak dir), " +
"or replace the account's with `logicsrc keyring sync --use-local`."
);
}
}
if (!localMeta && remoteMeta) {
store.writeMeta(remoteMeta);
report.adoptedRemote = true;
}
if (localMeta && !remoteMeta) {
const put = await remote.putMeta(localMeta);
if (!put.ok && !sameKeyring(put.meta, localMeta)) {
throw new KeyringDivergedError("Another machine created a different keyring in the account just now. Run `logicsrc keyring sync` again.");
}
report.createdRemote = true;
}
const local = new Map(store.allEntries().map((e) => [e.id, e]));
const remoteById = new Map(remoteEntries.map((e) => [e.id, e]));
for (const id of new Set([...local.keys(), ...remoteById.keys()])) {
const l = local.get(id);
const r = remoteById.get(id);
if (r && (!l || stamp(r) > stamp(l))) {
store.write(r);
(r.deletedAt ? report.deleted : report.pulled).push(r.name);
} else if (l && (!r || stamp(l) > stamp(r))) {
const put = await remote.putEntry(l);
if (put.ok) report.pushed.push(l.name);
else {
store.write(put.current);
report.pulled.push(put.current.name);
}
}
}
const settings = store.readSync();
store.writeSync({ ...settings, cloud: true, lastSyncAt: new Date().toISOString() });
return report;
}
export function describeKeyringSync(r: KeyringSyncReport, label: string): string {
const parts = [
r.adoptedRemote ? "took the account's keyring" : "",
r.createdRemote ? "created the account copy" : "",
r.pushed.length ? `pushed ${r.pushed.length} (${r.pushed.join(", ")})` : "",
r.pulled.length ? `pulled ${r.pulled.length} (${r.pulled.join(", ")})` : "",
r.deleted.length ? `removed ${r.deleted.length} deleted elsewhere` : "",
r.backup ? `old local keyring kept at ${r.backup}` : ""
].filter(Boolean);
return `Keyring synced with ${label}: ${parts.length ? parts.join("; ") : "already up to date"}. Only ciphertext and public keys were sent.`;
}
class HttpError extends Error {
constructor(message: string, readonly status: number) {
super(message);
}
}
/** The logged-in account's keyring, or undefined when not logged in. */
export function accountKeyringRemote(): KeyringRemote | undefined {
const envKey = process.env.LOGICSRC_API_KEY?.trim();
const identity = readIdentity();
const token = envKey || identity?.apiToken;
if (!token) return undefined;
return createKeyringRemote(resolveApiUrl(identity), token, envKey ? undefined : identity?.email);
}
export function createKeyringRemote(apiUrl: string, token: string, email?: string, doFetch: typeof fetch = fetch): KeyringRemote {
const base = apiUrl.replace(/\/+$/, "");
let host = base;
try {
host = new URL(base).host;
} catch {
/* keep base */
}
async function call(method: string, path: string, body?: unknown, ok: number[] = []): Promise<{ status: number; body: Record<string, unknown> }> {
const res = await doFetch(`${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);
return { status: res.status, body: json };
}
return {
label: email ? `${host} (${email})` : host,
async get() {
const { body } = await call("GET", "/api/keyring?include=envelopes");
return { meta: (body.meta as VaultMeta) ?? null, entries: (body.entries as KeyringEntry[]) ?? [] };
},
async putMeta(meta) {
const { status, body } = await call("PUT", "/api/keyring/meta", { meta }, [409]);
return status === 409 ? { ok: false, meta: body.meta as VaultMeta } : { ok: true };
},
async putEntry(entry) {
const { status, body } = await call("PUT", `/api/keyring/entries/${encodeURIComponent(entry.id)}`, { entry }, [409]);
return status === 409 ? { ok: false, current: body.entry as KeyringEntry } : { ok: true };
},
async wipe() {
await call("DELETE", "/api/keyring");
}
};
}

View file

@ -0,0 +1,213 @@
import { spawnSync } from "node:child_process";
import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import type { VaultMeta } from "@logicsrc/opencreds";
import {
KeyringStore,
authorizedKeysLines,
createKeyring,
detectType,
fingerprintOf,
looksPrivate,
openEntry,
publicEntry,
restoreToDisk,
sealEntry,
unlockKeyring,
type KeyringEntry
} from "./keyring.js";
import { KeyringDivergedError, syncKeyring, type KeyringRemote } from "./keyring-sync.js";
const hasSshKeygen = spawnSync("ssh-keygen", ["-?"], { stdio: "ignore" }).error === undefined;
function throwawayKey(dir: string, name = "id_ed25519"): { privateKey: string; publicKey: string; path: string } {
const path = join(dir, name);
const out = spawnSync("ssh-keygen", ["-q", "-t", "ed25519", "-N", "", "-C", "throwaway@test", "-f", path], { stdio: "ignore" });
if (out.status !== 0) throw new Error("ssh-keygen failed");
return { privateKey: readFileSync(path, "utf8"), publicKey: readFileSync(`${path}.pub`, "utf8").trim(), path };
}
const mode = (p: string) => (statSync(p).mode & 0o777).toString(8);
let dir: string;
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "keyring-test-"));
});
afterEach(() => rmSync(dir, { recursive: true, force: true }));
describe.skipIf(!hasSshKeygen)("keyring crypto", () => {
it("round-trips a private key through the OpenCreds envelope, and the envelope holds no plaintext", async () => {
const key = throwawayKey(dir);
const { meta, userKey, recoveryKey } = await createKeyring("pass phrase");
const entry = await sealEntry(userKey, { name: "id_ed25519", privateKey: key.privateKey, publicKey: key.publicKey });
expect(entry.type).toBe("ssh-ed25519");
expect(entry.filename).toBe("id_ed25519");
expect(entry.comment).toBe("throwaway@test");
expect(JSON.stringify(entry)).not.toContain("PRIVATE KEY");
expect(looksPrivate(JSON.stringify(entry))).toBe(false);
// Unlock from the stored meta, by passphrase and by recovery key.
const again = await unlockKeyring(meta, { passphrase: "pass phrase" });
expect((await openEntry(again, entry)).privateKey).toBe(key.privateKey);
const viaRecovery = await unlockKeyring(meta, { recoveryKey });
expect((await openEntry(viaRecovery, entry)).privateKey).toBe(key.privateKey);
await expect(unlockKeyring(meta, { passphrase: "wrong" })).rejects.toThrow(/Wrong keyring passphrase/);
});
it("fingerprints exactly like ssh-keygen -lf", async () => {
const key = throwawayKey(dir);
const ssh = spawnSync("ssh-keygen", ["-lf", `${key.path}.pub`], { encoding: "utf8" }).stdout.split(" ")[1];
expect(fingerprintOf(key.publicKey)).toBe(ssh);
});
it("binds the envelope to its id (a swapped envelope does not open)", async () => {
const a = throwawayKey(dir, "a");
const b = throwawayKey(dir, "b");
const { userKey } = await createKeyring("p");
const ea = await sealEntry(userKey, { name: "a", privateKey: a.privateKey, publicKey: a.publicKey });
const eb = await sealEntry(userKey, { name: "b", privateKey: b.privateKey, publicKey: b.publicKey });
await expect(openEntry(userKey, { ...ea, envelope: { ...eb.envelope!, id: ea.id } })).rejects.toThrow();
});
it("refuses private material in the public field", async () => {
const key = throwawayKey(dir);
const { userKey } = await createKeyring("p");
await expect(sealEntry(userKey, { name: "x", privateKey: key.privateKey, publicKey: key.privateKey })).rejects.toThrow(/private key material/);
});
});
describe("type detection", () => {
it("knows ssh, gpg, age and falls back to generic", () => {
expect(detectType("", "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQ== x")).toBe("ssh-rsa");
expect(detectType("", "ssh-rsa AAAAC3NzaC1lZDI1NTE5AAAAIFK+ x")).toBe("generic"); // blob names another algorithm
expect(detectType("-----BEGIN PGP PRIVATE KEY BLOCK-----", "")).toBe("gpg");
expect(detectType("AGE-SECRET-KEY-1ABC", "age1qqqq")).toBe("age");
expect(detectType("-----BEGIN PRIVATE KEY-----", "something")).toBe("generic");
});
});
describe.skipIf(!hasSshKeygen)("restore", () => {
async function sealedPair() {
const key = throwawayKey(dir, "src");
const { userKey } = await createKeyring("p");
const entry = await sealEntry(userKey, { name: "id_ed25519", privateKey: key.privateKey, publicKey: key.publicKey, filename: "id_ed25519" });
return { key, entry, userKey };
}
it("writes the default file name with 600/644 and a 700 directory", async () => {
const { key, entry, userKey } = await sealedPair();
const to = join(dir, "dot-ssh");
const { privateKey } = await openEntry(userKey, entry);
const r = restoreToDisk(publicEntry(entry), privateKey, { dir: to });
expect(r.privatePath).toBe(join(to, "id_ed25519"));
expect(readFileSync(r.privatePath, "utf8")).toBe(key.privateKey);
expect(readFileSync(`${r.privatePath}.pub`, "utf8").trim()).toBe(key.publicKey);
expect(mode(r.privatePath)).toBe("600");
expect(mode(`${r.privatePath}.pub`)).toBe("644");
expect(mode(to)).toBe("700");
// ssh agrees it is the same key.
const fp = spawnSync("ssh-keygen", ["-lf", r.privatePath], { encoding: "utf8" }).stdout.split(" ")[1];
expect(fp).toBe(entry.fingerprint);
});
it("is a no-op on an identical file, refuses a different one, and backs up before --force", async () => {
const { entry, userKey } = await sealedPair();
const to = join(dir, "dot-ssh");
const { privateKey } = await openEntry(userKey, entry);
restoreToDisk(publicEntry(entry), privateKey, { dir: to });
expect(restoreToDisk(publicEntry(entry), privateKey, { dir: to }).wrote).toBe(false);
const other = throwawayKey(dir, "other");
writeFileSync(join(to, "id_ed25519"), other.privateKey, { mode: 0o600 });
expect(() => restoreToDisk(publicEntry(entry), privateKey, { dir: to })).toThrow(/different key/);
expect(readFileSync(join(to, "id_ed25519"), "utf8")).toBe(other.privateKey); // untouched
const forced = restoreToDisk(publicEntry(entry), privateKey, { dir: to, force: true });
expect(forced.wrote).toBe(true);
expect(forced.backups).toHaveLength(1);
expect(readFileSync(forced.backups[0]!, "utf8")).toBe(other.privateKey);
expect(mode(forced.backups[0]!)).toBe("600");
expect(readFileSync(join(to, "id_ed25519"), "utf8")).toBe(privateKey);
});
it("exports authorized_keys lines from public halves only", async () => {
const { entry } = await sealedPair();
const lines = authorizedKeysLines([publicEntry(entry)]);
expect(lines).toEqual([entry.publicKey]);
expect(lines.join("\n")).not.toContain("PRIVATE");
});
});
/** An in-memory account that, like the real server, refuses anything that looks private. */
function fakeAccount(): KeyringRemote & { meta: VaultMeta | null; rows: Map<string, KeyringEntry> } {
const state = { meta: null as VaultMeta | null, rows: new Map<string, KeyringEntry>() };
return Object.assign(state, {
label: "fake",
async get() {
return { meta: state.meta, entries: [...state.rows.values()] };
},
async putMeta(meta: VaultMeta) {
if (state.meta && state.meta.kdfSalt !== meta.kdfSalt) return { ok: false as const, meta: state.meta };
state.meta = meta;
return { ok: true as const };
},
async putEntry(entry: KeyringEntry) {
if (looksPrivate(JSON.stringify(entry))) throw new Error("plaintext private key uploaded");
state.rows.set(entry.id, JSON.parse(JSON.stringify(entry)));
return { ok: true as const };
},
async wipe() {
state.meta = null;
state.rows.clear();
}
});
}
describe.skipIf(!hasSshKeygen)("sync", () => {
it("pushes ciphertext only, restores on a second machine, and propagates a removal", async () => {
const key = throwawayKey(dir);
const account = fakeAccount();
const a = new KeyringStore(join(dir, "machine-a"));
const { meta, userKey } = await createKeyring("pp");
a.writeMeta(meta);
const entry = await sealEntry(userKey, { name: "id_ed25519", privateKey: key.privateKey, publicKey: key.publicKey });
a.write(entry);
const pushed = await syncKeyring(a, account);
expect(pushed.createdRemote).toBe(true);
expect(pushed.pushed).toEqual(["id_ed25519"]);
expect(JSON.stringify([...account.rows.values()])).not.toContain("PRIVATE KEY");
// A new machine: no local keyring, just a login.
const b = new KeyringStore(join(dir, "machine-b"));
const pulled = await syncKeyring(b, account);
expect(pulled.adoptedRemote).toBe(true);
const bKey = await unlockKeyring(b.readMeta()!, { passphrase: "pp" });
const { privateKey } = await openEntry(bKey, b.get("id_ed25519"));
expect(privateKey).toBe(key.privateKey);
// Remove on b; a sees it gone after its next sync.
const now = new Date(Date.now() + 1000).toISOString();
b.write({ ...b.get("id_ed25519"), envelope: null, deletedAt: now, updatedAt: now });
await syncKeyring(b, account);
await syncKeyring(a, account);
expect(a.find("id_ed25519")).toBeUndefined();
});
it("refuses to merge two different keyrings unless told which wins", async () => {
const account = fakeAccount();
const first = await createKeyring("one");
await account.putMeta(first.meta);
const local = new KeyringStore(join(dir, "c"));
local.writeMeta((await createKeyring("two")).meta);
await expect(syncKeyring(local, account)).rejects.toBeInstanceOf(KeyringDivergedError);
const r = await syncKeyring(local, account, "use-remote");
expect(r.backup && existsSync(r.backup)).toBe(true);
expect(local.readMeta()!.kdfSalt).toBe(first.meta.kdfSalt);
expect(readdirSync(dir).some((f) => f.startsWith("c.bak-"))).toBe(true);
});
});

445
packages/cli/src/keyring.ts Normal file
View file

@ -0,0 +1,445 @@
import { createHash, randomUUID } from "node:crypto";
import {
chmodSync,
copyFileSync,
existsSync,
mkdirSync,
readFileSync,
readdirSync,
renameSync,
rmSync,
statSync,
writeFileSync
} from "node:fs";
import { homedir } from "node:os";
import { basename, join, resolve } from "node:path";
import {
createItem,
createVault,
decryptItem,
encryptItem,
unlockVault,
unlockWithRecoveryKey,
type Envelope,
type Item,
type KeyKind,
type VaultMeta
} from "@logicsrc/opencreds";
/**
* The LogicSRC keyring: SSH keys and other public/private key pairs, kept
* end-to-end encrypted, optionally synced to the logicsrc account.
*
* No new cryptography. A keyring is an OpenCreds `user`-profile vault (the
* `logicsrc vault` scheme): a random user key wrapped under a passphrase via
* PBKDF2-SHA256 (600k) + HKDF, plus a one-time recovery key. Each private key
* is an OpenCreds `key` item encrypted with AES-256-GCM under that user key,
* with the item id bound as AAD. The server, when there is one, receives the
* wrapped meta and the envelopes: it can read neither.
*
* What is NOT secret, and so is kept in the clear beside each envelope so that
* `list`, `show`, `export --pub` and the web page work without a passphrase:
* the name, type, filename, public key, fingerprint and comment.
*
* Layout under ~/.config/logicsrc/keyring (or LOGICSRC_KEYRING_HOME):
* meta.json OpenCreds VaultMeta (key material, all of it wrapped)
* entries/<id>.json KeyringEntry: public half + envelope (or a tombstone)
* sync.json { cloud: boolean, lastSyncAt }
*/
export const KEYRING_TYPES = ["ssh-ed25519", "ssh-rsa", "ssh-ecdsa", "gpg", "age", "generic"] as const;
export type KeyringType = (typeof KEYRING_TYPES)[number];
export interface KeyringEntry {
id: string;
name: string;
type: KeyringType;
/** The file it restores to, by default name: id_ed25519. Never invented. */
filename: string;
publicKey: string;
fingerprint: string;
comment: string;
createdAt: string;
updatedAt: string;
/** Ciphertext of an OpenCreds `key` item. null on a tombstone. */
envelope: Envelope | null;
deletedAt?: string | null;
}
/** What `list`/`show`/the API expose: never the envelope's insides. */
export type PublicEntry = Omit<KeyringEntry, "envelope">;
export function keyringHome(): string {
const override = process.env.LOGICSRC_KEYRING_HOME;
if (override && override.trim()) return override;
const config = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
return join(config, "logicsrc", "keyring");
}
// ---------------------------------------------------------------- parsing ----
const PRIVATE_MARKERS = [
/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/,
/-----BEGIN PGP PRIVATE KEY BLOCK-----/,
/AGE-SECRET-KEY-1[0-9A-Z]+/,
/PuTTY-User-Key-File-/
];
/** True when the text carries private key material in any format we know. */
export function looksPrivate(text: string): boolean {
return PRIVATE_MARKERS.some((re) => re.test(text));
}
/** `ssh-ed25519 AAAA… comment` → type, blob, comment. */
export function parseSshPublicKey(line: string): { algo: string; blob: Buffer; comment: string } | null {
const parts = line.trim().split(/\s+/);
if (parts.length < 2) return null;
const [algo, b64, ...rest] = parts as [string, string, ...string[]];
if (!/^(ssh-|ecdsa-sha2-|sk-)/.test(algo)) return null;
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(b64)) return null;
const blob = Buffer.from(b64, "base64");
// The blob starts with its own algorithm name; a mismatch is a corrupt line.
if (blob.length < 4) return null;
const n = blob.readUInt32BE(0);
if (blob.subarray(4, 4 + n).toString("utf8") !== algo) return null;
return { algo, blob, comment: rest.join(" ") };
}
/**
* The fingerprint people compare. For SSH it is exactly what `ssh-keygen -lf`
* prints (SHA256 of the key blob, unpadded base64). For anything else it is
* the SHA256 of the trimmed public text, in the same notation.
*/
export function fingerprintOf(publicKey: string): string {
const ssh = parseSshPublicKey(publicKey);
const digest = createHash("sha256").update(ssh ? ssh.blob : Buffer.from(publicKey.trim(), "utf8")).digest("base64");
return `SHA256:${digest.replace(/=+$/, "")}`;
}
export function sshTypeOf(algo: string): KeyringType {
if (algo === "ssh-ed25519" || algo === "sk-ssh-ed25519@openssh.com") return "ssh-ed25519";
if (algo === "ssh-rsa") return "ssh-rsa";
if (algo.startsWith("ecdsa-sha2-") || algo.startsWith("sk-ecdsa-")) return "ssh-ecdsa";
return "generic";
}
/** Work out a key's type from what it looks like. */
export function detectType(privateKey: string, publicKey: string): KeyringType {
const ssh = parseSshPublicKey(publicKey);
if (ssh) return sshTypeOf(ssh.algo);
if (/BEGIN PGP PRIVATE KEY BLOCK/.test(privateKey) || /BEGIN PGP PUBLIC KEY BLOCK/.test(publicKey)) return "gpg";
if (/AGE-SECRET-KEY-1/.test(privateKey) || /^age1[0-9a-z]+$/.test(publicKey.trim())) return "age";
return "generic";
}
function opencredsKeyKind(type: KeyringType): KeyKind {
if (type.startsWith("ssh-")) return "ssh";
if (type === "gpg") return "pgp";
return "symmetric";
}
/** An age identity file names its recipient in a `# public key: age1…` comment. */
export function agePublicFromIdentity(privateKey: string): string | undefined {
return /#\s*public key:\s*(age1[0-9a-z]+)/.exec(privateKey)?.[1];
}
export function validateName(name: string): string {
const clean = name.trim();
if (!/^[A-Za-z0-9][A-Za-z0-9._@-]{0,127}$/.test(clean)) {
throw new Error(`Invalid key name ${JSON.stringify(name)}: use letters, digits, . _ @ - (max 128).`);
}
return clean;
}
// ------------------------------------------------------------------ store ----
function writePrivate(path: string, contents: string): void {
writeFileSync(path, contents, { encoding: "utf8", mode: 0o600 });
try {
chmodSync(path, 0o600);
} catch {
/* no modes on this filesystem */
}
}
export interface SyncSettings {
cloud: boolean;
lastSyncAt?: string;
}
export class KeyringStore {
readonly entriesDir: string;
constructor(readonly baseDir: string = keyringHome()) {
this.entriesDir = join(baseDir, "entries");
}
exists(): boolean {
return existsSync(join(this.baseDir, "meta.json"));
}
private ensure(): void {
mkdirSync(this.entriesDir, { recursive: true, mode: 0o700 });
try {
chmodSync(this.baseDir, 0o700);
} catch {
/* ignore */
}
}
readMeta(): VaultMeta | undefined {
const path = join(this.baseDir, "meta.json");
return existsSync(path) ? (JSON.parse(readFileSync(path, "utf8")) as VaultMeta) : undefined;
}
writeMeta(meta: VaultMeta): void {
this.ensure();
writePrivate(join(this.baseDir, "meta.json"), JSON.stringify(meta, null, 2) + "\n");
}
/** Every entry including tombstones. */
allEntries(): KeyringEntry[] {
if (!existsSync(this.entriesDir)) return [];
return readdirSync(this.entriesDir)
.filter((f) => f.endsWith(".json"))
.map((f) => JSON.parse(readFileSync(join(this.entriesDir, f), "utf8")) as KeyringEntry);
}
/** Live entries, sorted by name. */
entries(): KeyringEntry[] {
return this.allEntries()
.filter((e) => !e.deletedAt && e.envelope)
.sort((a, b) => a.name.localeCompare(b.name));
}
find(ref: string): KeyringEntry | undefined {
const live = this.entries();
return live.find((e) => e.name === ref) ?? live.find((e) => e.id === ref) ?? live.find((e) => e.fingerprint === ref);
}
get(ref: string): KeyringEntry {
const found = this.find(ref);
if (!found) throw new Error(`No key "${ref}" in the keyring. See them: logicsrc keyring list`);
return found;
}
write(entry: KeyringEntry): void {
this.ensure();
if (!/^[A-Za-z0-9-]{1,64}$/.test(entry.id)) throw new Error(`Bad entry id ${entry.id}`);
writePrivate(join(this.entriesDir, `${entry.id}.json`), JSON.stringify(entry, null, 2) + "\n");
}
remove(id: string): void {
rmSync(join(this.entriesDir, `${id}.json`), { force: true });
}
readSync(): SyncSettings {
const path = join(this.baseDir, "sync.json");
return existsSync(path) ? (JSON.parse(readFileSync(path, "utf8")) as SyncSettings) : { cloud: false };
}
writeSync(settings: SyncSettings): void {
this.ensure();
writePrivate(join(this.baseDir, "sync.json"), JSON.stringify(settings, null, 2) + "\n");
}
/** Move the whole keyring aside (before adopting the account's copy). */
backup(): string {
let n = 1;
let target: string;
do target = `${this.baseDir}.bak-${String(n++).padStart(3, "0")}`;
while (existsSync(target));
renameSync(this.baseDir, target);
return target;
}
}
// ----------------------------------------------------------------- crypto ----
/** Create a keyring's meta + user key from a passphrase (OpenCreds createVault). */
export async function createKeyring(passphrase: string): Promise<{ meta: VaultMeta; userKey: Uint8Array; recoveryKey: string }> {
return createVault(passphrase);
}
export async function unlockKeyring(meta: VaultMeta, secret: { passphrase?: string; recoveryKey?: string }): Promise<Uint8Array> {
if (secret.recoveryKey) return unlockWithRecoveryKey(meta, secret.recoveryKey);
if (!secret.passphrase) throw new Error("The keyring passphrase is required.");
try {
return await unlockVault(meta, secret.passphrase);
} catch {
throw new Error("Wrong keyring passphrase.");
}
}
export interface NewKeyInput {
name: string;
privateKey: string;
publicKey: string;
type?: KeyringType;
filename?: string;
comment?: string;
/** The passphrase that protects the private key file itself, if any. Stored inside the ciphertext. */
keyPassphrase?: string;
}
/** Seal a key pair: the private half becomes an OpenCreds envelope, the public half stays readable. */
export async function sealEntry(userKey: Uint8Array, input: NewKeyInput, existing?: KeyringEntry): Promise<KeyringEntry> {
const name = validateName(input.name);
const publicKey = input.publicKey.trim();
if (looksPrivate(publicKey)) throw new Error("The public key text contains private key material. Refusing.");
if (!input.privateKey.trim()) throw new Error("The private key is empty.");
const type = input.type ?? detectType(input.privateKey, publicKey);
const filename = basename(input.filename ?? name);
const comment = input.comment ?? parseSshPublicKey(publicKey)?.comment ?? "";
const fingerprint = publicKey ? fingerprintOf(publicKey) : "";
const now = new Date().toISOString();
const item: Item = createItem("key", {
name,
key: {
keyType: opencredsKeyKind(type),
algorithm: type,
publicKey,
privateKey: input.privateKey,
passphrase: input.keyPassphrase ?? "",
fingerprint,
value: "",
path: `~/.ssh/${filename}`,
mode: "0600",
expiresAt: ""
}
});
item.id = existing?.id ?? randomUUID();
const envelope = await encryptItem(userKey, item);
return {
id: item.id,
name,
type,
filename,
publicKey,
fingerprint,
comment,
createdAt: existing?.createdAt ?? now,
updatedAt: now,
envelope,
deletedAt: null
};
}
/** Open an entry's envelope. Only ever called locally, with the unlocked user key. */
export async function openEntry(userKey: Uint8Array, entry: KeyringEntry): Promise<{ privateKey: string; keyPassphrase: string }> {
if (!entry.envelope) throw new Error(`${entry.name} has been deleted.`);
const item = await decryptItem(userKey, entry.envelope);
return { privateKey: String(item.key?.privateKey ?? ""), keyPassphrase: String(item.key?.passphrase ?? "") };
}
export function publicEntry(entry: KeyringEntry): PublicEntry {
const { envelope: _e, ...rest } = entry;
return rest;
}
// ---------------------------------------------------------------- restore ----
export interface RestorePlan {
privatePath: string;
publicPath: string;
}
export interface RestoreResult {
privatePath: string;
publicPath?: string;
wrote: boolean;
backups: string[];
note: string;
}
function backupPath(path: string): string {
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
let candidate = `${path}.bak-${stamp}`;
let n = 1;
while (existsSync(candidate)) candidate = `${path}.bak-${stamp}-${n++}`;
return candidate;
}
function sameText(path: string, text: string): boolean {
try {
return readFileSync(path, "utf8").trim() === text.trim();
} catch {
return false;
}
}
/**
* Write a key pair to disk under its default filename.
*
* - private 0600, public 0644, directory 0700 when it is created here
* - an identical file already there: nothing is written
* - a DIFFERENT file already there: refused, unless `force`, and then the old
* file is copied to `<file>.bak-<time>` before it is replaced
*/
export function restoreToDisk(
entry: PublicEntry,
privateKey: string,
options: { dir: string; force?: boolean }
): RestoreResult {
const dir = resolve(options.dir);
if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
const privatePath = join(dir, entry.filename);
const publicPath = entry.publicKey ? `${privatePath}.pub` : undefined;
const privateText = privateKey.endsWith("\n") ? privateKey : `${privateKey}\n`;
const publicText = entry.publicKey ? `${entry.publicKey.trim()}\n` : "";
const privSame = existsSync(privatePath) && sameText(privatePath, privateText);
const pubSame = !publicPath || (existsSync(publicPath) && sameText(publicPath, publicText));
const privConflict = existsSync(privatePath) && !privSame;
const pubConflict = Boolean(publicPath && existsSync(publicPath) && !pubSame);
if ((privConflict || pubConflict) && !options.force) {
const which = [privConflict ? privatePath : "", pubConflict ? publicPath : ""].filter(Boolean).join(" and ");
throw new Error(
`${which} already exists and holds a different key. Nothing was written. ` +
`Re-run with --force to replace it (the current file is backed up first), or restore elsewhere with --to <dir>.`
);
}
const backups: string[] = [];
let wrote = false;
if (!privSame) {
if (existsSync(privatePath)) {
const bak = backupPath(privatePath);
copyFileSync(privatePath, bak);
chmodSync(bak, 0o600);
backups.push(bak);
}
writePrivate(privatePath, privateText);
wrote = true;
} else {
chmodSync(privatePath, 0o600);
}
if (publicPath && !pubSame) {
if (existsSync(publicPath)) {
const bak = backupPath(publicPath);
copyFileSync(publicPath, bak);
backups.push(bak);
}
writeFileSync(publicPath, publicText, { encoding: "utf8", mode: 0o644 });
wrote = true;
}
if (publicPath) chmodSync(publicPath, 0o644);
return {
privatePath,
publicPath,
wrote,
backups,
note: wrote ? (backups.length ? `replaced (old copies: ${backups.join(", ")})` : "written") : "already there, identical"
};
}
export function fileMode(path: string): string {
return (statSync(path).mode & 0o777).toString(8).padStart(4, "0");
}
/** authorized_keys lines for the given entries (public halves only). */
export function authorizedKeysLines(entries: PublicEntry[]): string[] {
return entries.filter((e) => parseSshPublicKey(e.publicKey)).map((e) => e.publicKey.trim());
}

View file

@ -0,0 +1,61 @@
import { describe, expect, it } from "vitest";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import { createLogicSrcMcpServer } from "./server.js";
type Call = { url: string; method: string; body: unknown };
const PUB = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFK+fzMc3AneHlJ9+KGxhlTbhQDv4xlwE0oNmVCPpEL1 throwaway@test";
const entry = { id: "e1", name: "id_ed25519", type: "ssh-ed25519", filename: "id_ed25519", publicKey: PUB, fingerprint: "SHA256:abc", comment: "", createdAt: "2026-10-28T00:00:00Z", updatedAt: "2026-10-28T00:00:00Z", deletedAt: null };
function fakeApi(calls: Call[], payload: (url: string) => unknown): typeof fetch {
return (async (input: string | URL | Request, init?: RequestInit) => {
calls.push({ url: String(input), method: init?.method ?? "GET", body: init?.body ? JSON.parse(String(init.body)) : undefined });
return new Response(JSON.stringify(payload(String(input))), { status: 200, headers: { "content-type": "application/json" } });
}) as typeof fetch;
}
async function connect(doFetch: typeof fetch) {
const [c, s] = InMemoryTransport.createLinkedPair();
const server = createLogicSrcMcpServer({ apiKeys: { env: { LOGICSRC_API_KEY: "lsk_person" }, fetch: doFetch } });
const client = new Client({ name: "t", version: "0.1.0" });
await server.connect(s);
await client.connect(c);
return { client, close: async () => { await client.close(); await server.close(); } };
}
const text = (r: unknown) => ((r as { content: Array<{ text: string }> }).content[0]?.text ?? "");
describe("keyring tools", () => {
it("lists public halves and exports authorized_keys", async () => {
const calls: Call[] = [];
const { client, close } = await connect(fakeApi(calls, () => ({ meta: null, entries: [entry] })));
const names = (await client.listTools()).tools.map((t) => t.name);
expect(names).toEqual(expect.arrayContaining(["list_keyring_keys", "show_keyring_key", "export_authorized_keys", "add_keyring_key_ciphertext", "remove_keyring_key", "keyring_restore_instructions"]));
expect(text(await client.callTool({ name: "list_keyring_keys", arguments: {} }))).toContain("SHA256:abc");
expect(text(await client.callTool({ name: "export_authorized_keys", arguments: {} }))).toBe(PUB);
expect(calls[0]!.url).toBe("https://app.logicsrc.com/api/keyring");
await close();
});
it("refuses a plaintext private key and never relays one back", async () => {
const calls: Call[] = [];
const { client, close } = await connect(fakeApi(calls, () => ({ entry: { ...entry, publicKey: "-----BEGIN OPENSSH PRIVATE KEY-----" } })));
const bad = await client.callTool({
name: "add_keyring_key_ciphertext",
arguments: { entry: { ...entry, deletedAt: undefined, envelope: { id: "e1", type: 5, ciphertext: Buffer.from("-----BEGIN OPENSSH PRIVATE KEY-----").toString("base64"), iv: "AAAAAAAAAAAAAAAA" } } }
});
expect((bad as { isError?: boolean }).isError).toBe(true);
expect(calls).toHaveLength(0);
const shown = await client.callTool({ name: "show_keyring_key", arguments: { name: "id_ed25519" } });
expect((shown as { isError?: boolean }).isError).toBe(true);
expect(text(shown)).not.toContain("BEGIN OPENSSH");
await close();
});
it("restore instructions name the default file and the fingerprint", async () => {
const { client, close } = await connect(fakeApi([], () => ({ entry })));
const out = text(await client.callTool({ name: "keyring_restore_instructions", arguments: { name: "id_ed25519" } }));
expect(out).toContain("logicsrc keyring restore id_ed25519");
expect(out).toContain("~/.ssh/id_ed25519");
await close();
});
});

View file

@ -0,0 +1,170 @@
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import { DEFAULT_API_URL, type ApiKeyToolsOptions } from "./apikeys.js";
/**
* Keyring tools: the caller's `logicsrc keyring` (SSH keys and other key
* pairs) as stored in the account at app.logicsrc.com/api/keyring.
*
* These tools NEVER return a plaintext private key and cannot: the account
* holds only ciphertext sealed on the user's machine, and the passphrase that
* opens it is never given to an agent. Listing and showing return public
* halves and fingerprints. Adding takes an entry that is ALREADY sealed by the
* CLI (ciphertext envelope); anything that looks like private key material is
* refused here and again by the server. Restoring a key onto a machine is a
* terminal step for the person, and `keyring_restore_instructions` says how.
*/
const PRIVATE_MATERIAL = [
/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/,
/-----BEGIN PGP PRIVATE KEY BLOCK-----/,
/AGE-SECRET-KEY-1/,
/PuTTY-User-Key-File-/,
/b3BlbnNzaC1rZXktdjE/
];
const looksPrivate = (text: string) => PRIVATE_MATERIAL.some((re) => re.test(text));
class ToolError extends Error {}
function client(options: ApiKeyToolsOptions) {
const env = options.env ?? process.env;
const doFetch = options.fetch ?? fetch;
return async function call(method: string, path: string, body?: unknown): Promise<unknown> {
const token = env.LOGICSRC_API_KEY?.trim();
if (!token) throw new ToolError("LOGICSRC_API_KEY is not set. Give this MCP server a person's LogicSRC API key (logicsrc keys create <name> --kind user).");
const base = (env.LOGICSRC_API || env.LOGICSRC_API_URL || DEFAULT_API_URL).replace(/\/+$/, "");
const headers: Record<string, string> = { accept: "application/json", authorization: `Bearer ${token}` };
if (body !== undefined) headers["content-type"] = "application/json";
const res = await doFetch(`${base}${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
const text = await res.text();
let parsed: unknown;
try { parsed = text ? JSON.parse(text) : undefined; } catch { parsed = undefined; }
if (!res.ok) {
const message = parsed && typeof parsed === "object" && "error" in parsed ? String((parsed as { error: unknown }).error) : `${res.status} ${res.statusText}`;
throw new ToolError(`${method} ${path} failed (${res.status}): ${message}`);
}
// Defence in depth: never pass anything that looks like a private key back to the agent.
if (looksPrivate(text)) throw new ToolError("The response contained private key material and was withheld.");
return parsed;
};
}
const textResult = (text: string, isError = false) => ({ content: [{ type: "text" as const, text }], ...(isError ? { isError: true } : {}) });
async function guarded(fn: () => Promise<unknown>) {
try {
const out = await fn();
return textResult(typeof out === "string" ? out : JSON.stringify(out, null, 2));
} catch (error) {
return textResult(error instanceof Error ? error.message : String(error), true);
}
}
const entrySchema = z.object({
id: z.string().min(1).max(64),
name: z.string().min(1).max(128),
type: z.enum(["ssh-ed25519", "ssh-rsa", "ssh-ecdsa", "gpg", "age", "generic"]),
filename: z.string().min(1).max(255),
publicKey: z.string().max(16384),
fingerprint: z.string().max(128),
comment: z.string().max(1024).optional(),
createdAt: z.string(),
updatedAt: z.string(),
envelope: z.object({ id: z.string(), type: z.number(), ciphertext: z.string(), iv: z.string(), v: z.number().optional() }),
deletedAt: z.null().optional()
});
export function registerKeyring(server: McpServer, options: ApiKeyToolsOptions = {}): void {
const call = client(options);
server.registerTool(
"list_keyring_keys",
{
title: "List Keyring Keys",
description: "Lists the caller's LogicSRC keyring (SSH keys and other key pairs): name, type, file name it restores to, public key, fingerprint, comment. Public halves only; private keys are ciphertext the server cannot open and are never returned. Needs LOGICSRC_API_KEY (a person's key).",
annotations: { readOnlyHint: true, openWorldHint: true }
},
async () => guarded(async () => ((await call("GET", "/api/keyring")) as { entries: unknown[] }).entries)
);
server.registerTool(
"show_keyring_key",
{
title: "Show Keyring Key",
description: "Shows one keyring key's public half and fingerprint, by name or id. Never the private key.",
inputSchema: { name: z.string().min(1).describe("Key name (e.g. id_ed25519) or id.") },
annotations: { readOnlyHint: true, openWorldHint: true }
},
async ({ name }) => guarded(async () => ((await call("GET", `/api/keyring/entries/${encodeURIComponent(name)}`)) as { entry: unknown }).entry)
);
server.registerTool(
"export_authorized_keys",
{
title: "Export authorized_keys",
description: "Returns the keyring's SSH public keys as authorized_keys lines, for granting access to a server. Public keys only.",
inputSchema: { names: z.array(z.string()).optional().describe("Only these key names (default: every SSH key).") },
annotations: { readOnlyHint: true, openWorldHint: true }
},
async ({ names }) =>
guarded(async () => {
const { entries } = (await call("GET", "/api/keyring")) as { entries: Array<{ name: string; type: string; publicKey: string }> };
return entries
.filter((e) => e.type.startsWith("ssh-") && (!names?.length || names.includes(e.name)))
.map((e) => e.publicKey.trim())
.join("\n");
})
);
server.registerTool(
"add_keyring_key_ciphertext",
{
title: "Add Sealed Key To Keyring",
description: "Stores a keyring entry that was ALREADY encrypted on the user's machine (an OpenCreds envelope from `logicsrc keyring`, found in ~/.config/logicsrc/keyring/entries/<id>.json). Refuses anything containing a plaintext private key. To import a key file, the person runs `logicsrc keyring add ~/.ssh/id_ed25519 --sync` instead; never ask them for a private key or passphrase.",
inputSchema: { entry: entrySchema.describe("The sealed entry JSON.") },
annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true }
},
async ({ entry }) =>
guarded(async () => {
if (looksPrivate(JSON.stringify(entry)) || looksPrivate(Buffer.from(entry.envelope.ciphertext, "base64").toString("latin1"))) {
throw new ToolError("Refused: this entry contains a plaintext private key. Seal it with `logicsrc keyring add <file>` first.");
}
return call("PUT", `/api/keyring/entries/${encodeURIComponent(entry.id)}`, { entry });
})
);
server.registerTool(
"remove_keyring_key",
{
title: "Remove Keyring Key",
description: "Removes a key from the account keyring (a tombstone that reaches the user's other machines on their next `logicsrc keyring sync`). Files already restored on disk are not touched.",
inputSchema: { name: z.string().min(1).describe("Key name or id.") },
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true }
},
async ({ name }) => guarded(() => call("DELETE", `/api/keyring/entries/${encodeURIComponent(name)}`))
);
server.registerTool(
"keyring_restore_instructions",
{
title: "Keyring Restore Instructions",
description: "How the person restores a keyring key onto a machine. Restoring needs their keyring passphrase, which an agent must never hold, so this returns the commands for them to run.",
inputSchema: { name: z.string().min(1).describe("Key name, e.g. id_ed25519."), dir: z.string().optional().describe("Target directory (default ~/.ssh).") },
annotations: { readOnlyHint: true, openWorldHint: true }
},
async ({ name, dir }) =>
guarded(async () => {
const { entry } = (await call("GET", `/api/keyring/entries/${encodeURIComponent(name)}`)) as { entry: { name: string; filename: string; fingerprint: string } };
const to = dir ?? "~/.ssh";
return [
`Key ${entry.name} (${entry.fingerprint}) restores to ${to}/${entry.filename} (600) and ${entry.filename}.pub (644).`,
"On the target machine, the person runs:",
" curl -fsSL https://logicsrc.com/install.sh | sh # if logicsrc is not installed",
" logicsrc login",
" logicsrc keyring sync",
` logicsrc keyring restore ${entry.name}${dir ? ` --to ${dir}` : ""}`,
` ssh-keygen -lf ${to}/${entry.filename} # should print ${entry.fingerprint}`,
"An existing different key at that path is refused unless --force, which backs it up first."
].join("\n");
})
);
}

View file

@ -4,6 +4,7 @@ import { assertSchemaKind, parseDocument, schemas, validate, type SchemaKind } f
import { registerOpenOntology } from "./openontology.js";
import { registerOpenPrd } from "./openprd.js";
import { registerApiKeys, type ApiKeyToolsOptions } from "./apikeys.js";
import { registerKeyring } from "./keyring.js";
const docs = {
"communication-accounts": `LogicSRC Communication Accounts defines shared contracts for connecting social and email identities, granting scoped human/agent/plugin access, evaluating policy gates, brokering credentials, and auditing every account action without exposing raw secrets.`,
@ -157,6 +158,7 @@ export function createLogicSrcMcpServer(options: { apiKeys?: ApiKeyToolsOptions
registerOpenOntology(server);
registerOpenPrd(server);
registerApiKeys(server, options.apiKeys);
registerKeyring(server, options.apiKeys);
return server;
}

View file

@ -248,3 +248,5 @@ export {
SIMPLE_CSV_COLUMNS,
type SecretCategory,
} from "./categories.js";
export { promptSecret, promptNewSecret, resolveSecretFlag } from "./prompt.js";