logicsrc/apps/pwa/src/lib/session.mjs
Anthony Ettinger ae6298851b 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>
2026-10-28 16:04:22 +00:00

88 lines
3.6 KiB
JavaScript

// Cookie sessions + auth middleware + CSRF (double-submit).
import { get, run } from "../db.mjs";
import { id, token, sign, unsign, sha256 } from "./crypto.mjs";
import { config } from "../config.mjs";
const COOKIE = "mc_sess";
const CSRF = "mc_csrf";
const TTL = 1000 * 60 * 60 * 24 * 30; // 30 days
function cookieOpts(extra = {}) {
return { httpOnly: true, sameSite: "lax", secure: config.secure, path: "/", ...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 (?,?,?,?)`,
[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 = ?`, [sha256(String(t))]);
res.clearCookie(COOKIE, cookieOpts());
}
// Attach req.user (or null) from the session cookie, and ensure a CSRF token.
export async function sessionMiddleware(req, res, next) {
req.user = null;
const t = req.cookies?.[COOKIE];
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 > ?`,
[sha256(String(t)), Date.now()]
);
if (row) req.user = row;
else res.clearCookie(COOKIE, cookieOpts());
}
// double-submit CSRF token
let csrf = req.cookies?.[CSRF];
if (!csrf) { csrf = token(16); res.cookie(CSRF, csrf, cookieOpts({ httpOnly: false, maxAge: TTL })); }
req.csrfToken = csrf;
next();
}
export function requireAuth(req, res, next) {
if (!req.user) { setNext(res, req.originalUrl); return res.redirect("/"); }
next();
}
// Remember where to go after login (safe local paths only), across any auth method.
export function setNext(res, pathname) {
if (typeof pathname === "string" && pathname.startsWith("/") && !pathname.startsWith("//")) {
res.cookie("mc_next", sign(pathname), cookieOpts({ maxAge: 1000 * 60 * 10 }));
}
}
export function takeNext(req, res) {
const p = unsign(req.cookies?.mc_next);
if (req.cookies?.mc_next) res.clearCookie("mc_next", cookieOpts());
return typeof p === "string" && p.startsWith("/") && !p.startsWith("//") ? p : null;
}
// CSRF guard for unsafe methods on browser (form) routes. API/webhooks are Bearer/HMAC.
export function csrfGuard(req, res, next) {
if (["GET", "HEAD", "OPTIONS"].includes(req.method)) return next();
// machine endpoints are Bearer/HMAC/PKCE-authenticated, not cookie sessions
if (req.path.startsWith("/api/") || req.path.startsWith("/webhooks/") ||
req.path === "/cli/token" || req.path.startsWith("/cli/device/")) return next();
const sent = req.body?._csrf || req.get("x-csrf-token");
if (!sent || sent !== req.cookies?.[CSRF]) return res.status(403).send("bad csrf token");
next();
}
export const csrfInput = (req) => `<input type="hidden" name="_csrf" value="${req.csrfToken}">`;
// ---- ephemeral auth-ceremony state (webauthn challenge / oauth pkce) in signed cookies ----
export function setCeremony(res, name, value, ttlMs = 1000 * 60 * 5) {
res.cookie(`mc_c_${name}`, sign({ v: value, exp: Date.now() + ttlMs }), cookieOpts({ maxAge: ttlMs }));
}
export function getCeremony(req, name) {
const data = unsign(req.cookies?.[`mc_c_${name}`]);
if (!data || data.exp < Date.now()) return null;
return data.v;
}
export function clearCeremony(res, name) { res.clearCookie(`mc_c_${name}`, cookieOpts()); }