chore: port lab5 solution as lab6 base

This commit is contained in:
2026-11-18 18:40:47 +03:00
parent 470d9d6f1e
commit 98d5787545
105 changed files with 21898 additions and 0 deletions
+51
View File
@@ -0,0 +1,51 @@
import {
Controller,
Delete,
Headers,
HttpCode,
Post,
Req,
UseGuards,
} from '@nestjs/common';
import { FastifyRequest } from 'fastify';
import { ApiError } from '../common/filters/api-error';
import { toUserResponse, UserResponse } from '../users/dto/user.response';
import { AuthGuard } from './auth.guard';
import { AuthService } from './auth.service';
interface SessionResponse {
token: string;
token_type: 'Bearer';
expires_at: string;
user: UserResponse;
}
@Controller('api/v1/auth/sessions')
export class AuthController {
constructor(private readonly auth: AuthService) {}
@Post()
@HttpCode(201)
async create(
@Headers('authorization') authorization: string | undefined,
@Req() request: FastifyRequest,
): Promise<SessionResponse> {
if (request.body !== undefined) {
throw new ApiError('invalid_request', 'request body is not allowed');
}
const session = await this.auth.login(authorization);
return {
token: session.token,
token_type: 'Bearer',
expires_at: session.expiresAt.toISOString(),
user: toUserResponse(session.user),
};
}
@Delete('current')
@HttpCode(204)
@UseGuards(AuthGuard)
async revoke(@Req() request: FastifyRequest): Promise<void> {
await this.auth.revoke(request.sessionTokenHash!);
}
}
+25
View File
@@ -0,0 +1,25 @@
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { FastifyRequest } from 'fastify';
import { ApiError } from '../common/filters/api-error';
import { AuthService } from './auth.service';
const BEARER_CHALLENGE = 'Bearer realm="messenger"';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private readonly auth: AuthService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<FastifyRequest>();
const match = /^Bearer (\S+)$/i.exec(request.headers.authorization ?? '');
const session = match ? await this.auth.resolve(match[1]) : null;
if (!session) {
throw new ApiError('unauthorized', 'missing or invalid session', {
'WWW-Authenticate': BEARER_CHALLENGE,
});
}
request.currentUser = session.user;
request.sessionTokenHash = session.tokenHash;
return true;
}
}
+12
View File
@@ -0,0 +1,12 @@
import { Global, Module } from '@nestjs/common';
import { AuthController } from './auth.controller';
import { AuthGuard } from './auth.guard';
import { AuthService } from './auth.service';
@Global()
@Module({
controllers: [AuthController],
providers: [AuthService, AuthGuard],
exports: [AuthService, AuthGuard],
})
export class AuthModule {}
+155
View File
@@ -0,0 +1,155 @@
import { Injectable } from '@nestjs/common';
import { createHash, randomBytes } from 'crypto';
import { CacheService } from '../cache/cache.service';
import { codePointLength } from '../common/dto/code-point-length.validator';
import { User } from '../common/domain';
import { ApiError } from '../common/filters/api-error';
import { PrismaService } from '../db/prisma.service';
import { toUser } from '../users/users.service';
import { verifyPassword } from './password';
const BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"';
const USERNAME_PATTERN = /^[a-z0-9_]{3,32}$/;
const CACHE_TTL_MS = 60_000;
const REVOKED = 'revoked';
interface CachedSession {
user: User;
expiresAt: number;
}
export interface CreatedSession {
token: string;
expiresAt: Date;
user: User;
}
export interface ResolvedSession {
tokenHash: string;
user: User;
}
@Injectable()
export class AuthService {
private readonly ttlSeconds = readSessionTtl();
constructor(
private readonly prisma: PrismaService,
private readonly cache: CacheService,
) {}
async login(authorization: string | undefined): Promise<CreatedSession> {
const credentials = parseBasic(authorization);
if (!credentials) {
throw invalidCredentials();
}
const row = await this.prisma.user.findUnique({
where: { username: credentials.username },
});
const valid = await verifyPassword(
row?.passwordHash ?? null,
credentials.password,
);
if (!row || !valid) {
throw invalidCredentials();
}
const token = randomBytes(32).toString('base64url');
const expiresAt = new Date(Date.now() + this.ttlSeconds * 1000);
await this.prisma.session.create({
data: { tokenHash: hashToken(token), userId: row.id, expiresAt },
});
return { token, expiresAt, user: toUser(row) };
}
async resolve(token: string): Promise<ResolvedSession | null> {
const tokenHash = hashToken(token);
const key = cacheKey(tokenHash);
const cached = await this.cache.get(key);
if (cached === REVOKED) {
return null;
}
if (cached) {
const entry = JSON.parse(cached) as CachedSession;
if (entry.expiresAt > Date.now()) {
return { tokenHash, user: entry.user };
}
}
const session = await this.prisma.session.findUnique({
where: { tokenHash },
include: { user: true },
});
const remainingMs = session
? session.expiresAt.getTime() - Date.now()
: 0;
if (!session || remainingMs <= 0) {
return null;
}
const user = toUser(session.user);
const entry: CachedSession = {
user,
expiresAt: session.expiresAt.getTime(),
};
await this.cache.set(
key,
JSON.stringify(entry),
Math.min(remainingMs, CACHE_TTL_MS),
true,
);
return { tokenHash, user };
}
async revoke(tokenHash: string): Promise<void> {
const marked = await this.cache.setStrict(
cacheKey(tokenHash),
REVOKED,
CACHE_TTL_MS,
);
if (!marked) {
throw new ApiError('unavailable', 'session cache unavailable');
}
await this.prisma.session.deleteMany({ where: { tokenHash } });
}
}
function cacheKey(tokenHash: string): string {
return `session:v1:${tokenHash}`;
}
function parseBasic(
header: string | undefined,
): { username: string; password: string } | null {
const match = /^Basic ([A-Za-z0-9+/]+={0,2})$/i.exec(header ?? '');
if (!match) {
return null;
}
const decoded = Buffer.from(match[1], 'base64').toString('utf8');
const separator = decoded.indexOf(':');
if (separator < 0) {
return null;
}
const username = decoded.slice(0, separator);
const password = decoded.slice(separator + 1);
const length = codePointLength(password);
if (!USERNAME_PATTERN.test(username) || length < 12 || length > 128) {
return null;
}
return { username, password };
}
function hashToken(token: string): string {
return createHash('sha256').update(token).digest('hex');
}
function invalidCredentials(): ApiError {
return new ApiError('unauthorized', 'invalid credentials', {
'WWW-Authenticate': BASIC_CHALLENGE,
});
}
function readSessionTtl(): number {
const ttl = Number(process.env.SESSION_TTL_SECONDS ?? 3600);
if (!Number.isInteger(ttl) || ttl <= 0) {
throw new Error('SESSION_TTL_SECONDS must be a positive integer');
}
return ttl;
}
+20
View File
@@ -0,0 +1,20 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { FastifyRequest } from 'fastify';
import { User } from '../common/domain';
declare module 'fastify' {
interface FastifyRequest {
currentUser?: User;
sessionTokenHash?: string;
}
}
export const CurrentUser = createParamDecorator(
(_data: unknown, ctx: ExecutionContext): User => {
const request = ctx.switchToHttp().getRequest<FastifyRequest>();
if (!request.currentUser) {
throw new Error('CurrentUser used without AuthGuard');
}
return request.currentUser;
},
);
+17
View File
@@ -0,0 +1,17 @@
import { argon2id, hash, verify } from 'argon2';
const OPTIONS = { type: argon2id, memoryCost: 19456, timeCost: 2, parallelism: 1 };
const dummyHash = hash('timing-equalizer-password', OPTIONS);
export function hashPassword(password: string): Promise<string> {
return hash(password, OPTIONS);
}
export async function verifyPassword(
passwordHash: string | null,
password: string,
): Promise<boolean> {
const valid = await verify(passwordHash ?? (await dummyHash), password);
return passwordHash !== null && valid;
}