import { BadRequestException, Body, Controller, Delete, Headers, HttpCode, HttpStatus, Post, UnauthorizedException, UseGuards, } from '@nestjs/common'; import { TextDecoder } from 'node:util'; import { AuthService } from './auth.service.js'; import { CurrentUserGuard } from '../common/auth/current-user.guard.js'; const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u; const BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'; function basicUnauthorized(): UnauthorizedException { return new UnauthorizedException({ message: 'Unauthorized', challenge: BASIC_CHALLENGE, }); } function bearerUnauthorized(): UnauthorizedException { return new UnauthorizedException({ message: 'Unauthorized', challenge: 'Bearer realm="messenger"', }); } function parseBasic(value: string | undefined): [string, string] { if (typeof value !== 'string') throw basicUnauthorized(); const match = /^Basic[ \t]+([^ \t]+)$/iu.exec(value); if (!match || !BASE64.test(match[1])) throw basicUnauthorized(); const bytes = Buffer.from(match[1], 'base64'); if (bytes.toString('base64') !== match[1]) throw basicUnauthorized(); let decoded: string; try { decoded = new TextDecoder('utf-8', { fatal: true }).decode(bytes); } catch { throw basicUnauthorized(); } const separator = decoded.indexOf(':'); if (separator < 1) throw basicUnauthorized(); return [decoded.slice(0, separator), decoded.slice(separator + 1)]; } @Controller('api/v1/auth/sessions') export class AuthController { constructor(private readonly auth: AuthService) {} @Post() create( @Headers('authorization') authorization: string | undefined, @Body() body: unknown, ) { const [username, password] = parseBasic(authorization); if (body !== undefined) throw new BadRequestException( 'Session creation does not accept a body', ); return this.auth.createSession(username, password); } @Delete('current') @UseGuards(CurrentUserGuard) @HttpCode(HttpStatus.NO_CONTENT) async delete( @Headers('authorization') authorization: string | undefined, ): Promise { if (!authorization || !/^Bearer\s+[^\s]+$/iu.test(authorization)) throw bearerUnauthorized(); await this.auth.deleteSession(authorization.slice(7).trim()); } }