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

@ -41,6 +41,7 @@ const GUIDE_SUBTITLES: Record<string, string> = {
tui: "Terminal rendering for the dashboard and Waiting Arcade",
config: "Where config lives, and what each key does",
permissions: "Explicit, scoped, auditable permission grants",
keyring: "SSH keys and key pairs, end-to-end encrypted, with optional cloud sync",
plugins: "The plugin system, and the plugins that ship with it",
"openontology-governance": "An agent proposes, a human applies",
"openontology-interoperability": "Mapping to RDF, SHACL and PROV-O, and where it stops",

View file

@ -148,6 +148,7 @@ export const GUIDES: Array<{ slug: string; name: string }> = [
{ slug: "tui", name: "TUI" },
{ slug: "config", name: "Config" },
{ slug: "permissions", name: "Permissions" },
{ slug: "keyring", name: "Keyring" },
{ slug: "plugins", name: "Plugins" },
{ slug: "openontology-governance", name: "OpenOntology governance" },
{ slug: "openontology-interoperability", name: "OpenOntology interoperability" }

107
apps/pwa/public/keyring.js Normal file
View file

@ -0,0 +1,107 @@
// /keyring: copy a public key, or decrypt a private key IN THIS TAB and save it.
//
// The derivation is OpenCreds' (packages/opencreds/src/kdf.ts + vault-key.ts +
// items.ts), over WebCrypto, exactly as the CLI does it:
// master = PBKDF2-SHA256(passphrase, meta.kdfSalt, meta.kdfIterations)
// wrap = HKDF-SHA256(master, info "<ns>:vault:wrap:v1")
// userKey = AES-GCM-open(wrap, meta.protectedUserKeyIv, meta.protectedUserKey)
// item = AES-GCM-open(userKey, env.iv, env.ciphertext, AAD "<ns>:vault:item:<v>:<id>")
// The passphrase, the user key and the private key never leave this page.
(() => {
const b64 = (s) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0));
const enc = new TextEncoder();
const REGISTERED = ["opencreds", "marksyncr"];
const MIN_ITERATIONS = 100000;
async function userKeyFrom(meta, passphrase) {
if (!REGISTERED.includes(meta.namespace)) throw new Error("Unknown keyring namespace.");
if (meta.kdf !== "pbkdf2-sha256" || !(meta.kdfIterations >= MIN_ITERATIONS)) throw new Error("Refusing weak or unknown KDF parameters.");
const pw = await crypto.subtle.importKey("raw", enc.encode(passphrase), "PBKDF2", false, ["deriveBits"]);
const master = await crypto.subtle.deriveBits({ name: "PBKDF2", salt: b64(meta.kdfSalt), iterations: meta.kdfIterations, hash: "SHA-256" }, pw, 256);
const hk = await crypto.subtle.importKey("raw", master, "HKDF", false, ["deriveBits"]);
const wrapBits = await crypto.subtle.deriveBits({ name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0), info: enc.encode(`${meta.namespace}:vault:wrap:v1`) }, hk, 256);
const wrap = await crypto.subtle.importKey("raw", wrapBits, "AES-GCM", false, ["decrypt"]);
try {
return await crypto.subtle.decrypt({ name: "AES-GCM", iv: b64(meta.protectedUserKeyIv) }, wrap, b64(meta.protectedUserKey));
} catch {
throw new Error("Wrong keyring passphrase.");
}
}
async function openEnvelope(meta, userKeyBytes, env) {
const key = await crypto.subtle.importKey("raw", userKeyBytes, "AES-GCM", false, ["decrypt"]);
const aad = enc.encode(`${meta.namespace}:vault:item:${env.v || 1}:${env.id}`);
const plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv: b64(env.iv), additionalData: aad }, key, b64(env.ciphertext));
const item = JSON.parse(new TextDecoder().decode(plain));
if (item.id !== env.id) throw new Error("Envelope id mismatch.");
return String(item.key?.privateKey || "");
}
// Loaded outside a page (the test suite): expose the crypto and stop.
if (typeof document === "undefined") {
globalThis.__logicsrcKeyring = { userKeyFrom, openEnvelope };
return;
}
const status = document.getElementById("kr-status");
const say = (msg) => { if (status) status.textContent = msg; };
function askPassphrase(file) {
return new Promise((resolve) => {
const dlg = document.createElement("dialog");
dlg.innerHTML = `<form method="dialog" style="display:flex;flex-direction:column;gap:10px;min-width:280px">
<label class="label">Keyring passphrase for <code></code></label>
<input type="password" autocomplete="current-password" required>
<div style="display:flex;gap:8px;justify-content:flex-end"><button class="btn" value="cancel" formnovalidate>Cancel</button><button class="btn acid" value="ok">Decrypt</button></div>
</form>`;
dlg.querySelector("code").textContent = file;
document.body.appendChild(dlg);
const input = dlg.querySelector("input");
dlg.addEventListener("close", () => {
const value = dlg.returnValue === "ok" ? input.value : null;
input.value = "";
dlg.remove();
resolve(value);
});
dlg.showModal();
input.focus();
});
}
function save(name, text) {
const url = URL.createObjectURL(new Blob([text.endsWith("\n") ? text : text + "\n"], { type: "application/octet-stream" }));
const a = Object.assign(document.createElement("a"), { href: url, download: name });
document.body.appendChild(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
document.addEventListener("click", async (ev) => {
const copy = ev.target.closest("[data-kr-copy]");
if (copy) {
const pre = document.querySelector(`[data-kr-pub="${CSS.escape(copy.dataset.krCopy)}"]`);
await navigator.clipboard.writeText(pre ? pre.textContent.trim() : "");
say("Public key copied.");
return;
}
const dl = ev.target.closest("[data-kr-download]");
if (!dl) return;
const file = dl.dataset.krFile || "id_key";
const passphrase = await askPassphrase(file);
if (!passphrase) return;
try {
say("Deriving the key (600,000 PBKDF2 rounds)…");
const res = await fetch("/api/keyring?include=envelopes", { credentials: "same-origin", headers: { accept: "application/json" } });
if (!res.ok) throw new Error(`The server answered ${res.status}.`);
const { meta, entries } = await res.json();
const entry = entries.find((e) => e.id === dl.dataset.krDownload && !e.deletedAt);
if (!meta || !entry?.envelope) throw new Error("That key is no longer in the keyring.");
const userKey = await userKeyFrom(meta, passphrase);
const privateKey = await openEnvelope(meta, userKey, entry.envelope);
save(file, privateKey);
say(`Decrypted ${file} in this tab and saved it. Put it in ~/.ssh and run: chmod 600 ~/.ssh/${file}`);
} catch (e) {
say(e.message || String(e));
}
});
})();

