mirror of
https://github.com/profullstack/logicsrc.git
synced 2026-11-29 15:51:52 +00:00
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:
parent
ae4615e61d
commit
1bff3e975c
21 changed files with 2168 additions and 3 deletions
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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
107
apps/pwa/public/keyring.js
Normal 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));
|
||||
}
|
||||
});
|
||||
})();
|
||||
|
|
@ -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>`;
|
||||
|
|
|
|||
28
apps/pwa/src/migrations-pg/008_keyring.sql
Normal file
28
apps/pwa/src/migrations-pg/008_keyring.sql
Normal 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);
|
||||
33
apps/pwa/src/migrations/008_keyring.sql
Normal file
33
apps/pwa/src/migrations/008_keyring.sql
Normal 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);
|
||||
253
apps/pwa/src/routes/keyring.mjs
Normal file
253
apps/pwa/src/routes/keyring.mjs
Normal 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 & 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 && 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 & 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>`
|
||||
}));
|
||||
});
|
||||
|
|
@ -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
|
||||
|
|
|
|||
194
apps/pwa/test/keyring.test.mjs
Normal file
194
apps/pwa/test/keyring.test.mjs
Normal 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 : "@@"));
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue