security: harden credentials app after the 2026-10-27 dev2 incident (CLI 0.10.0)

An attacker with root on dev2 read identity.json (identity secret key + a user
lsk_ token) and used the token against app.logicsrc.com. This closes the gaps
that made that worse than it had to be, and adds the tools to recover.

Identity keys
- A registered identity public key is never replaced by a login any more
  ("last login wins" let a stolen token swap in an attacker key). Changing it
  needs `logicsrc teams rotate-identity`: the server seals a random answer to
  the CURRENT key (single use, 5 min); the CLI proves possession and re-seals
  every vault grant to the new key in one transaction (POST /keys/rotate).
- Lost key: reset from a signed-in browser (Settings), which drops every grant
  sealed to the old key. `logicsrc teams key --import` moves a key to a new box.

Vault re-key
- `logicsrc teams rekey <team> <project> <env>` and `--all`: new vault key,
  values re-encrypted client side, re-sealed to every current member and
  machine key. Server bumps credshare_vaults.key_version; writes that name a
  retired version get 409, and the rekey UPDATE only touches rows whose value
  did not change mid-flight. A verify pass (per vault and a final sweep)
  re-seals any value a racing older client wrote under the retired key.

Key pinning (TOFU)
- CLI pins teammates' and machine keys' fingerprints in known-keys.json (0600)
  and refuses to seal (grant, rekey) to a changed key without
  --accept-key-change. `teams members` shows fingerprints and pin status;
  the dashboard shows fingerprints and public/pins.js flags changes.

Audit
- Every person read of a vault key (/grant) and of ciphertext (/secrets) is
  audited with IP and user agent (also denied reads and identity events).
  GET /teams/:slug/audit, `logicsrc teams audit`, and tables on the dashboard
  and vault pages.

At rest / transport
- Session tokens stored as sha256 (rows hashed in migration 007); CLI auth
  codes hashed. New API keys no longer travel in the /settings URL.
- CSP (script-src 'self', no inline script or handlers, frame-ancestors none),
  HSTS, X-Frame-Options, Referrer-Policy no-referrer, COOP/CORP, no-store on
  authenticated pages. Inline scripts moved to /app.js and
  /vendor/profile-enhance.js.
- The shared footer renders from the bundled template of a pinned
  @profullstack/footer 0.5.0 (allowlist sanitizer); no runtime CDN fetch.
- Migrations can run as a separate owner role (MIGRATE_DATABASE_URL) so the
  app can connect as a DML-only role with an append-only audit table.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Anthony Ettinger 2026-10-28 16:04:22 +00:00
parent 18477340e7
commit ae6298851b
34 changed files with 1633 additions and 112 deletions

View file

