Files
mtusi2026lab2/src/auth/auth.service.ts
T
2026-10-21 11:01:29 +03:00

149 lines
4.0 KiB
TypeScript

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> {
await this.prisma.session.deleteMany({ where: { tokenHash } });
await this.cache.set(cacheKey(tokenHash), REVOKED, CACHE_TTL_MS);
}
}
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;
}