Storage→Spaces, security hardening, production-blocker fixes, tests + CI
Storage - Migrate document/media storage from local disk to DigitalOcean Spaces (S3); lib/storage.ts now streams via the S3 SDK; SPACES_* env vars required. - Add scripts/migrate-storage-to-spaces.ts (idempotent, one-time). Security hardening (all report findings) - DB pool fails closed in production when the CA cert is missing (no more silent unverified TLS); warns in dev. - trustProxy: 1 (was true) so X-Forwarded-For can't be spoofed to evade rate limits. - Login lockout keyed by (email, ip) so an attacker can't lock out a victim. - Superadmin auto-grant now requires a verified email. - CSRF tokens HMAC-signed; exact-path exemptions; logout no longer exempt. - Upload content-sniffing (magic bytes) rejects spoofed MIME types. - create-admin.ts reads creds from env/argv; seed-demo.ts guarded behind ALLOW_SEED. Production-blocker fixes - SPA deep-link/refresh no longer 500s (decorateReply fix); index.html served no-cache. - Invoice numbering is transaction-safe (per-firm advisory lock + max sequence), eliminating concurrent collisions and delete-reuse — no schema change. - Checkout guards against double-billing a firm already on a paid plan. - Fix render-loop in CreateInvoiceDrawer / ManualEntryDrawer (unstable effect deps). Honesty / trust - Remove fabricated testimonials, stats, strikethrough "was" prices, contact SLA, and the login-panel stats; replace with non-fabricated copy. - Fix cookie-policy consent-key mismatch. (Legal pages still need lawyer review.) Quality - Add Vitest unit tests (file-signature, password hashing) and GitHub Actions CI. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
parent
310568690b
commit
97e1d4c60b
@@ -10,12 +10,42 @@ const TOKEN_BYTES = 32;
|
||||
|
||||
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
|
||||
|
||||
// Routes that legitimately bypass CSRF — they receive their own auth (signature check)
|
||||
// or have no session yet, so a CSRF attack against them is meaningless.
|
||||
const CSRF_EXEMPT_PREFIXES = ['/api/auth/', '/api/contact', '/api/webhooks/', '/api/tool-usage'];
|
||||
// Exact routes that legitimately bypass CSRF: they run pre-session (login/signup/reset) or carry
|
||||
// their own authentication (Stripe signature), so a CSRF attack against them is meaningless.
|
||||
// Exact-match only — no prefix matching, so nothing new is silently exempted, and authenticated
|
||||
// state-changing routes like /api/auth/logout are NOT exempt (the browser client sends the token).
|
||||
const CSRF_EXEMPT_PATHS = new Set([
|
||||
'/api/auth/login',
|
||||
'/api/auth/signup',
|
||||
'/api/auth/request-password-reset',
|
||||
'/api/auth/reset-password',
|
||||
'/api/contact',
|
||||
'/api/tool-usage',
|
||||
'/api/webhooks/stripe',
|
||||
]);
|
||||
|
||||
// CSRF tokens are HMAC-signed with CSRF_SECRET: `${random}.${sig}`. Signing means a token can't be
|
||||
// forged by a party that doesn't hold the secret, so an attacker on a sibling/compromised subdomain
|
||||
// cannot plant a self-consistent cookie+header pair (the classic weakness of naive double-submit).
|
||||
function signCsrf(value: string): string {
|
||||
return crypto.createHmac('sha256', env.CSRF_SECRET).update(value).digest('base64url');
|
||||
}
|
||||
|
||||
export function generateCsrfToken(): string {
|
||||
return crypto.randomBytes(TOKEN_BYTES).toString('base64url');
|
||||
const random = crypto.randomBytes(TOKEN_BYTES).toString('base64url');
|
||||
return `${random}.${signCsrf(random)}`;
|
||||
}
|
||||
|
||||
function isValidCsrfToken(token: string): boolean {
|
||||
const dot = token.lastIndexOf('.');
|
||||
if (dot <= 0) return false;
|
||||
const random = token.slice(0, dot);
|
||||
const sig = token.slice(dot + 1);
|
||||
const expected = signCsrf(random);
|
||||
const a = Buffer.from(sig);
|
||||
const b = Buffer.from(expected);
|
||||
if (a.length !== b.length) return false;
|
||||
return crypto.timingSafeEqual(a, b);
|
||||
}
|
||||
|
||||
function constantTimeEqual(a: string, b: string): boolean {
|
||||
@@ -52,11 +82,13 @@ async function plugin(app: FastifyInstance) {
|
||||
});
|
||||
});
|
||||
|
||||
// Auto-mint a CSRF token whenever an authenticated session exists but no CSRF cookie is set.
|
||||
// This makes the protection self-bootstrapping after sessions created before CSRF was enabled.
|
||||
// Auto-mint a CSRF token whenever an authenticated session exists but no valid CSRF cookie is
|
||||
// set. Self-bootstrapping for sessions created before CSRF existed, and self-healing: a stale or
|
||||
// unsigned cookie (fails signature) is replaced with a fresh signed one instead of wedging.
|
||||
app.addHook('onRequest', async (req, reply) => {
|
||||
if (!req.cookies?.[SESSION_COOKIE]) return;
|
||||
if (req.cookies?.[CSRF_COOKIE]) return;
|
||||
const existing = req.cookies?.[CSRF_COOKIE];
|
||||
if (existing && isValidCsrfToken(existing)) return;
|
||||
const token = generateCsrfToken();
|
||||
app.setCsrfCookie(reply, token);
|
||||
req.cookies = { ...req.cookies, [CSRF_COOKIE]: token };
|
||||
@@ -67,11 +99,13 @@ async function plugin(app: FastifyInstance) {
|
||||
if (SAFE_METHODS.has(req.method)) return;
|
||||
if (!req.cookies?.[SESSION_COOKIE]) return; // unauthenticated → nothing to protect
|
||||
const url = req.routeOptions.url || req.url;
|
||||
if (CSRF_EXEMPT_PREFIXES.some((p) => url.startsWith(p))) return;
|
||||
if (CSRF_EXEMPT_PATHS.has(url)) return;
|
||||
|
||||
const cookie = req.cookies?.[CSRF_COOKIE];
|
||||
const header = (req.headers[CSRF_HEADER] as string | undefined) ?? '';
|
||||
if (!cookie || !header || !constantTimeEqual(cookie, header)) {
|
||||
// Require: cookie and header present, they match (double-submit), and the token carries a
|
||||
// valid signature (proves it was minted by this server, not planted by another origin).
|
||||
if (!cookie || !header || !constantTimeEqual(cookie, header) || !isValidCsrfToken(cookie)) {
|
||||
return reply.code(403).send({ error: 'csrf_failed' });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -37,6 +37,7 @@ async function plugin(app: FastifyInstance) {
|
||||
session.user.id,
|
||||
session.user.email,
|
||||
session.user.isSuperadmin,
|
||||
session.user.emailVerifiedAt,
|
||||
);
|
||||
|
||||
req.user = {
|
||||
|
||||
@@ -6,11 +6,32 @@ export function isSuperadminEmail(email: string): boolean {
|
||||
return env.superadminEmails.includes(email.toLowerCase());
|
||||
}
|
||||
|
||||
// Promote any user whose email is on the SUPERADMIN_EMAILS list. Idempotent.
|
||||
// Called on signup/login so the assignment happens automatically as soon as the user shows up.
|
||||
export async function ensureSuperadminFlag(userId: string, email: string, currentFlag: boolean) {
|
||||
const shouldBe = isSuperadminEmail(email);
|
||||
if (shouldBe === currentFlag) return shouldBe;
|
||||
await getDb().update(users).set({ isSuperadmin: shouldBe, updatedAt: new Date() }).where(eq(users.id, userId));
|
||||
return shouldBe;
|
||||
// Reconcile a user's superadmin flag against the SUPERADMIN_EMAILS allowlist. Idempotent.
|
||||
// Called on signup/login/every request.
|
||||
//
|
||||
// Security: promotion (false -> true) requires a VERIFIED email. Public signup never sets
|
||||
// emailVerifiedAt, so an attacker who registers a listed address before its owner does NOT
|
||||
// silently become superadmin. Legitimate superadmins are provisioned via scripts/create-admin.ts
|
||||
// (which sets isSuperadmin + emailVerifiedAt directly) or on an already-verified account.
|
||||
// Demotion (list removal) still happens immediately, regardless of verification.
|
||||
export async function ensureSuperadminFlag(
|
||||
userId: string,
|
||||
email: string,
|
||||
currentFlag: boolean,
|
||||
emailVerifiedAt: Date | null,
|
||||
) {
|
||||
const onList = isSuperadminEmail(email);
|
||||
|
||||
if (!onList) {
|
||||
if (currentFlag) {
|
||||
await getDb().update(users).set({ isSuperadmin: false, updatedAt: new Date() }).where(eq(users.id, userId));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if (currentFlag) return true; // already a superadmin — keep it
|
||||
if (!emailVerifiedAt) return false; // on the list but unverified — do NOT auto-promote
|
||||
|
||||
await getDb().update(users).set({ isSuperadmin: true, updatedAt: new Date() }).where(eq(users.id, userId));
|
||||
return true;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user