diff --git a/apps/logicsrc-web/src/lib/docs.ts b/apps/logicsrc-web/src/lib/docs.ts index f6d3ec44..80b09a62 100644 --- a/apps/logicsrc-web/src/lib/docs.ts +++ b/apps/logicsrc-web/src/lib/docs.ts @@ -41,6 +41,7 @@ const GUIDE_SUBTITLES: Record = { 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", diff --git a/apps/logicsrc-web/src/lib/specs.ts b/apps/logicsrc-web/src/lib/specs.ts index bc26ff8b..6b15336d 100644 --- a/apps/logicsrc-web/src/lib/specs.ts +++ b/apps/logicsrc-web/src/lib/specs.ts @@ -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" } diff --git a/apps/pwa/public/keyring.js b/apps/pwa/public/keyring.js new file mode 100644 index 00000000..fc50b4cf --- /dev/null +++ b/apps/pwa/public/keyring.js @@ -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 ":vault:wrap:v1") +// userKey = AES-GCM-open(wrap, meta.protectedUserKeyIv, meta.protectedUserKey) +// item = AES-GCM-open(userKey, env.iv, env.ciphertext, AAD ":vault:item::") +// 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 = `
+ + +
+
`; + 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)); + } + }); +})(); diff --git a/apps/pwa/src/lib/html.mjs b/apps/pwa/src/lib/html.mjs index 0383068e..77e90620 100644 --- a/apps/pwa/src/lib/html.mjs +++ b/apps/pwa/src/lib/html.mjs @@ -139,6 +139,7 @@ export function appBar(req) {
${user ? `${esc(user.email || user.display_name || "signed in")} + Keyring Settings
` : `Sign in`} @@ -148,6 +149,6 @@ export function appBar(req) { export const footer = ``; diff --git a/apps/pwa/src/migrations-pg/008_keyring.sql b/apps/pwa/src/migrations-pg/008_keyring.sql new file mode 100644 index 00000000..6efae9f5 --- /dev/null +++ b/apps/pwa/src/migrations-pg/008_keyring.sql @@ -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); diff --git a/apps/pwa/src/migrations/008_keyring.sql b/apps/pwa/src/migrations/008_keyring.sql new file mode 100644 index 00000000..be26bd37 --- /dev/null +++ b/apps/pwa/src/migrations/008_keyring.sql @@ -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); diff --git a/apps/pwa/src/routes/keyring.mjs b/apps/pwa/src/routes/keyring.mjs new file mode 100644 index 00000000..fed056f9 --- /dev/null +++ b/apps/pwa/src/routes/keyring.mjs @@ -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 + ? `
${rows.map((r) => ` + + + + + + + `).join("")}
NameTypeFingerprintCommentUpdated (UTC)
${esc(r.name)}
restores to ~/.ssh/${esc(r.filename)}
${esc(r.key_type)}${esc(r.fingerprint || "—")}${esc(r.comment || "—")}${esc(when(r.updated_at))} +
${esc(r.public_key)}
` + : `

No keys yet. From a terminal: logicsrc keyring add ~/.ssh/id_ed25519 && logicsrc keyring sync

`; + return `
+

Keyring

${rows.length}
+

SSH keys and other key pairs from logicsrc keyring. Public keys are shown as stored. Private keys are held only as ciphertext; Decrypt & download asks for your keyring passphrase and decrypts in this tab. The passphrase and the private key are never sent to the server.

+
${list} +
+
+
Restore from a terminal +
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)
+
`; +} + +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: `` + })); +}); diff --git a/apps/pwa/src/server.mjs b/apps/pwa/src/server.mjs index 9fe7d8c9..8f248fd2 100644 --- a/apps/pwa/src/server.mjs +++ b/apps/pwa/src/server.mjs @@ -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 diff --git a/apps/pwa/test/keyring.test.mjs b/apps/pwa/test/keyring.test.mjs new file mode 100644 index 00000000..a45fc392 --- /dev/null +++ b/apps/pwa/test/keyring.test.mjs @@ -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 : "@@")); +}); diff --git a/bun.lock b/bun.lock index 22ea81d7..afeccb2f 100644 --- a/bun.lock +++ b/bun.lock @@ -147,7 +147,7 @@ }, "packages/cli": { "name": "@logicsrc/cli", - "version": "0.10.0", + "version": "0.12.0", "bin": { "logicsrc": "./dist/index.js", }, diff --git a/docs/keyring.md b/docs/keyring.md new file mode 100644 index 00000000..88f5435a --- /dev/null +++ b/docs/keyring.md @@ -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 [--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 [--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 ` | Public key and fingerprint. `--print-private` also prints the private key (it asks for the passphrase). | +| `keyring restore [--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 [--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 ` 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 `.bak-