import { randomUUID } from "node:crypto"; import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify"; import type { Db, TxDb } from "../../db/db.ts"; import { RateLimiter } from "./rate-limit.ts"; import { checkPassword, hashPassword, hashToken, newToken, normalizeEmail, validEmail, validPassword, } from "./security.ts"; export const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000; const COOKIE = "sid"; export interface AccountsOptions { db: TxDb; /** Secure-флаг cookie; по умолчанию — NODE_ENV=production. */ secureCookie?: boolean; now?: () => number; } type Role = "buyer" | "org_admin" | "operator"; interface SessionUser { id: string; email: string; role: Role; orgId: string | null; csrf: string; } const fail = (reply: FastifyReply, code: number, error: string) => reply.code(code).send({ error }); function parseCookies(header: string | undefined): Record { const out: Record = {}; for (const part of (header ?? "").split(";")) { const i = part.indexOf("="); if (i > 0) out[part.slice(0, i).trim()] = part.slice(i + 1).trim(); } return out; } /** Удаляет истёкшие сессии; возвращает их число. */ export async function purgeExpiredSessions(db: Db): Promise { const r = await db.query("DELETE FROM sessions WHERE expires_at <= now()"); return r.rowCount ?? 0; } export async function accountsModule(app: FastifyInstance, opts: AccountsOptions): Promise { const { db } = opts; const secure = opts.secureCookie ?? process.env.NODE_ENV === "production"; const now = opts.now ?? Date.now; const loginByEmail = new RateLimiter(5, undefined, now); const loginByIp = new RateLimiter(20, undefined, now); const registerByIp = new RateLimiter(10, undefined, now); const timer = setInterval(() => void purgeExpiredSessions(db).catch(() => undefined), 60 * 60 * 1000); timer.unref(); app.addHook("onClose", async () => clearInterval(timer)); const cookieHeader = (value: string, maxAgeSec: number): string => `${COOKIE}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSec}${secure ? "; Secure" : ""}`; async function createSession(reply: FastifyReply, userId: string): Promise { const token = newToken(); const csrf = newToken(); await db.query("INSERT INTO sessions (token_hash, user_id, csrf_token, expires_at) VALUES ($1, $2, $3, $4)", [ hashToken(token), userId, csrf, new Date(now() + SESSION_TTL_MS), ]); reply.header("set-cookie", cookieHeader(token, SESSION_TTL_MS / 1000)); return csrf; } async function loadSession(req: FastifyRequest): Promise { const token = parseCookies(req.headers.cookie)[COOKIE]; if (!token) return null; const r = await db.query<{ id: string; email: string; role: Role; org_id: string | null; csrf_token: string }>( `SELECT u.id, u.email, u.role, u.org_id, s.csrf_token FROM sessions s JOIN users u ON u.id = s.user_id WHERE s.token_hash = $1 AND s.expires_at > $2`, [hashToken(token), new Date(now())], ); const row = r.rows[0]; return row ? { id: row.id, email: row.email, role: row.role, orgId: row.org_id, csrf: row.csrf_token } : null; } /** Требует сессию и CSRF-токен; при отказе отвечает сам и возвращает null. */ async function authed(req: FastifyRequest, reply: FastifyReply, csrf: boolean): Promise { const user = await loadSession(req); if (!user) { await fail(reply, 401, "unauthenticated"); return null; } if (csrf && req.headers["x-csrf-token"] !== user.csrf) { await fail(reply, 403, "csrf_failed"); return null; } return user; } /** Запросы без сессии: только JSON и свой Origin. */ function anonymousGuard(req: FastifyRequest, reply: FastifyReply): boolean { const origin = req.headers.origin; const ctype = req.headers["content-type"] ?? ""; let originOk = true; if (origin !== undefined) { try { originOk = new URL(origin).host === req.headers.host; } catch { originOk = false; } } if (!originOk || !ctype.toLowerCase().startsWith("application/json")) { void fail(reply, 403, "csrf_failed"); return false; } return true; } const body = (req: FastifyRequest): Record => req.body && typeof req.body === "object" ? (req.body as Record) : {}; const isUniqueViolation = (err: unknown): boolean => (err as { code?: string })?.code === "23505"; async function register( req: FastifyRequest, reply: FastifyReply, kind: "buyer" | "org", ): Promise { if (!anonymousGuard(req, reply)) return reply; if (registerByIp.blocked(req.ip)) return fail(reply, 429, "rate_limited"); registerByIp.hit(req.ip); const b = body(req); const email = typeof b.email === "string" ? normalizeEmail(b.email) : ""; const orgName = typeof b.orgName === "string" ? b.orgName.trim() : ""; if (!validEmail(email) || !validPassword(b.password) || (kind === "org" && (orgName.length < 1 || orgName.length > 200))) { return fail(reply, 400, "invalid_input"); } const passwordHash = await hashPassword(b.password); const userId = randomUUID(); const role: Role = kind === "org" ? "org_admin" : "buyer"; try { await db.tx(async (tx) => { let orgId: string | null = null; if (kind === "org") { orgId = randomUUID(); await tx.query("INSERT INTO organizations (id, name) VALUES ($1, $2)", [orgId, orgName]); } await tx.query("INSERT INTO users (id, email, password_hash, role, org_id) VALUES ($1, $2, $3, $4, $5)", [ userId, email, passwordHash, role, orgId, ]); }); } catch (err) { if (isUniqueViolation(err)) return fail(reply, 409, "email_taken"); throw err; } const csrf = await createSession(reply, userId); return reply.code(201).send({ role, email, csrfToken: csrf }); } app.post("/api/auth/register", (req, reply) => register(req, reply, "buyer")); app.post("/api/auth/register-org", (req, reply) => register(req, reply, "org")); app.post("/api/auth/login", async (req, reply) => { if (!anonymousGuard(req, reply)) return reply; const b = body(req); const email = typeof b.email === "string" ? normalizeEmail(b.email) : ""; if (loginByEmail.blocked(email) || loginByIp.blocked(req.ip)) return fail(reply, 429, "rate_limited"); const password = typeof b.password === "string" ? b.password : ""; const r = await db.query<{ id: string; password_hash: string; role: Role }>( "SELECT id, password_hash, role FROM users WHERE lower(email) = $1", [email], ); const user = r.rows[0]; if (!(await checkPassword(user?.password_hash ?? null, password)) || !user) { loginByEmail.hit(email); loginByIp.hit(req.ip); return fail(reply, 401, "invalid_credentials"); } loginByEmail.reset(email); await purgeExpiredSessions(db); const csrf = await createSession(reply, user.id); return reply.send({ role: user.role, email, csrfToken: csrf }); }); app.post("/api/auth/logout", async (req, reply) => { const user = await authed(req, reply, true); if (!user) return reply; const token = parseCookies(req.headers.cookie)[COOKIE] ?? ""; await db.query("DELETE FROM sessions WHERE token_hash = $1", [hashToken(token)]); reply.header("set-cookie", cookieHeader("", 0)); return reply.code(204).send(); }); app.get("/api/session", async (req, reply) => { const user = await authed(req, reply, false); if (!user) return reply; return reply.send({ email: user.email, role: user.role, orgId: user.orgId, csrfToken: user.csrf }); }); app.post("/api/org/operators", async (req, reply) => { const user = await authed(req, reply, true); if (!user) return reply; if (user.role !== "org_admin" || !user.orgId) return fail(reply, 403, "forbidden"); const b = body(req); const email = typeof b.email === "string" ? normalizeEmail(b.email) : ""; if (!validEmail(email) || !validPassword(b.password)) return fail(reply, 400, "invalid_input"); try { await db.query("INSERT INTO users (id, email, password_hash, role, org_id) VALUES ($1, $2, $3, 'operator', $4)", [ randomUUID(), email, await hashPassword(b.password), user.orgId, ]); } catch (err) { if (isUniqueViolation(err)) return fail(reply, 409, "email_taken"); throw err; } return reply.code(201).send({ email, role: "operator" }); }); app.delete("/api/account", async (req, reply) => { const user = await authed(req, reply, true); if (!user) return reply; const password = typeof body(req).password === "string" ? (body(req).password as string) : ""; const r = await db.query<{ password_hash: string }>("SELECT password_hash FROM users WHERE id = $1", [user.id]); if (!(await checkPassword(r.rows[0]?.password_hash ?? null, password))) { return fail(reply, 401, "invalid_credentials"); } const result = await db.tx(async (tx) => { if (user.orgId) { const others = await tx.query<{ role: Role }>("SELECT role FROM users WHERE org_id = $1 AND id <> $2", [ user.orgId, user.id, ]); if (user.role === "org_admin" && others.rows.length > 0) return "org_has_members" as const; await tx.query("DELETE FROM users WHERE id = $1", [user.id]); if (others.rows.length === 0) await tx.query("DELETE FROM organizations WHERE id = $1", [user.orgId]); } else { await tx.query("DELETE FROM users WHERE id = $1", [user.id]); } return "ok" as const; }); if (result === "org_has_members") return fail(reply, 409, "org_has_members"); reply.header("set-cookie", cookieHeader("", 0)); return reply.code(204).send(); }); }