View file

@ -139,6 +139,7 @@ export function appBar(req) {
<div class="bar-right">
${user
? `<span class="mono faint" style="font-size:.78rem">${esc(user.email || user.display_name || "signed in")}</span>
<a class="btn" href="/keyring">Keyring</a>
<a class="btn" href="/settings">Settings</a>
<form method="post" action="/auth/logout" style="margin:0"><input type="hidden" name="_csrf" value="${esc(req?.csrfToken)}"><button class="btn">Sign out</button></form>`
: `<a class="btn acid" href="/">Sign in</a>`}
@ -148,6 +149,6 @@ export function appBar(req) {
export const footer = `<footer><div class="wrap foot">
<div class="brand" style="font-size:.9rem;color:var(--ink)"><span class="mark" style="width:20px;height:20px;font-size:.62rem">LS</span>LogicSRC</div>
<div style="display:flex;gap:20px;flex-wrap:wrap"><a href="https://logicsrc.com">logicsrc.com</a><a href="/">Teams</a><a href="/settings">Settings</a></div>
<div style="display:flex;gap:20px;flex-wrap:wrap"><a href="https://logicsrc.com">logicsrc.com</a><a href="/">Teams</a><a href="/keyring">Keyring</a><a href="/settings">Settings</a></div>
<div class="green">end-to-end encrypted. <b>the server never sees your secrets.</b></div>
</div></footer>`;

View file

@ -0,0 +1,28 @@
-- Postgres copy of migrations/008_keyring.sql (INTEGER -> bigint). Additive only.
-- The keyring (`logicsrc keyring`): wrapped meta + AES-GCM envelopes; public
-- halves in the clear on purpose.
create table if not exists keyring_vaults (
user_id text PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
meta text NOT NULL,
created_at bigint NOT NULL,
updated_at bigint NOT NULL
);
create table if not exists keyring_entries (
user_id text NOT NULL REFERENCES users(id) ON DELETE CASCADE,
id text NOT NULL,
name text NOT NULL,
key_type text NOT NULL,
filename text NOT NULL,
public_key text NOT NULL,
fingerprint text NOT NULL,
comment text NOT NULL DEFAULT '',
envelope text,
created_at bigint NOT NULL,
updated_at bigint NOT NULL,
deleted_at bigint,
PRIMARY KEY (user_id, id)
);
CREATE INDEX IF NOT EXISTS idx_keyring_entries_user ON keyring_entries(user_id, updated_at);

View file

@ -0,0 +1,33 @@
-- The keyring (`logicsrc keyring`): SSH keys and other key pairs, synced to the
-- account. Additive only. Zero-knowledge like opencreds: meta is OpenCreds
-- VaultMeta (the user key wrapped under the keyring passphrase), and each
-- entry's private key is an AES-GCM envelope under that user key. The public
-- half (name, type, public key, fingerprint, comment) is stored in the clear
-- on purpose: it is public, and the web page lists it without a passphrase.
CREATE TABLE IF NOT EXISTS keyring_vaults (
user_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
meta TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
-- envelope NULL + deleted_at set = a tombstone, kept so the removal reaches
-- every other machine. updated_at is the client's clock (ms), used for
-- last-writer-wins.
CREATE TABLE IF NOT EXISTS keyring_entries (
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
id TEXT NOT NULL,
name TEXT NOT NULL,
key_type TEXT NOT NULL,
filename TEXT NOT NULL,
public_key TEXT NOT NULL,
fingerprint TEXT NOT NULL,
comment TEXT NOT NULL DEFAULT '',
envelope TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
deleted_at INTEGER,
PRIMARY KEY (user_id, id)
);
CREATE INDEX IF NOT EXISTS idx_keyring_entries_user ON keyring_entries(user_id, updated_at);

View file

@ -0,0 +1,253 @@
// The keyring (`logicsrc keyring`): SSH keys and other key pairs, synced to the
// account as ciphertext.
//
// Zero-knowledge. The CLI uploads the keyring's meta (OpenCreds VaultMeta: the
// user key wrapped under the keyring passphrase, which never leaves the
// client) and per key: the public half in the clear and the private half as an
// AES-256-GCM envelope. Nothing here can decrypt an envelope, and every write
// is checked so that a buggy or hostile client cannot park a plaintext private
// key in the database by mistake: any field that looks like private key
// material is refused with 422.
//
// Auth: a person's `Bearer lsk_…` key (the CLI, the MCP server) for every
// call; a browser session may read (GET) for the /keyring page. Machine keys
// are refused: the keyring is the person's alone. Mounted at /api/keyring, and
// the page at /keyring.
import { Router } from "express";
import { get, all, run } from "../db.mjs";
import { bearer, keyForBearer } from "../lib/apikey.mjs";
import { page, footer, appBar, esc } from "../lib/html.mjs";
import { requireAuth } from "../lib/session.mjs";
export const keyringRouter = Router();
export const KEYRING_TYPES = ["ssh-ed25519", "ssh-rsa", "ssh-ecdsa", "gpg", "age", "generic"];
export const MAX_ENTRIES = 1000;
// Private key material in every format we know of. Checked against the whole
// request body, so it does not matter which field it was smuggled into.
const PRIVATE_MATERIAL = [
/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/,
/-----BEGIN PGP PRIVATE KEY BLOCK-----/,
/AGE-SECRET-KEY-1/,
/PuTTY-User-Key-File-/,
/b3BlbnNzaC1rZXktdjE/ // base64 of "openssh-key-v1", the OpenSSH private key body
];
export const containsPrivateMaterial = (text) => PRIVATE_MATERIAL.some((re) => re.test(text));
const B64 = /^[A-Za-z0-9+/]+={0,2}$/;
const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
const str = (v, max) => typeof v === "string" && v.length <= max;
function auth({ write }) {
return (handler) => async (req, res) => {
let user = null;
const token = bearer(req);
if (token) {
const found = await keyForBearer(token);
if (!found) return res.status(401).json({ error: "Not authenticated. Run: logicsrc login" });
if (found.key.kind === "machine") {
return res.status(403).json({ error: "A machine API key cannot use the personal keyring.", code: "machine_key_forbidden" });
}
user = found.user;
} else if (req.user && !write) {
user = req.user;
} else if (req.user && write) {
return res.status(403).json({ error: "Changes to the keyring go through the CLI (Bearer key), not the browser session." });
} else {
return res.status(401).json({ error: "Not authenticated. Run: logicsrc login" });
}
try {
await handler(req, res, user);
} catch (e) {
console.error("keyring:", e);
res.status(500).json({ error: e.message || String(e) });
}
};
}
const reader = auth({ write: false });
const writer = auth({ write: true });
const iso = (ms) => (ms === null || ms === undefined ? null : new Date(Number(ms)).toISOString());
export function entryJson(row, { envelope = true } = {}) {
return {
id: row.id,
name: row.name,
type: row.key_type,
filename: row.filename,
publicKey: row.public_key,
fingerprint: row.fingerprint,
comment: row.comment || "",
createdAt: iso(row.created_at),
updatedAt: iso(row.updated_at),
deletedAt: iso(row.deleted_at),
...(envelope ? { envelope: row.envelope ? JSON.parse(row.envelope) : null } : {})
};
}
/** Validate an uploaded entry; returns an error string or null. */
export function entryProblem(id, e) {
if (!isObject(e)) return "Expected { entry }.";
if (containsPrivateMaterial(JSON.stringify(e))) {
return "Refused: the entry contains plaintext private key material. Only ciphertext may be uploaded.";
}
if (e.id !== id || !/^[A-Za-z0-9-]{1,64}$/.test(id)) return "entry.id must match the URL and be a uuid.";
if (!str(e.name, 128) || !e.name) return "entry.name is required (max 128).";
if (!KEYRING_TYPES.includes(e.type)) return `entry.type must be one of ${KEYRING_TYPES.join(", ")}.`;
if (!str(e.filename, 255) || !e.filename || /[/\\]/.test(e.filename)) return "entry.filename must be a bare file name.";
if (!str(e.publicKey ?? "", 16384)) return "entry.publicKey is too long.";
if (!str(e.fingerprint ?? "", 128)) return "entry.fingerprint is too long.";
if (!str(e.comment ?? "", 1024)) return "entry.comment is too long.";
if (Number.isNaN(Date.parse(e.updatedAt))) return "entry.updatedAt must be an ISO date.";
if (e.deletedAt) {
if (e.envelope !== null && e.envelope !== undefined) return "A deleted entry carries no envelope.";
} else {
const env = e.envelope;
if (!isObject(env)) return "entry.envelope is required.";
const extra = Object.keys(env).filter((k) => !["id", "type", "ciphertext", "iv", "v", "revision"].includes(k));
if (extra.length) return `entry.envelope has unexpected fields: ${extra.join(", ")}.`;
if (env.id !== id) return "entry.envelope.id must match the entry id (it is bound into the ciphertext).";
if (typeof env.ciphertext !== "string" || !B64.test(env.ciphertext) || env.ciphertext.length < 24 || env.ciphertext.length > 262144) {
return "entry.envelope.ciphertext must be base64 AES-GCM ciphertext.";
}
// A "ciphertext" that decodes to a PEM/OpenSSH/age key is a plaintext key in base64.
if (containsPrivateMaterial(Buffer.from(env.ciphertext, "base64").toString("latin1"))) {
return "Refused: entry.envelope.ciphertext decodes to a plaintext private key. Only ciphertext may be uploaded.";
}
if (typeof env.iv !== "string" || !B64.test(env.iv) || Buffer.from(env.iv, "base64").length !== 12) return "entry.envelope.iv must be a base64 96-bit IV.";
}
return null;
}
const metaProblem = (meta) =>
!isObject(meta) || typeof meta.protectedUserKey !== "string" || !meta.protectedUserKey || typeof meta.kdfSalt !== "string"
? "Expected { meta } with protectedUserKey and kdfSalt (OpenCreds VaultMeta)."
: containsPrivateMaterial(JSON.stringify(meta))
? "Refused: meta contains private key material."
: null;
const sameKeyring = (a, b) => a.kdfSalt === b.kdfSalt && a.protectedUserKey === b.protectedUserKey;
// ---- API ----
// The whole keyring. Envelopes only when asked (?include=envelopes): the page
// and the MCP list need public halves alone.
keyringRouter.get("/api/keyring", reader(async (req, res, user) => {
const withEnvelopes = String(req.query.include || "") === "envelopes";
const vault = await get(`SELECT * FROM keyring_vaults WHERE user_id = ?`, [user.id]);
const rows = await all(`SELECT * FROM keyring_entries WHERE user_id = ? ORDER BY name`, [user.id]);
const entries = rows
.filter((r) => withEnvelopes || !r.deleted_at)
.map((r) => entryJson(r, { envelope: withEnvelopes }));
res.set("Cache-Control", "no-store");
res.json({ meta: vault ? JSON.parse(vault.meta) : null, entries });
}));
keyringRouter.get("/api/keyring/entries/:id", reader(async (req, res, user) => {
const row = await get(`SELECT * FROM keyring_entries WHERE user_id = ? AND (id = ? OR name = ?) AND deleted_at IS NULL`, [user.id, req.params.id, req.params.id]);
if (!row) return res.status(404).json({ error: "No such key." });
res.set("Cache-Control", "no-store");
res.json({ entry: entryJson(row, { envelope: String(req.query.include || "") === "envelope" }) });
}));
keyringRouter.put("/api/keyring/meta", writer(async (req, res, user) => {
const meta = req.body?.meta;
const problem = metaProblem(meta);
if (problem) return res.status(422).json({ error: problem });
const now = Date.now();
await run(`INSERT INTO keyring_vaults (user_id, meta, created_at, updated_at) VALUES (?,?,?,?) ON CONFLICT (user_id) DO NOTHING`,
[user.id, JSON.stringify(meta), now, now]);
const row = await get(`SELECT meta FROM keyring_vaults WHERE user_id = ?`, [user.id]);
const current = JSON.parse(row.meta);
if (sameKeyring(current, meta)) return res.json({ ok: true });
res.status(409).json({ ok: false, meta: current, error: "The account already holds a different keyring." });
}));
// Upsert one entry, last-writer-wins on the client's updatedAt/deletedAt.
keyringRouter.put("/api/keyring/entries/:id", writer(async (req, res, user) => {
const id = req.params.id;
const e = req.body?.entry;
const problem = entryProblem(id, e);
if (problem) return res.status(422).json({ error: problem });
if (!(await get(`SELECT 1 FROM keyring_vaults WHERE user_id = ?`, [user.id]))) {
return res.status(409).json({ error: "Push the keyring meta first." });
}
const count = await get(`SELECT COUNT(*) AS n FROM keyring_entries WHERE user_id = ?`, [user.id]);
const existing = await get(`SELECT * FROM keyring_entries WHERE user_id = ? AND id = ?`, [user.id, id]);
if (!existing && Number(count?.n || 0) >= MAX_ENTRIES) return res.status(413).json({ error: `At most ${MAX_ENTRIES} keys.` });
const updatedAt = Date.parse(e.updatedAt);
const deletedAt = e.deletedAt ? Date.parse(e.deletedAt) : null;
const stamp = Math.max(updatedAt, deletedAt || 0);
if (existing && Math.max(Number(existing.updated_at), Number(existing.deleted_at || 0)) > stamp) {
return res.status(409).json({ ok: false, entry: entryJson(existing) });
}
const envelope = e.deletedAt ? null : JSON.stringify({ id: e.envelope.id, type: e.envelope.type, ciphertext: e.envelope.ciphertext, iv: e.envelope.iv, ...(e.envelope.v ? { v: e.envelope.v } : {}) });
const createdAt = Date.parse(e.createdAt) || updatedAt;
const args = [e.name, e.type, e.filename, e.publicKey || "", e.fingerprint || "", e.comment || "", envelope, updatedAt, deletedAt];
if (existing) {
await run(`UPDATE keyring_entries SET name = ?, key_type = ?, filename = ?, public_key = ?, fingerprint = ?, comment = ?, envelope = ?, updated_at = ?, deleted_at = ? WHERE user_id = ? AND id = ?`,
[...args, user.id, id]);
} else {
await run(`INSERT INTO keyring_entries (name, key_type, filename, public_key, fingerprint, comment, envelope, updated_at, deleted_at, user_id, id, created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)`,
[...args, user.id, id, createdAt]);
}
res.json({ ok: true });
}));
// Remove one key: a tombstone, so the removal reaches the user's other machines.
keyringRouter.delete("/api/keyring/entries/:id", writer(async (req, res, user) => {
const row = await get(`SELECT * FROM keyring_entries WHERE user_id = ? AND (id = ? OR name = ?) AND deleted_at IS NULL`, [user.id, req.params.id, req.params.id]);
if (!row) return res.status(404).json({ error: "No such key." });
const now = Date.now();
await run(`UPDATE keyring_entries SET envelope = NULL, deleted_at = ?, updated_at = ? WHERE user_id = ? AND id = ?`, [now, now, user.id, row.id]);
res.json({ ok: true, id: row.id, name: row.name });
}));
// Replace the account's keyring (`logicsrc keyring sync --use-local`).
keyringRouter.delete("/api/keyring", writer(async (_req, res, user) => {
await run(`DELETE FROM keyring_entries WHERE user_id = ?`, [user.id]);
await run(`DELETE FROM keyring_vaults WHERE user_id = ?`, [user.id]);
res.json({ ok: true });
}));
// ---- the page ----
const when = (ms) => (ms ? new Date(Number(ms)).toISOString().slice(0, 16).replace("T", " ") : "—");
export function keyringPageBody(rows) {
const list = rows.length
? `<div class="table-scroll"><table><thead><tr><th>Name</th><th>Type</th><th>Fingerprint</th><th>Comment</th><th>Updated (UTC)</th><th></th></tr></thead><tbody>${rows.map((r) => `<tr>
<td><code>${esc(r.name)}</code><div class="faint mono" style="font-size:.72rem">restores to ~/.ssh/${esc(r.filename)}</div></td>
<td class="mono">${esc(r.key_type)}</td>
<td><code class="fp">${esc(r.fingerprint || "—")}</code></td>
<td>${esc(r.comment || "—")}</td>
<td class="mono" style="white-space:nowrap">${esc(when(r.updated_at))}</td>
<td style="white-space:nowrap"><button class="btn compact" data-kr-copy="${esc(r.id)}">Copy public</button>
<button class="btn compact" data-kr-download="${esc(r.id)}" data-kr-file="${esc(r.filename)}">Decrypt &amp; download</button></td>
</tr><tr class="kr-pub"><td colspan="6"><pre class="mono" data-kr-pub="${esc(r.id)}" style="white-space:pre-wrap;word-break:break-all;margin:0;font-size:.74rem">${esc(r.public_key)}</pre></td></tr>`).join("")}</tbody></table></div>`
: `<p class="faint mono" style="font-size:.85rem">No keys yet. From a terminal: <code>logicsrc keyring add ~/.ssh/id_ed25519 &amp;&amp; logicsrc keyring sync</code></p>`;
return `<main class="wrap" style="max-width:920px;padding:26px 0 40px">
<div class="section-title"><h1 style="font-size:1.6rem">Keyring</h1><span class="count">${rows.length}</span></div>
<p class="dim" style="font-size:.9rem">SSH keys and other key pairs from <code>logicsrc keyring</code>. Public keys are shown as stored. Private keys are held only as ciphertext; <b>Decrypt &amp; download</b> asks for your keyring passphrase and decrypts in this tab. The passphrase and the private key are never sent to the server.</p>
<div class="card"><div class="card-body">${list}
<div id="kr-status" class="mono faint" style="font-size:.8rem;margin-top:10px" role="status"></div>
</div></div>
<details style="margin-top:18px"><summary class="dim" style="cursor:pointer">Restore from a terminal</summary>
<pre class="mono" style="font-size:.8rem">curl -fsSL https://logicsrc.com/install.sh | sh
logicsrc login
logicsrc keyring sync
logicsrc keyring restore id_ed25519 # writes ~/.ssh/id_ed25519 (600) + .pub (644)</pre></details>
</main>`;
}
keyringRouter.get("/keyring", requireAuth, async (req, res) => {
const rows = await all(`SELECT id, name, key_type, filename, public_key, fingerprint, comment, updated_at FROM keyring_entries WHERE user_id = ? AND deleted_at IS NULL ORDER BY name`, [req.user.id]);
res.set("Cache-Control", "no-store");
res.type("html").send(page({
title: "LogicSRC ▸ keyring",
body: `${appBar(req)}${keyringPageBody(rows)}${footer}`,
head: `<script src="/keyring.js" defer></script>`
}));
});

View file

@ -12,6 +12,7 @@ import { coinpayRouter } from "./routes/coinpay.mjs";
import { credshareRouter } from "./routes/credshare.mjs";
import { apiKeysRouter } from "./routes/apikeys.mjs";
import { opencredsRouter } from "./routes/opencreds.mjs";
import { keyringRouter } from "./routes/keyring.mjs";
import { cliRouter } from "./routes/cli.mjs";
import { pagesRouter } from "./routes/pages.mjs";
import { profileRouter } from "./lib/profile.mjs";
@ -75,6 +76,7 @@ app.use(coinpayRouter);
app.use(credshareRouter); // /api/credshare/* (session or lsk_ Bearer)
app.use(apiKeysRouter); // /api/keys (session or a person's lsk_ key; never a machine key)
app.use(opencredsRouter); // /api/opencreds/* — personal vault sync (session or lsk_ Bearer)
app.use(keyringRouter); // /api/keyring/* + /keyring — SSH keys / key pairs, ciphertext only
app.use(cliRouter); // /cli/authorize, /cli/token, /api/me
app.use(profileRouter); // /api/v1/me/profile (session cookie)
app.use(pagesRouter); // /dashboard, /teams/*, /settings

View file

@ -0,0 +1,194 @@
// /api/keyring + /keyring: the account copy of `logicsrc keyring`. The server
// must hold ciphertext only: real envelopes made with the OpenCreds reference
// code are accepted, anything carrying plaintext private key material is
// refused, the stored row never contains it, and the page's in-browser
// decryption (public/keyring.js) opens what the CLI sealed.
process.env.DATABASE_URL = process.env.PWA_TEST_DATABASE_URL || ":memory:";
import test from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { runInThisContext } from "node:vm";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import { generateKeyPairSync } from "node:crypto";
import express from "express";
import { createItem, createVault, encryptItem } from "@logicsrc/opencreds";
const here = dirname(fileURLToPath(import.meta.url));
const { db, run, all, isPostgres } = await import("../src/db.mjs");
const { keyringRouter, containsPrivateMaterial } = await import("../src/routes/keyring.mjs");
if (isPostgres) {
await db.execute("DROP SCHEMA public CASCADE");
await db.execute("CREATE SCHEMA public");
}
const { readdirSync } = await import("node:fs");
const migDir = join(here, "..", "src", isPostgres ? "migrations-pg" : "migrations");
for (const file of readdirSync(migDir).filter((f) => f.endsWith(".sql")).sort()) {
const sql = readFileSync(join(migDir, file), "utf8");
for (const statement of sql.split(/;\s*$/m).map((s) => s.trim()).filter(Boolean)) await db.execute(statement);
}
for (const uid of ["u1", "u2"]) await run(`INSERT INTO users (id, email, created_at) VALUES (?,?,?)`, [uid, `${uid}@e.test`, Date.now()]);
// Bearer handling is the shared lib's; here a header stands in for a person's key.
const app = express();
app.use(express.json({ limit: "10mb" }));
app.use((req, _res, next) => {
const u = req.get("x-user");
req.user = u ? { id: u, email: `${u}@e.test` } : null;
next();
});
app.use(keyringRouter);
const server = app.listen(0);
await new Promise((r) => server.once("listening", r));
const base = `http://127.0.0.1:${server.address().port}`;
async function call(user, method, path, body) {
const res = await fetch(base + path, {
method,
headers: { ...(user ? { "x-user": user } : {}), ...(body ? { "content-type": "application/json" } : {}) },
body: body ? JSON.stringify(body) : undefined
});
const text = await res.text();
let json; try { json = JSON.parse(text); } catch { json = text; }
return { status: res.status, body: json };
}
// The write path: real person API keys, resolved by the real lib/apikey lookup.
const bearerApp = express();
bearerApp.use(express.json({ limit: "10mb" }));
bearerApp.use((req, _res, next) => { req.user = null; next(); });
const realUser = await import("../src/lib/apikey.mjs");
// Insert real person API keys so keyForBearer resolves them.
const keyFor = {};
for (const uid of ["u1", "u2"]) {
const created = await realUser.createApiKey(uid, `test-${uid}`, { kind: "user" });
keyFor[uid] = created.plaintext;
}
bearerApp.use(keyringRouter);
const server2 = bearerApp.listen(0);
await new Promise((r) => server2.once("listening", r));
const base2 = `http://127.0.0.1:${server2.address().port}`;
test.after(() => Promise.all([new Promise((r) => server.close(r)), new Promise((r) => server2.close(r))]));
async function cli(user, method, path, body) {
const res = await fetch(base2 + path, {
method,
headers: { authorization: `Bearer ${keyFor[user]}`, ...(body ? { "content-type": "application/json" } : {}) },
body: body ? JSON.stringify(body) : undefined
});
return { status: res.status, body: await res.json() };
}
const PASS = "correct horse battery staple";
const vault = await createVault(PASS);
const { privateKey: PRIV } = generateKeyPairSync("ed25519", { privateKeyEncoding: { type: "pkcs8", format: "pem" }, publicKeyEncoding: { type: "spki", format: "pem" } });
const PUB = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFK+fzMc3AneHlJ9+KGxhlTbhQDv4xlwE0oNmVCPpEL1 throwaway@test";
// A browser session may only read; writes need the CLI's Bearer key.
test("no session, no key: 401; a session cannot write", async () => {
assert.equal((await call(null, "GET", "/api/keyring")).status, 401);
assert.equal((await call("u1", "PUT", "/api/keyring/meta", { meta: {} })).status, 403);
});
async function sealed(id, privateKey = PRIV) {
const item = createItem("key", { name: "id_ed25519", key: { keyType: "ssh", algorithm: "ssh-ed25519", publicKey: PUB, privateKey } });
item.id = id;
const envelope = await encryptItem(vault.userKey, item);
const now = new Date().toISOString();
return { id, name: "id_ed25519", type: "ssh-ed25519", filename: "id_ed25519", publicKey: PUB, fingerprint: "SHA256:xlBmhjCwKIXfA2QBSQxLR8zil6z3Lm7SqPFQmHW0jkI", comment: "throwaway@test", createdAt: now, updatedAt: now, envelope, deletedAt: null };
}
test("meta: created once, identical re-put ok, a different keyring is 409", async () => {
assert.deepEqual((await cli("u1", "GET", "/api/keyring")).body, { meta: null, entries: [] });
assert.equal((await cli("u1", "PUT", "/api/keyring/meta", { meta: vault.meta })).status, 200);
assert.equal((await cli("u1", "PUT", "/api/keyring/meta", { meta: vault.meta })).status, 200);
const other = await createVault("another");
const r = await cli("u1", "PUT", "/api/keyring/meta", { meta: other.meta });
assert.equal(r.status, 409);
assert.equal(r.body.meta.kdfSalt, vault.meta.kdfSalt);
});
test("an entry with a real envelope is stored; the row holds ciphertext only", async () => {
const entry = await sealed("11111111-1111-4111-8111-111111111111");
assert.equal((await cli("u1", "PUT", `/api/keyring/entries/${entry.id}`, { entry })).status, 200);
const rows = await all(`SELECT * FROM keyring_entries WHERE user_id = ?`, ["u1"]);
assert.equal(rows.length, 1);
const dump = JSON.stringify(rows);
assert.ok(!dump.includes("PRIVATE KEY"), "no PEM header in the row");
assert.ok(!dump.includes(PRIV.split("\n")[1]), "no private key body in the row");
assert.ok(!containsPrivateMaterial(dump));
assert.equal(JSON.parse(rows[0].envelope).ciphertext, entry.envelope.ciphertext);
// Default listing: public halves only, no envelopes.
const list = await cli("u1", "GET", "/api/keyring");
assert.equal(list.body.entries[0].publicKey, PUB);
assert.equal(list.body.entries[0].envelope, undefined);
// Other users see nothing.
assert.deepEqual((await cli("u2", "GET", "/api/keyring")).body.entries, []);
});
test("plaintext private key material is refused wherever it is put", async () => {
const id = "22222222-2222-4222-8222-222222222222";
const good = await sealed(id);
const cases = [
{ ...good, publicKey: PRIV },
{ ...good, comment: "-----BEGIN OPENSSH PRIVATE KEY-----" },
{ ...good, envelope: { ...good.envelope, ciphertext: Buffer.from(PRIV).toString("base64").replace(/=+$/, "") + "==" , iv: good.envelope.iv } },
{ ...good, envelope: { ...good.envelope, privateKey: PRIV } },
{ ...good, envelope: { ...good.envelope, extra: "x" } },
{ ...good, envelope: { ...good.envelope, ciphertext: "not base64!" } },
{ ...good, envelope: null },
{ ...good, comment: "AGE-SECRET-KEY-1QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ" }
];
for (const entry of cases) {
const r = await cli("u1", "PUT", `/api/keyring/entries/${id}`, { entry });
assert.equal(r.status, 422, `case refused: ${JSON.stringify(r.body)}`);
}
const rows = await all(`SELECT * FROM keyring_entries WHERE user_id = ? AND id = ?`, ["u1", id]);
for (const row of rows) assert.ok(!containsPrivateMaterial(JSON.stringify(row)));
});
test("last writer wins; tombstones reach the listing with include=envelopes", async () => {
const id = "33333333-3333-4333-8333-333333333333";
const first = await sealed(id);
assert.equal((await cli("u1", "PUT", `/api/keyring/entries/${id}`, { entry: first })).status, 200);
const stale = { ...first, comment: "older", updatedAt: new Date(Date.parse(first.updatedAt) - 60_000).toISOString() };
const r = await cli("u1", "PUT", `/api/keyring/entries/${id}`, { entry: stale });
assert.equal(r.status, 409);
assert.equal(r.body.entry.comment, "throwaway@test");
const del = await cli("u1", "DELETE", `/api/keyring/entries/${id}`);
assert.equal(del.status, 200);
const all1 = await cli("u1", "GET", "/api/keyring?include=envelopes");
const tomb = all1.body.entries.find((e) => e.id === id);
assert.ok(tomb.deletedAt);
assert.equal(tomb.envelope, null);
assert.ok(!(await cli("u1", "GET", "/api/keyring")).body.entries.some((e) => e.id === id));
});
test("the page's in-browser decryption opens what the CLI sealed", async () => {
runInThisContext(readFileSync(join(here, "..", "public", "keyring.js"), "utf8"));
const { userKeyFrom, openEnvelope } = globalThis.__logicsrcKeyring;
const { body } = await cli("u1", "GET", "/api/keyring?include=envelopes");
const entry = body.entries.find((e) => e.envelope);
const userKey = await userKeyFrom(body.meta, PASS);
assert.equal(await openEnvelope(body.meta, userKey, entry.envelope), PRIV);
await assert.rejects(() => userKeyFrom(body.meta, "wrong"), /Wrong keyring passphrase/);
});
test("a machine key is refused", async () => {
const machine = await realUser.createApiKey("u1", "box", { kind: "machine" });
const res = await fetch(base2 + "/api/keyring", { headers: { authorization: `Bearer ${machine.plaintext}` } });
assert.equal(res.status, 403);
});
test("the /keyring page lists public halves and never an envelope", async () => {
const { keyringPageBody } = await import("../src/routes/keyring.mjs");
const rows = await all(`SELECT * FROM keyring_entries WHERE user_id = ? AND deleted_at IS NULL`, ["u1"]);
const html = keyringPageBody(rows);
assert.ok(html.includes("SHA256:xlBmhjCwKIXfA2QBSQxLR8zil6z3Lm7SqPFQmHW0jkI"));
assert.ok(html.includes("ssh-ed25519 AAAAC3"));
assert.ok(!html.includes(rows[0].envelope ? JSON.parse(rows[0].envelope).ciphertext : "@@"));
});

View file

@ -147,7 +147,7 @@
},
"packages/cli": {
"name": "@logicsrc/cli",
"version": "0.10.0",
"version": "0.12.0",
"bin": {
"logicsrc": "./dist/index.js",
},

129
docs/keyring.md Normal file
View file

@ -0,0 +1,129 @@
# Keyring
`logicsrc keyring` keeps SSH keys and other public/private key pairs (GPG, age,
any generic pair) **end-to-end encrypted**. It works entirely on one machine with
no account. Turn on sync and the account at app.logicsrc.com holds a copy, but
only as ciphertext. You can then restore a key onto a new machine with one
command.
The keyring exists because private keys kept in plaintext, in a repo or a backup,
are one leak away from a compromise. The keyring makes the safe path the easy one.
Keys are sealed on your machine and synced as ciphertext. Restoring puts them back
under their default file names with the right permissions.
## Quick start
```sh
curl -fsSL https://logicsrc.com/install.sh | sh # or: logicsrc update
# Import your key (and its .pub). You pick a keyring passphrase the first time
# and get a one-time recovery key: store it offline.
logicsrc keyring add ~/.ssh/id_ed25519
# Optional: sync the ciphertext to your account.
logicsrc login
logicsrc keyring sync
# On a new machine:
logicsrc login
logicsrc keyring sync
logicsrc keyring restore id_ed25519 # ~/.ssh/id_ed25519 (600) + id_ed25519.pub (644)
ssh-keygen -lf ~/.ssh/id_ed25519 # compare with: logicsrc keyring show id_ed25519
```
## Commands
| Command | What it does |
| --- | --- |
| `keyring init [--cloud]` | Create the keyring. Asks for a passphrase and prints a one-time recovery key. `add` and `gen` call this for you. |
| `keyring add <file> [--name n] [--pub f] [--type t] [--sync]` | Import a private key file and its `.pub`. If there is no `.pub`, the public half is derived with `ssh-keygen -y`, or read from an age identity's comment. |
| `keyring gen <name> [--type ed25519\|rsa\|ecdsa]` | Generate a pair straight into the keyring. Nothing is written to `~/.ssh` until you `restore`. |
| `keyring list` | Name, type, fingerprint, comment. Needs no passphrase. |
| `keyring show <name>` | Public key and fingerprint. `--print-private` also prints the private key (it asks for the passphrase). |
| `keyring restore <name> [--to dir] [--force]` | Decrypt and write the key under its **default file name**. |
| `keyring export --pub [names…]` | `authorized_keys` lines (public keys only). |
| `keyring rm <name> [--sync]` | Remove a key. The removal reaches your other machines on their next sync. |
| `keyring sync [--use-remote\|--use-local\|--off]` | Turn on cloud sync and exchange ciphertext with your account. |
| `keyring status` | Where the keyring lives, how many keys it holds, and whether sync is on. |
For non-interactive use, set `LOGICSRC_KEYRING_PASSPHRASE` or pipe the passphrase
on stdin. `--recovery-key <key>` unlocks with the recovery key instead.
(`logicsrc keys` is a different command: it manages API keys.)
### Restore rules
- The private key is written `0600` and the public key `0644`. A directory created by `restore` is `0700`.
- If an identical file is already there, nothing is written.
- If a **different** key is already at that path, restore refuses and writes nothing. With `--force`, it copies the existing file to `<file>.bak-<time>` first and then replaces it.
- Keys go back under the file name they were imported from (`id_ed25519`). Restore never invents a new name.
- The private key is never printed unless you pass `--print-private`.
## How it is encrypted
The keyring uses no new cryptography. It is an [OpenCreds](https://logicsrc.com/opencreds)
`user`-profile vault, the same scheme as `logicsrc vault`:
- A random 256-bit **user key** is wrapped under your passphrase. The passphrase is
stretched with PBKDF2-HMAC-SHA256 (600,000 iterations), then HKDF splits out a
wrap key. The keyring also stores a copy of the user key wrapped under a
**recovery key**, which is shown once when the keyring is created.
- Each private key is an OpenCreds `key` item encrypted with **AES-256-GCM** under
the user key. The item id is bound in as additional authenticated data, so an
envelope cannot be moved onto another entry.
- These stay readable on purpose, because they are not secret: the name, type,
file name, **public key**, fingerprint and comment. That is why `list`, `show`
and `export --pub` need no passphrase, and why the web page can show them.
Locally the keyring lives in `~/.config/logicsrc/keyring/`, or in
`LOGICSRC_KEYRING_HOME` if that is set. Every file is `0600` and the directory is
`0700`.
## Cloud sync (optional)
Once you run `keyring sync`, every `add`, `gen` and `rm` on that machine pushes
the change. A `list` pulls first. Merging is last-writer-wins per key, and a
removal travels as a tombstone. If the machine and the account hold two different
keyrings (two separate `init`s), sync refuses to merge them. Pick one:
`--use-remote` moves the local keyring to a `.bak` directory, and `--use-local`
replaces the account's copy.
The server stores only the wrapped meta, plus for each key its public half and
its envelope. It refuses any upload that contains private key material in any
field, including a "ciphertext" that is just a base64-encoded PEM key. Machine
API keys cannot reach the keyring. It belongs to the person.
### API
All endpoints take `Authorization: Bearer lsk_…` (a person's key). A signed-in
browser session can read.
| Method | Path | |
| --- | --- | --- |
| GET | `/api/keyring` | `{ meta, entries }`: public halves. Add `?include=envelopes` to get the ciphertext and tombstones too. |
| GET | `/api/keyring/entries/:idOrName` | One entry (public half). |
| PUT | `/api/keyring/meta` | `{ meta }`. Creates the account keyring. A different keyring gets `409`. |
| PUT | `/api/keyring/entries/:id` | `{ entry }`: a sealed entry. Last writer wins (`409` returns the newer one). Plaintext is refused with `422`. |
| DELETE | `/api/keyring/entries/:idOrName` | Leaves a tombstone. |
| DELETE | `/api/keyring` | Drops the account keyring (`sync --use-local`). |
### Web
[app.logicsrc.com/keyring](https://app.logicsrc.com/keyring) lists your keys:
name, type, fingerprint and public key, with a copy button. **Decrypt &
download** asks for the keyring passphrase and decrypts the key in the browser
tab with WebCrypto, using the same derivation as the CLI. Neither the passphrase
nor the private key is sent anywhere.
### MCP
`logicsrc mcp` (with `LOGICSRC_API_KEY`) adds these tools:
- `list_keyring_keys`
- `show_keyring_key`
- `export_authorized_keys`
- `add_keyring_key_ciphertext` (takes an already-sealed entry and refuses plaintext)
- `remove_keyring_key`
- `keyring_restore_instructions`
None of them return a private key. Restoring needs the passphrase, which an agent
never holds, so the restore tool returns the commands for the person to run.

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";