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

@ -11,7 +11,7 @@
"test": "node --test"
},
"dependencies": {
"@profullstack/footer": "latest",
"@profullstack/footer": "0.5.0",
"@profullstack/libsql-pg": "^0.1.4",
"@profullstack/profile": "0.1.6",
"@simplewebauthn/browser": "^14.0.0",

8
apps/pwa/public/app.js Normal file
View file

@ -0,0 +1,8 @@
// Page-wide behaviour that used to be inline script (the CSP now allows none):
// the service worker, and confirm() before destructive forms (data-confirm="…").
if ("serviceWorker" in navigator) navigator.serviceWorker.register("/sw.js").catch(() => {});
document.addEventListener("submit", (event) => {
const form = event.target;
const question = form instanceof HTMLFormElement ? form.dataset.confirm : null;
if (question && !window.confirm(question)) event.preventDefault();
}, true);

44
apps/pwa/public/pins.js Normal file
View file

@ -0,0 +1,44 @@
// Trust-on-first-use pins for teammates' identity keys, in this browser.
//
// The dashboard shows each member's key fingerprint (sha256 of the public key).
// The first time this browser sees a member's fingerprint it is pinned; if the
// server later shows a DIFFERENT one, the row is flagged until you accept it.
// A changed key is normal after `logicsrc teams rotate-identity` or a reset, and
// exactly what a swapped-in attacker key looks like: confirm with the person
// out of band before granting them anything. The CLI keeps its own pins
// (~/.config/logicsrc/known-keys.json) and refuses to seal to a changed key.
(function () {
const STORE = "logicsrc.keyPins.v1";
let pins = {};
try { pins = JSON.parse(localStorage.getItem(STORE) || "{}") || {}; } catch (_) { pins = {}; }
const save = () => { try { localStorage.setItem(STORE, JSON.stringify(pins)); } catch (_) { /* storage blocked: pins last this page only */ } };
for (const el of document.querySelectorAll("code.fp[data-fp-email][data-fp]")) {
const id = `${el.dataset.fpTeam || ""}/${el.dataset.fpEmail}`;
const fp = el.dataset.fp;
const known = pins[id];
if (!known) {
pins[id] = { fp, firstSeen: Date.now() };
continue;
}
if (known.fp === fp) continue;
el.style.color = "var(--danger)";
const note = document.createElement("div");
note.className = "mono";
note.style.cssText = "font-size:.72rem;color:var(--danger);margin-top:4px";
note.textContent = `KEY CHANGED since this browser last saw it (was ${known.fp}). Confirm with ${el.dataset.fpEmail} before granting anything. `;
const accept = document.createElement("button");
accept.type = "button";
accept.className = "btn compact";
accept.textContent = "I checked: accept";
accept.addEventListener("click", () => {
pins[id] = { fp, firstSeen: Date.now(), acceptedChangeFrom: known.fp };
save();
note.remove();
el.style.color = "";
});
note.appendChild(accept);
el.insertAdjacentElement("afterend", note);
}
save();
})();

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());

View file

@ -9,7 +9,17 @@
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { db, run, all, isPostgres } from "./db.mjs";
import { db, run as appRun, all as appAll, isPostgres, isPostgresUrl } from "./db.mjs";
import { createClient as createPgClient } from "@profullstack/libsql-pg";
// The app connects as a least-privilege role (DML only, append-only audit). DDL
// needs the schema owner, so migrations run on MIGRATE_DATABASE_URL when it is
// set (the owner role), and fall back to the app's own connection otherwise
// (local dev, tests, a single-role setup).
const MIGRATE_URL = process.env.MIGRATE_DATABASE_URL || "";
const migrator = MIGRATE_URL && isPostgresUrl(MIGRATE_URL) ? createPgClient({ url: MIGRATE_URL, dialect: "sqlite" }) : null;
const run = migrator ? (sql, args = []) => migrator.execute({ sql, args }) : appRun;
const all = migrator ? async (sql, args = []) => (await migrator.execute({ sql, args })).rows : appAll;
const HERE = path.dirname(fileURLToPath(import.meta.url));
export const MIGRATIONS_DIR = path.join(HERE, isPostgres ? "migrations-pg" : "migrations");
@ -31,6 +41,7 @@ export async function migrate() {
console.log(`✓ ${file}`);
}
console.log("migrations up to date");
await migrator?.close?.();
}
// Run directly (npm run migrate) — not when imported by the server.

View file

@ -0,0 +1,31 @@
-- Hardening after the 2026-10-27 dev2 incident (a stolen lsk_ user token and identity key).
--
-- * credshare_audit gains ip + user_agent, so every read of a vault key or of a
-- vault's ciphertext can be traced to where it came from.
-- * credshare_vaults.key_version counts re-keys. A grant read returns it and a
-- write that names an older one is refused, so a push that fetched the vault
-- key just before a re-key cannot land ciphertext under the retired key.
-- * credshare_key_challenges: replacing a registered identity public key needs
-- proof of the CURRENT secret key (a random answer sealed to it), so a stolen
-- API token alone can no longer swap in an attacker's key ("last login wins").
-- * Session tokens are stored as sha256 hex, like API keys already are. The
-- raw-token rows are hashed in place; CLI auth codes live 5 minutes, so the
-- few in flight are dropped instead.
ALTER TABLE credshare_audit ADD COLUMN ip TEXT;
ALTER TABLE credshare_audit ADD COLUMN user_agent TEXT;
CREATE INDEX IF NOT EXISTS idx_credshare_audit_team ON credshare_audit(team_id, created_at DESC);
ALTER TABLE credshare_vaults ADD COLUMN key_version bigint NOT NULL DEFAULT 1;
CREATE TABLE IF NOT EXISTS credshare_key_challenges (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
public_key TEXT NOT NULL,
answer_hash TEXT NOT NULL,
created_at bigint NOT NULL,
expires_at bigint NOT NULL,
used_at bigint
);
CREATE INDEX IF NOT EXISTS idx_key_challenges_user ON credshare_key_challenges(user_id);
UPDATE sessions SET token = encode(sha256(convert_to(token, 'UTF8')), 'hex') WHERE length(token) <> 64;
DELETE FROM cli_auth_codes;

View file

@ -0,0 +1,32 @@
-- Hardening after the 2026-10-27 dev2 incident (a stolen lsk_ user token and identity key).
--
-- * credshare_audit gains ip + user_agent, so every read of a vault key or of a
-- vault's ciphertext can be traced to where it came from.
-- * credshare_vaults.key_version counts re-keys. A grant read returns it and a
-- write that names an older one is refused, so a push that fetched the vault
-- key just before a re-key cannot land ciphertext under the retired key.
-- * credshare_key_challenges: replacing a registered identity public key needs
-- proof of the CURRENT secret key (a random answer sealed to it), so a stolen
-- API token alone can no longer swap in an attacker's key ("last login wins").
-- * Session tokens are stored as sha256 hex, like API keys already are. The
-- raw-token rows are hashed in place; CLI auth codes live 5 minutes, so the
-- few in flight are dropped instead.
ALTER TABLE credshare_audit ADD COLUMN ip TEXT;
ALTER TABLE credshare_audit ADD COLUMN user_agent TEXT;
CREATE INDEX IF NOT EXISTS idx_credshare_audit_team ON credshare_audit(team_id, created_at DESC);
ALTER TABLE credshare_vaults ADD COLUMN key_version INTEGER NOT NULL DEFAULT 1;
CREATE TABLE IF NOT EXISTS credshare_key_challenges (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
public_key TEXT NOT NULL,
answer_hash TEXT NOT NULL,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL,
used_at INTEGER
);
CREATE INDEX IF NOT EXISTS idx_key_challenges_user ON credshare_key_challenges(user_id);
-- SQLite has no sha256(): local dev databases just sign everyone out.
DELETE FROM sessions;
DELETE FROM cli_auth_codes;

View file

