Addresses the findings from the platform security audit. Verified green: all-workspace typecheck, web build, 16 API unit tests, 23 e2e auth tests, and 0 high/critical production dependency vulnerabilities. Dependencies (High): - Bump drizzle-orm 0.36→0.45.2 (GHSA-gpj5-g38j-94v9 SQLi-via-identifier) and drizzle-kit→0.31.10; npm audit fix cleared fast-uri path-traversal and the react-router open-redirect. Remaining audit items are dev-only build tooling (esbuild/vite), not shipped at runtime. AI cost control + storage quota (new ai_usage table, migration 0002): - Per-firm monthly AI token budget enforced before each completion (429), with every completion recorded to an ai_usage ledger (lib/ai-usage.ts). - Enforce per-plan storage quota on upload (402) and maintain storage_bytes_used on upload/delete (lib/storage-quota.ts); widen the column int→bigint so 8GB/50GB plans don't overflow. Auth (defense-in-depth): - Constant-time login: verify against a dummy argon2 hash when the account doesn't exist, closing the timing/enumeration oracle (verifyPasswordSafe). - Enforce suspension on requireSuperadmin, /auth/me, /auth/resend-verification. Web: - Validate the post-login ?next= redirect to same-origin paths only (open-redirect / phishing). Deploy hardening: - docker-compose: memory/CPU limits so a spike can't OOM the Dokploy host. - .dockerignore: keep destructive one-off scripts (seed-demo, create-admin, migrate-storage) out of the runtime image; retain the cron scripts. - seed-demo.ts: hard-refuse NODE_ENV=production and the prod DB host. Webhooks / config: - Stripe idempotency via a stripe_events ledger (skip already-processed events; record only after successful processing so a transient failure still retries); make the plan-upgraded email non-blocking. - Rate-limit account export and invoice PDF; cap invoice item arrays at 200. - Require TURNSTILE_SECRET_KEY in production (bot protection no longer fails open on a forgotten key); don't load .env under NODE_ENV=test so the suite is hermetic. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
96 lines
3.2 KiB
TypeScript
96 lines
3.2 KiB
TypeScript
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
|
|
import fp from 'fastify-plugin';
|
|
import { SESSION_COOKIE, loadSession } from './sessions';
|
|
import { isProd, env } from '../env';
|
|
import { ensureSuperadminFlag } from './superadmin';
|
|
|
|
declare module 'fastify' {
|
|
interface FastifyRequest {
|
|
user?: {
|
|
id: string;
|
|
email: string;
|
|
firmId: string | null;
|
|
role: string;
|
|
isSuperadmin: boolean;
|
|
isSuspended: boolean;
|
|
emailVerified: boolean;
|
|
};
|
|
}
|
|
interface FastifyInstance {
|
|
requireAuth: (req: FastifyRequest, reply: FastifyReply) => Promise<void>;
|
|
requireFirm: (req: FastifyRequest, reply: FastifyReply) => Promise<void>;
|
|
requireSuperadmin: (req: FastifyRequest, reply: FastifyReply) => Promise<void>;
|
|
setSessionCookie: (reply: FastifyReply, token: string, expiresAt: Date) => void;
|
|
clearSessionCookie: (reply: FastifyReply) => void;
|
|
}
|
|
}
|
|
|
|
async function plugin(app: FastifyInstance) {
|
|
app.addHook('onRequest', async (req) => {
|
|
const token = req.cookies?.[SESSION_COOKIE];
|
|
if (!token) return;
|
|
|
|
const session = await loadSession(token);
|
|
if (!session) return;
|
|
|
|
// Auto-promote/demote based on SUPERADMIN_EMAILS env var, every request — cheap and self-healing.
|
|
const isSuperadmin = await ensureSuperadminFlag(
|
|
session.user.id,
|
|
session.user.email,
|
|
session.user.isSuperadmin,
|
|
session.user.emailVerifiedAt,
|
|
);
|
|
|
|
req.user = {
|
|
id: session.user.id,
|
|
email: session.user.email,
|
|
firmId: session.user.firmId,
|
|
role: session.user.role,
|
|
isSuperadmin,
|
|
isSuspended: session.user.isSuspended,
|
|
emailVerified: Boolean(session.user.emailVerifiedAt),
|
|
};
|
|
});
|
|
|
|
app.decorate('requireAuth', async (req: FastifyRequest, reply: FastifyReply) => {
|
|
if (!req.user) return reply.code(401).send({ error: 'unauthorized' });
|
|
if (req.user.isSuspended) return reply.code(403).send({ error: 'account_suspended' });
|
|
});
|
|
|
|
app.decorate('requireFirm', async (req: FastifyRequest, reply: FastifyReply) => {
|
|
if (!req.user) return reply.code(401).send({ error: 'unauthorized' });
|
|
if (req.user.isSuspended) return reply.code(403).send({ error: 'account_suspended' });
|
|
if (!req.user.firmId) return reply.code(403).send({ error: 'no_firm' });
|
|
});
|
|
|
|
app.decorate('requireSuperadmin', async (req: FastifyRequest, reply: FastifyReply) => {
|
|
if (!req.user) return reply.code(401).send({ error: 'unauthorized' });
|
|
if (req.user.isSuspended) return reply.code(403).send({ error: 'account_suspended' });
|
|
if (!req.user.isSuperadmin) return reply.code(403).send({ error: 'forbidden' });
|
|
});
|
|
|
|
app.decorate('setSessionCookie', (reply: FastifyReply, token: string, expiresAt: Date) => {
|
|
reply.setCookie(SESSION_COOKIE, token, {
|
|
path: '/',
|
|
httpOnly: true,
|
|
secure: isProd,
|
|
sameSite: 'lax',
|
|
domain: env.COOKIE_DOMAIN || undefined,
|
|
expires: expiresAt,
|
|
signed: false,
|
|
});
|
|
});
|
|
|
|
app.decorate('clearSessionCookie', (reply: FastifyReply) => {
|
|
reply.clearCookie(SESSION_COOKIE, {
|
|
path: '/',
|
|
httpOnly: true,
|
|
secure: isProd,
|
|
sameSite: 'lax',
|
|
domain: env.COOKIE_DOMAIN || undefined,
|
|
});
|
|
});
|
|
}
|
|
|
|
export const authPlugin = fp(plugin, { name: 'auth' });
|