import { Inject, Injectable } from '@nestjs/common'; import { randomBytes } from 'node:crypto'; import type { PublicUser, Session, User } from '../domain/models'; import { SESSION_REPOSITORY, USER_REPOSITORY, type SessionRepository, type UserRepository, } from '../domain/ports'; import { sessionTtlDays } from './auth.constants'; // Owns the server-side session lifecycle. The cookie carries only the opaque // id; everything authoritative (which user, expiry) lives in the sessions // table, so a logout or expiry can't be undone client-side. @Injectable() export class SessionService { constructor( @Inject(SESSION_REPOSITORY) private readonly sessions: SessionRepository, @Inject(USER_REPOSITORY) private readonly users: UserRepository, ) {} // Strip the hash before anything leaves the service boundary. static toPublicUser(u: User): PublicUser { return { id: u.id, username: u.username, role: u.role, provider: u.provider }; } async create(userId: string): Promise { // 256 bits of entropy, url-safe. Opportunistically prune expired rows so // the table doesn't grow without bound (no separate cron needed). await this.sessions.deleteExpired(); const id = randomBytes(32).toString('base64url'); const expires = new Date(Date.now() + sessionTtlDays() * 24 * 60 * 60 * 1000); // UTC text format, matching the stored expires_at. const expiresAt = expires.toISOString().replace('T', ' ').slice(0, 19); return this.sessions.create({ id, user_id: userId, expires_at: expiresAt }); } // Resolves a session id to its user, or null if the session is missing, // expired, or its user was deleted. async resolve(sessionId: string | undefined): Promise { if (!sessionId) return null; const session = await this.sessions.findValid(sessionId); if (!session) return null; const user = await this.users.findById(session.user_id); return user ? SessionService.toPublicUser(user) : null; } async destroy(sessionId: string | undefined): Promise { if (sessionId) await this.sessions.delete(sessionId); } // Revoke every session of a user - after a password change or an operator // reset, any session in unknown hands must die with the old password. async destroyAllForUser(userId: string): Promise { await this.sessions.deleteByUser(userId); } }