@ -7,7 +7,7 @@ import { createUserWithPassword, userByEmail } from "../lib/users.mjs";
import { dashboardHandler } from "./pages.mjs";
import { config } from "../config.mjs";
import { ringFooter } from "../lib/ring-footer.mjs";
import { renderProfileFields, PROFILE_ENHANCE_SCRIPT, saveSignupProfile, validateProfile } from "@profullstack/profile";
import { renderProfileFields, saveSignupProfile, validateProfile } from "@profullstack/profile";
import { profiles } from "../lib/profile.mjs";
// Asked for when creating an account, beside the email box; never on sign-in.
@ -47,7 +47,7 @@ function authPage(req, { error = "", mode = "in", values = {}, errors = {} } = {
</div></div>
</main>${footer}${ringFooter()}
<script src="/vendor/simplewebauthn-browser.umd.js"></script>
<script src="/passkey.js"></script>${mode === "up" ? `<script>${PROFILE_ENHANCE_SCRIPT}</script>` : ""}`;
<script src="/passkey.js"></script>${mode === "up" ? `<script src="/vendor/profile-enhance.js" defer></script>` : ""}`;
return page({ title: "LogicSRC ▸ sign in", body });
}

View file

@ -63,7 +63,7 @@ cliRouter.post("/cli/authorize", requireAuth, async (req, res) => {
const now = Date.now();
await run(
`INSERT INTO cli_auth_codes (code,user_id,code_challenge,redirect_uri,name,created_at,expires_at) VALUES (?,?,?,?,?,?,?)`,
[code, req.user.id, code_challenge, redirect_uri, String(name || "cli").slice(0, 40), now, now + 5 * 60 * 1000]
[sha256(code), req.user.id, code_challenge, redirect_uri, String(name || "cli").slice(0, 40), now, now + 5 * 60 * 1000]
);
const u = new URL(redirect_uri);
u.searchParams.set("code", code);
@ -74,14 +74,14 @@ cliRouter.post("/cli/authorize", requireAuth, async (req, res) => {
cliRouter.post("/cli/token", async (req, res) => {
const { code, code_verifier } = req.body || {};
if (!code || !code_verifier) return res.status(400).json({ error: "code and code_verifier required" });
const row = await get(`SELECT * FROM cli_auth_codes WHERE code = ?`, [code]);
const row = await get(`SELECT * FROM cli_auth_codes WHERE code = ?`, [sha256(String(code))]);
if (!row || row.used || row.expires_at < Date.now()) return res.status(400).json({ error: "invalid or expired code" });
// PKCE: base64url(sha256(verifier)) must equal the stored challenge
const challenge = crypto.createHash("sha256").update(String(code_verifier)).digest("base64url");
if (challenge !== row.code_challenge) return res.status(400).json({ error: "PKCE verification failed" });
await run(`UPDATE cli_auth_codes SET used = 1 WHERE code = ?`, [code]);
await run(`UPDATE cli_auth_codes SET used = 1 WHERE code = ?`, [sha256(String(code))]);
const user = await get(`SELECT * FROM users WHERE id = ?`, [row.user_id]);
const { plaintext } = await createApiKey(user.id, row.name || "logicsrc cli");
res.json({ access_token: plaintext, token_type: "bearer", user: { id: user.id, email: user.email || null, name: user.display_name } });

View file

@ -14,7 +14,9 @@
// write except registering its own public key.
import { Router } from "express";
import { get, all, run, batch } from "../db.mjs";
import { id, sha256 } from "../lib/crypto.mjs";
import { id, sha256, token } from "../lib/crypto.mjs";
import { keyFingerprint, requestOriginInfo } from "../lib/keyfp.mjs";
import sodium from "libsodium-wrappers";
import { bearer, keyForBearer, keyCoversVault, normalizeKey } from "../lib/apikey.mjs";
import {
TeamMemberError,
@ -84,9 +86,23 @@ async function publicKeyFor(userId) {
return r?.public_key ?? null;
}
/** The audit row for an event, as a batch statement (so it can ride in a transaction). */
function auditStatement(ev) {
const { ip, userAgent } = requestOriginInfo(ev.req);
return {
sql: `INSERT INTO credshare_audit (id, team_id, vault_id, actor_user_id, action, key_name, fingerprint, created_at, actor_key_id, ip, user_agent) VALUES (?,?,?,?,?,?,?,?,?,?,?)`,
args: [id(), ev.teamId ?? null, ev.vaultId ?? null, ev.actorUserId, ev.action, ev.keyName ?? null, ev.fingerprint ?? null, ev.at ?? Date.now(), ev.actorKeyId ?? ev.req?.apiKey?.id ?? null, ip, userAgent]
};
}
async function audit(ev) {
await run(`INSERT INTO credshare_audit (id, team_id, vault_id, actor_user_id, action, key_name, fingerprint, created_at, actor_key_id) VALUES (?,?,?,?,?,?,?,?,?)`,
[id(), ev.teamId ?? null, ev.vaultId ?? null, ev.actorUserId, ev.action, ev.keyName ?? null, ev.fingerprint ?? null, Date.now(), ev.actorKeyId ?? null]);
const st = auditStatement(ev);
await run(st.sql, st.args);
}
/** Every team the user is an active member of (identity events are logged in each). */
async function activeTeamIds(userId) {
return (await all(`SELECT team_id FROM credshare_members WHERE user_id = ? AND status = 'active'`, [userId])).map((r) => r.team_id);
}
/** The key facts a client needs about its own credential (null for a browser session). */
@ -120,15 +136,124 @@ credshareRouter.post("/api/credshare/keys", api(async (req, res, user, key) => {
}
if (key.public_key !== publicKey) {
await run(`UPDATE api_keys SET public_key = ? WHERE id = ?`, [publicKey, key.id]);
await audit({ teamId: key.team_id, actorUserId: user.id, actorKeyId: key.id, action: "key:register", keyName: key.name });
await audit({ req, teamId: key.team_id, actorUserId: user.id, actorKeyId: key.id, action: "key:register", keyName: key.name });
}
return res.json({ email: user.email, publicKey, keyId: key.id, droppedGrants: dropped });
}
await run(`INSERT INTO credshare_keys (user_id, public_key, updated_at) VALUES (?,?,?) ON CONFLICT(user_id) DO UPDATE SET public_key = excluded.public_key, updated_at = excluded.updated_at`,
[user.id, publicKey, Date.now()]);
res.json({ email: user.email, publicKey });
// A person's identity key is registered ONCE. Replacing it used to be "last
// login wins", so anyone holding a stolen lsk_ token could swap in their own
// key and have teammates seal vaults to it. Now a different key is refused:
// it changes only through POST /keys/rotate, which needs proof of the current
// secret key, or a reset from a signed-in browser (Settings), which drops
// every grant sealed to the old key.
const current = await publicKeyFor(user.id);
if (current === publicKey) return res.json({ email: user.email, publicKey, fingerprint: keyFingerprint(publicKey) });
if (!isValidPublicKey(publicKey)) return res.status(422).json({ error: "publicKey must be a base64 X25519 public key (32 bytes)." });
if (current) {
return res.status(409).json({
error:
`${user.email} already has an identity key registered (fingerprint ${keyFingerprint(current)}), and this one (${keyFingerprint(publicKey)}) is different. ` +
"Copy your identity from the machine that has it (there: logicsrc teams key; here: logicsrc teams key --import), " +
"rotate it from that machine (logicsrc teams rotate-identity), or reset it in Settings on the web app (drops your vault grants).",
code: "identity_key_mismatch",
fingerprint: keyFingerprint(current)
});
}
const now = Date.now();
await run(`INSERT INTO credshare_keys (user_id, public_key, updated_at) VALUES (?,?,?) ON CONFLICT(user_id) DO NOTHING`, [user.id, publicKey, now]);
for (const teamId of await activeTeamIds(user.id)) {
await audit({ req, teamId, actorUserId: user.id, action: "identity:register", fingerprint: keyFingerprint(publicKey) });
}
res.json({ email: user.email, publicKey, fingerprint: keyFingerprint(publicKey) });
}, { machine: "register" }));
const CHALLENGE_TTL_MS = 5 * 60 * 1000;
function isValidPublicKey(b64) {
try { return typeof b64 === "string" && Buffer.from(b64, "base64").length === 32 && /^[A-Za-z0-9+/]+={0,2}$/.test(b64); } catch { return false; }
}
// Proof of possession for identity rotation. X25519 cannot sign, so the server
// seals a random answer to the CURRENT public key; only the holder of the
// matching secret key can open it. Single use, five minutes.
credshareRouter.post("/api/credshare/keys/challenge", api(async (req, res, user) => {
const current = await publicKeyFor(user.id);
if (!current) return res.status(409).json({ error: "No identity key is registered yet; there is nothing to rotate. Run: logicsrc login", code: "no_identity_key" });
await sodium.ready;
const answer = token(32);
const sealed = sodium.to_base64(
sodium.crypto_box_seal(sodium.from_string(answer), sodium.from_base64(current, sodium.base64_variants.ORIGINAL)),
sodium.base64_variants.ORIGINAL
);
const now = Date.now();
const challengeId = id();
await run(`DELETE FROM credshare_key_challenges WHERE user_id = ? AND (expires_at < ? OR used_at IS NOT NULL)`, [user.id, now]);
await run(`INSERT INTO credshare_key_challenges (id, user_id, public_key, answer_hash, created_at, expires_at) VALUES (?,?,?,?,?,?)`,
[challengeId, user.id, current, sha256(answer), now, now + CHALLENGE_TTL_MS]);
res.json({ challengeId, sealed, publicKey: current, fingerprint: keyFingerprint(current), expiresAt: now + CHALLENGE_TTL_MS });
}));
// Rotate a person's identity key: the new public key and EVERY vault grant
// re-sealed to it, in one transaction, behind the challenge above. The grants
// still carry the same vault keys (re-key the vaults afterwards if the old
// secret key leaked: logicsrc teams rekey <team> --all).
credshareRouter.post("/api/credshare/keys/rotate", api(async (req, res, user) => {
const { publicKey, challengeId, answer } = req.body || {};
const grantsIn = Array.isArray(req.body?.grants) ? req.body.grants : null;
if (!isValidPublicKey(publicKey) || typeof challengeId !== "string" || typeof answer !== "string" || !grantsIn) {
return res.status(422).json({ error: "Expected { publicKey, challengeId, answer, grants: [{ vaultId, wrappedDek }] }." });
}
const current = await publicKeyFor(user.id);
if (!current) return res.status(409).json({ error: "No identity key is registered yet.", code: "no_identity_key" });
const now = Date.now();
const ch = await get(`SELECT * FROM credshare_key_challenges WHERE id = ? AND user_id = ?`, [challengeId, user.id]);
const valid = ch && !ch.used_at && Number(ch.expires_at) > now && ch.public_key === current && ch.answer_hash === sha256(answer);
// Burn the challenge whatever the outcome: one guess per challenge.
if (ch) await run(`UPDATE credshare_key_challenges SET used_at = ? WHERE id = ?`, [now, ch.id]);
if (!valid) {
for (const teamId of await activeTeamIds(user.id)) {
await audit({ req, teamId, actorUserId: user.id, action: "identity:rotate:denied", fingerprint: keyFingerprint(publicKey) });
}
return res.status(403).json({ error: "Proof of the current identity key failed (wrong, expired or reused challenge). Run the rotation from the machine that holds the current key.", code: "bad_challenge" });
}
if (publicKey === current) return res.status(422).json({ error: "The new public key is the current one." });
const held = await all(`SELECT vault_id FROM credshare_vault_grants WHERE user_id = ?`, [user.id]);
const heldIds = new Set(held.map((g) => g.vault_id));
const byVault = new Map();
for (const g of grantsIn) {
if (!g || typeof g.vaultId !== "string" || typeof g.wrappedDek !== "string" || !g.wrappedDek) {
return res.status(422).json({ error: "Each grant needs { vaultId, wrappedDek }." });
}
if (!heldIds.has(g.vaultId)) return res.status(409).json({ error: `You hold no grant on vault ${g.vaultId}. Re-read your grants and retry.`, code: "grants_changed" });
byVault.set(g.vaultId, g.wrappedDek);
}
const missing = [...heldIds].filter((v) => !byVault.has(v));
if (missing.length) {
return res.status(409).json({ error: `The rotation re-seals ${byVault.size} grant(s) but you hold ${heldIds.size}; ${missing.length} missing. Re-read your grants and retry.`, code: "grants_changed", missing });
}
const statements = [];
for (const [vaultId, wrappedDek] of byVault) {
statements.push({ sql: `UPDATE credshare_vault_grants SET wrapped_dek = ? WHERE vault_id = ? AND user_id = ?`, args: [wrappedDek, vaultId, user.id] });
}
statements.push({ sql: `UPDATE credshare_keys SET public_key = ?, updated_at = ? WHERE user_id = ?`, args: [publicKey, now, user.id] });
for (const teamId of await activeTeamIds(user.id)) {
statements.push(auditStatement({ req, teamId, actorUserId: user.id, action: "identity:rotate", keyName: keyFingerprint(current), fingerprint: keyFingerprint(publicKey), at: now }));
}
await batch(statements);
res.json({ ok: true, publicKey, fingerprint: keyFingerprint(publicKey), previousFingerprint: keyFingerprint(current), regranted: byVault.size });
}));
/** Every vault grant the caller holds (for re-sealing them during an identity rotation). */
credshareRouter.get("/api/credshare/me/grants", api(async (_req, res, user) => {
const rows = await all(
`SELECT g.vault_id, g.wrapped_dek, v.name, t.slug FROM credshare_vault_grants g JOIN credshare_vaults v ON v.id = g.vault_id JOIN credshare_teams t ON t.id = v.team_id WHERE g.user_id = ? ORDER BY t.slug, v.name`,
[user.id]
);
res.json({ grants: rows.map((r) => ({ vaultId: r.vault_id, vault: r.name, team: r.slug, wrappedDek: r.wrapped_dek })) });
}));
credshareRouter.get("/api/credshare/me", api(async (_req, res, user, key) => {
if (isMachine(key)) {
const teams = await all(`SELECT t.id, t.slug, t.name FROM credshare_teams t JOIN credshare_members m ON m.team_id = t.id WHERE m.user_id = ? AND m.status = 'active' AND t.id = ?`, [user.id, key.team_id]);
@ -143,7 +268,8 @@ credshareRouter.get("/api/credshare/users", api(async (req, res) => {
const email = norm(req.query.email);
if (!email) return res.status(422).json({ error: "Expected ?email=" });
const u = await get(`SELECT id FROM users WHERE email = ?`, [email]);
res.json({ email, userId: u?.id ?? null, publicKey: u ? await publicKeyFor(u.id) : null });
const publicKey = u ? await publicKeyFor(u.id) : null;
res.json({ email, userId: u?.id ?? null, publicKey, fingerprint: keyFingerprint(publicKey) });
}));
// ---- teams / members / invites ----
@ -155,7 +281,7 @@ credshareRouter.post("/api/credshare/teams", api(async (req, res, user) => {
await run(`INSERT INTO credshare_teams (id, slug, name, created_by, created_at) VALUES (?,?,?,?,?)`, [team.id, team.slug, team.name, team.createdBy, team.createdAt]);
await run(`INSERT INTO credshare_members (id, team_id, user_id, email, role, status, joined_at, created_at) VALUES (?,?,?,?,?,?,?,?)`,
[id(), team.id, user.id, norm(user.email) || user.id, "owner", "active", Date.now(), Date.now()]);
await audit({ teamId: team.id, actorUserId: user.id, actorKeyId: req.apiKey?.id, action: "team:create" });
await audit({ req, teamId: team.id, actorUserId: user.id, actorKeyId: req.apiKey?.id, action: "team:create" });
res.status(201).json({ team: { id: team.id, slug: team.slug, name: team.name } });
}));
@ -170,7 +296,10 @@ credshareRouter.get("/api/credshare/teams/:slug/members", api(async (req, res, u
const ctx = await requireMember(res, req.params.slug, user.id); if (!ctx) return;
const rows = await all(`SELECT * FROM credshare_members WHERE team_id = ? ORDER BY created_at`, [ctx.team.id]);
const members = [];
for (const m of rows) members.push({ id: m.id, email: m.email, role: m.role, status: m.status, hasPublicKey: m.user_id ? Boolean(await publicKeyFor(m.user_id)) : false, joinedAt: m.joined_at });
for (const m of rows) {
const publicKey = m.user_id ? await publicKeyFor(m.user_id) : null;
members.push({ id: m.id, email: m.email, role: m.role, status: m.status, hasPublicKey: Boolean(publicKey), publicKey, fingerprint: keyFingerprint(publicKey), joinedAt: m.joined_at });
}
res.json({ members });
}));
@ -237,7 +366,7 @@ credshareRouter.post("/api/credshare/invites/accept", api(async (req, res, user)
if (norm(invite.email) !== norm(user.email)) return res.status(403).json({ error: `This invite is for ${invite.email}, not ${user.email}.` });
await run(`UPDATE credshare_members SET user_id = ?, status = 'active', joined_at = ? WHERE team_id = ? AND email = ?`, [user.id, Date.now(), invite.team_id, norm(invite.email)]);
await run(`UPDATE credshare_invites SET accepted_at = ? WHERE id = ?`, [Date.now(), invite.id]);
await audit({ teamId: invite.team_id, actorUserId: user.id, actorKeyId: req.apiKey?.id, action: "team:join" });
await audit({ req, teamId: invite.team_id, actorUserId: user.id, actorKeyId: req.apiKey?.id, action: "team:join" });
const team = await get(`SELECT id, slug, name FROM credshare_teams WHERE id = ?`, [invite.team_id]);
res.json({ ok: true, team });
}));
@ -303,7 +432,7 @@ credshareRouter.post("/api/credshare/teams/:slug/vaults", api(async (req, res, u
if (existing) return res.json({ vault: { id: existing.id, name: existing.name } });
const vault = { id: id(), name };
await run(`INSERT INTO credshare_vaults (id, team_id, name, created_by, created_at) VALUES (?,?,?,?,?)`, [vault.id, ctx.team.id, name, user.id, Date.now()]);
await audit({ teamId: ctx.team.id, vaultId: vault.id, actorUserId: user.id, actorKeyId: req.apiKey?.id, action: "vault:create" });
await audit({ req, teamId: ctx.team.id, vaultId: vault.id, actorUserId: user.id, actorKeyId: req.apiKey?.id, action: "vault:create" });
res.status(201).json({ vault });
}));
@ -325,12 +454,18 @@ credshareRouter.get("/api/credshare/vaults/:id/grant", api(async (req, res, user
const kg = await get(`SELECT wrapped_dek FROM credshare_key_grants WHERE vault_id = ? AND api_key_id = ?`, [vault.id, key.id]);
if (!kg) return res.status(403).json({ error: `This machine key (${key.name}) has not been granted this vault yet. A member runs: logicsrc teams grant <team> <project> <env> --key ${key.name}`, code: "no_key_grant" });
// The one moment a machine can decrypt: worth a line in the vault's audit trail.
await audit({ teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, actorKeyId: key.id, action: "vault:read", keyName: key.name });
return res.json({ wrappedDek: kg.wrapped_dek });
await audit({ req, teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, actorKeyId: key.id, action: "vault:read", keyName: key.name });
return res.json({ wrappedDek: kg.wrapped_dek, keyVersion: Number(vault.key_version ?? 1) });
}
const grant = await get(`SELECT wrapped_dek FROM credshare_vault_grants WHERE vault_id = ? AND user_id = ?`, [vault.id, user.id]);
if (!grant) return res.status(403).json({ error: "You do not have access to this vault yet. Ask a member to grant you." });
res.json({ wrappedDek: grant.wrapped_dek });
if (!grant) {
await audit({ req, teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, action: "vault:read:denied", keyName: key?.name ?? null });
return res.status(403).json({ error: "You do not have access to this vault yet. Ask a member to grant you." });
}
// A person opening the vault key is the moment they can decrypt: always audited,
// with where it came from (a stolen token shows up here as a foreign IP).
await audit({ req, teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, action: "vault:read", keyName: key?.name ?? (req.user ? "browser session" : null) });
res.json({ wrappedDek: grant.wrapped_dek, keyVersion: Number(vault.key_version ?? 1) });
}, { machine: "read" }));
credshareRouter.get("/api/credshare/vaults/:id/grants", api(async (req, res, user) => {
@ -443,8 +578,11 @@ credshareRouter.post("/api/credshare/vaults/:id/rekey", api(async (req, res, use
const statements = [];
for (const s of secrets) {
statements.push({
sql: `UPDATE credshare_secrets SET nonce = ?, ciphertext = ?, version = version + 1, updated_by = ?, updated_at = ? WHERE vault_id = ? AND name = ?`,
args: [s.nonce, s.ciphertext, user.id, now, vault.id, s.name]
// Only while the value is still the one this re-key read: a push that lands
// between the check above and this commit keeps its value (the CLI's
// verify pass then re-seals it under the new key).
sql: `UPDATE credshare_secrets SET nonce = ?, ciphertext = ?, version = version + 1, updated_by = ?, updated_at = ? WHERE vault_id = ? AND name = ? AND fingerprint = ?`,
args: [s.nonce, s.ciphertext, user.id, now, vault.id, s.name, s.fingerprint]
});
}
for (const g of resolved) {
@ -463,20 +601,17 @@ credshareRouter.post("/api/credshare/vaults/:id/rekey", api(async (req, res, use
args: [vault.id, g.keyId, g.wrappedDek, user.id, now]
});
}
statements.push({
sql: `INSERT INTO credshare_audit (id, team_id, vault_id, actor_user_id, action, key_name, fingerprint, created_at) VALUES (?,?,?,?,?,?,?,?)`,
args: [id(), vault.team_id, vault.id, user.id, "vault:rekey", null, null, now]
});
statements.push({ sql: `UPDATE credshare_vaults SET key_version = key_version + 1 WHERE id = ?`, args: [vault.id] });
statements.push(auditStatement({ req, teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, action: "vault:rekey", at: now }));
for (const r of revokedUsers) {
statements.push({
sql: `INSERT INTO credshare_audit (id, team_id, vault_id, actor_user_id, action, key_name, fingerprint, created_at) VALUES (?,?,?,?,?,?,?,?)`,
args: [id(), vault.team_id, vault.id, user.id, "vault:revoke", r.email, null, now]
});
statements.push(auditStatement({ req, teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, action: "vault:revoke", keyName: r.email, at: now }));
}
await batch(statements);
const after = await get(`SELECT key_version FROM credshare_vaults WHERE id = ?`, [vault.id]);
res.json({
ok: true,
keyVersion: Number(after?.key_version ?? 1),
rekeyed: secrets.length,
granted: resolved.map((g) => g.email),
revoked: revokedUsers.map((r) => r.email),
@ -497,7 +632,7 @@ credshareRouter.post("/api/credshare/vaults/:id/grants", api(async (req, res, us
if (!(await publicKeyFor(target.id))) return res.status(409).json({ error: "Target user has not uploaded a public key yet." });
await run(`INSERT INTO credshare_vault_grants (vault_id, user_id, wrapped_dek, granted_by, created_at) VALUES (?,?,?,?,?) ON CONFLICT(vault_id, user_id) DO UPDATE SET wrapped_dek = excluded.wrapped_dek, granted_by = excluded.granted_by, created_at = excluded.created_at`,
[vault.id, target.id, wrappedDek, user.id, Date.now()]);
await audit({ teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, actorKeyId: req.apiKey?.id, action: "vault:grant", keyName: email });
await audit({ req, teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, actorKeyId: req.apiKey?.id, action: "vault:grant", keyName: email });
res.status(201).json({ ok: true });
}));
@ -554,7 +689,7 @@ credshareRouter.post("/api/credshare/vaults/:id/key-grants", api(async (req, res
}
await run(`INSERT INTO credshare_key_grants (vault_id, api_key_id, wrapped_dek, granted_by, created_at) VALUES (?,?,?,?,?) ON CONFLICT(vault_id, api_key_id) DO UPDATE SET wrapped_dek = excluded.wrapped_dek, granted_by = excluded.granted_by, created_at = excluded.created_at`,
[vault.id, target.id, wrappedDek, user.id, Date.now()]);
await audit({ teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, actorKeyId: req.apiKey?.id, action: "vault:grant:key", keyName: target.name });
await audit({ req, teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, actorKeyId: req.apiKey?.id, action: "vault:grant:key", keyName: target.name });
res.status(201).json({ ok: true, keyId: target.id, name: target.name });
}));
@ -568,14 +703,15 @@ credshareRouter.delete("/api/credshare/vaults/:id/key-grants/:keyId", api(async
const iHold = await get(`SELECT 1 FROM credshare_vault_grants WHERE vault_id = ? AND user_id = ?`, [vault.id, user.id]);
if (!iHold && row.user_id !== user.id) return res.status(403).json({ error: "Only the key's owner or a member with vault access can revoke it." });
await run(`DELETE FROM credshare_key_grants WHERE vault_id = ? AND api_key_id = ?`, [vault.id, row.id]);
await audit({ teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, actorKeyId: req.apiKey?.id, action: "vault:revoke:key", keyName: row.name });
await audit({ req, teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, actorKeyId: req.apiKey?.id, action: "vault:revoke:key", keyName: row.name });
res.json({ ok: true, revoked: row.name });
}));
credshareRouter.get("/api/credshare/vaults/:id/secrets", api(async (req, res, user, key) => {
const vault = await vaultCtx(res, req.params.id, user.id, key); if (!vault) return;
const rows = await all(`SELECT * FROM credshare_secrets WHERE vault_id = ? ORDER BY name`, [vault.id]);
res.json({ vaultId: vault.id, secrets: rows.map((s) => ({ name: s.name, nonce: s.nonce, ciphertext: s.ciphertext, fingerprint: s.fingerprint, version: s.version, updatedAt: s.updated_at })) });
await audit({ req, teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, action: "secrets:fetch", keyName: key?.name ?? (req.user ? "browser session" : null) });
res.json({ vaultId: vault.id, keyVersion: Number(vault.key_version ?? 1), secrets: rows.map((s) => ({ name: s.name, nonce: s.nonce, ciphertext: s.ciphertext, fingerprint: s.fingerprint, version: s.version, updatedAt: s.updated_at })) });
}, { machine: "read" }));
credshareRouter.put("/api/credshare/vaults/:id/secrets", api(async (req, res, user, key) => {
@ -584,6 +720,12 @@ credshareRouter.put("/api/credshare/vaults/:id/secrets", api(async (req, res, us
return res.status(403).json({ error: "A machine key can only write a vault it has been granted.", code: "no_key_grant" });
}
const actorKeyId = key?.id ?? null;
// A client that read the vault key before a re-key must not write ciphertext
// under the retired key: nobody could open it afterwards.
const sentVersion = req.body?.keyVersion;
if (sentVersion !== undefined && sentVersion !== null && Number(sentVersion) !== Number(vault.key_version ?? 1)) {
return res.status(409).json({ error: `This vault was re-keyed (key version ${vault.key_version}, you used ${sentVersion}). Run the command again.`, code: "vault_rekeyed", keyVersion: Number(vault.key_version ?? 1) });
}
const upserts = Array.isArray(req.body?.upserts) ? req.body.upserts : [];
const deletes = Array.isArray(req.body?.deletes) ? req.body.deletes : [];
const applied = [];
@ -595,14 +737,14 @@ credshareRouter.put("/api/credshare/vaults/:id/secrets", api(async (req, res, us
const version = (prev?.version ?? 0) + 1;
await run(`INSERT INTO credshare_secrets (vault_id, name, nonce, ciphertext, fingerprint, version, updated_by, updated_at) VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(vault_id, name) DO UPDATE SET nonce = excluded.nonce, ciphertext = excluded.ciphertext, fingerprint = excluded.fingerprint, version = excluded.version, updated_by = excluded.updated_by, updated_at = excluded.updated_at`,
[vault.id, u.name, u.nonce, u.ciphertext, u.fingerprint, version, user.id, Date.now()]);
await audit({ teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, action: prev ? "secret:update" : "secret:add", keyName: u.name, fingerprint: u.fingerprint, actorKeyId });
await audit({ req, teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, action: prev ? "secret:update" : "secret:add", keyName: u.name, fingerprint: u.fingerprint, actorKeyId });
applied.push(u.name);
}
for (const raw of deletes) {
const name = typeof raw === "string" ? raw : null;
if (!name) continue;
await run(`DELETE FROM credshare_secrets WHERE vault_id = ? AND name = ?`, [vault.id, name]);
await audit({ teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, action: "secret:remove", keyName: name, actorKeyId });
await audit({ req, teamId: vault.team_id, vaultId: vault.id, actorUserId: user.id, action: "secret:remove", keyName: name, actorKeyId });
applied.push(name);
}
res.json({ ok: true, applied });
@ -610,6 +752,49 @@ credshareRouter.put("/api/credshare/vaults/:id/secrets", api(async (req, res, us
credshareRouter.get("/api/credshare/vaults/:id/audit", api(async (req, res, user, key) => {
const vault = await vaultCtx(res, req.params.id, user.id, key); if (!vault) return;
const auditRows = await all(`SELECT * FROM credshare_audit WHERE vault_id = ? ORDER BY created_at DESC`, [vault.id]);
const auditRows = await all(`SELECT * FROM credshare_audit WHERE vault_id = ? ORDER BY created_at DESC LIMIT 1000`, [vault.id]);
res.json({ audit: auditRows });
}, { machine: "read" }));
/**
* The team's audit trail, newest first: who read which vault key or ciphertext,
* from which IP and user agent, plus grants, re-keys and identity changes.
* Filters: ?vault=<name> &actor=<email> &action=<prefix> &since=<ms> &limit (max 1000).
*/
credshareRouter.get("/api/credshare/teams/:slug/audit", api(async (req, res, user) => {
const ctx = await requireMember(res, req.params.slug, user.id); if (!ctx) return;
res.json({ audit: await teamAudit(ctx.team.id, req.query) });
}));
export async function teamAudit(teamId, q = {}) {
const where = ["a.team_id = ?"];
const args = [teamId];
if (q.vault) { where.push("v.name = ?"); args.push(String(q.vault)); }
if (q.actor) { where.push("u.email = ?"); args.push(norm(q.actor)); }
if (q.action) { where.push("a.action LIKE ?"); args.push(`${String(q.action).replace(/[%_]/g, "")}%`); }
if (q.since && Number.isFinite(Number(q.since))) { where.push("a.created_at >= ?"); args.push(Number(q.since)); }
const limit = Math.min(Math.max(Number(q.limit) || 200, 1), 1000);
const rows = await all(
`SELECT a.created_at, a.action, a.key_name, a.fingerprint, a.ip, a.user_agent, u.email AS actor, v.name AS vault, k.name AS api_key, k.kind AS api_key_kind
FROM credshare_audit a
LEFT JOIN users u ON u.id = a.actor_user_id
LEFT JOIN credshare_vaults v ON v.id = a.vault_id
LEFT JOIN api_keys k ON k.id = a.actor_key_id
WHERE ${where.join(" AND ")}
ORDER BY a.created_at DESC
LIMIT ${limit}`,
args
);
return rows.map((r) => ({
at: Number(r.created_at),
action: r.action,
actor: r.actor ?? null,
vault: r.vault ?? null,
target: r.key_name ?? null,
fingerprint: r.fingerprint ?? null,
apiKey: r.api_key ?? null,
apiKeyKind: r.api_key_kind ?? null,
ip: r.ip ?? null,
userAgent: r.user_agent ?? null
}));
}

View file

@ -3,7 +3,7 @@
// page can, in the browser, once the member pastes their identity key
// (public/vault.js); everything else here is ciphertext metadata.
import { Router } from "express";
import { get, all, run } from "../db.mjs";
import { get, all, run, batch } from "../db.mjs";
import { id, sha256 } from "../lib/crypto.mjs";
import { page, footer, appBar, esc } from "../lib/html.mjs";
import { requireAuth, csrfInput } from "../lib/session.mjs";
@ -11,6 +11,9 @@ import { ApiKeyError, createApiKey, keyCoversVault, listApiKeys, machineKeyOptio
import { requestOrigin } from "../lib/origin.mjs";
import { CLI_HINT } from "../lib/cli-hint.mjs";
import { vaultPageBody } from "../lib/vault-page.mjs";
import { keyFingerprint } from "../lib/keyfp.mjs";
import { teamAudit } from "./credshare.mjs";
import { setCeremony, getCeremony, clearCeremony } from "../lib/session.mjs";
import { config } from "../config.mjs";
import { COLUMNS, renderProfileFields, validateProfile } from "@profullstack/profile";
import { profiles } from "../lib/profile.mjs";
@ -35,7 +38,8 @@ async function teamCard(team, uid) {
const memberRows = [];
for (const m of members) {
const key = m.user_id ? await get(`SELECT 1 FROM credshare_keys WHERE user_id = ?`, [m.user_id]) : null;
const key = m.user_id ? await get(`SELECT public_key FROM credshare_keys WHERE user_id = ?`, [m.user_id]) : null;
const fp = keyFingerprint(key?.public_key);
const roleControl = me.role === "owner"
? `<form method="post" action="/teams/${esc(team.slug)}/members/${esc(m.id)}/role" class="member-role-form">${CSRF}
<select name="role" aria-label="Permission for ${esc(m.email)}">
@ -45,9 +49,9 @@ async function teamCard(team, uid) {
const canResend = m.status === "invited" && (me.role === "owner" || (me.role === "admin" && m.role === "member"));
const actions = [
canResend ? `<form method="post" action="/teams/${esc(team.slug)}/members/${esc(m.id)}/resend" style="margin:0">${CSRF}<button class="btn compact">Resend</button></form>` : "",
canManageMember(me, m) ? `<form method="post" action="/teams/${esc(team.slug)}/members/${esc(m.id)}/delete" style="margin:0" onsubmit="return confirm('Remove this team member?')">${CSRF}<button class="btn compact danger">Remove</button></form>` : ""
canManageMember(me, m) ? `<form method="post" action="/teams/${esc(team.slug)}/members/${esc(m.id)}/delete" style="margin:0" data-confirm="Remove this team member?">${CSRF}<button class="btn compact danger">Remove</button></form>` : ""
].filter(Boolean).join("");
memberRows.push(`<tr><td>${esc(m.email)}</td><td>${roleControl}</td><td><span class="pill ${m.status === "active" ? "on" : "warn"}">${esc(m.status)}</span></td><td>${key ? "✓" : "—"}</td><td><div class="member-actions">${actions || "—"}</div></td></tr>`);
memberRows.push(`<tr><td>${esc(m.email)}</td><td>${roleControl}</td><td><span class="pill ${m.status === "active" ? "on" : "warn"}">${esc(m.status)}</span></td><td>${fp ? `<code class="fp" data-fp-team="${esc(team.slug)}" data-fp-email="${esc(m.email)}" data-fp="${esc(fp)}" title="Identity key fingerprint. Compare it with ${esc(m.email)} out of band.">${esc(fp)}</code>` : "—"}</td><td><div class="member-actions">${actions || "—"}</div></td></tr>`);
}
const vaultRows = [];
for (const v of vaults) {
@ -60,7 +64,7 @@ async function teamCard(team, uid) {
<div class="card-head"><span class="h">${esc(team.name)} <span class="faint">/${esc(team.slug)}</span></span><span class="pill">${me ? esc(me.role) : "member"}</span></div>
<div class="card-body">
<div class="label" style="margin-bottom:6px">Members</div>
<div class="table-scroll"><table><thead><tr><th>Email</th><th>Permission</th><th>Status</th><th>Key</th><th>Actions</th></tr></thead><tbody>${memberRows.join("")}</tbody></table></div>
<div class="table-scroll"><table><thead><tr><th>Email</th><th>Permission</th><th>Status</th><th>Key fingerprint</th><th>Actions</th></tr></thead><tbody>${memberRows.join("")}</tbody></table></div>
${canInvite ? `<form method="post" action="/teams/${esc(team.slug)}/invite" style="display:flex;gap:8px;margin-top:12px">${CSRF}
<input type="email" name="email" placeholder="teammate@example.com" required style="flex:1">
${me.role === "owner" ? `<select name="role" aria-label="Permission" style="width:auto"><option value="member">member</option><option value="admin">admin</option><option value="owner">owner</option></select>` : `<input type="hidden" name="role" value="member">`}
@ -68,9 +72,24 @@ async function teamCard(team, uid) {
<div class="label" style="margin:18px 0 6px">Vaults</div>
${vaults.length ? `<table><thead><tr><th>Vault</th><th>Secrets</th><th>Your access</th></tr></thead><tbody>${vaultRows.join("")}</tbody></table>`
: `<p class="faint mono" style="font-size:.82rem">No vaults yet — create one from the CLI: <code>logicsrc teams push ${esc(team.slug)} &lt;project&gt; &lt;env&gt;</code></p>`}
<div class="label" style="margin:18px 0 6px">Recent access <span class="faint">(full trail: <code>logicsrc teams audit ${esc(team.slug)}</code>)</span></div>
${auditTable(await teamAudit(team.id, { limit: 25 }))}
</div></div>`;
}
/** Audit rows as a table: when, who, what, which vault, from where. */
export function auditTable(rows) {
if (!rows.length) return `<p class="faint mono" style="font-size:.82rem">Nothing recorded yet.</p>`;
const when = (ms) => new Date(Number(ms)).toISOString().slice(0, 19).replace("T", " ");
return `<div class="table-scroll"><table class="audit"><thead><tr><th>When (UTC)</th><th>Who</th><th>What</th><th>Vault</th><th>From</th></tr></thead><tbody>${rows.map((r) => `<tr>
<td class="mono" style="white-space:nowrap">${esc(when(r.at))}</td>
<td>${esc(r.actor || "?")}${r.apiKey ? `<div class="faint mono" style="font-size:.72rem">${esc(r.apiKeyKind === "machine" ? "machine key" : "key")} ${esc(r.apiKey)}</div>` : ""}</td>
<td class="mono">${esc(r.action)}${r.target && !r.apiKey ? ` <span class="faint">${esc(r.target)}</span>` : ""}</td>
<td>${r.vault ? `<code>${esc(r.vault)}</code>` : "—"}</td>
<td class="mono" style="font-size:.76rem">${esc(r.ip || "—")}${r.userAgent ? `<div class="faint" style="max-width:260px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="${esc(r.userAgent)}">${esc(r.userAgent)}</div>` : ""}</td>
</tr>`).join("")}</tbody></table></div>`;
}
export async function dashboardHandler(req, res) {
const uid = req.user.id;
const teams = await all(`SELECT t.* FROM credshare_teams t JOIN credshare_members m ON m.team_id = t.id WHERE m.user_id = ? AND m.status = 'active' ORDER BY t.created_at`, [uid]);
@ -106,7 +125,7 @@ export async function dashboardHandler(req, res) {
<div class="card-body"><form method="post" action="/teams" style="display:flex;gap:8px">${csrfInput(req)}
<input name="slug" placeholder="team-slug" required style="flex:1"><button class="btn acid">Create team</button></form></div></div>
</main>${footer}`;
res.type("html").send(page({ title: "LogicSRC ▸ teams", body }));
res.type("html").send(page({ title: "LogicSRC ▸ teams", body, head: `<script src="/pins.js" defer></script>` }));
}
pagesRouter.get("/dashboard", requireAuth, dashboardHandler);
@ -133,7 +152,7 @@ pagesRouter.get("/teams/:slug/vaults/:vaultId", requireAuth, async (req, res, ne
hasGrant: Boolean(grant),
publicKey: key?.public_key || "",
email: req.user.email
})}${footer}`;
})}<main class="wrap" style="max-width:820px;padding:0 0 40px"><div class="card"><div class="card-head"><span class="h">Who opened this vault</span></div><div class="card-body">${auditTable(await teamAudit(ctx.team.id, { vault: vault.name, limit: 50 }))}</div></div></main>${footer}`;
res.set("Cache-Control", "no-store");
res.type("html").send(page({ title: `LogicSRC ▸ ${vault.name}`, body }));
});
@ -278,7 +297,13 @@ pagesRouter.get("/settings", requireAuth, async (req, res) => {
const profileValues = Object.fromEntries(COLUMNS.map((c) => [c, mine[c] ?? null]));
profileValues.email ??= req.user.email || null;
const teams = await all(`SELECT t.slug FROM credshare_teams t JOIN credshare_members m ON m.team_id = t.id WHERE m.user_id = ? AND m.status = 'active' ORDER BY t.slug`, [req.user.id]);
const newKey = req.query.key ? String(req.query.key) : "";
// A new API key is handed over in a short-lived httpOnly cookie, never in the
// URL (where it would sit in history, proxy logs and Referer headers).
const newKey = typeof getCeremony(req, "newkey") === "string" ? getCeremony(req, "newkey") : "";
if (newKey) clearCeremony(res, "newkey");
res.set("Cache-Control", "no-store");
const myKey = await get(`SELECT public_key, updated_at FROM credshare_keys WHERE user_id = ?`, [req.user.id]);
const myGrants = await get(`SELECT COUNT(*) AS n FROM credshare_vault_grants WHERE user_id = ?`, [req.user.id]);
const err = req.query.err ? String(req.query.err).slice(0, 200) : "";
const keysHtml = keys.length ? keys.map((k) => keyRow(req, k)).join("") : `<div class="faint mono" style="font-size:.78rem;padding:6px 0">no keys yet</div>`;
const body = `${appBar(req)}
@ -287,6 +312,19 @@ pagesRouter.get("/settings", requireAuth, async (req, res) => {
${newKey ? `<div class="notice ok">New API key (copy it now — shown once):<br><b class="mono" style="word-break:break-all">${esc(newKey)}</b></div>` : ""}
${err ? `<div class="notice err">${esc(KEY_ERRORS[err] || err)}</div>` : ""}
${req.query.saved === "profile" ? `<div class="notice ok">Your details are saved.</div>` : ""}
${req.query.saved === "identity-reset" ? `<div class="notice ok">Your identity key is reset and your vault grants are gone. Run <code>logicsrc login</code> to register a new key, then ask a teammate to grant you each vault again.</div>` : ""}
<div class="card" style="margin-bottom:20px"><div class="card-head"><span class="h">Identity key</span></div>
<div class="card-body">
${myKey?.public_key
? `<p style="margin-top:0">Fingerprint <code class="fp">${esc(keyFingerprint(myKey.public_key))}</code> <span class="faint mono" style="font-size:.76rem">registered ${esc(new Date(Number(myKey.updated_at)).toISOString().slice(0, 10))}, sealed into ${Number(myGrants?.n || 0)} vault grant(s)</span></p>
<p class="dim" style="font-size:.85rem">Teammates seal vault keys to this key. It changes only with <code>logicsrc teams rotate-identity</code>, run on the machine that holds it (it proves possession of the current key). A login with a different key is refused.</p>
<details><summary class="dim" style="cursor:pointer;font-size:.85rem">Lost the key, or it leaked and you cannot rotate it?</summary>
<form method="post" action="/settings/identity/reset" style="margin-top:12px">${csrfInput(req)}
<p class="dim" style="font-size:.85rem;margin-top:0">Reset removes the registered key and <b>deletes every vault grant sealed to it</b>. You then register a new key with <code>logicsrc login</code> and teammates grant you again; their CLI will show your key as changed and ask them to confirm. If the old key leaked, also ask a teammate to re-key the vaults.</p>
<label class="field"><span>Type RESET to confirm</span><input name="confirm" autocomplete="off" required pattern="RESET"></label>
<button class="btn danger">Reset my identity key</button></form></details>`
: `<p class="dim" style="margin-top:0;font-size:.88rem">No identity key registered yet. Run <code>logicsrc login</code>.</p>`}
</div></div>
<div class="card" style="margin-bottom:20px"><div class="card-head"><span class="h">Your details</span></div>
<div class="card-body">
<form method="post" action="/settings/profile">${csrfInput(req)}
@ -348,8 +386,32 @@ pagesRouter.post("/settings/apikeys", requireAuth, async (req, res) => {
}
}
const { plaintext } = await createApiKey(req.user.id, name, opts);
res.redirect("/settings?key=" + encodeURIComponent(plaintext));
setCeremony(res, "newkey", plaintext, 60 * 1000);
res.redirect("/settings?created=1");
});
// Reset the identity key from a signed-in browser (never from an API key: a
// stolen lsk_ token is exactly what this must not be able to do). Every grant
// sealed to the old key goes too, so a reset gains nobody any access: a
// teammate has to grant the new key, and their pinned fingerprint flags it.
pagesRouter.post("/settings/identity/reset", requireAuth, async (req, res) => {
if (String(req.body.confirm || "") !== "RESET") return res.redirect("/settings?err=" + encodeURIComponent("Type RESET to confirm the identity reset."));
const before = await get(`SELECT public_key FROM credshare_keys WHERE user_id = ?`, [req.user.id]);
const teams = await all(`SELECT team_id FROM credshare_members WHERE user_id = ? AND status = 'active'`, [req.user.id]);
const now = Date.now();
const ip = (req.ip || "").replace(/^::ffff:/, "") || null;
const ua = String(req.get("user-agent") || "").slice(0, 300) || null;
const statements = [
{ sql: `DELETE FROM credshare_vault_grants WHERE user_id = ?`, args: [req.user.id] },
{ sql: `DELETE FROM credshare_keys WHERE user_id = ?`, args: [req.user.id] },
...teams.map((t) => ({
sql: `INSERT INTO credshare_audit (id, team_id, vault_id, actor_user_id, action, key_name, fingerprint, created_at, actor_key_id, ip, user_agent) VALUES (?,?,?,?,?,?,?,?,?,?,?)`,
args: [id(), t.team_id, null, req.user.id, "identity:reset", null, keyFingerprint(before?.public_key), now, null, ip, ua]
}))
];
await batch(statements);
res.redirect("/settings?saved=identity-reset");
});
pagesRouter.post("/settings/apikeys/:id/delete", requireAuth, async (req, res) => {
await revokeApiKey(req.user.id, req.params.id);
res.redirect("/settings");

View file

@ -16,12 +16,18 @@ import { cliRouter } from "./routes/cli.mjs";
import { pagesRouter } from "./routes/pages.mjs";
import { profileRouter } from "./lib/profile.mjs";
import { descriptor } from "@profullstack/footer";
import { RING_FOOTER_OPTIONS, startRingFooterRefresh } from "./lib/ring-footer.mjs";
import { RING_FOOTER_OPTIONS } from "./lib/ring-footer.mjs";
import { securityHeaders } from "./lib/security-headers.mjs";
import { PROFILE_ENHANCE_SCRIPT } from "@profullstack/profile";
const app = express();
app.disable("x-powered-by");
if (config.secure) app.set("trust proxy", 1); // Railway terminates TLS
// Security headers on every response (CSP with no inline or third-party script,
// HSTS, no framing, no referrer). See lib/security-headers.mjs.
app.use(securityHeaders);
// body parsing — keep the raw body for HMAC signature verification
// A vault push carries hundreds of encrypted items; parse it under a larger cap
// first. The global parser below skips a body that is already parsed.
@ -50,6 +56,8 @@ const sodiumWrappers = requireHere.resolve("libsodium-wrappers");
const sodiumCore = createRequire(sodiumWrappers).resolve("libsodium");
app.get("/vendor/libsodium.js", (_req, res) => res.sendFile(sodiumCore));
app.get("/vendor/libsodium-wrappers.js", (_req, res) => res.sendFile(sodiumWrappers));
// The signup profile's progressive enhancement, as a file: the CSP allows no inline script.
app.get("/vendor/profile-enhance.js", (_req, res) => res.type("application/javascript").set("Cache-Control", "public, max-age=3600").send(PROFILE_ENHANCE_SCRIPT));
// The Profullstack webring descriptor (the ring footer is on the sign-in page, /).
app.get("/.well-known/openwebring.json", (_req, res) =>
@ -82,7 +90,6 @@ app.use((err, _req, res, _next) => {
async function main() {
await migrate();
startRingFooterRefresh();
app.listen(config.port, () => console.log(`🔐 logicsrc credentials on :${config.port} (${config.env}) — ${config.origin}`));
}
main().catch((e) => { console.error("boot failed:", e); process.exit(1); });

View file

@ -28,7 +28,7 @@ async function migrate() {
await db.execute("DROP SCHEMA public CASCADE");
await db.execute("CREATE SCHEMA public");
}
for (const file of ["001_auth.sql", "002_credshare.sql", "005_machine_keys.sql"]) {
for (const file of ["001_auth.sql", "002_credshare.sql", "005_machine_keys.sql", "007_hardening.sql"]) {
const sql = readFileSync(join(here, "..", "src", isPostgres ? "migrations-pg" : "migrations", file), "utf8");
for (const statement of sql.split(/;\s*$/m).map((s) => s.trim()).filter(Boolean)) {
await db.execute(statement);

View file

@ -33,7 +33,7 @@ async function migrate() {
await db.execute("DROP SCHEMA public CASCADE");
await db.execute("CREATE SCHEMA public");
}
for (const file of ["001_auth.sql", "002_credshare.sql", "005_machine_keys.sql"]) {
for (const file of ["001_auth.sql", "002_credshare.sql", "005_machine_keys.sql", "007_hardening.sql"]) {
const sql = readFileSync(join(here, "..", "src", isPostgres ? "migrations-pg" : "migrations", file), "utf8");
for (const statement of sql.split(/;\s*$/m).map((s) => s.trim()).filter(Boolean)) {
await db.execute(statement);

View file

@ -0,0 +1,188 @@
// Post-incident hardening (2026-10-28): a stolen lsk_ token must not be able to
// swap a person's identity key; rotation needs proof of the current secret key
// and re-seals every grant in one transaction; person reads are audited with IP
// and user agent; a write under a retired vault key is refused; sessions are
// stored hashed; every response carries the security headers.
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 { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import express from "express";
import cookieParser from "cookie-parser";
import sodium from "libsodium-wrappers";
const here = dirname(fileURLToPath(import.meta.url));
const { db, run, get, all, isPostgres } = await import("../src/db.mjs");
const { credshareRouter } = await import("../src/routes/credshare.mjs");
const { createApiKey } = await import("../src/lib/apikey.mjs");
const { createSession, sessionMiddleware } = await import("../src/lib/session.mjs");
const { sha256 } = await import("../src/lib/crypto.mjs");
const { securityHeaders } = await import("../src/lib/security-headers.mjs");
const { keyFingerprint } = await import("../src/lib/keyfp.mjs");
await sodium.ready;
const b64 = (u8) => sodium.to_base64(u8, sodium.base64_variants.ORIGINAL);
const unb64 = (s) => sodium.from_base64(s, sodium.base64_variants.ORIGINAL);
const keypair = () => { const k = sodium.crypto_box_keypair(); return { publicKey: b64(k.publicKey), secretKey: b64(k.privateKey) }; };
const seal = (msg, pk) => b64(sodium.crypto_box_seal(typeof msg === "string" ? sodium.from_string(msg) : msg, unb64(pk)));
const open = (box, kp) => sodium.crypto_box_seal_open(unb64(box), unb64(kp.publicKey), unb64(kp.secretKey));
for (const file of ["001_auth.sql", "002_credshare.sql", "005_machine_keys.sql", "007_hardening.sql"]) {
if (isPostgres && file === "001_auth.sql") { await db.execute("DROP SCHEMA public CASCADE"); await db.execute("CREATE SCHEMA public"); }
const sql = readFileSync(join(here, "..", "src", isPostgres ? "migrations-pg" : "migrations", file), "utf8");
for (const statement of sql.split(/;\s*$/m).map((s) => s.trim()).filter(Boolean)) await db.execute(statement);
}
const now = Date.now();
const ann = keypair();
await run(`INSERT INTO users (id, email, created_at) VALUES (?,?,?)`, ["u_ann", "ann@example.com", now]);
await run(`INSERT INTO users (id, email, created_at) VALUES (?,?,?)`, ["u_new", "new@example.com", now]);
await run(`INSERT INTO credshare_keys (user_id, public_key, updated_at) VALUES (?,?,?)`, ["u_ann", ann.publicKey, now]);
await run(`INSERT INTO credshare_teams (id, slug, name, created_by, created_at) VALUES (?,?,?,?,?)`, ["t_acme", "acme", "acme", "u_ann", now]);
await run(`INSERT INTO credshare_members (id, team_id, user_id, email, role, status, created_at) VALUES (?,?,?,?,?,?,?)`, ["m_ann", "t_acme", "u_ann", "ann@example.com", "owner", "active", now]);
await run(`INSERT INTO credshare_members (id, team_id, user_id, email, role, status, created_at) VALUES (?,?,?,?,?,?,?)`, ["m_new", "t_acme", "u_new", "new@example.com", "member", "active", now]);
const dek = sodium.randombytes_buf(32);
for (const v of ["v_web", "v_api"]) {
await run(`INSERT INTO credshare_vaults (id, team_id, name, created_by, created_at) VALUES (?,?,?,?,?)`, [v, "t_acme", v === "v_web" ? "web--prod" : "api--prod", "u_ann", now]);
await run(`INSERT INTO credshare_vault_grants (vault_id, user_id, wrapped_dek, granted_by, created_at) VALUES (?,?,?,?,?)`, [v, "u_ann", seal(dek, ann.publicKey), "u_ann", now]);
}
const app = express();
app.set("trust proxy", 1);
app.use(securityHeaders);
app.use(express.json());
app.use(cookieParser());
app.use(sessionMiddleware);
app.post("/test/session", async (_req, res) => { await createSession(res, "u_ann"); res.json({ ok: true }); });
app.get("/test/whoami", (req, res) => res.json({ user: req.user?.id ?? null }));
app.use(credshareRouter);
const server = app.listen(0);
await new Promise((r) => server.once("listening", r));
const base = `http://127.0.0.1:${server.address().port}`;
const call = async (method, path, token, body, headers = {}) => {
const h = { accept: "application/json", ...headers };
if (token) h.authorization = `Bearer ${token}`;
if (body !== undefined) h["content-type"] = "application/json";
const res = await fetch(`${base}${path}`, { method, headers: h, body: body === undefined ? undefined : JSON.stringify(body) });
const text = await res.text();
let parsed = null; try { parsed = text ? JSON.parse(text) : null; } catch { parsed = text; }
return { status: res.status, body: parsed, headers: res.headers };
};
test.after(() => new Promise((r) => server.close(r)));
const { plaintext: annToken } = await createApiKey("u_ann", "cli");
const { plaintext: newToken } = await createApiKey("u_new", "cli");
test("a stolen token cannot replace a registered identity key", async () => {
const attacker = keypair();
const r = await call("POST", "/api/credshare/keys", annToken, { publicKey: attacker.publicKey });
assert.equal(r.status, 409);
assert.equal(r.body.code, "identity_key_mismatch");
assert.equal((await get(`SELECT public_key FROM credshare_keys WHERE user_id = ?`, ["u_ann"])).public_key, ann.publicKey);
// re-registering the SAME key is still fine
assert.equal((await call("POST", "/api/credshare/keys", annToken, { publicKey: ann.publicKey })).status, 200);
});
test("a first key still registers, and is audited", async () => {
const k = keypair();
const r = await call("POST", "/api/credshare/keys", newToken, { publicKey: k.publicKey }, { "x-forwarded-for": "203.0.113.9" });
assert.equal(r.status, 200);
assert.equal(r.body.fingerprint, keyFingerprint(k.publicKey));
const row = await get(`SELECT * FROM credshare_audit WHERE action = 'identity:register' AND actor_user_id = 'u_new'`);
assert.ok(row);
});
test("rotation needs the answer sealed to the CURRENT key, and the challenge burns on a wrong guess", async () => {
const ch = (await call("POST", "/api/credshare/keys/challenge", annToken)).body;
const next = keypair();
const grants = (await call("GET", "/api/credshare/me/grants", annToken)).body.grants;
const bad = await call("POST", "/api/credshare/keys/rotate", annToken, { publicKey: next.publicKey, challengeId: ch.challengeId, answer: "guess", grants: [] });
assert.equal(bad.status, 403);
// the real answer no longer works on the burned challenge
const answer = sodium.to_string(open(ch.sealed, ann));
const reuse = await call("POST", "/api/credshare/keys/rotate", annToken, { publicKey: next.publicKey, challengeId: ch.challengeId, answer, grants: grants.map((g) => ({ vaultId: g.vaultId, wrappedDek: seal(open(g.wrappedDek, ann), next.publicKey) })) });
assert.equal(reuse.status, 403);
assert.equal((await get(`SELECT public_key FROM credshare_keys WHERE user_id = ?`, ["u_ann"])).public_key, ann.publicKey);
});
test("rotation must re-seal every grant, then swaps key and grants together", async () => {
const next = keypair();
const grants = (await call("GET", "/api/credshare/me/grants", annToken)).body.grants;
assert.equal(grants.length, 2);
let ch = (await call("POST", "/api/credshare/keys/challenge", annToken)).body;
let answer = sodium.to_string(open(ch.sealed, ann));
const partial = await call("POST", "/api/credshare/keys/rotate", annToken, { publicKey: next.publicKey, challengeId: ch.challengeId, answer, grants: [{ vaultId: grants[0].vaultId, wrappedDek: seal(dek, next.publicKey) }] });
assert.equal(partial.status, 409);
assert.equal(partial.body.code, "grants_changed");
ch = (await call("POST", "/api/credshare/keys/challenge", annToken)).body;
answer = sodium.to_string(open(ch.sealed, ann));
const ok = await call("POST", "/api/credshare/keys/rotate", annToken, {
publicKey: next.publicKey, challengeId: ch.challengeId, answer,
grants: grants.map((g) => ({ vaultId: g.vaultId, wrappedDek: seal(open(g.wrappedDek, ann), next.publicKey) }))
});
assert.equal(ok.status, 200, JSON.stringify(ok.body));
assert.equal(ok.body.regranted, 2);
assert.equal((await get(`SELECT public_key FROM credshare_keys WHERE user_id = ?`, ["u_ann"])).public_key, next.publicKey);
for (const g of (await call("GET", "/api/credshare/me/grants", annToken)).body.grants) {
assert.deepEqual(open(g.wrappedDek, next), dek);
}
assert.ok(await get(`SELECT 1 FROM credshare_audit WHERE action = 'identity:rotate'`));
Object.assign(ann, next);
});
test("a person's grant read is audited with IP and user agent, and returns the key version", async () => {
const r = await call("GET", "/api/credshare/vaults/v_web/grant", annToken, undefined, { "x-forwarded-for": "35.241.182.141", "user-agent": "curl/8.0" });
assert.equal(r.status, 200);
assert.equal(r.body.keyVersion, 1);
const row = await get(`SELECT * FROM credshare_audit WHERE action = 'vault:read' AND vault_id = 'v_web' ORDER BY created_at DESC`);
assert.equal(row.ip, "35.241.182.141");
assert.equal(row.user_agent, "curl/8.0");
const listed = await call("GET", "/api/credshare/vaults/v_web/secrets", annToken);
assert.equal(listed.body.keyVersion, 1);
assert.ok(await get(`SELECT 1 FROM credshare_audit WHERE action = 'secrets:fetch' AND vault_id = 'v_web'`));
const trail = await call("GET", "/api/credshare/teams/acme/audit?vault=web--prod&limit=5", annToken);
assert.equal(trail.status, 200);
assert.ok(trail.body.audit.some((a) => a.ip === "35.241.182.141" && a.actor === "ann@example.com"));
});
test("a write naming a retired key version is refused", async () => {
await run(`UPDATE credshare_vaults SET key_version = 2 WHERE id = 'v_api'`);
const stale = await call("PUT", "/api/credshare/vaults/v_api/secrets", annToken, { keyVersion: 1, upserts: [{ name: "A", nonce: "n", ciphertext: "c", fingerprint: "f" }], deletes: [] });
assert.equal(stale.status, 409);
assert.equal(stale.body.code, "vault_rekeyed");
const fresh = await call("PUT", "/api/credshare/vaults/v_api/secrets", annToken, { keyVersion: 2, upserts: [{ name: "A", nonce: "n", ciphertext: "c", fingerprint: "f" }], deletes: [] });
assert.equal(fresh.status, 200);
});
test("members carry fingerprints", async () => {
const r = await call("GET", "/api/credshare/teams/acme/members", annToken);
const me = r.body.members.find((m) => m.email === "ann@example.com");
assert.equal(me.fingerprint, keyFingerprint(ann.publicKey));
assert.match(me.fingerprint, /^([0-9a-f]{4} ){7}[0-9a-f]{4}$/);
});
test("sessions are stored as sha256 of the cookie, and still sign in", async () => {
const r = await fetch(`${base}/test/session`, { method: "POST" });
const cookie = r.headers.getSetCookie().map((c) => c.split(";")[0]).find((c) => c.startsWith("mc_sess="));
const raw = decodeURIComponent(cookie.split("=")[1]);
assert.ok(await get(`SELECT 1 FROM sessions WHERE token = ?`, [sha256(raw)]));
assert.equal(await get(`SELECT 1 FROM sessions WHERE token = ?`, [raw]), null);
const who = await (await fetch(`${base}/test/whoami`, { headers: { cookie } })).json();
assert.equal(who.user, "u_ann");
});
test("security headers: CSP without inline script, HSTS, no framing, no referrer", async () => {
const r = await call("GET", "/api/credshare/me", annToken);
const csp = r.headers.get("content-security-policy");
assert.match(csp, /script-src 'self'/);
assert.doesNotMatch(csp, /script-src[^;]*unsafe-inline/);
assert.match(csp, /frame-ancestors 'none'/);
assert.match(r.headers.get("strict-transport-security"), /max-age=\d+/);
assert.equal(r.headers.get("referrer-policy"), "no-referrer");
assert.equal(r.headers.get("x-frame-options"), "DENY");
assert.equal(r.headers.get("cache-control"), "no-store");
});

View file

@ -29,7 +29,7 @@ async function migrate() {
await db.execute("DROP SCHEMA public CASCADE");
await db.execute("CREATE SCHEMA public");
}
for (const file of ["001_auth.sql", "002_credshare.sql", "005_machine_keys.sql"]) {
for (const file of ["001_auth.sql", "002_credshare.sql", "005_machine_keys.sql", "007_hardening.sql"]) {
const sql = readFileSync(join(here, "..", "src", isPostgres ? "migrations-pg" : "migrations", file), "utf8");
for (const statement of sql.split(/;\s*$/m).map((s) => s.trim()).filter(Boolean)) {
await db.execute(statement);

View file

@ -1,20 +1,26 @@
// The sign-in page carries the Profullstack footer (webring row + badges), and
// the refresh only ever swaps in a footer that still links the ring.
// The sign-in page carries the Profullstack footer (webring row + badges), from
// the template bundled in the pinned package only: nothing is fetched at runtime.
import assert from "node:assert/strict";
import test from "node:test";
import { readFileSync } from "node:fs";
import { ringFooter, setRingFooter } from "../src/lib/ring-footer.mjs";
import * as ringFooterModule from "../src/lib/ring-footer.mjs";
test("the bundled footer links the ring and both badges for app.logicsrc.com", () => {
const html = ringFooter();
const html = ringFooterModule.ringFooter();
assert.match(html, /rssamplifier\.com\/ring\/profullstack/);
assert.match(html, /built\.indie\.pit\.world/);
assert.match(html, /pwamart\.com\/for\.svg\?site=https%3A%2F%2Fapp\.logicsrc\.com%2F|pwamart\.com\/for\.svg\?site=https:\/\/app\.logicsrc\.com\//);
});
test("a refresh without the ring row is ignored", () => {
const before = ringFooter();
assert.equal(setRingFooter("<footer>nope</footer>"), false);
assert.equal(setRingFooter(undefined), false);
assert.equal(ringFooter(), before);
test("the footer cannot be swapped at runtime (no CDN refresh)", () => {
assert.equal("setRingFooter" in ringFooterModule, false);
assert.equal("startRingFooterRefresh" in ringFooterModule, false);
const src = readFileSync(new URL("../src/lib/ring-footer.mjs", import.meta.url), "utf8");
assert.doesNotMatch(src, /footerHtml\(/);
});
test("the footer package is pinned to an exact version", () => {
const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
assert.match(pkg.dependencies["@profullstack/footer"], /^\d+\.\d+\.\d+$/);
});

View file

@ -21,7 +21,7 @@ if (isPostgres) {
await db.execute("DROP SCHEMA public CASCADE");
await db.execute("CREATE SCHEMA public");
}
for (const file of ["001_auth.sql", "002_credshare.sql", "005_machine_keys.sql"]) {
for (const file of ["001_auth.sql", "002_credshare.sql", "005_machine_keys.sql", "007_hardening.sql"]) {
const sql = readFileSync(join(here, "..", "src", isPostgres ? "migrations-pg" : "migrations", file), "utf8");
for (const statement of sql.split(/;\s*$/m).map((s) => s.trim()).filter(Boolean)) await db.execute(statement);
}

View file

@ -23,7 +23,7 @@ async function migrate() {
await db.execute("DROP SCHEMA public CASCADE");
await db.execute("CREATE SCHEMA public");
}
for (const file of ["001_auth.sql", "002_credshare.sql", "005_machine_keys.sql"]) {
for (const file of ["001_auth.sql", "002_credshare.sql", "005_machine_keys.sql", "007_hardening.sql"]) {
const sql = readFileSync(join(here, "..", "src", isPostgres ? "migrations-pg" : "migrations", file), "utf8");
for (const statement of sql.split(/;\s*$/m).map((s) => s.trim()).filter(Boolean)) {
await db.execute(statement);