a8c6d6e714
Booth reality breaks a fixed clock (relief late/absent, forced double shifts), and a shift is a separate explicit boundary. Drop expiresIn from the global jwt config and from login; the token carries no exp. Cookie maxAge = 30 days so a browser restart doesn't log out an active operator; logout still clears it.
113 lines
4.2 KiB
TypeScript
113 lines
4.2 KiB
TypeScript
import { randomBytes } from "node:crypto";
|
|
import type { FastifyReply, FastifyRequest } from "fastify";
|
|
import type { Role } from "@parking/shared";
|
|
|
|
// Local JWT auth helpers — fully local, no external identity provider
|
|
// (offline-first). The JWT is carried in an HttpOnly cookie (JS can't read it);
|
|
// a separate readable CSRF cookie + matching header defends mutations
|
|
// (double-submit). See wiki/entities/local-jwt-auth.md.
|
|
|
|
declare module "@fastify/jwt" {
|
|
interface FastifyJWT {
|
|
payload: { sub: string; username: string; role: Role; csrf: string };
|
|
user: { sub: string; username: string; role: Role; csrf: string };
|
|
}
|
|
}
|
|
|
|
export const TOKEN_COOKIE = "parking_token";
|
|
export const CSRF_COOKIE = "parking_csrf";
|
|
export const CSRF_HEADER = "x-csrf-token";
|
|
|
|
// Session lifetime: the JWT has NO expiry — a login is valid until explicit
|
|
// logout. Booth reality breaks any fixed clock (relief late/absent, forced double
|
|
// shifts), and a shift is a separate explicit boundary, not the token's lifetime.
|
|
// See wiki/entities/local-jwt-auth.md + wiki/concepts/shift.md.
|
|
//
|
|
// The cookie still needs a maxAge so it survives a browser restart (a session
|
|
// cookie would log out an active operator on browser close — the opposite of
|
|
// "until logout"). Use a long fixed window; the server clears it on logout.
|
|
export const COOKIE_MAX_AGE_SECONDS = 30 * 24 * 60 * 60; // 30 days
|
|
|
|
/**
|
|
* Resolve the JWT signing secret, refusing to start without a strong one.
|
|
* There is deliberately no fallback default — a missing, short, or placeholder
|
|
* secret throws so the server never runs with forgeable tokens.
|
|
*/
|
|
export function requireJwtSecret(): string {
|
|
const secret = process.env.JWT_SECRET;
|
|
if (!secret || secret.length < 32 || /change.?me|insecure|dev-only/i.test(secret)) {
|
|
throw new Error(
|
|
"JWT_SECRET must be set to a strong random value (>=32 chars). " +
|
|
"Generate one with: openssl rand -hex 32",
|
|
);
|
|
}
|
|
return secret;
|
|
}
|
|
|
|
/** Cookies are secure in production; relaxed for local http dev. */
|
|
function secureCookies(): boolean {
|
|
return process.env.NODE_ENV === "production";
|
|
}
|
|
|
|
export function newCsrfToken(): string {
|
|
return randomBytes(32).toString("hex");
|
|
}
|
|
|
|
/** Set the auth (HttpOnly) + CSRF (readable) cookies after a successful login. */
|
|
export function setAuthCookies(reply: FastifyReply, jwt: string, csrf: string): void {
|
|
const secure = secureCookies();
|
|
reply.setCookie(TOKEN_COOKIE, jwt, {
|
|
httpOnly: true,
|
|
sameSite: "strict",
|
|
secure,
|
|
path: "/",
|
|
maxAge: COOKIE_MAX_AGE_SECONDS,
|
|
});
|
|
// Readable by JS so the SPA can echo it back in the CSRF header (double-submit).
|
|
reply.setCookie(CSRF_COOKIE, csrf, {
|
|
httpOnly: false,
|
|
sameSite: "strict",
|
|
secure,
|
|
path: "/",
|
|
maxAge: COOKIE_MAX_AGE_SECONDS,
|
|
});
|
|
}
|
|
|
|
export function clearAuthCookies(reply: FastifyReply): void {
|
|
reply.clearCookie(TOKEN_COOKIE, { path: "/" });
|
|
reply.clearCookie(CSRF_COOKIE, { path: "/" });
|
|
}
|
|
|
|
const MUTATING = new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
|
|
|
/**
|
|
* Double-submit CSRF check: the X-CSRF-Token header must match the CSRF cookie.
|
|
* The CSRF token is bound into the JWT at login, so a stolen/forged cookie pair
|
|
* still can't pass unless it matches the signed token. Only enforced on
|
|
* state-changing methods (safe reads are exempt).
|
|
*/
|
|
function assertCsrf(req: FastifyRequest): void {
|
|
if (!MUTATING.has(req.method)) return;
|
|
const header = req.headers[CSRF_HEADER];
|
|
const cookie = req.cookies[CSRF_COOKIE];
|
|
const tokenCsrf = (req.user as { csrf?: string } | undefined)?.csrf;
|
|
if (!header || !cookie || header !== cookie || (tokenCsrf && header !== tokenCsrf)) {
|
|
throw Object.assign(new Error("invalid CSRF token"), { statusCode: 403 });
|
|
}
|
|
}
|
|
|
|
/**
|
|
* preHandler role guard. Verifies the JWT (from the HttpOnly cookie), enforces
|
|
* CSRF on mutations, then checks the role. Authorization is a simple per-route
|
|
* role check — no Casbin/RBAC engine needed at this scale.
|
|
*/
|
|
export function requireRole(...allowed: Role[]) {
|
|
return async (req: FastifyRequest, _reply: FastifyReply) => {
|
|
await req.jwtVerify(); // reads the token cookie (configured in server.ts)
|
|
assertCsrf(req);
|
|
if (!req.user || !allowed.includes(req.user.role)) {
|
|
throw Object.assign(new Error("forbidden"), { statusCode: 403 });
|
|
}
|
|
};
|
|
}
|