@ -120,7 +120,7 @@ export function page({ title = "LogicSRC ▸ credentials", body = "", head = ""
${head}
</head>
<body>${body}
<script>if('serviceWorker' in navigator){navigator.serviceWorker.register('/sw.js').catch(()=>{})}</script>
<script src="/app.js" defer></script>
</body>
</html>`;
}

View file

@ -0,0 +1,23 @@
// Identity-key fingerprints, the same everywhere: the CLI (known-keys pinning),
// the PWA pages and public/pins.js all compute sha256 over the RAW 32-byte X25519
// public key and show the first 16 bytes as eight groups of four hex digits.
// Two people comparing fingerprints out loud (or a pin noticing a change) is how
// a swapped key gets caught; the server cannot prove a key is the person's own.
import crypto from "node:crypto";
export function keyFingerprint(publicKeyB64) {
if (typeof publicKeyB64 !== "string" || !publicKeyB64) return null;
let raw;
try { raw = Buffer.from(publicKeyB64, "base64"); } catch { return null; }
if (raw.length !== 32) return null;
const hex = crypto.createHash("sha256").update(raw).digest("hex").slice(0, 32);
return hex.match(/.{4}/g).join(" ");
}
/** Where a request came from, for the audit trail. Behind nginx, req.ip honours trust proxy. */
export function requestOriginInfo(req) {
if (!req) return { ip: null, userAgent: null };
const ip = (req.ip || req.socket?.remoteAddress || "").replace(/^::ffff:/, "") || null;
const ua = String(req.get?.("user-agent") || "").slice(0, 300) || null;
return { ip, userAgent: ua };
}

View file

@ -3,31 +3,16 @@
// sign-in page. It is rendered into the HTML on the server because rssamplifier's
// ring verifier reads the page and never runs script.
//
// Pages render synchronously, so the footer is kept as a string: the bundled
// template at boot, then the @latest template from the CDN, refreshed every 15
// minutes (a footer release reaches us with no redeploy). A failed refresh keeps
// the last good copy. No CSP on this app, so the footer brings its own styles.
import { footerHtml, footerHtmlSync } from "@profullstack/footer";
// This origin holds vault identity keys in browser storage, so the footer is the
// template BUNDLED in the pinned package version only. It used to be refreshed
// from jsdelivr @latest every 15 minutes, which made whoever could publish the
// footer package able to put HTML on this origin, past a bypassable sanitizer.
// A footer change now reaches this app by bumping the pinned dependency.
import { footerHtmlSync } from "@profullstack/footer";
export const RING_FOOTER_OPTIONS = { site: "https://app.logicsrc.com/" };
let html = footerHtmlSync(RING_FOOTER_OPTIONS);
const html = footerHtmlSync(RING_FOOTER_OPTIONS);
/** The footer markup; never empty. */
export const ringFooter = () => html;
/** Accept a rendered footer only when it still links the ring. */
export function setRingFooter(next) {
if (typeof next !== "string" || !next.includes("/ring/profullstack") || next.length > 64_000) return false;
html = next;
return true;
}
export function startRingFooterRefresh(everyMs = 15 * 60_000) {
if (process.env.PROFULLSTACK_FOOTER_OFFLINE === "1") return () => {};
const run = () => footerHtml(RING_FOOTER_OPTIONS).then(setRingFooter, () => {});
run();
const timer = setInterval(run, everyMs);
timer.unref?.();
return () => clearInterval(timer);
}

View file

@ -0,0 +1,42 @@
// Security headers for app.logicsrc.com.
//
// The vault page decrypts in the browser with the member's identity secret key,
// which can sit in sessionStorage/localStorage for the whole origin. So no page
// on this origin may run script we did not ship: scripts come from 'self' only
// (no inline <script>, no event-handler attributes, no CDN), and the page cannot
// be framed. Styles stay 'unsafe-inline' (the views use style attributes); CSS
// cannot read storage.
//
// form-action allows the CLI's loopback login redirect (http://127.0.0.1:<port>)
// and the shared footer's newsletter form (pit.world).
export const CSP = [
"default-src 'self'",
"script-src 'self' 'wasm-unsafe-eval'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data: https:",
"font-src 'self' data:",
"connect-src 'self'",
"worker-src 'self'",
"manifest-src 'self'",
"object-src 'none'",
"base-uri 'none'",
"frame-src 'none'",
"frame-ancestors 'none'",
"form-action 'self' http://127.0.0.1:* http://localhost:* https://pit.world"
].join("; ");
export function securityHeaders(req, res, next) {
res.set("Content-Security-Policy", CSP);
res.set("Strict-Transport-Security", "max-age=63072000; includeSubDomains");
res.set("X-Frame-Options", "DENY");
res.set("X-Content-Type-Options", "nosniff");
res.set("Referrer-Policy", "no-referrer");
res.set("Cross-Origin-Opener-Policy", "same-origin");
res.set("Cross-Origin-Resource-Policy", "same-origin");
res.set("Permissions-Policy", "camera=(), microphone=(), geolocation=(), payment=(), usb=(), interest-cohort=()");
// Nothing an authenticated page or API answer says should outlive the tab.
if (req.path.startsWith("/api/") || req.path.startsWith("/teams") || req.path.startsWith("/settings") || req.path.startsWith("/dashboard") || req.path.startsWith("/cli/")) {
res.set("Cache-Control", "no-store");
}
next();
}

View file

@ -1,6 +1,6 @@
// Cookie sessions + auth middleware + CSRF (double-submit).
import { get, run } from "../db.mjs";
import { id, token, sign, unsign } from "./crypto.mjs";
import { id, token, sign, unsign, sha256 } from "./crypto.mjs";
import { config } from "../config.mjs";
const COOKIE = "mc_sess";
@ -14,14 +14,16 @@ function cookieOpts(extra = {}) {
export async function createSession(res, userId) {
const t = token();
const now = Date.now();
// Only sha256(token) is stored, like API keys: a database read (or dump)
// yields nothing that signs anyone in.
await run(`INSERT INTO sessions (token, user_id, created_at, expires_at) VALUES (?,?,?,?)`,
[t, userId, now, now + TTL]);
[sha256(t), userId, now, now + TTL]);
res.cookie(COOKIE, t, cookieOpts({ maxAge: TTL }));
}
export async function destroySession(req, res) {
const t = req.cookies?.[COOKIE];
if (t) await run(`DELETE FROM sessions WHERE token = ?`, [t]);
if (t) await run(`DELETE FROM sessions WHERE token = ?`, [sha256(String(t))]);
res.clearCookie(COOKIE, cookieOpts());
}
@ -32,7 +34,7 @@ export async function sessionMiddleware(req, res, next) {
if (t) {
const row = await get(
`SELECT u.* FROM sessions s JOIN users u ON u.id = s.user_id WHERE s.token = ? AND s.expires_at > ?`,
[t, Date.now()]
[sha256(String(t)), Date.now()]
);
if (row) req.user = row;
else res.clearCookie(COOKIE, cookieOpts());