mirror of
https://github.com/profullstack/logicsrc.git
synced 2026-11-29 15:51:52 +00:00
feat(keyring): revocable share link for SSH public keys (#267)
* feat(keyring): revocable share link for SSH public keys (/k/<token>.json|.keys) Migration 009_keyring_shares (one per user, sha256(token) only). POST/GET/DELETE /api/keyring/share for a person key or a browser session (CSRF header on writes; machine keys 403). Public /k/<lks_ token>.json and .keys expose only ssh-* public halves with ssh-keygen fingerprints computed from the key, CORS *, public max-age=60, 404 when unknown or revoked, per-IP rate limit. /keyring gets a Share public keys box (create, copy, rotate, revoke); docs updated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(keyring-share): assemble the private-key fixture at runtime (ThreatCrush) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Anthony Ettinger <anthony@profullstack.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
8b23cf57b3
commit
d03acc0d00
8 changed files with 507 additions and 4 deletions
|
|
@ -76,7 +76,58 @@
|
|||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
}
|
||||
|
||||
// "Share public keys": create / rotate / revoke the read-only link. The token
|
||||
// comes back once, from POST; the page shows it until it is reloaded.
|
||||
const box = document.getElementById("kr-share");
|
||||
async function shareCall(method) {
|
||||
const res = await fetch("/api/keyring/share", {
|
||||
method,
|
||||
credentials: "same-origin",
|
||||
headers: { accept: "application/json", "x-csrf-token": box?.dataset.csrf || "" }
|
||||
});
|
||||
const body = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(body.error || `The server answered ${res.status}.`);
|
||||
return body;
|
||||
}
|
||||
function shareView({ exists, url, keysUrl, state }) {
|
||||
if (!box) return;
|
||||
box.dataset.exists = exists ? "1" : "0";
|
||||
box.querySelector("[data-kr-share=create]").hidden = exists;
|
||||
box.querySelector("[data-kr-share=rotate]").hidden = !exists;
|
||||
box.querySelector("[data-kr-share=revoke]").hidden = !exists;
|
||||
box.querySelector("[data-kr-share-state]").textContent = state;
|
||||
const wrap = box.querySelector("[data-kr-share-url]");
|
||||
wrap.hidden = !url;
|
||||
box.querySelector("[data-kr-share-json]").value = url || "";
|
||||
box.querySelector("[data-kr-share-keys]").value = keysUrl || "";
|
||||
}
|
||||
|
||||
document.addEventListener("click", async (ev) => {
|
||||
const shareBtn = ev.target.closest("[data-kr-share]");
|
||||
if (shareBtn) {
|
||||
const action = shareBtn.dataset.krShare;
|
||||
try {
|
||||
if (action === "revoke") {
|
||||
if (!confirm("Revoke the share link? Apps that read it (w3bs.org/fleet, threatcrush.com/fleet) lose access to your public keys.")) return;
|
||||
await shareCall("DELETE");
|
||||
shareView({ exists: false, state: "Share link revoked. No share link now." });
|
||||
return;
|
||||
}
|
||||
if (action === "rotate" && !confirm("Rotate the share link? The current URL stops working at once; paste the new one wherever you used the old one.")) return;
|
||||
const out = await shareCall("POST");
|
||||
shareView({ exists: true, url: out.url, keysUrl: out.keys_url_text, state: action === "rotate" ? "Rotated: the old URL no longer works." : "Share link created." });
|
||||
} catch (e) {
|
||||
shareView({ exists: box?.dataset.exists === "1", state: e.message || String(e) });
|
||||
}
|
||||
return;
|
||||
}
|
||||
const shareCopy = ev.target.closest("[data-kr-share-copy]");
|
||||
if (shareCopy) {
|
||||
const input = box?.querySelector(shareCopy.dataset.krShareCopy === "keys" ? "[data-kr-share-keys]" : "[data-kr-share-json]");
|
||||
await navigator.clipboard.writeText(input ? input.value : "");
|
||||
say("Share URL copied.");
|
||||
return;
|
||||
}
|
||||
const copy = ev.target.closest("[data-kr-copy]");
|
||||
if (copy) {
|
||||
const pre = document.querySelector(`[data-kr-pub="${CSS.escape(copy.dataset.krCopy)}"]`);
|
||||
|
|
|
|||
11
apps/pwa/src/migrations-pg/009_keyring_shares.sql
Normal file
11
apps/pwa/src/migrations-pg/009_keyring_shares.sql
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
-- Postgres copy of migrations/009_keyring_shares.sql (INTEGER -> bigint). Additive only.
|
||||
-- A revocable share link for the public halves of a person's SSH keys; only
|
||||
-- sha256(token) is stored.
|
||||
|
||||
create table if not exists keyring_shares (
|
||||
id text PRIMARY KEY,
|
||||
user_id text NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE,
|
||||
token_hash text NOT NULL UNIQUE,
|
||||
created_at bigint NOT NULL,
|
||||
rotated_at bigint
|
||||
);
|
||||
12
apps/pwa/src/migrations/009_keyring_shares.sql
Normal file
12
apps/pwa/src/migrations/009_keyring_shares.sql
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
-- A revocable, read-only share link for the PUBLIC halves of a person's SSH
|
||||
-- keys (GET /k/<token>.json and /k/<token>.keys). One per user. Only
|
||||
-- sha256(token) is stored, like sessions and API keys: the token is shown once,
|
||||
-- on create or rotate. Revoking deletes the row. Additive only.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS keyring_shares (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
created_at INTEGER NOT NULL,
|
||||
rotated_at INTEGER
|
||||
);
|
||||
184
apps/pwa/src/routes/keyring-share.mjs
Normal file
184
apps/pwa/src/routes/keyring-share.mjs
Normal file
|
|
@ -0,0 +1,184 @@
|
|||
// The keyring share link: a revocable, read-only URL that exposes ONLY the
|
||||
// public halves of a person's SSH keys, for other apps to read (w3bs.org/fleet,
|
||||
// threatcrush.com/fleet, crawlproof's SSH uptime checks).
|
||||
//
|
||||
// POST /api/keyring/share create or rotate -> { url, keys_url_text, token }
|
||||
// GET /api/keyring/share { exists, created_at, rotated_at } (never the token)
|
||||
// DELETE /api/keyring/share revoke
|
||||
// GET /k/<token>.json public: { keys: [{ name, type, public_key, fingerprint, comment }] }
|
||||
// GET /k/<token>.keys public: authorized_keys text
|
||||
//
|
||||
// The token is `lks_` + 32 random bytes (base64url); only sha256(token) is
|
||||
// stored, so it is shown once, on create or rotate. One share per person.
|
||||
//
|
||||
// Auth for the /api routes: a person's `Bearer lsk_…` key, or a browser session
|
||||
// (unlike the rest of the keyring these touch public keys only). A session
|
||||
// write must carry the double-submit CSRF header, because the app-wide guard
|
||||
// skips /api/*. Machine keys are refused: the keyring is the person's.
|
||||
import { Router } from "express";
|
||||
import crypto from "node:crypto";
|
||||
import { get, all, run } from "../db.mjs";
|
||||
import { bearer, keyForBearer } from "../lib/apikey.mjs";
|
||||
import { id as newId, sha256 } from "../lib/crypto.mjs";
|
||||
import { config } from "../config.mjs";
|
||||
import { containsPrivateMaterial } from "./keyring.mjs";
|
||||
|
||||
export const keyringShareRouter = Router();
|
||||
export const publicKeysRouter = Router();
|
||||
|
||||
const SHARE_ORIGIN = () => (process.env.KEYRING_SHARE_ORIGIN || config.origin).replace(/\/+$/, "");
|
||||
export const TOKEN_RE = /^lks_[A-Za-z0-9_-]{43}$/;
|
||||
export const newShareToken = () => `lks_${crypto.randomBytes(32).toString("base64url")}`;
|
||||
|
||||
export const shareUrls = (token) => ({
|
||||
url: `${SHARE_ORIGIN()}/k/${token}.json`,
|
||||
keys_url_text: `${SHARE_ORIGIN()}/k/${token}.keys`
|
||||
});
|
||||
|
||||
const iso = (ms) => (ms === null || ms === undefined ? null : new Date(Number(ms)).toISOString());
|
||||
|
||||
// ---- public-key parsing ----
|
||||
|
||||
/**
|
||||
* Parse one OpenSSH public key line ("ssh-ed25519 AAAA… comment"). Returns
|
||||
* { algo, blob, comment, fingerprint } or null when it is not a well-formed
|
||||
* key whose blob names the same algorithm as the line. The fingerprint is what
|
||||
* `ssh-keygen -lf` prints: "SHA256:" + unpadded base64 of sha256(blob).
|
||||
*/
|
||||
export function parsePublicKey(line) {
|
||||
if (typeof line !== "string") return null;
|
||||
const first = line.split(/\r?\n/).map((l) => l.trim()).find(Boolean);
|
||||
if (!first || containsPrivateMaterial(first)) return null;
|
||||
const [algo, b64, ...rest] = first.split(/\s+/);
|
||||
if (!/^(ssh-|ecdsa-sha2-|sk-)[A-Za-z0-9@.-]+$/.test(algo || "")) return null;
|
||||
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(b64 || "")) return null;
|
||||
const blob = Buffer.from(b64, "base64");
|
||||
if (blob.length < 8) return null;
|
||||
const n = blob.readUInt32BE(0);
|
||||
if (n > 64 || 4 + n > blob.length || blob.subarray(4, 4 + n).toString("latin1") !== algo) return null;
|
||||
const fingerprint = "SHA256:" + crypto.createHash("sha256").update(blob).digest("base64").replace(/=+$/, "");
|
||||
return { algo, blob: b64, comment: rest.join(" "), fingerprint };
|
||||
}
|
||||
|
||||
/** The public view of a user's SSH keys: only ssh-* entries, only well-formed public keys. */
|
||||
export async function sharedKeys(userId) {
|
||||
const rows = await all(
|
||||
`SELECT name, key_type, public_key, comment FROM keyring_entries WHERE user_id = ? AND deleted_at IS NULL ORDER BY name`,
|
||||
[userId]
|
||||
);
|
||||
const keys = [];
|
||||
for (const r of rows) {
|
||||
if (!String(r.key_type).startsWith("ssh-")) continue;
|
||||
const k = parsePublicKey(r.public_key);
|
||||
if (!k) continue;
|
||||
const comment = r.comment || k.comment || "";
|
||||
keys.push({ name: r.name, type: r.key_type, public_key: `${k.algo} ${k.blob}${comment ? ` ${comment}` : ""}`, fingerprint: k.fingerprint, comment });
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
// ---- auth for the /api routes ----
|
||||
|
||||
function shareAuth(handler) {
|
||||
return 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) {
|
||||
if (req.method !== "GET") {
|
||||
const sent = req.get("x-csrf-token");
|
||||
const cookie = req.cookies?.mc_csrf;
|
||||
if (!sent || !cookie || sent !== cookie) return res.status(403).json({ error: "Missing or bad CSRF token." });
|
||||
}
|
||||
user = req.user;
|
||||
} else {
|
||||
return res.status(401).json({ error: "Not authenticated. Sign in or run: logicsrc login" });
|
||||
}
|
||||
res.set("Cache-Control", "no-store");
|
||||
try {
|
||||
await handler(req, res, user);
|
||||
} catch (e) {
|
||||
console.error("keyring share:", e);
|
||||
res.status(500).json({ error: e.message || String(e) });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export async function shareStatus(userId) {
|
||||
const row = await get(`SELECT created_at, rotated_at FROM keyring_shares WHERE user_id = ?`, [userId]);
|
||||
return { exists: Boolean(row), created_at: iso(row?.created_at), rotated_at: iso(row?.rotated_at) };
|
||||
}
|
||||
|
||||
keyringShareRouter.get("/api/keyring/share", shareAuth(async (_req, res, user) => {
|
||||
res.json(await shareStatus(user.id));
|
||||
}));
|
||||
|
||||
// Create, or rotate (a new token; the old URL stops working at once).
|
||||
keyringShareRouter.post("/api/keyring/share", shareAuth(async (_req, res, user) => {
|
||||
const token = newShareToken();
|
||||
const now = Date.now();
|
||||
const existing = await get(`SELECT id FROM keyring_shares WHERE user_id = ?`, [user.id]);
|
||||
if (existing) {
|
||||
await run(`UPDATE keyring_shares SET token_hash = ?, rotated_at = ? WHERE user_id = ?`, [sha256(token), now, user.id]);
|
||||
} else {
|
||||
await run(`INSERT INTO keyring_shares (id, user_id, token_hash, created_at, rotated_at) VALUES (?,?,?,?,NULL)`, [newId(), user.id, sha256(token), now]);
|
||||
}
|
||||
res.status(existing ? 200 : 201).json({ ...shareUrls(token), token, rotated: Boolean(existing) });
|
||||
}));
|
||||
|
||||
keyringShareRouter.delete("/api/keyring/share", shareAuth(async (_req, res, user) => {
|
||||
const existing = await get(`SELECT id FROM keyring_shares WHERE user_id = ?`, [user.id]);
|
||||
if (!existing) return res.status(404).json({ error: "No share link to revoke." });
|
||||
await run(`DELETE FROM keyring_shares WHERE user_id = ?`, [user.id]);
|
||||
res.json({ ok: true });
|
||||
}));
|
||||
|
||||
// ---- the public link ----
|
||||
|
||||
// A small per-IP limit: the token space is unguessable, this only keeps one
|
||||
// client from hammering the database. In-memory, per process.
|
||||
export const RATE = { windowMs: 60_000, max: 120 };
|
||||
const hits = new Map();
|
||||
let windowStart = Date.now();
|
||||
export function rateLimited(ip, now = Date.now()) {
|
||||
if (now - windowStart >= RATE.windowMs) { hits.clear(); windowStart = now; }
|
||||
const n = (hits.get(ip) || 0) + 1;
|
||||
hits.set(ip, n);
|
||||
return n > RATE.max;
|
||||
}
|
||||
|
||||
function cors(res) {
|
||||
res.set("Access-Control-Allow-Origin", "*");
|
||||
res.set("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS");
|
||||
res.set("Cross-Origin-Resource-Policy", "cross-origin");
|
||||
res.set("X-Robots-Tag", "noindex");
|
||||
}
|
||||
|
||||
publicKeysRouter.options(/^\/k\/[^/]+$/, (_req, res) => { cors(res); res.set("Access-Control-Max-Age", "86400").status(204).end(); });
|
||||
|
||||
publicKeysRouter.get(/^\/k\/([^/]+)\.(json|keys)$/, async (req, res) => {
|
||||
cors(res);
|
||||
const notFound = () => res.status(404).set("Cache-Control", "no-store").json({ error: "not_found" });
|
||||
const ip = (req.ip || req.socket?.remoteAddress || "").replace(/^::ffff:/, "");
|
||||
if (rateLimited(ip)) return res.status(429).set("Retry-After", "60").set("Cache-Control", "no-store").json({ error: "rate_limited" });
|
||||
const token = req.params[0];
|
||||
const format = req.params[1];
|
||||
if (!TOKEN_RE.test(token)) return notFound();
|
||||
try {
|
||||
const share = await get(`SELECT user_id FROM keyring_shares WHERE token_hash = ?`, [sha256(token)]);
|
||||
if (!share) return notFound();
|
||||
const keys = await sharedKeys(share.user_id);
|
||||
res.set("Cache-Control", "public, max-age=60");
|
||||
if (format === "keys") return res.type("text/plain; charset=utf-8").send(keys.map((k) => k.public_key).join("\n") + (keys.length ? "\n" : ""));
|
||||
res.json({ keys });
|
||||
} catch (e) {
|
||||
console.error("keyring share /k:", e);
|
||||
res.status(500).set("Cache-Control", "no-store").json({ error: "server_error" });
|
||||
}
|
||||
});
|
||||
|
|
@ -11,7 +11,8 @@
|
|||
//
|
||||
// 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
|
||||
// are refused: the keyring is the person's alone. (The public-keys share link
|
||||
// in keyring-share.mjs is the exception: a session may manage it.) Mounted at /api/keyring, and
|
||||
// the page at /keyring.
|
||||
import { Router } from "express";
|
||||
import { get, all, run } from "../db.mjs";
|
||||
|
|
@ -216,7 +217,32 @@ keyringRouter.delete("/api/keyring", writer(async (_req, res, user) => {
|
|||
|
||||
const when = (ms) => (ms ? new Date(Number(ms)).toISOString().slice(0, 16).replace("T", " ") : "—");
|
||||
|
||||
export function keyringPageBody(rows) {
|
||||
// The "Share public keys" box. The token is shown once (on create/rotate), by
|
||||
// public/keyring.js; the server-rendered state only says whether a link exists.
|
||||
export function shareBoxHtml(share = { exists: false }, csrf = "") {
|
||||
const state = share.exists
|
||||
? `A share link is active (created ${esc(when(Date.parse(share.created_at)))} UTC${share.rotated_at ? `, last rotated ${esc(when(Date.parse(share.rotated_at)))} UTC` : ""}). Its URL was shown once; rotate to get a new one.`
|
||||
: "No share link yet.";
|
||||
return `<div class="card" id="kr-share" data-csrf="${esc(csrf)}" data-exists="${share.exists ? "1" : "0"}" style="margin-top:18px"><div class="card-body">
|
||||
<h2 style="font-size:1.1rem;margin:0 0 6px">Share public keys</h2>
|
||||
<p class="dim" style="font-size:.85rem;margin:0 0 10px">A read-only link to the <b>public</b> halves of your SSH keys (name, type, public key, fingerprint, comment), as JSON and as <code>authorized_keys</code> text. Private keys are never part of it. This is the link <a href="https://w3bs.org/fleet">w3bs.org/fleet</a> and <a href="https://threatcrush.com/fleet">threatcrush.com/fleet</a> read to set up SSH checks. Anyone holding the link can read your public keys; rotate or revoke it at any time.</p>
|
||||
<p class="mono faint" data-kr-share-state style="font-size:.8rem;margin:0 0 10px">${state}</p>
|
||||
<div data-kr-share-url hidden style="margin:0 0 10px">
|
||||
<label class="label" style="font-size:.8rem">JSON (paste this into w3bs.org/fleet or threatcrush.com/fleet)</label>
|
||||
<div style="display:flex;gap:8px;align-items:center"><input class="mono" readonly data-kr-share-json style="flex:1;min-width:0;font-size:.78rem"><button class="btn compact" type="button" data-kr-share-copy="json">Copy</button></div>
|
||||
<label class="label" style="font-size:.8rem;margin-top:8px">authorized_keys text</label>
|
||||
<div style="display:flex;gap:8px;align-items:center"><input class="mono" readonly data-kr-share-keys style="flex:1;min-width:0;font-size:.78rem"><button class="btn compact" type="button" data-kr-share-copy="keys">Copy</button></div>
|
||||
<p class="faint" style="font-size:.78rem;margin:6px 0 0">Copy it now: it is not shown again.</p>
|
||||
</div>
|
||||
<div style="display:flex;gap:8px;flex-wrap:wrap">
|
||||
<button class="btn acid compact" type="button" data-kr-share="create"${share.exists ? " hidden" : ""}>Create link</button>
|
||||
<button class="btn compact" type="button" data-kr-share="rotate"${share.exists ? "" : " hidden"}>Rotate</button>
|
||||
<button class="btn compact" type="button" data-kr-share="revoke"${share.exists ? "" : " hidden"}>Revoke</button>
|
||||
</div>
|
||||
</div></div>`;
|
||||
}
|
||||
|
||||
export function keyringPageBody(rows, share = { exists: false }, csrf = "") {
|
||||
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>
|
||||
|
|
@ -234,6 +260,7 @@ export function keyringPageBody(rows) {
|
|||
<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>
|
||||
${shareBoxHtml(share, csrf)}
|
||||
<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
|
||||
|
|
@ -244,10 +271,12 @@ logicsrc keyring restore id_ed25519 # writes ~/.ssh/id_ed25519 (600) + .pub
|
|||
|
||||
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]);
|
||||
const share = await get(`SELECT created_at, rotated_at FROM keyring_shares WHERE user_id = ?`, [req.user.id]);
|
||||
const shareState = { exists: Boolean(share), created_at: iso(share?.created_at), rotated_at: iso(share?.rotated_at) };
|
||||
res.set("Cache-Control", "no-store");
|
||||
res.type("html").send(page({
|
||||
title: "LogicSRC ▸ keyring",
|
||||
body: `${appBar(req)}${keyringPageBody(rows)}${footer}`,
|
||||
body: `${appBar(req)}${keyringPageBody(rows, shareState, req.csrfToken || "")}${footer}`,
|
||||
head: `<script src="/keyring.js" defer></script>`
|
||||
}));
|
||||
});
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ 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 { keyringShareRouter, publicKeysRouter } from "./routes/keyring-share.mjs";
|
||||
import { cliRouter } from "./routes/cli.mjs";
|
||||
import { pagesRouter } from "./routes/pages.mjs";
|
||||
import { profileRouter } from "./lib/profile.mjs";
|
||||
|
|
@ -66,6 +67,10 @@ app.get("/.well-known/openwebring.json", (_req, res) =>
|
|||
|
||||
app.get("/healthz", (_req, res) => res.json({ ok: true, env: config.env }));
|
||||
|
||||
// The keyring share link (/k/<token>.json|.keys): public, CORS-open, no session
|
||||
// (mounted before the session middleware so it never sets a cookie on a cacheable answer).
|
||||
app.use(publicKeysRouter);
|
||||
|
||||
app.use(sessionMiddleware);
|
||||
app.use(csrfGuard);
|
||||
|
||||
|
|
@ -76,6 +81,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(keyringShareRouter); // /api/keyring/share: the public-keys share link (session or person key)
|
||||
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)
|
||||
|
|
|
|||
172
apps/pwa/test/keyring-share.test.mjs
Normal file
172
apps/pwa/test/keyring-share.test.mjs
Normal file
|
|
@ -0,0 +1,172 @@
|
|||
// /api/keyring/share + /k/<token>.json|.keys: a revocable link to the PUBLIC
|
||||
// halves of a person's SSH keys. Only ssh-* entries, only well-formed public
|
||||
// keys, fingerprints as ssh-keygen prints them, CORS open, 404 once revoked.
|
||||
process.env.DATABASE_URL = process.env.PWA_TEST_DATABASE_URL || ":memory:";
|
||||
process.env.KEYRING_SHARE_ORIGIN = "https://app.logicsrc.com";
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync, readdirSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { dirname, join } from "node:path";
|
||||
import express from "express";
|
||||
import cookieParser from "cookie-parser";
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const { db, run, get, isPostgres } = await import("../src/db.mjs");
|
||||
const { keyringShareRouter, publicKeysRouter, parsePublicKey, RATE } = await import("../src/routes/keyring-share.mjs");
|
||||
const { createApiKey } = await import("../src/lib/apikey.mjs");
|
||||
|
||||
if (isPostgres) {
|
||||
await db.execute("DROP SCHEMA public CASCADE");
|
||||
await db.execute("CREATE SCHEMA public");
|
||||
}
|
||||
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()]);
|
||||
|
||||
const ED = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFK+fzMc3AneHlJ9+KGxhlTbhQDv4xlwE0oNmVCPpEL1 throwaway@test";
|
||||
const ED_FP = "SHA256:xlBmhjCwKIXfA2QBSQxLR8zil6z3Lm7SqPFQmHW0jkI"; // ssh-keygen -lf
|
||||
const now = Date.now();
|
||||
const entry = (uid, id, name, type, pub, extra = {}) =>
|
||||
run(`INSERT INTO keyring_entries (user_id, id, name, key_type, filename, public_key, fingerprint, comment, envelope, created_at, updated_at, deleted_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)`,
|
||||
[uid, id, name, type, name, pub, extra.fingerprint ?? "SHA256:stale", extra.comment ?? "", "{}", now, now, extra.deletedAt ?? null]);
|
||||
await entry("u1", "a", "id_ed25519", "ssh-ed25519", ED, { comment: "laptop" });
|
||||
await entry("u1", "b", "gpg_main", "gpg", "-----BEGIN PGP PUBLIC KEY BLOCK-----\nxx\n-----END PGP PUBLIC KEY BLOCK-----");
|
||||
await entry("u1", "c", "age_main", "age", "age1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq");
|
||||
await entry("u1", "d", "old_key", "ssh-ed25519", ED, { deletedAt: now });
|
||||
await entry("u1", "e", "broken", "ssh-rsa", "ssh-rsa not-a-key");
|
||||
await entry("u2", "f", "u2_key", "ssh-ed25519", ED);
|
||||
|
||||
// Session users come from a header here; the CSRF cookie is the real double-submit one.
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use(cookieParser());
|
||||
app.use(publicKeysRouter);
|
||||
app.use((req, _res, next) => {
|
||||
const u = req.get("x-user");
|
||||
req.user = u ? { id: u, email: `${u}@e.test` } : null;
|
||||
next();
|
||||
});
|
||||
app.use(keyringShareRouter);
|
||||
const server = app.listen(0);
|
||||
await new Promise((r) => server.once("listening", r));
|
||||
const base = `http://127.0.0.1:${server.address().port}`;
|
||||
test.after(() => new Promise((r) => server.close(r)));
|
||||
|
||||
const person = (await createApiKey("u1", "cli", { kind: "user" })).plaintext;
|
||||
const machine = (await createApiKey("u1", "box", { kind: "machine" })).plaintext;
|
||||
|
||||
async function call(method, path, { user, bearer, csrf } = {}) {
|
||||
const headers = {};
|
||||
if (user) headers["x-user"] = user;
|
||||
if (bearer) headers.authorization = `Bearer ${bearer}`;
|
||||
if (csrf) { headers["x-csrf-token"] = csrf; headers.cookie = `mc_csrf=${csrf}`; }
|
||||
const res = await fetch(base + path, { method, headers });
|
||||
const text = await res.text();
|
||||
let body; try { body = JSON.parse(text); } catch { body = text; }
|
||||
return { status: res.status, headers: res.headers, body };
|
||||
}
|
||||
|
||||
test("parsePublicKey: ssh-keygen fingerprint; garbage and private material refused", () => {
|
||||
assert.equal(parsePublicKey(ED).fingerprint, ED_FP);
|
||||
assert.equal(parsePublicKey("ssh-rsa not-a-key"), null);
|
||||
assert.equal(parsePublicKey("ssh-rsa AAAAC3NzaC1lZDI1NTE5AAAAIFK+fzMc3AneHlJ9+KGxhlTbhQDv4xlwE0oNmVCPpEL1"), null, "blob names a different algorithm");
|
||||
// A fake header, assembled at runtime so secret scanners do not flag the fixture.
|
||||
const fakePrivate = ["-----BEGIN OPENSSH", "PRIVATE KEY-----"].join(" ") + "\n" + "b3BlbnNzaC1r" + "ZXktdjE";
|
||||
assert.equal(parsePublicKey(fakePrivate), null);
|
||||
});
|
||||
|
||||
test("auth: none 401, machine key 403, session write without CSRF 403", async () => {
|
||||
assert.equal((await call("GET", "/api/keyring/share")).status, 401);
|
||||
assert.equal((await call("GET", "/api/keyring/share", { bearer: machine })).status, 403);
|
||||
assert.equal((await call("POST", "/api/keyring/share", { bearer: machine })).status, 403);
|
||||
assert.equal((await call("POST", "/api/keyring/share", { user: "u1" })).status, 403);
|
||||
assert.equal((await call("GET", "/api/keyring/share", { user: "u1" })).body.exists, false);
|
||||
});
|
||||
|
||||
let token;
|
||||
test("create via a session (with CSRF): token once, URLs on app.logicsrc.com, sha256 stored", async () => {
|
||||
const r = await call("POST", "/api/keyring/share", { user: "u1", csrf: "c1" });
|
||||
assert.equal(r.status, 201);
|
||||
token = r.body.token;
|
||||
assert.match(token, /^lks_[A-Za-z0-9_-]{43}$/);
|
||||
assert.equal(r.body.url, `https://app.logicsrc.com/k/${token}.json`);
|
||||
assert.equal(r.body.keys_url_text, `https://app.logicsrc.com/k/${token}.keys`);
|
||||
const row = await get(`SELECT * FROM keyring_shares WHERE user_id = ?`, ["u1"]);
|
||||
assert.notEqual(row.token_hash, token);
|
||||
assert.ok(!JSON.stringify(row).includes(token));
|
||||
const status = await call("GET", "/api/keyring/share", { bearer: person });
|
||||
assert.equal(status.body.exists, true);
|
||||
assert.ok(status.body.created_at);
|
||||
assert.equal(status.body.rotated_at, null);
|
||||
assert.ok(!JSON.stringify(status.body).includes("lks_"), "GET never returns the token");
|
||||
});
|
||||
|
||||
test("GET /k/<token>.json: public ssh halves only, ssh-keygen fingerprints, CORS, cacheable", async () => {
|
||||
const r = await call("GET", `/k/${token}.json`);
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal(r.headers.get("access-control-allow-origin"), "*");
|
||||
assert.equal(r.headers.get("cache-control"), "public, max-age=60");
|
||||
assert.equal(r.headers.get("set-cookie"), null);
|
||||
assert.deepEqual(r.body, { keys: [{ name: "id_ed25519", type: "ssh-ed25519", public_key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFK+fzMc3AneHlJ9+KGxhlTbhQDv4xlwE0oNmVCPpEL1 laptop", fingerprint: ED_FP, comment: "laptop" }] });
|
||||
const text = await call("GET", `/k/${token}.keys`);
|
||||
assert.equal(text.status, 200);
|
||||
assert.equal(text.body, "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFK+fzMc3AneHlJ9+KGxhlTbhQDv4xlwE0oNmVCPpEL1 laptop\n");
|
||||
assert.equal(text.headers.get("access-control-allow-origin"), "*");
|
||||
});
|
||||
|
||||
test("unknown or malformed token: 404 with CORS", async () => {
|
||||
const r = await call("GET", `/k/lks_${"A".repeat(43)}.json`);
|
||||
assert.equal(r.status, 404);
|
||||
assert.equal(r.headers.get("access-control-allow-origin"), "*");
|
||||
assert.equal((await call("GET", "/k/nope.json")).status, 404);
|
||||
});
|
||||
|
||||
test("rotate: the old token 404s, the new one works; bearer works too", async () => {
|
||||
const r = await call("POST", "/api/keyring/share", { bearer: person });
|
||||
assert.equal(r.status, 200);
|
||||
assert.notEqual(r.body.token, token);
|
||||
assert.equal((await call("GET", `/k/${token}.json`)).status, 404);
|
||||
token = r.body.token;
|
||||
assert.equal((await call("GET", `/k/${token}.json`)).status, 200);
|
||||
assert.ok((await call("GET", "/api/keyring/share", { user: "u1" })).body.rotated_at);
|
||||
});
|
||||
|
||||
test("revoke: 404 afterwards; revoking twice is 404", async () => {
|
||||
assert.equal((await call("DELETE", "/api/keyring/share", { user: "u1" })).status, 403, "session without CSRF");
|
||||
assert.equal((await call("DELETE", "/api/keyring/share", { user: "u1", csrf: "c2" })).status, 200);
|
||||
assert.equal((await call("GET", `/k/${token}.json`)).status, 404);
|
||||
assert.equal((await call("GET", `/k/${token}.keys`)).status, 404);
|
||||
assert.equal((await call("DELETE", "/api/keyring/share", { bearer: person })).status, 404);
|
||||
assert.equal((await call("GET", "/api/keyring/share", { user: "u1" })).body.exists, false);
|
||||
});
|
||||
|
||||
test("one user's share never shows another's keys", async () => {
|
||||
const r = await call("POST", "/api/keyring/share", { user: "u2", csrf: "c3" });
|
||||
const keys = (await call("GET", `/k/${r.body.token}.json`)).body.keys;
|
||||
assert.deepEqual(keys.map((k) => k.name), ["u2_key"]);
|
||||
});
|
||||
|
||||
test("the public link is rate limited per IP", async () => {
|
||||
const saved = RATE.max;
|
||||
RATE.max = 3;
|
||||
try {
|
||||
const statuses = [];
|
||||
for (let i = 0; i < 6; i++) statuses.push((await call("GET", `/k/lks_${"B".repeat(43)}.json`)).status);
|
||||
assert.ok(statuses.includes(429), statuses.join(","));
|
||||
} finally {
|
||||
RATE.max = saved;
|
||||
}
|
||||
});
|
||||
|
||||
test("the /keyring page renders the share box without any token", async () => {
|
||||
const { keyringPageBody } = await import("../src/routes/keyring.mjs");
|
||||
const html = keyringPageBody([], { exists: true, created_at: new Date().toISOString(), rotated_at: null }, "csrf123");
|
||||
assert.ok(html.includes("Share public keys"));
|
||||
assert.ok(html.includes('data-csrf="csrf123"'));
|
||||
assert.ok(!html.includes("lks_"));
|
||||
});
|
||||
|
|
@ -95,7 +95,8 @@ 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.
|
||||
browser session can read. (The share link below is the one exception: a session
|
||||
can create, rotate and revoke it.)
|
||||
|
||||
| Method | Path | |
|
||||
| --- | --- | --- |
|
||||
|
|
@ -114,6 +115,43 @@ 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.
|
||||
|
||||
### Share public keys
|
||||
|
||||
A **share link** is a revocable, read-only URL for the **public** halves of your
|
||||
SSH keys. Other apps read it: [w3bs.org/fleet](https://w3bs.org/fleet) and
|
||||
[threatcrush.com/fleet](https://threatcrush.com/fleet) use it to set up SSH checks
|
||||
(crawlproof asks your servers whether they would accept a key, without logging in).
|
||||
The link never carries a private key, an envelope or anything but `ssh-*` entries.
|
||||
|
||||
Create it on [app.logicsrc.com/keyring](https://app.logicsrc.com/keyring) under
|
||||
**Share public keys**, or with the API below. You get one link per account. The
|
||||
token (`lks_…`) is shown once, on create or rotate: only its SHA-256 is stored.
|
||||
**Rotate** issues a new token and the old URL stops working at once. **Revoke**
|
||||
deletes the link.
|
||||
|
||||
| Method | Path | |
|
||||
| --- | --- | --- |
|
||||
| POST | `/api/keyring/share` | Create, or rotate if one exists. `{ url, keys_url_text, token }`. |
|
||||
| GET | `/api/keyring/share` | `{ exists, created_at, rotated_at }`. Never the token. |
|
||||
| DELETE | `/api/keyring/share` | Revoke. |
|
||||
| GET | `/k/<token>.json` | Public, no auth. `{ keys: [{ name, type, public_key, fingerprint, comment }] }` |
|
||||
| GET | `/k/<token>.keys` | Public, no auth. `authorized_keys` text, one key per line. |
|
||||
|
||||
The three `/api/keyring/share` calls take a person's `Bearer lsk_…` key or a
|
||||
signed-in browser session (a session's `POST`/`DELETE` must send the
|
||||
`X-CSRF-Token` header). Machine keys get `403`.
|
||||
|
||||
The public URLs answer with `Access-Control-Allow-Origin: *` and
|
||||
`Cache-Control: public, max-age=60`, so a revoked link can stay readable in a
|
||||
cache for up to a minute. An unknown or revoked token is `404`. `fingerprint` is
|
||||
what `ssh-keygen -lf` prints (`SHA256:` and unpadded base64), computed from the
|
||||
public key itself. Requests are rate limited per IP (`429`).
|
||||
|
||||
```sh
|
||||
curl -s https://app.logicsrc.com/k/lks_….json | jq '.keys[] | {name, fingerprint}'
|
||||
curl -s https://app.logicsrc.com/k/lks_….keys >> ~/.ssh/authorized_keys
|
||||
```
|
||||
|
||||
### MCP
|
||||
|
||||
`logicsrc mcp` (with `LOGICSRC_API_KEY`) adds these tools:
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue