dorfteich/apps/api/src/auth/auth.guard.ts
Claude Fable 5 db4c5ce9ca
All checks were successful
CI / Lint, typecheck, test (pull_request) Successful in 4m53s
CI / Build container images (pull_request) Successful in 3m55s
CI / Auth e2e pack (pull_request) Successful in 7m53s
CI / Import/export fidelity gate (pull_request) Successful in 55s
CD / Build and push images (push) Successful in 19s
CD / Deploy to Test (push) Successful in 12s
CD / Smoke tests against Test (push) Successful in 1m17s
CD / Promote to Int (push) Successful in 11s
CI / Lint, typecheck, test (push) Successful in 4m53s
CI / Build container images (push) Has been skipped
CI / Auth e2e pack (push) Successful in 7m37s
CI / Import/export fidelity gate (push) Successful in 52s
#190: configurable session lifetime with a server-side idle timeout
SESSION_ABSOLUTE_HOURS (default 168 h) caps a session's total lifetime
from login: expiresAt is set once at creation and never extended — the
old sliding 30-day renewal is gone. SESSION_IDLE_HOURS (default 72 h)
ends sessions unused for that long, enforced server-side against
lastSeenAt with a write throttle scaled to the idle bound so short idle
windows still renew. Expired rows are removed on validation and the
session list applies both bounds, so idle-dead sessions never show as
active. The cookie maxAge follows the configured absolute bound.

Documented in .env.example (with the VS-NfD reference values for the
upcoming hardening guide #227), compose passes the variables through,
security.md and ADR 0007 record the amendment.

Refs #190

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0168Ph5uBmHm8X28CSVpbpnJ
2026-07-30 11:11:15 +02:00

143 lines
4.7 KiB
TypeScript

import {
CanActivate,
ExecutionContext,
ForbiddenException,
Injectable,
SetMetadata,
UnauthorizedException,
createParamDecorator,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import type { CurrentUser as CurrentUserShape } from '@dorfteich/shared';
import type { User } from '@prisma/client';
import type { Request, Response } from 'express';
import { AppConfig } from '../config/app-config.service';
import { SessionsService } from './sessions.service';
export const SESSION_COOKIE = 'dt_session';
const IS_PUBLIC_KEY = 'isPublic';
/** Marks a route as reachable without a session (login, signup, healthz…). */
export const Public = (): MethodDecorator & ClassDecorator => SetMetadata(IS_PUBLIC_KEY, true);
export interface AuthedRequest extends Request {
user?: User;
sessionId?: string;
sessionToken?: string;
}
/** Injects the authenticated Prisma user into a handler parameter. */
export const CurrentUser = createParamDecorator((_data: unknown, context: ExecutionContext) => {
return context.switchToHttp().getRequest<AuthedRequest>().user;
});
export function toCurrentUser(user: User): CurrentUserShape {
return {
id: user.id,
username: user.username,
email: user.email,
displayName: user.displayName,
locale: user.locale === 'de' ? 'de' : 'en',
isSiteAdmin: user.isSiteAdmin,
autoWatchOwnPages: user.autoWatchOwnPages,
autoWatchOnComment: user.autoWatchOnComment,
digestFrequency:
user.digestFrequency === 'daily' || user.digestFrequency === 'off'
? user.digestFrequency
: 'hourly',
};
}
/**
* Session cookie contract shared by login and the setup wizard (issue #80).
* `maxAgeMs` follows the configured absolute session bound (#190) — the
* server-side idle/absolute checks are authoritative, the cookie merely
* stops outliving them.
*/
export function setSessionCookie(
response: Response,
token: string,
production: boolean,
maxAgeMs: number,
): void {
response.cookie(SESSION_COOKIE, token, {
httpOnly: true,
sameSite: 'lax',
secure: production,
maxAge: maxAgeMs,
path: '/',
});
}
const MUTATING_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
/**
* Global authentication guard: routes are protected by default and opt
* out with @Public(). Also enforces the CSRF origin check on mutating
* requests that carry a session cookie — SameSite=Lax is the first line
* of defense, this is the second (security.md).
*/
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private readonly reflector: Reflector,
private readonly sessions: SessionsService,
private readonly config: AppConfig,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<AuthedRequest>();
const rawToken = (request.cookies as Record<string, string> | undefined)?.[SESSION_COOKIE];
if (rawToken && MUTATING_METHODS.has(request.method)) {
this.assertSameOrigin(request);
}
// Attach the user whenever the cookie is valid — public routes may
// still want to know who is asking.
if (rawToken) {
const validated = await this.sessions.validate(rawToken);
if (validated) {
request.user = validated.user;
request.sessionId = validated.session.id;
request.sessionToken = rawToken;
}
}
const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
context.getHandler(),
context.getClass(),
]);
if (isPublic) return true;
if (!request.user) throw new UnauthorizedException();
return true;
}
/**
* Fail closed (#189): a cookie-carrying mutation must prove its origin —
* browsers always send `Origin` on cross- and same-origin mutations, so a
* missing header means "not a browser page of ours" and is rejected like a
* mismatch. Non-browser clients (curl, scripts) either send a matching
* `Origin` explicitly or authenticate with a PAT/bearer token and no
* cookie, which never reaches this check — the exception for them is
* structural (bound to the cookie), never a header loophole.
*/
private assertSameOrigin(request: Request): void {
const origin = request.headers.origin ?? request.headers.referer;
if (!origin) throw new ForbiddenException({ code: 'csrf_origin_mismatch' });
const expected = new URL(this.config.env.APP_BASE_URL).origin;
let actual: string;
try {
actual = new URL(origin).origin;
} catch {
// An unparsable Origin/Referer is a broken or hostile client, not ours.
throw new ForbiddenException({ code: 'csrf_origin_mismatch' });
}
if (actual !== expected) {
throw new ForbiddenException({ code: 'csrf_origin_mismatch' });
}
}
}