mirror of
https://github.com/profullstack/logicsrc.git
synced 2026-11-29 15:51:52 +00:00
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:
parent
18477340e7
commit
ae6298851b
34 changed files with 1633 additions and 112 deletions
|
|
@ -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
8
apps/pwa/public/app.js
Normal 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
44
apps/pwa/public/pins.js
Normal 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();
|
||||
})();
|
||||
|
|
@ -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>`;
|
||||
}
|
||||
|
|
|
|||
23
apps/pwa/src/lib/keyfp.mjs
Normal file
23
apps/pwa/src/lib/keyfp.mjs
Normal 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 };
|
||||
}
|
||||
|
|
@ -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);
|
||||
}
|
||||
|
|
|
|||
42
apps/pwa/src/lib/security-headers.mjs
Normal file
42
apps/pwa/src/lib/security-headers.mjs
Normal 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();
|
||||
}
|
||||
|
|
@ -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());
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
31
apps/pwa/src/migrations-pg/007_hardening.sql
Normal file
31
apps/pwa/src/migrations-pg/007_hardening.sql
Normal 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;
|
||||
32
apps/pwa/src/migrations/007_hardening.sql
Normal file
32
apps/pwa/src/migrations/007_hardening.sql
Normal 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;
|
||||
|
|
@ -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 });
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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 } });
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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)} <project> <env></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");
|
||||
|
|
|
|||
|
|
@ -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); });
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
188
apps/pwa/test/identity-hardening.test.mjs
Normal file
188
apps/pwa/test/identity-hardening.test.mjs
Normal 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");
|
||||
});
|
||||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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+$/);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
8
bun.lock
8
bun.lock
|
|
@ -82,7 +82,7 @@
|
|||
"name": "@logicsrc/pwa",
|
||||
"version": "0.1.1",
|
||||
"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",
|
||||
|
|
@ -147,7 +147,7 @@
|
|||
},
|
||||
"packages/cli": {
|
||||
"name": "@logicsrc/cli",
|
||||
"version": "0.9.0",
|
||||
"version": "0.10.0",
|
||||
"bin": {
|
||||
"logicsrc": "./dist/index.js",
|
||||
},
|
||||
|
|
@ -754,7 +754,7 @@
|
|||
|
||||
"@profullstack/emailer": ["@profullstack/emailer@1.0.3", "", {}, "sha512-VyAtCcfnSI6LOwJvWogCr3ZNmEsaZw+iuWrqnosLsdcKsbRyCrCmXigMNZJZEjlgYlR+lK//PwNPG+xtCFvWAw=="],
|
||||
|
||||
"@profullstack/footer": ["@profullstack/footer@0.4.0", "", { "peerDependencies": { "react": ">=18" }, "optionalPeers": ["react"], "bin": { "profullstack-footer": "bin/profullstack-footer.js" } }, "sha512-EJZnMUQmWDi9Gzx6BAjogloeaPFFSSCHtHJuC9dsXiOz8M87hfn6Z+Zx9AMYWk8s6xemPrPlkXKGB3PZugkcEA=="],
|
||||
"@profullstack/footer": ["@profullstack/footer@0.5.0", "", { "peerDependencies": { "react": ">=18" }, "optionalPeers": ["react"], "bin": { "profullstack-footer": "bin/profullstack-footer.js" } }, "sha512-TrllS87nK7J0c/UgYckaFIWVhLOtr6m73XXFSHIuSfOg7NfuWUdwjtsfMXGaZiiUnmMYj3zhGcfzW0DicDwl8w=="],
|
||||
|
||||
"@profullstack/form-guard": ["@profullstack/form-guard@0.1.1", "", {}, "sha512-RGLGfQhjq40f+JqEhSmsJnS0I5sFWjYdrYx4VYtkUqz8xvioN2yyR+6uFK0mnDAStKrYytlngg3meUsrChm/OQ=="],
|
||||
|
||||
|
|
@ -1446,6 +1446,8 @@
|
|||
|
||||
"@logicsrc/openmcp/@profullstack/footer": ["@profullstack/footer@0.2.6", "", { "peerDependencies": { "react": ">=18" }, "optionalPeers": ["react"], "bin": { "profullstack-footer": "bin/profullstack-footer.js" } }, "sha512-BKwbDszAc7e0mYIBiPjgr/5WS8WyDt8IW718s/zW/8pCWOIB1BGwSNs6fmImRSo5kqIjQKUVbXp22jZQ5GEipA=="],
|
||||
|
||||
"@logicsrc/web/@profullstack/footer": ["@profullstack/footer@0.4.0", "", { "peerDependencies": { "react": ">=18" }, "optionalPeers": ["react"], "bin": { "profullstack-footer": "bin/profullstack-footer.js" } }, "sha512-EJZnMUQmWDi9Gzx6BAjogloeaPFFSSCHtHJuC9dsXiOz8M87hfn6Z+Zx9AMYWk8s6xemPrPlkXKGB3PZugkcEA=="],
|
||||
|
||||
"@modelcontextprotocol/sdk/content-type": ["content-type@1.0.5", "", {}, "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA=="],
|
||||
|
||||
"@profullstack/libsql-pg/@libsql/client": ["@libsql/client@0.15.15", "", { "dependencies": { "@libsql/core": "^0.15.14", "@libsql/hrana-client": "^0.7.0", "js-base64": "^3.7.5", "libsql": "^0.5.22", "promise-limit": "^2.7.0" } }, "sha512-twC0hQxPNHPKfeOv3sNT6u2pturQjLcI+CnpTM0SjRpocEGgfiZ7DWKXLNnsothjyJmDqEsBQJ5ztq9Wlu470w=="],
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@logicsrc/cli",
|
||||
"version": "0.9.0",
|
||||
"version": "0.10.0",
|
||||
"description": "LogicSRC CLI: every LogicSRC standard and tool as one command.",
|
||||
"type": "module",
|
||||
"main": "./dist/index.js",
|
||||
|
|
|
|||
183
packages/cli/src/hardening.test.ts
Normal file
183
packages/cli/src/hardening.test.ts
Normal file
|
|
@ -0,0 +1,183 @@
|
|||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import type { Server } from "node:http";
|
||||
|
||||
/**
|
||||
* The post-incident flow end to end against the real credentials-app routes on
|
||||
* an in-memory database:
|
||||
*
|
||||
* rotate-identity new keypair, every grant re-sealed, proof of the old key
|
||||
* rekey new vault key, values unchanged, members + machine keys re-sealed
|
||||
* race a value written under the retired key is re-sealed by the verify pass
|
||||
* pins a teammate's changed key is refused until accepted
|
||||
* login a different local key is refused instead of replacing the registered one
|
||||
*/
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const pwa = (rel: string) => pathToFileURL(join(here, "..", "..", "..", "apps", "pwa", "src", rel)).href;
|
||||
|
||||
type Db = { execute(stmt: string | { sql: string; args: unknown[] }): Promise<{ rows: Array<Record<string, unknown>> }> };
|
||||
let db: Db;
|
||||
let server: Server;
|
||||
let base = "";
|
||||
let annToken = "";
|
||||
let bobToken = "";
|
||||
const scratch = mkdtempSync(join(process.env.LOGICSRC_TEST_TMP || tmpdir(), "logicsrc-hardening-"));
|
||||
const annHome = join(scratch, "ann");
|
||||
const bobHome = join(scratch, "bob");
|
||||
const otherHome = join(scratch, "ann-other-machine");
|
||||
const saved = { ...process.env };
|
||||
|
||||
const as = (home: string) => {
|
||||
process.env.LOGICSRC_HOME = home;
|
||||
delete process.env.LOGICSRC_API_KEY;
|
||||
};
|
||||
const identityOf = (home: string) => JSON.parse(readFileSync(join(home, "identity.json"), "utf8"));
|
||||
const envFile = (name: string, body: string) => {
|
||||
const p = join(scratch, name);
|
||||
writeFileSync(p, body);
|
||||
return p;
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
process.env.DATABASE_URL = ":memory:";
|
||||
delete process.env.LOGICSRC_IDENTITY_FILE;
|
||||
({ db } = (await import(pwa("db.mjs"))) as { db: Db });
|
||||
for (const file of ["001_auth.sql", "002_credshare.sql", "005_machine_keys.sql", "007_hardening.sql"]) {
|
||||
const sql = readFileSync(fileURLToPath(pwa(join("migrations", file))), "utf8");
|
||||
for (const statement of sql.split(/;\s*$/m).map((s) => s.trim()).filter(Boolean)) await db.execute(statement);
|
||||
}
|
||||
for (const [id, email] of [["u_ann", "ann@example.com"], ["u_bob", "bob@example.com"]]) {
|
||||
await db.execute({ sql: "INSERT INTO users (id, email, created_at) VALUES (?,?,?)", args: [id, email, Date.now()] });
|
||||
}
|
||||
const expressModule = "express";
|
||||
const { default: express } = (await import(expressModule)) as { default: any };
|
||||
const { credshareRouter } = await import(pwa("routes/credshare.mjs"));
|
||||
const { apiKeysRouter } = await import(pwa("routes/apikeys.mjs"));
|
||||
const { createApiKey } = await import(pwa("lib/apikey.mjs"));
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use(credshareRouter);
|
||||
app.use(apiKeysRouter);
|
||||
server = app.listen(0);
|
||||
await new Promise((resolve) => server.once("listening", resolve));
|
||||
base = `http://127.0.0.1:${(server.address() as { port: number }).port}`;
|
||||
process.env.LOGICSRC_API = base;
|
||||
annToken = (await createApiKey("u_ann", "ann-laptop")).plaintext;
|
||||
bobToken = (await createApiKey("u_bob", "bob-laptop")).plaintext;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await new Promise((resolve) => server?.close(resolve));
|
||||
for (const key of Object.keys(process.env)) if (!(key in saved)) delete process.env[key];
|
||||
Object.assign(process.env, saved);
|
||||
rmSync(scratch, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("identity rotation, re-key and key pinning", () => {
|
||||
it("sets up: ann and bob log in, ann pushes two vaults and grants bob one", async () => {
|
||||
const { loginAction, teamsPushAction, teamsGrantAction } = await import("./teams.js");
|
||||
const { TeamClient } = await import("@logicsrc/plugin-credential-sharing");
|
||||
as(bobHome);
|
||||
await loginAction({ token: bobToken });
|
||||
as(annHome);
|
||||
await loginAction({ token: annToken });
|
||||
const ann = new TeamClient({ apiUrl: base, token: annToken });
|
||||
await ann.createTeam("acme");
|
||||
const invite = await ann.invite("acme", "bob@example.com");
|
||||
await new TeamClient({ apiUrl: base, token: bobToken }).acceptInvite(invite.token!);
|
||||
await teamsPushAction("acme", "web", "prod", { env: envFile("web.env", "A=1\nB=two\n"), format: "json" });
|
||||
await teamsPushAction("acme", "api", "prod", { env: envFile("api.env", "C=3\n"), format: "json" });
|
||||
await teamsGrantAction("acme", "web", "prod", "bob@example.com", "json");
|
||||
const pins = JSON.parse(readFileSync(join(annHome, "known-keys.json"), "utf8"));
|
||||
expect(Object.keys(pins.keys).some((k) => k.endsWith("|bob@example.com"))).toBe(true);
|
||||
expect(statSync(join(annHome, "known-keys.json")).mode & 0o777).toBe(0o600);
|
||||
});
|
||||
|
||||
it("a login on another machine cannot replace ann's registered key", async () => {
|
||||
const { loginAction } = await import("./teams.js");
|
||||
const before = identityOf(annHome).keys.publicKey;
|
||||
as(otherHome);
|
||||
await expect(loginAction({ token: annToken })).rejects.toThrow(/not the registered one/);
|
||||
const r = await db.execute({ sql: "SELECT public_key FROM credshare_keys WHERE user_id = ?", args: ["u_ann"] });
|
||||
expect(r.rows[0]?.public_key).toBe(before);
|
||||
});
|
||||
|
||||
it("rotate-identity swaps ann's key and every grant, and she can still pull", async () => {
|
||||
const { teamsRotateIdentityAction } = await import("./hardening.js");
|
||||
const { teamsPullAction } = await import("./teams.js");
|
||||
as(annHome);
|
||||
const before = identityOf(annHome).keys.publicKey;
|
||||
await teamsRotateIdentityAction({ format: "json" });
|
||||
const after = identityOf(annHome).keys.publicKey;
|
||||
expect(after).not.toBe(before);
|
||||
expect(statSync(join(annHome, "identity.json")).mode & 0o777).toBe(0o600);
|
||||
const r = await db.execute({ sql: "SELECT public_key FROM credshare_keys WHERE user_id = ?", args: ["u_ann"] });
|
||||
expect(r.rows[0]?.public_key).toBe(after);
|
||||
const out = join(scratch, "web-after-rotate.env");
|
||||
await teamsPullAction("acme", "web", "prod", { env: out, format: "json" });
|
||||
expect(readFileSync(out, "utf8")).toMatch(/B=two/);
|
||||
});
|
||||
|
||||
it("bob's CLI refuses to seal to ann's changed key until he accepts it", async () => {
|
||||
const { teamsGrantAction } = await import("./teams.js");
|
||||
as(bobHome);
|
||||
// bob pins ann's (old) key the first time he sees it...
|
||||
const { checkAndPinKey } = await import("@logicsrc/plugin-credential-sharing");
|
||||
checkAndPinKey(base, "ann@example.com", "B".repeat(43) + "=");
|
||||
// ...so the rotated key is a change.
|
||||
await expect(teamsGrantAction("acme", "web", "prod", "ann@example.com", "json")).rejects.toThrow(/CHANGED/);
|
||||
await teamsGrantAction("acme", "web", "prod", "ann@example.com", "json", { acceptKeyChange: ["ann@example.com"] });
|
||||
});
|
||||
|
||||
it("rekey --all changes every vault key, keeps the values, and keeps bob", async () => {
|
||||
const { teamsRekeyAction } = await import("./hardening.js");
|
||||
const { teamsPullAction } = await import("./teams.js");
|
||||
as(annHome);
|
||||
const grantsBefore = await db.execute({ sql: "SELECT vault_id, user_id, wrapped_dek FROM credshare_vault_grants ORDER BY vault_id, user_id", args: [] });
|
||||
await teamsRekeyAction("acme", undefined, undefined, { all: true, format: "json" });
|
||||
const grantsAfter = await db.execute({ sql: "SELECT vault_id, user_id, wrapped_dek FROM credshare_vault_grants ORDER BY vault_id, user_id", args: [] });
|
||||
expect(grantsAfter.rows.length).toBe(grantsBefore.rows.length);
|
||||
for (let i = 0; i < grantsAfter.rows.length; i++) expect(grantsAfter.rows[i]!.wrapped_dek).not.toBe(grantsBefore.rows[i]!.wrapped_dek);
|
||||
const versions = await db.execute({ sql: "SELECT key_version FROM credshare_vaults", args: [] });
|
||||
expect(versions.rows.every((r) => Number(r.key_version) === 2)).toBe(true);
|
||||
as(bobHome);
|
||||
const out = join(scratch, "bob-web.env");
|
||||
await teamsPullAction("acme", "web", "prod", { env: out, format: "json" });
|
||||
expect(readFileSync(out, "utf8")).toMatch(/A=1/);
|
||||
});
|
||||
|
||||
it("a value written under the retired key during a re-key is re-sealed, not lost", async () => {
|
||||
const { teamsRekeyAction, verifyAndRepair } = await import("./hardening.js");
|
||||
const { teamsPullAction } = await import("./teams.js");
|
||||
const { TeamClient, unwrapVaultKey, encryptValue, fingerprintValue } = await import("@logicsrc/plugin-credential-sharing");
|
||||
as(annHome);
|
||||
const ann = identityOf(annHome);
|
||||
const client = new TeamClient({ apiUrl: base, token: annToken });
|
||||
const { vaults } = await client.listVaults("acme");
|
||||
const web = vaults.find((v) => v.name === "web--prod")!;
|
||||
// An old client: read the key now, write after the re-key, sending no key version.
|
||||
const staleDek = await unwrapVaultKey((await client.getMyGrant(web.id)).wrappedDek, ann.keys);
|
||||
await teamsRekeyAction("acme", "web", "prod", { format: "json" });
|
||||
const sealed = await encryptValue("late-value", staleDek);
|
||||
await client.putSecrets(web.id, [{ name: "LATE", ...sealed, fingerprint: fingerprintValue("late-value") }], []);
|
||||
// The verify pass a re-key run ends with re-seals it under the current key.
|
||||
const fixed = await verifyAndRepair(client, ann.keys, { vaultId: web.id, vault: web.name, oldDeks: [staleDek] });
|
||||
expect(fixed.repaired).toBe(1);
|
||||
expect(fixed.unreadable).toEqual([]);
|
||||
const out = join(scratch, "web-late.env");
|
||||
await teamsPullAction("acme", "web", "prod", { env: out, format: "json" });
|
||||
expect(readFileSync(out, "utf8")).toMatch(/LATE=late-value/);
|
||||
});
|
||||
|
||||
it("the audit trail records the reads with the acting user", async () => {
|
||||
const { TeamClient } = await import("@logicsrc/plugin-credential-sharing");
|
||||
const { audit } = await new TeamClient({ apiUrl: base, token: annToken }).teamAudit("acme", { action: "vault:read" });
|
||||
expect(audit.some((a) => a.actor === "bob@example.com" && a.vault === "web--prod")).toBe(true);
|
||||
const rot = await new TeamClient({ apiUrl: base, token: annToken }).teamAudit("acme", { action: "identity:rotate" });
|
||||
expect(rot.audit.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
404
packages/cli/src/hardening.ts
Normal file
404
packages/cli/src/hardening.ts
Normal file
|
|
@ -0,0 +1,404 @@
|
|||
import { existsSync, readFileSync, rmSync } from "node:fs";
|
||||
import {
|
||||
TeamApiError,
|
||||
checkAndPinKey,
|
||||
decryptValue,
|
||||
encryptValue,
|
||||
fingerprintValue,
|
||||
fingerprintsEqual,
|
||||
generateIdentityKeyPair,
|
||||
identityPath,
|
||||
keyFingerprint,
|
||||
planVaultRekey,
|
||||
publicKeyForSecret,
|
||||
readIdentity,
|
||||
repinKey,
|
||||
resolveApiUrl,
|
||||
saveIdentity,
|
||||
unwrapVaultKey,
|
||||
wrapVaultKey,
|
||||
type RemoteVault,
|
||||
type TeamClient
|
||||
} from "@logicsrc/plugin-credential-sharing";
|
||||
import { authedClient, splitVaultName, vaultName } from "./teams.js";
|
||||
import { print, type OutputFormat } from "./format.js";
|
||||
|
||||
/**
|
||||
* Post-incident commands (2026-10-28): rotate your identity key, re-key vaults,
|
||||
* read the audit trail, and import an identity copied from another machine.
|
||||
*
|
||||
* All crypto stays on this machine. The server sees public keys, sealed boxes
|
||||
* and ciphertext only, as everywhere else in `logicsrc teams`.
|
||||
*/
|
||||
|
||||
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
const b64ToUtf8 = (b64: string) => Buffer.from(b64, "base64").toString("utf8");
|
||||
|
||||
function personClient() {
|
||||
const { client, identity } = authedClient();
|
||||
if (identity.keyKind === "machine") {
|
||||
throw new Error("This needs a person's login (logicsrc login), not a machine API key.");
|
||||
}
|
||||
return { client, identity, apiUrl: resolveApiUrl(identity) };
|
||||
}
|
||||
|
||||
/** The server's key must be the one this machine holds, or nothing here can work. */
|
||||
async function assertLocalKeyIsRegistered(client: TeamClient, publicKey: string): Promise<void> {
|
||||
const me = await client.me();
|
||||
if (me.user.publicKey !== publicKey) {
|
||||
throw new Error(
|
||||
`This machine's identity key (${keyFingerprint(publicKey)}) is not the one registered for ${me.user.email} (${keyFingerprint(me.user.publicKey) ?? "none"}). ` +
|
||||
"Run this on the machine that holds the registered key, or import it here: logicsrc teams key --import"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- rotate-identity
|
||||
|
||||
export async function teamsRotateIdentityAction(options: { format: OutputFormat }): Promise<void> {
|
||||
const { client, identity, apiUrl } = personClient();
|
||||
if (!identity.keys?.secretKey || (await publicKeyForSecret(identity.keys.secretKey)) !== identity.keys.publicKey) {
|
||||
throw new Error(`${identityPath()} is missing or damaged; cannot prove the current key.`);
|
||||
}
|
||||
await assertLocalKeyIsRegistered(client, identity.keys.publicKey);
|
||||
|
||||
const next = await generateIdentityKeyPair();
|
||||
// Keep the new key on disk BEFORE the server switches to it: if this process
|
||||
// dies between the server's commit and the local write, the key is not lost.
|
||||
const pending = `${identityPath()}.next`;
|
||||
saveIdentity({ ...identity, keys: next }, pending);
|
||||
|
||||
let result: Awaited<ReturnType<TeamClient["rotateIdentity"]>> | undefined;
|
||||
for (let attempt = 1; attempt <= 3 && !result; attempt++) {
|
||||
const { grants } = await client.myGrants();
|
||||
const resealed: Array<{ vaultId: string; wrappedDek: string }> = [];
|
||||
for (const g of grants) {
|
||||
const dek = await unwrapVaultKey(g.wrappedDek, identity.keys);
|
||||
resealed.push({ vaultId: g.vaultId, wrappedDek: await wrapVaultKey(dek, next.publicKey) });
|
||||
}
|
||||
const challenge = await client.identityChallenge();
|
||||
const answer = b64ToUtf8(await unwrapVaultKey(challenge.sealed, identity.keys));
|
||||
try {
|
||||
result = await client.rotateIdentity({ publicKey: next.publicKey, challengeId: challenge.challengeId, answer, grants: resealed });
|
||||
} catch (error) {
|
||||
// A grant added or removed while we were re-sealing: read them again.
|
||||
if (error instanceof TeamApiError && error.status === 409 && attempt < 3) { await sleep(500); continue; }
|
||||
rmSync(pending, { force: true });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
if (!result) {
|
||||
rmSync(pending, { force: true });
|
||||
throw new Error("Identity rotation did not complete; nothing changed.");
|
||||
}
|
||||
|
||||
const stored = readIdentity() ?? identity;
|
||||
saveIdentity({ ...stored, keys: next });
|
||||
rmSync(pending, { force: true });
|
||||
repinKey(apiUrl, identity.email, next.publicKey);
|
||||
|
||||
console.error(
|
||||
`Rotated your identity key: ${result.previousFingerprint} -> ${result.fingerprint}. Re-sealed ${result.regranted} vault grant(s). ` +
|
||||
`${identityPath()} now holds the new key (0600).`
|
||||
);
|
||||
console.error(
|
||||
"The vault keys themselves did not change. If the old secret key leaked, re-key the vaults now: logicsrc teams rekey <team> --all\n" +
|
||||
"Other machines with the old key must import the new one (logicsrc teams key here, then logicsrc teams key --import there). " +
|
||||
"Teammates will see your fingerprint change and must confirm it before granting you anything."
|
||||
);
|
||||
print({ previousFingerprint: result.previousFingerprint, fingerprint: result.fingerprint, regranted: result.regranted }, options.format);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ key import
|
||||
|
||||
export async function teamsKeyImportAction(options: { format: OutputFormat }): Promise<void> {
|
||||
const raw = readFileSync(0, "utf8").trim();
|
||||
if (!raw) throw new Error("Paste the identity secret key (or the whole identity.json) on stdin.");
|
||||
let secretKey = raw;
|
||||
if (raw.startsWith("{")) {
|
||||
const parsed = JSON.parse(raw) as { keys?: { secretKey?: string }; secretKey?: string };
|
||||
secretKey = parsed.keys?.secretKey ?? parsed.secretKey ?? "";
|
||||
}
|
||||
if (!/^[A-Za-z0-9+/]{43}=$/.test(secretKey)) throw new Error("That is not a base64 X25519 secret key.");
|
||||
const publicKey = await publicKeyForSecret(secretKey);
|
||||
const current = readIdentity();
|
||||
if (current?.apiToken) {
|
||||
const { client } = authedClient();
|
||||
const me = await client.me();
|
||||
if (me.user.publicKey && me.user.publicKey !== publicKey) {
|
||||
throw new Error(
|
||||
`That key (${keyFingerprint(publicKey)}) is not the one registered for ${me.user.email} (${keyFingerprint(me.user.publicKey)}). Nothing written.`
|
||||
);
|
||||
}
|
||||
if (!me.user.publicKey) await client.uploadPublicKey(publicKey);
|
||||
}
|
||||
if (current?.keys?.secretKey && current.keys.publicKey !== publicKey && existsSync(identityPath())) {
|
||||
console.error(`Replacing this machine's previous identity key (${keyFingerprint(current.keys.publicKey)}).`);
|
||||
}
|
||||
saveIdentity({ ...(current ?? { createdAt: new Date().toISOString() }), keys: { publicKey, secretKey } } as Parameters<typeof saveIdentity>[0]);
|
||||
console.error(`Imported identity key ${keyFingerprint(publicKey)} into ${identityPath()} (0600).`);
|
||||
print({ fingerprint: keyFingerprint(publicKey), file: identityPath() }, options.format);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------- rekey
|
||||
|
||||
export interface RekeyOptions {
|
||||
all?: boolean;
|
||||
acceptKeyChange?: string[];
|
||||
concurrency?: number;
|
||||
dryRun?: boolean;
|
||||
format: OutputFormat;
|
||||
}
|
||||
|
||||
interface RekeyOutcome {
|
||||
vault: string;
|
||||
status: "rekeyed" | "planned" | "skipped" | "failed";
|
||||
secrets?: number;
|
||||
members?: number;
|
||||
machineKeys?: number;
|
||||
keysDropped?: string[];
|
||||
repaired?: number;
|
||||
unreadable?: string[];
|
||||
keyVersion?: number;
|
||||
note?: string;
|
||||
}
|
||||
|
||||
interface Retired {
|
||||
vaultId: string;
|
||||
vault: string;
|
||||
oldDeks: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Check every secret opens under the vault's CURRENT key. A value that does
|
||||
* not, but opens under a retired one, was pushed by a client that read the old
|
||||
* key just before the re-key: re-seal it under the current key. Values never
|
||||
* change here (the fingerprint is checked both ways).
|
||||
*/
|
||||
export async function verifyAndRepair(client: TeamClient, identityKeys: { publicKey: string; secretKey: string }, retired: Retired) {
|
||||
const { wrappedDek, keyVersion } = await client.getMyGrant(retired.vaultId);
|
||||
const dek = await unwrapVaultKey(wrappedDek, identityKeys);
|
||||
const { secrets } = await client.listSecrets(retired.vaultId);
|
||||
const repairs: Array<{ name: string; nonce: string; ciphertext: string; fingerprint: string }> = [];
|
||||
const unreadable: string[] = [];
|
||||
for (const s of secrets) {
|
||||
let value: string | null = null;
|
||||
try {
|
||||
value = await decryptValue({ nonce: s.nonce, ciphertext: s.ciphertext }, dek);
|
||||
if (fingerprintsEqual(s.fingerprint, fingerprintValue(value))) continue;
|
||||
value = null;
|
||||
} catch { /* not under the current key */ }
|
||||
for (const old of retired.oldDeks) {
|
||||
try {
|
||||
const v = await decryptValue({ nonce: s.nonce, ciphertext: s.ciphertext }, old);
|
||||
if (fingerprintsEqual(s.fingerprint, fingerprintValue(v))) { value = v; break; }
|
||||
} catch { /* try the next */ }
|
||||
}
|
||||
if (value === null) { unreadable.push(s.name); continue; }
|
||||
const sealed = await encryptValue(value, dek);
|
||||
repairs.push({ name: s.name, nonce: sealed.nonce, ciphertext: sealed.ciphertext, fingerprint: fingerprintValue(value) });
|
||||
}
|
||||
if (repairs.length) await client.putSecrets(retired.vaultId, repairs, [], keyVersion);
|
||||
return { repaired: repairs.length, unreadable, secrets: secrets.length };
|
||||
}
|
||||
|
||||
async function rekeyOne(
|
||||
client: TeamClient,
|
||||
identity: { email: string; keys: { publicKey: string; secretKey: string } },
|
||||
apiUrl: string,
|
||||
v: RemoteVault,
|
||||
options: RekeyOptions,
|
||||
retiredOut: Retired[]
|
||||
): Promise<RekeyOutcome> {
|
||||
if (!v.hasAccess) return { vault: v.name, status: "skipped", note: "you hold no grant" };
|
||||
const accept = options.acceptKeyChange ?? [];
|
||||
const oldDeks: string[] = [];
|
||||
for (let attempt = 1; attempt <= 4; attempt++) {
|
||||
const [{ wrappedDek }, { secrets }, { grants }, { keyGrants }] = await Promise.all([
|
||||
client.getMyGrant(v.id),
|
||||
client.listSecrets(v.id),
|
||||
client.listGrants(v.id),
|
||||
client.listKeyGrants(v.id)
|
||||
]);
|
||||
// Seal only to keys this machine has pinned (or pins now, first use).
|
||||
for (const g of grants) {
|
||||
if (!g.hasAccess || !g.publicKey) continue;
|
||||
if (g.email.toLowerCase() === identity.email.toLowerCase()) {
|
||||
if (g.publicKey !== identity.keys.publicKey) throw new Error(`The server holds a different key for you (${keyFingerprint(g.publicKey)}) than this machine (${keyFingerprint(identity.keys.publicKey)}). Refusing to re-key.`);
|
||||
continue;
|
||||
}
|
||||
checkAndPinKey(apiUrl, g.email, g.publicKey, accept);
|
||||
}
|
||||
for (const k of keyGrants) {
|
||||
if (k.publicKey) checkAndPinKey(apiUrl, `key:${k.keyId}`, k.publicKey, accept.includes(k.name) || accept.includes(k.keyId) || accept.includes(`key:${k.keyId}`));
|
||||
}
|
||||
const oldDek = await unwrapVaultKey(wrappedDek, identity.keys);
|
||||
if (!oldDeks.includes(oldDek)) oldDeks.push(oldDek);
|
||||
const plan = await planVaultRekey({
|
||||
myWrappedDek: wrappedDek,
|
||||
identity: identity.keys,
|
||||
secrets: secrets.map((s) => ({ name: s.name, nonce: s.nonce, ciphertext: s.ciphertext, fingerprint: s.fingerprint })),
|
||||
members: grants.map((g) => ({ email: g.email, publicKey: g.publicKey, status: g.status, hasAccess: g.hasAccess })),
|
||||
scope: "all",
|
||||
machineKeys: keyGrants.map((k) => ({ keyId: k.keyId, name: k.name, owner: k.owner, publicKey: k.publicKey }))
|
||||
});
|
||||
if (options.dryRun) {
|
||||
return { vault: v.name, status: "planned", secrets: plan.secrets.length, members: plan.grants.length, machineKeys: plan.keyGrants.length, keysDropped: plan.keysDropped };
|
||||
}
|
||||
try {
|
||||
const result = await client.rekeyVault(v.id, { grants: plan.grants, secrets: plan.secrets, revoke: plan.revoked, keyGrants: plan.keyGrants });
|
||||
const retired = { vaultId: v.id, vault: v.name, oldDeks };
|
||||
retiredOut.push(retired);
|
||||
const check = await verifyAndRepair(client, identity.keys, retired);
|
||||
return {
|
||||
vault: v.name,
|
||||
status: "rekeyed",
|
||||
secrets: result.rekeyed,
|
||||
members: result.granted.length,
|
||||
machineKeys: result.keysResealed?.length ?? 0,
|
||||
keysDropped: result.keysDropped ?? [],
|
||||
repaired: check.repaired,
|
||||
unreadable: check.unreadable,
|
||||
keyVersion: result.keyVersion
|
||||
};
|
||||
} catch (error) {
|
||||
// 409: a push changed the vault between our read and the re-key. Read again.
|
||||
if (error instanceof TeamApiError && error.status === 409 && attempt < 4) { await sleep(400 * attempt); continue; }
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
return { vault: v.name, status: "failed", note: "kept changing under us" };
|
||||
}
|
||||
|
||||
async function mapLimit<T, R>(items: readonly T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]> {
|
||||
const out = new Array<R>(items.length);
|
||||
let next = 0;
|
||||
const worker = async () => {
|
||||
while (next < items.length) {
|
||||
const i = next++;
|
||||
out[i] = await fn(items[i]!);
|
||||
}
|
||||
};
|
||||
await Promise.all(Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, worker));
|
||||
return out;
|
||||
}
|
||||
|
||||
export async function teamsRekeyAction(slug: string, project: string | undefined, env: string | undefined, options: RekeyOptions): Promise<void> {
|
||||
const { client, identity, apiUrl } = personClient();
|
||||
await assertLocalKeyIsRegistered(client, identity.keys.publicKey);
|
||||
const { vaults } = await client.listVaults(slug);
|
||||
let selected: RemoteVault[];
|
||||
if (options.all) {
|
||||
if (project || env) throw new Error("Give <project> <env> or --all, not both.");
|
||||
selected = vaults;
|
||||
} else {
|
||||
if (!project || !env) throw new Error("Re-key which vault? Give <project> <env>, or --all for every vault you can open.");
|
||||
const name = vaultName(project, env);
|
||||
const found = vaults.find((v) => v.name === name);
|
||||
if (!found) throw new Error(`Vault "${name}" not found in team "${slug}".`);
|
||||
selected = [found];
|
||||
}
|
||||
|
||||
const retired: Retired[] = [];
|
||||
let done = 0;
|
||||
const outcomes = await mapLimit(selected, Math.max(1, Math.min(options.concurrency ?? 4, 8)), async (v) => {
|
||||
try {
|
||||
return await rekeyOne(client, identity, apiUrl, v, options, retired);
|
||||
} catch (error) {
|
||||
return { vault: v.name, status: "failed", note: error instanceof Error ? error.message.split("\n")[0] : String(error) } as RekeyOutcome;
|
||||
} finally {
|
||||
done++;
|
||||
if (selected.length > 1 && process.stderr.isTTY) process.stderr.write(`\r ${done}/${selected.length} vaults`);
|
||||
}
|
||||
});
|
||||
if (selected.length > 1 && process.stderr.isTTY) process.stderr.write("\n");
|
||||
|
||||
// A push that read the old key moments before a re-key can land after the
|
||||
// per-vault check. One more pass over everything re-keyed catches it.
|
||||
let lateRepairs = 0;
|
||||
if (!options.dryRun && retired.length) {
|
||||
await sleep(2000);
|
||||
const byVault = new Map(outcomes.map((o) => [o.vault, o]));
|
||||
await mapLimit(retired, Math.max(1, Math.min(options.concurrency ?? 4, 8)), async (r) => {
|
||||
try {
|
||||
const check = await verifyAndRepair(client, identity.keys, r);
|
||||
lateRepairs += check.repaired;
|
||||
const o = byVault.get(r.vault);
|
||||
if (o) { o.repaired = (o.repaired ?? 0) + check.repaired; o.unreadable = check.unreadable; }
|
||||
} catch (error) {
|
||||
const o = byVault.get(r.vault);
|
||||
if (o) o.note = `verify failed: ${error instanceof Error ? error.message : String(error)}`;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const count = (s: RekeyOutcome["status"]) => outcomes.filter((o) => o.status === s).length;
|
||||
const unreadable = outcomes.filter((o) => o.unreadable?.length);
|
||||
console.error(
|
||||
options.dryRun
|
||||
? `Dry run: ${count("planned")} vault(s) would be re-keyed, ${count("skipped")} skipped, ${count("failed")} cannot be.`
|
||||
: `Re-keyed ${count("rekeyed")} vault(s); ${count("skipped")} skipped (no grant), ${count("failed")} failed. ` +
|
||||
`Repaired ${outcomes.reduce((n, o) => n + (o.repaired ?? 0), 0)} value(s) written under a retired key (${lateRepairs} in the final pass).` +
|
||||
(unreadable.length ? ` ${unreadable.length} vault(s) hold values that open under no key we know: see "unreadable".` : "")
|
||||
);
|
||||
print(
|
||||
outcomes.map((o) => ({
|
||||
vault: o.vault,
|
||||
status: o.status,
|
||||
secrets: o.secrets ?? "",
|
||||
members: o.members ?? "",
|
||||
machineKeys: o.machineKeys ?? "",
|
||||
...(o.keysDropped?.length ? { keysDropped: o.keysDropped.join(",") } : {}),
|
||||
...(o.repaired ? { repaired: o.repaired } : {}),
|
||||
...(o.unreadable?.length ? { unreadable: o.unreadable.join(",") } : {}),
|
||||
...(o.note ? { note: o.note } : {})
|
||||
})),
|
||||
options.format
|
||||
);
|
||||
if (count("failed")) process.exitCode = 1;
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------- audit
|
||||
|
||||
function parseSince(value: string | undefined): number | undefined {
|
||||
if (!value) return undefined;
|
||||
const m = /^(\d+)\s*(m|h|d|w)$/i.exec(value.trim());
|
||||
if (m) return Date.now() - Number(m[1]) * { m: 60e3, h: 3600e3, d: 86400e3, w: 7 * 86400e3 }[m[2]!.toLowerCase() as "m"];
|
||||
const t = Date.parse(value);
|
||||
if (Number.isNaN(t)) throw new Error(`Cannot read --since "${value}". Use 24h, 7d, or a date.`);
|
||||
return t;
|
||||
}
|
||||
|
||||
export async function teamsAuditAction(
|
||||
slug: string,
|
||||
project: string | undefined,
|
||||
env: string | undefined,
|
||||
options: { actor?: string; action?: string; since?: string; limit?: string; format: OutputFormat }
|
||||
): Promise<void> {
|
||||
const { client } = authedClient();
|
||||
if (project && !env) throw new Error("Give both <project> and <env>, or neither.");
|
||||
const { audit } = await client.teamAudit(slug, {
|
||||
vault: project && env ? vaultName(project, env) : undefined,
|
||||
actor: options.actor,
|
||||
action: options.action,
|
||||
since: parseSince(options.since),
|
||||
limit: options.limit ? Number(options.limit) : 200
|
||||
});
|
||||
print(
|
||||
audit.length
|
||||
? audit.map((a) => ({
|
||||
at: new Date(a.at).toISOString().replace("T", " ").slice(0, 19),
|
||||
actor: a.actor ?? "?",
|
||||
via: a.apiKey ? `${a.apiKeyKind === "machine" ? "machine:" : ""}${a.apiKey}` : "",
|
||||
action: a.action,
|
||||
vault: a.vault ?? "",
|
||||
target: a.apiKey ? "" : (a.target ?? ""),
|
||||
ip: a.ip ?? "",
|
||||
userAgent: options.format === "table" ? (a.userAgent ?? "").slice(0, 40) : (a.userAgent ?? "")
|
||||
}))
|
||||
: [{ note: "No audit rows match." }],
|
||||
options.format
|
||||
);
|
||||
}
|
||||
|
||||
export { splitVaultName };
|
||||
|
|
@ -37,6 +37,7 @@ import { registerKeysCommands } from "./keys.js";
|
|||
import { sshAgentAction, sshListAction, sshPullAction, sshPushAction } from "./ssh.js";
|
||||
import { credentialsRotateAction } from "./rotate.js";
|
||||
import { teamsRotateKeysAction, teamsRotationAction, teamsRotationSetAction } from "./rotate-keys.js";
|
||||
import { teamsAuditAction, teamsKeyImportAction, teamsRekeyAction, teamsRotateIdentityAction } from "./hardening.js";
|
||||
import { boards, tasks } from "./fixtures.js";
|
||||
import { print, type OutputFormat } from "./format.js";
|
||||
import { parsePositiveInteger } from "./numeric-options.js";
|
||||
|
|
@ -742,6 +743,10 @@ Quick start (<team> is e.g. profullstack; see yours with "logicsrc teams list"):
|
|||
logicsrc teams push <team> <project> <env> ./.env -> vault
|
||||
logicsrc teams grant <team> <project> <env> dev@example.com
|
||||
logicsrc teams key your key, to read values in the web app
|
||||
logicsrc teams members <team> members + key fingerprints (pinned on first use)
|
||||
logicsrc teams audit <team> [project] [env] who read what, from where
|
||||
logicsrc teams rotate-identity new identity key, grants re-sealed
|
||||
logicsrc teams rekey <team> --all new vault keys, values re-encrypted
|
||||
logicsrc teams rotation <team> how each secret is rotated (agents: --format json)
|
||||
logicsrc teams rotate-keys <team> [project] [env] rotate values (dry run; --approve to write)
|
||||
|
||||
|
|
@ -978,9 +983,72 @@ there; the key is checked against your registered public key and never sent.
|
|||
Examples:
|
||||
logicsrc teams key print it
|
||||
logicsrc teams key | pbcopy straight to the clipboard (macOS; wl-copy / xclip on Linux)
|
||||
logicsrc teams key --import < key use a key copied from your other machine (must be the registered one)
|
||||
`
|
||||
)
|
||||
.action(() => teamsKeyAction());
|
||||
.option("--import", "Read an identity secret key (or identity.json) from stdin and use it on this machine")
|
||||
.option("--format <format>", "table, json, or markdown", "table")
|
||||
.action((options) => (options.import ? teamsKeyImportAction({ format: options.format as OutputFormat }) : teamsKeyAction()));
|
||||
|
||||
teams
|
||||
.command("rotate-identity")
|
||||
.option("--format <format>", "table, json, or markdown", "table")
|
||||
.description("Replace your identity key: new keypair, every vault grant re-sealed to it, registered with proof of the current key.")
|
||||
.addHelpText(
|
||||
"after",
|
||||
`
|
||||
Run it on the machine that holds your current key (the server seals a challenge
|
||||
to it). The vault keys are unchanged, so if the old secret key leaked, follow
|
||||
with: logicsrc teams rekey <team> --all
|
||||
Other machines then import the new key: logicsrc teams key | ssh other 'logicsrc teams key --import'`
|
||||
)
|
||||
.action((options) => teamsRotateIdentityAction({ format: options.format as OutputFormat }));
|
||||
|
||||
teams
|
||||
.command("rekey")
|
||||
.argument("<slug>", "Team slug")
|
||||
.argument("[project]", "Project name")
|
||||
.argument("[env]", "Environment name")
|
||||
.option("--all", "Every vault in the team you can open")
|
||||
.option("--accept-key-change <email>", "Seal to this member's (or machine key's) CHANGED key; repeat or comma-separate", collectList)
|
||||
.option("--concurrency <n>", "Vaults in flight at once (1-8)", "4")
|
||||
.option("--dry-run", "Plan only; change nothing")
|
||||
.option("--format <format>", "table, json, or markdown", "table")
|
||||
.description("New vault key: re-encrypt every value here, re-seal to every current member and machine key (pinned keys only).")
|
||||
.addHelpText(
|
||||
"after",
|
||||
`
|
||||
Values do not change. Everyone who holds the vault keeps it, under a fresh key;
|
||||
anyone holding only an OLD wrapped key (or the old key itself) loses it. A push
|
||||
racing the re-key is caught: the vault is re-checked afterwards and any value
|
||||
written under the retired key is re-sealed under the new one.
|
||||
|
||||
logicsrc teams rekey acme web prod
|
||||
logicsrc teams rekey acme --all --dry-run
|
||||
logicsrc teams rekey acme --all`
|
||||
)
|
||||
.action((slug, project, env, options) =>
|
||||
teamsRekeyAction(slug, project, env, {
|
||||
all: Boolean(options.all),
|
||||
acceptKeyChange: options.acceptKeyChange,
|
||||
concurrency: Number(options.concurrency) || 4,
|
||||
dryRun: Boolean(options.dryRun),
|
||||
format: options.format as OutputFormat
|
||||
})
|
||||
);
|
||||
|
||||
teams
|
||||
.command("audit")
|
||||
.argument("<slug>", "Team slug")
|
||||
.argument("[project]", "Project name (with env: one vault)")
|
||||
.argument("[env]", "Environment name")
|
||||
.option("--actor <email>", "Only this person")
|
||||
.option("--action <prefix>", "Only actions starting with this (vault:read, secrets:fetch, identity:, vault:rekey …)")
|
||||
.option("--since <when>", "24h, 7d, or a date")
|
||||
.option("--limit <n>", "Rows (max 1000)", "200")
|
||||
.option("--format <format>", "table, json, or markdown", "table")
|
||||
.description("Who read which vault key or ciphertext, when, from which IP and user agent; plus grants, re-keys and identity changes.")
|
||||
.action((slug, project, env, options) => teamsAuditAction(slug, project, env, { ...options, format: options.format as OutputFormat }));
|
||||
|
||||
teams
|
||||
.command("tui")
|
||||
|
|
@ -996,9 +1064,10 @@ teams
|
|||
.argument("<env>", "Environment name (prod, staging, …)")
|
||||
.argument("[email]", "Teammate email to grant vault access")
|
||||
.option("--key <name>", "Grant one of your machine API keys instead of a person (name, id, or prefix)")
|
||||
.option("--accept-key-change <email>", "Their key changed since you pinned it and you have confirmed the new fingerprint with them", collectList)
|
||||
.option("--format <format>", "table, json, or markdown", "table")
|
||||
.description("Grant a member, or a machine API key, decryption access to a vault (re-seals the vault key to their key).")
|
||||
.action((slug, project, env, email, options) => teamsGrantAction(slug, project, env, email, options.format as OutputFormat, { key: options.key }));
|
||||
.action((slug, project, env, email, options) => teamsGrantAction(slug, project, env, email, options.format as OutputFormat, { key: options.key, acceptKeyChange: options.acceptKeyChange }));
|
||||
|
||||
teams
|
||||
.command("push")
|
||||
|
|
|
|||
|
|
@ -50,7 +50,7 @@ beforeAll(async () => {
|
|||
process.env.LOGICSRC_IDENTITY_FILE = "";
|
||||
delete process.env.LOGICSRC_IDENTITY_FILE;
|
||||
({ db } = (await import(pwa("db.mjs"))) as { db: Db });
|
||||
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(fileURLToPath(pwa(join("migrations", file))), "utf8");
|
||||
for (const statement of sql.split(/;\s*$/m).map((s) => s.trim()).filter(Boolean)) await db.execute(statement);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -25,6 +25,9 @@ import {
|
|||
setActiveKey,
|
||||
activeKeyPath,
|
||||
readActiveKeyIdentity,
|
||||
checkAndPinKey,
|
||||
keyFingerprint,
|
||||
pinStatus,
|
||||
type CredentialEndpoint,
|
||||
type RemoteVault
|
||||
} from "@logicsrc/plugin-credential-sharing";
|
||||
|
|
@ -330,11 +333,22 @@ export async function loginAction(options: { apiUrl?: string; token?: string; ap
|
|||
}
|
||||
|
||||
const client = new TeamClient({ apiUrl, token: token! });
|
||||
await client.uploadPublicKey(identity.keys.publicKey);
|
||||
let keyMismatch: string | null = null;
|
||||
try {
|
||||
await client.uploadPublicKey(identity.keys.publicKey);
|
||||
} catch (error) {
|
||||
// Since 2026-10-28 a registered identity key is never silently replaced by a
|
||||
// login: that was how a stolen token could swap in an attacker's key.
|
||||
if (!(error instanceof TeamApiError) || error.status !== 409) throw error;
|
||||
keyMismatch = error.message;
|
||||
}
|
||||
await updateIdentity({ email: email ?? undefined, userId, apiToken: token, apiUrl });
|
||||
// A person login takes over from any key chosen with --api-key.
|
||||
rmSync(activeKeyPath(), { force: true });
|
||||
|
||||
if (keyMismatch) {
|
||||
throw new Error(`Logged in${email ? ` as ${email}` : ""}, but this machine's identity key is not the registered one, so it cannot open any vault.\n${keyMismatch}`);
|
||||
}
|
||||
console.error(`Logged in${email ? ` as ${email}` : ""}. Identity key registered on ${apiUrl}.`);
|
||||
print({ email, apiUrl }, "table");
|
||||
}
|
||||
|
|
@ -450,11 +464,29 @@ export async function teamsAcceptAction(token: string, format: OutputFormat): Pr
|
|||
print({ joined: result.team?.slug ?? null }, format);
|
||||
}
|
||||
|
||||
/** A member's key fingerprint and what this machine's pins say about it. */
|
||||
export function memberKeyColumns(apiUrl: string, email: string, publicKey: string | null | undefined, ownPublicKey?: string) {
|
||||
const fp = keyFingerprint(publicKey ?? null);
|
||||
if (!fp) return { fingerprint: "—", pin: "no key" };
|
||||
if (ownPublicKey && publicKey === ownPublicKey) return { fingerprint: fp, pin: "you" };
|
||||
const { status, pinned } = pinStatus(apiUrl, email, publicKey);
|
||||
return {
|
||||
fingerprint: fp,
|
||||
pin: status === "pinned" ? "pinned" : status === "new" ? "not pinned yet" : `CHANGED (pinned ${pinned?.fingerprint})`
|
||||
};
|
||||
}
|
||||
|
||||
export async function teamsMembersAction(slug: string, format: OutputFormat): Promise<void> {
|
||||
const { client } = authedClient();
|
||||
const { client, identity } = authedClient();
|
||||
const { members } = await client.listMembers(slug);
|
||||
const apiUrl = resolveApiUrl(identity);
|
||||
print(
|
||||
members.map((m) => ({ email: m.email, role: m.role, status: m.status, hasKey: m.hasPublicKey })),
|
||||
members.map((m) => ({
|
||||
email: m.email,
|
||||
role: m.role,
|
||||
status: m.status,
|
||||
...memberKeyColumns(apiUrl, m.email, m.publicKey ?? null, identity.keys?.publicKey)
|
||||
})),
|
||||
format
|
||||
);
|
||||
}
|
||||
|
|
@ -485,7 +517,7 @@ export async function teamsGrantAction(
|
|||
env: string,
|
||||
email: string | undefined,
|
||||
format: OutputFormat,
|
||||
options: { key?: string } = {}
|
||||
options: { key?: string; acceptKeyChange?: string[] } = {}
|
||||
): Promise<void> {
|
||||
if (!email && !options.key) throw new Error("Grant whom? Give a teammate's email, or --key <name> for a machine API key.");
|
||||
if (email && options.key) throw new Error("Give an email or --key, not both.");
|
||||
|
|
@ -522,7 +554,11 @@ export async function teamsGrantAction(
|
|||
}
|
||||
const dek = await unwrapVaultKey(myWrapped, identity.keys);
|
||||
|
||||
const apiUrl = resolveApiUrl(identity);
|
||||
const accept = options.acceptKeyChange ?? [];
|
||||
if (machineKey) {
|
||||
const pinned = checkAndPinKey(apiUrl, `key:${machineKey.id}`, machineKey.publicKey!, accept.includes(machineKey.name) || accept.includes(machineKey.id));
|
||||
if (pinned === "new") console.error(`Pinned machine key "${machineKey.name}" at ${keyFingerprint(machineKey.publicKey)}.`);
|
||||
await client.putKeyGrant(vaultId, machineKey.id, await wrapVaultKey(dek, machineKey.publicKey!));
|
||||
console.error(
|
||||
`Granted machine key "${machineKey.name}" ${machineKey.readOnly ? "read-only " : ""}access to ${slug}/${vault}. ` +
|
||||
|
|
@ -536,6 +572,10 @@ export async function teamsGrantAction(
|
|||
const target = await client.lookupUser(email);
|
||||
if (!target.userId) throw new Error(`${email} has not logged in yet. Ask them to run: logicsrc login --email ${email}`);
|
||||
if (!target.publicKey) throw new Error(`${email} has not registered a key yet. Ask them to run: logicsrc login --email ${email}`);
|
||||
// Trust on first use: seal only to the key pinned for this person, or pin it now.
|
||||
const pin = checkAndPinKey(apiUrl, email, target.publicKey, accept);
|
||||
if (pin === "new") console.error(`Pinned ${email}'s identity key at ${keyFingerprint(target.publicKey)}. Compare it with them (logicsrc teams members ${slug}).`);
|
||||
if (pin === "changed") console.error(`Accepted a CHANGED key for ${email}: now ${keyFingerprint(target.publicKey)}.`);
|
||||
|
||||
await client.putGrant(vaultId, email, await wrapVaultKey(dek, target.publicKey));
|
||||
console.error(`Granted ${email} access to ${slug}/${vault}. They can now: logicsrc teams pull ${slug} ${project} ${env}`);
|
||||
|
|
|
|||
|
|
@ -30,9 +30,26 @@ export interface RemoteMember {
|
|||
role: "owner" | "admin" | "member";
|
||||
status: "active" | "invited";
|
||||
hasPublicKey: boolean;
|
||||
/** The member's identity public key and its fingerprint (servers before 2026-10-28 omit these). */
|
||||
publicKey?: string | null;
|
||||
fingerprint?: string | null;
|
||||
joinedAt: string | null;
|
||||
}
|
||||
|
||||
/** One audit row, as GET /teams/:slug/audit returns it. */
|
||||
export interface RemoteAuditRow {
|
||||
at: number;
|
||||
action: string;
|
||||
actor: string | null;
|
||||
vault: string | null;
|
||||
target: string | null;
|
||||
fingerprint: string | null;
|
||||
apiKey: string | null;
|
||||
apiKeyKind: string | null;
|
||||
ip: string | null;
|
||||
userAgent: string | null;
|
||||
}
|
||||
|
||||
export interface RemoteVault {
|
||||
id: string;
|
||||
name: string;
|
||||
|
|
@ -66,6 +83,8 @@ export interface RekeyResult {
|
|||
/** Machine keys re-sealed to the new DEK, and the ones dropped (servers before machine keys omit these). */
|
||||
keysResealed?: string[];
|
||||
keysDropped?: string[];
|
||||
/** The vault's key version after this re-key. */
|
||||
keyVersion?: number;
|
||||
}
|
||||
|
||||
/** The credential a request was made with, as /api/credshare/me describes it. Null for a browser session. */
|
||||
|
|
@ -228,7 +247,24 @@ export class TeamClient {
|
|||
return this.request<{ vault: { id: string; name: string } }>("POST", `/teams/${encodeURIComponent(slug)}/vaults`, { name });
|
||||
}
|
||||
getMyGrant(vaultId: string) {
|
||||
return this.request<{ wrappedDek: string }>("GET", `/vaults/${encodeURIComponent(vaultId)}/grant`);
|
||||
return this.request<{ wrappedDek: string; keyVersion?: number }>("GET", `/vaults/${encodeURIComponent(vaultId)}/grant`);
|
||||
}
|
||||
/** Every vault grant the caller holds, for re-sealing them during an identity rotation. */
|
||||
myGrants() {
|
||||
return this.request<{ grants: Array<{ vaultId: string; vault: string; team: string; wrappedDek: string }> }>("GET", "/me/grants");
|
||||
}
|
||||
/** A random answer sealed to the caller's CURRENT identity key: opening it proves possession. */
|
||||
identityChallenge() {
|
||||
return this.request<{ challengeId: string; sealed: string; publicKey: string; fingerprint: string; expiresAt: number }>("POST", "/keys/challenge", {});
|
||||
}
|
||||
rotateIdentity(body: { publicKey: string; challengeId: string; answer: string; grants: Array<{ vaultId: string; wrappedDek: string }> }) {
|
||||
return this.request<{ ok: boolean; publicKey: string; fingerprint: string; previousFingerprint: string; regranted: number }>("POST", "/keys/rotate", body);
|
||||
}
|
||||
teamAudit(slug: string, query: { vault?: string; actor?: string; action?: string; since?: number; limit?: number } = {}) {
|
||||
const qs = new URLSearchParams();
|
||||
for (const [k, v] of Object.entries(query)) if (v !== undefined && v !== null && v !== "") qs.set(k, String(v));
|
||||
const suffix = qs.toString() ? `?${qs}` : "";
|
||||
return this.request<{ audit: RemoteAuditRow[] }>("GET", `/teams/${encodeURIComponent(slug)}/audit${suffix}`);
|
||||
}
|
||||
listGrants(vaultId: string) {
|
||||
return this.request<{ grants: RemoteGrantRow[] }>("GET", `/vaults/${encodeURIComponent(vaultId)}/grants`);
|
||||
|
|
@ -237,10 +273,15 @@ export class TeamClient {
|
|||
return this.request<{ ok: boolean }>("POST", `/vaults/${encodeURIComponent(vaultId)}/grants`, { email, wrappedDek });
|
||||
}
|
||||
listSecrets(vaultId: string) {
|
||||
return this.request<{ vaultId: string; secrets: RemoteSecret[] }>("GET", `/vaults/${encodeURIComponent(vaultId)}/secrets`);
|
||||
return this.request<{ vaultId: string; keyVersion?: number; secrets: RemoteSecret[] }>("GET", `/vaults/${encodeURIComponent(vaultId)}/secrets`);
|
||||
}
|
||||
putSecrets(vaultId: string, upserts: Array<{ name: string; nonce: string; ciphertext: string; fingerprint: string }>, deletes: string[]) {
|
||||
return this.request<{ ok: boolean; applied: string[] }>("PUT", `/vaults/${encodeURIComponent(vaultId)}/secrets`, { upserts, deletes });
|
||||
/**
|
||||
* `keyVersion` is the vault key version the ciphertext was made under (from
|
||||
* getMyGrant). The server refuses the write if the vault was re-keyed since,
|
||||
* so nothing lands under a retired key.
|
||||
*/
|
||||
putSecrets(vaultId: string, upserts: Array<{ name: string; nonce: string; ciphertext: string; fingerprint: string }>, deletes: string[], keyVersion?: number) {
|
||||
return this.request<{ ok: boolean; applied: string[] }>("PUT", `/vaults/${encodeURIComponent(vaultId)}/secrets`, { upserts, deletes, ...(keyVersion !== undefined ? { keyVersion } : {}) });
|
||||
}
|
||||
/**
|
||||
* Swap the vault to a fresh DEK. The whole next state goes over in one call
|
||||
|
|
|
|||
|
|
@ -83,6 +83,7 @@ export {
|
|||
type RemoteKeyInfo,
|
||||
type RemoteApiKey,
|
||||
type RemoteKeyGrant,
|
||||
type RemoteAuditRow,
|
||||
type CreateApiKeyInput
|
||||
} from "./client.js";
|
||||
export {
|
||||
|
|
@ -130,6 +131,16 @@ export {
|
|||
type CredentialStore
|
||||
} from "./store.js";
|
||||
export { fingerprintValue, fingerprintsEqual } from "./fingerprint.js";
|
||||
export {
|
||||
keyFingerprint,
|
||||
knownKeysPath,
|
||||
pinStatus,
|
||||
checkAndPinKey,
|
||||
repinKey,
|
||||
KeyChangedError,
|
||||
type KnownKey,
|
||||
type PinStatus
|
||||
} from "./known-keys.js";
|
||||
export {
|
||||
planVaultRekey,
|
||||
type RekeyPlan,
|
||||
|
|
|
|||
137
plugins/credential-sharing/src/known-keys.ts
Normal file
137
plugins/credential-sharing/src/known-keys.ts
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
import { createHash } from "node:crypto";
|
||||
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { logicsrcHome } from "./identity.js";
|
||||
|
||||
/**
|
||||
* Trust-on-first-use pins for the identity public keys this CLI seals vault
|
||||
* keys to (teammates and machine keys).
|
||||
*
|
||||
* The server hands out public keys, and a server (or a stolen session) that
|
||||
* swaps one in could get every vault re-sealed to an attacker. So the first
|
||||
* key seen for a member is pinned in `<home>/known-keys.json`, and a later
|
||||
* DIFFERENT key is refused for sealing until the user confirms it
|
||||
* (`--accept-key-change <email>`), after checking the fingerprint with the
|
||||
* person. A rotation (`teams rotate-identity`) or a reset changes a key
|
||||
* legitimately; this makes that change visible instead of silent.
|
||||
*
|
||||
* Fingerprints match the web app's: sha256 over the raw 32-byte key, first 16
|
||||
* bytes as eight groups of four hex digits.
|
||||
*/
|
||||
export function keyFingerprint(publicKeyB64: string | null | undefined): string | null {
|
||||
if (!publicKeyB64) return null;
|
||||
const raw = Buffer.from(publicKeyB64, "base64");
|
||||
if (raw.length !== 32) return null;
|
||||
const hex = createHash("sha256").update(raw).digest("hex").slice(0, 32);
|
||||
return hex.match(/.{4}/g)!.join(" ");
|
||||
}
|
||||
|
||||
export interface KnownKey {
|
||||
publicKey: string;
|
||||
fingerprint: string;
|
||||
firstSeen: string;
|
||||
lastSeen: string;
|
||||
/** Set when a change was accepted: the fingerprint it replaced. */
|
||||
replaced?: string;
|
||||
}
|
||||
|
||||
interface KnownKeysFile {
|
||||
version: 1;
|
||||
/** Keyed by `<apiUrl>|<email>` for people and `<apiUrl>|key:<id>` for machine keys. */
|
||||
keys: Record<string, KnownKey>;
|
||||
}
|
||||
|
||||
export type PinStatus = "pinned" | "new" | "changed" | "none";
|
||||
|
||||
export class KeyChangedError extends Error {
|
||||
constructor(
|
||||
public readonly subject: string,
|
||||
public readonly pinned: string,
|
||||
public readonly presented: string
|
||||
) {
|
||||
super(
|
||||
`The identity key for ${subject} CHANGED since this machine pinned it.\n` +
|
||||
` pinned: ${pinned}\n presented: ${presented}\n` +
|
||||
"This is expected after they ran `logicsrc teams rotate-identity` or reset their key, and it is exactly what a swapped-in attacker key looks like. " +
|
||||
`Confirm the new fingerprint with ${subject} out of band, then re-run with --accept-key-change ${subject}`
|
||||
);
|
||||
this.name = "KeyChangedError";
|
||||
}
|
||||
}
|
||||
|
||||
export function knownKeysPath(): string {
|
||||
return join(logicsrcHome(), "known-keys.json");
|
||||
}
|
||||
|
||||
function load(): KnownKeysFile {
|
||||
const file = knownKeysPath();
|
||||
if (!existsSync(file)) return { version: 1, keys: {} };
|
||||
try {
|
||||
const parsed = JSON.parse(readFileSync(file, "utf8")) as KnownKeysFile;
|
||||
return parsed && typeof parsed.keys === "object" ? parsed : { version: 1, keys: {} };
|
||||
} catch {
|
||||
throw new Error(`${file} is not valid JSON. Fix or remove it (removing it re-pins every key on first use).`);
|
||||
}
|
||||
}
|
||||
|
||||
function save(data: KnownKeysFile): void {
|
||||
const file = knownKeysPath();
|
||||
mkdirSync(dirname(file), { recursive: true });
|
||||
const tmp = `${file}.${process.pid}.tmp`;
|
||||
writeFileSync(tmp, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600 });
|
||||
renameSync(tmp, file);
|
||||
try { chmodSync(file, 0o600); } catch { /* no modes on this platform */ }
|
||||
}
|
||||
|
||||
const pinId = (apiUrl: string, subject: string) => `${apiUrl.replace(/\/+$/, "")}|${subject.toLowerCase()}`;
|
||||
|
||||
/** What we know about a key, without changing anything. */
|
||||
export function pinStatus(apiUrl: string, subject: string, publicKey: string | null | undefined): { status: PinStatus; pinned?: KnownKey } {
|
||||
if (!publicKey) return { status: "none" };
|
||||
const pinned = load().keys[pinId(apiUrl, subject)];
|
||||
if (!pinned) return { status: "new" };
|
||||
return { status: pinned.publicKey === publicKey ? "pinned" : "changed", pinned };
|
||||
}
|
||||
|
||||
/**
|
||||
* Check a key before sealing anything to it. Pins it on first use; throws
|
||||
* KeyChangedError on a change unless `accept` names the subject (or is true).
|
||||
* Returns what happened, so callers can tell the user about a new pin.
|
||||
*/
|
||||
export function checkAndPinKey(
|
||||
apiUrl: string,
|
||||
subject: string,
|
||||
publicKey: string,
|
||||
accept: boolean | string[] = false
|
||||
): PinStatus {
|
||||
const data = load();
|
||||
const id = pinId(apiUrl, subject);
|
||||
const fp = keyFingerprint(publicKey) ?? "(not a valid key)";
|
||||
const now = new Date().toISOString();
|
||||
const pinned = data.keys[id];
|
||||
if (!pinned) {
|
||||
data.keys[id] = { publicKey, fingerprint: fp, firstSeen: now, lastSeen: now };
|
||||
save(data);
|
||||
return "new";
|
||||
}
|
||||
if (pinned.publicKey === publicKey) {
|
||||
pinned.lastSeen = now;
|
||||
save(data);
|
||||
return "pinned";
|
||||
}
|
||||
const accepted = accept === true || (Array.isArray(accept) && accept.some((a) => a.toLowerCase() === subject.toLowerCase()));
|
||||
if (!accepted) throw new KeyChangedError(subject, pinned.fingerprint, fp);
|
||||
data.keys[id] = { publicKey, fingerprint: fp, firstSeen: now, lastSeen: now, replaced: pinned.fingerprint };
|
||||
save(data);
|
||||
return "changed";
|
||||
}
|
||||
|
||||
/** Record our OWN new key after a rotation, so our own machine does not flag it. */
|
||||
export function repinKey(apiUrl: string, subject: string, publicKey: string): void {
|
||||
const data = load();
|
||||
const id = pinId(apiUrl, subject);
|
||||
const now = new Date().toISOString();
|
||||
const previous = data.keys[id];
|
||||
data.keys[id] = { publicKey, fingerprint: keyFingerprint(publicKey) ?? "", firstSeen: now, lastSeen: now, ...(previous && previous.publicKey !== publicKey ? { replaced: previous.fingerprint } : {}) };
|
||||
save(data);
|
||||
}
|
||||
|
|
@ -55,9 +55,13 @@ async function resolveVaultId(ctx: TeamContext, slug: string, vault: string, cre
|
|||
|
||||
/** Fetch (or, for a brand-new vault, mint) the vault DEK, decrypting nothing yet. */
|
||||
async function acquireDek(ctx: TeamContext, slug: string, vault: string, vaultId: string, allowMint: boolean): Promise<string> {
|
||||
return (await acquireDekVersioned(ctx, slug, vault, vaultId, allowMint)).dek;
|
||||
}
|
||||
|
||||
async function acquireDekVersioned(ctx: TeamContext, slug: string, vault: string, vaultId: string, allowMint: boolean): Promise<{ dek: string; keyVersion?: number }> {
|
||||
try {
|
||||
const { wrappedDek } = await ctx.client.getMyGrant(vaultId);
|
||||
return unwrapVaultKey(wrappedDek, ctx.identity.keys);
|
||||
const { wrappedDek, keyVersion } = await ctx.client.getMyGrant(vaultId);
|
||||
return { dek: await unwrapVaultKey(wrappedDek, ctx.identity.keys), keyVersion };
|
||||
} catch (error) {
|
||||
if (!(error instanceof TeamApiError) || error.status !== 403) throw error;
|
||||
if (ctx.identity.keyKind === "machine") {
|
||||
|
|
@ -81,7 +85,7 @@ async function acquireDek(ctx: TeamContext, slug: string, vault: string, vaultId
|
|||
const dek = await generateVaultKey();
|
||||
const wrapped = await wrapVaultKey(dek, ctx.identity.keys.publicKey);
|
||||
await ctx.client.putGrant(vaultId, ctx.identity.email, wrapped);
|
||||
return dek;
|
||||
return { dek };
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -158,14 +162,18 @@ export const teamProvider: CredentialProvider = {
|
|||
|
||||
if (upsertNames.length === 0 && input.deletes.length === 0) return results;
|
||||
|
||||
const dek = upsertNames.length > 0 ? await acquireDek(ctx, slug, vault, vaultId, true) : undefined;
|
||||
const acquired = upsertNames.length > 0 ? await acquireDekVersioned(ctx, slug, vault, vaultId, true) : undefined;
|
||||
const dek = acquired?.dek;
|
||||
const encrypted: Array<{ name: string; nonce: string; ciphertext: string; fingerprint: string }> = [];
|
||||
for (const name of upsertNames) {
|
||||
const sealed = await encryptValue(input.upserts[name], dek!);
|
||||
encrypted.push({ name, nonce: sealed.nonce, ciphertext: sealed.ciphertext, fingerprint: fingerprintValue(input.upserts[name]) });
|
||||
}
|
||||
|
||||
const { applied } = await ctx.client.putSecrets(vaultId, encrypted, input.deletes);
|
||||
// The key version pins this write to the vault key it was encrypted under: a
|
||||
// re-key landing in between makes the server refuse it rather than store
|
||||
// ciphertext nobody can open. Re-running the push picks up the new key.
|
||||
const { applied } = await ctx.client.putSecrets(vaultId, encrypted, input.deletes, acquired?.keyVersion);
|
||||
const appliedSet = new Set(applied);
|
||||
for (const name of upsertNames) results.push({ key: name, applied: appliedSet.has(name) });
|
||||
for (const name of input.deletes) results.push({ key: name, applied: appliedSet.has(name) });
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue