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:
sh1pt-actions-fleet[bot] 2026-10-29 01:57:47 +00:00 • committed by GitHub
parent 8b23cf57b3
commit d03acc0d00
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 507 additions and 4 deletions

View 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" });
}
});

View file

@ -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>`
}));
});