Files
elegalsoftware/apps/api/src/auth/plugin.ts
T
Leon SerfatyandClaude Fable 5 97e1d4c60b 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>
2026-07-16 13:18:10 -04:00

93 lines
3.1 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;
};
}
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,
};
});
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.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' });