diff --git a/server/src/auth/auth.controller.ts b/server/src/auth/auth.controller.ts index 5b48d27..b71916c 100644 --- a/server/src/auth/auth.controller.ts +++ b/server/src/auth/auth.controller.ts @@ -15,35 +15,19 @@ import { ApiResponse, ApiTags, } from "@nestjs/swagger"; -import { IsNotEmpty, IsString, MaxLength } from "class-validator"; import type { Request, Response } from "express"; -import { AUTH_COOKIE_NAME } from "./auth.constants"; import { AuthenticatedRequest } from "./auth.guard"; -import { AuthService } from "./auth.service"; +import { AuthService, AuthSession, SafeUser } from "./auth.service"; import { Public } from "./public.decorator"; - -export class LoginDto { - @IsString() - @IsNotEmpty() - @MaxLength(250) - username: string; - - @IsString() - @IsNotEmpty() - @MaxLength(1024) - password: string; -} - -function isHttps(request: Request): boolean { - const forwarded = request.get("x-forwarded-proto")?.split(",")[0].trim(); - return request.secure || forwarded === "https"; -} - -function cookieOptions(request: Request): string[] { - const options = ["Path=/", "HttpOnly", "SameSite=Strict"]; - if (isHttps(request)) options.push("Secure"); - return options; -} +import { LoginDto } from "./dto/login.dto"; +import { + clearedSessionCookie, + loginResponse, + sessionCookie, + sessionUser, +} from "./auth.helpers"; +import { AuthFailure } from "./auth.error"; +import { LoginResponseDto, SafeUserDto } from "./dto/auth-response.dto"; @ApiTags("auth") @Controller("auth") @@ -54,40 +38,56 @@ export class AuthController { @HttpCode(200) @Public() @ApiOperation({ summary: "Sign in and start a browser session" }) - @ApiResponse({ status: 200, description: "Signed in; session cookie set" }) + @ApiResponse({ + status: 200, + description: "Signed in; session cookie set", + type: LoginResponseDto, + }) @ApiResponse({ status: 401, description: "Invalid username or password" }) async login( @Body() dto: LoginDto, @Req() request: Request, @Res({ passthrough: true }) response: Response, - ) { - const session = await this.auth.login(dto.username, dto.password); - const maxAge = Math.max( - 0, - Math.floor((session.expiresAt.getTime() - Date.now()) / 1000), - ); + ): Promise<{ user: SafeUser }> { + if (!this.auth.enabled) + throw new NotFoundException("Authentication is disabled."); + let session: AuthSession; + try { + session = await this.auth.login(dto.username, dto.password); + } catch (error) { + if (error instanceof AuthFailure && error.reason === "disabled") { + throw new NotFoundException("Authentication is disabled."); + } + if ( + error instanceof AuthFailure && + error.reason === "invalid-credentials" + ) { + throw new UnauthorizedException("Invalid username or password."); + } + throw error; + } response.setHeader( "Set-Cookie", - `${AUTH_COOKIE_NAME}=${encodeURIComponent(session.token)}; ${[ - ...cookieOptions(request), - `Max-Age=${maxAge}`, - `Expires=${session.expiresAt.toUTCString()}`, - ].join("; ")}`, + sessionCookie(request, session, this.auth.cookieName), ); - return { user: session.user }; + return loginResponse(session.user); } @Get("me") @ApiBearerAuth() @ApiOperation({ summary: "Return the current authenticated user" }) - @ApiResponse({ status: 200, description: "Safe account identity" }) + @ApiResponse({ + status: 200, + description: "Safe account identity", + type: SafeUserDto, + }) @ApiResponse({ status: 401, description: "Missing or invalid credential" }) - me(@Req() request: AuthenticatedRequest) { + me(@Req() request: AuthenticatedRequest): SafeUser { if (!this.auth.enabled) { throw new NotFoundException("Authentication is disabled."); } if (!request.authSession) throw new UnauthorizedException(); - return request.authSession.user; + return sessionUser(request.authSession); } @Post("logout") @@ -106,11 +106,7 @@ export class AuthController { await this.auth.revoke(request.authSession); response.setHeader( "Set-Cookie", - `${AUTH_COOKIE_NAME}=; ${[ - ...cookieOptions(request), - "Max-Age=0", - "Expires=Thu, 01 Jan 1970 00:00:00 GMT", - ].join("; ")}`, + clearedSessionCookie(request, this.auth.cookieName), ); } } diff --git a/server/src/auth/auth.error.ts b/server/src/auth/auth.error.ts new file mode 100644 index 0000000..223acc8 --- /dev/null +++ b/server/src/auth/auth.error.ts @@ -0,0 +1,9 @@ +export type AuthFailureReason = + "disabled" | "invalid-credentials" | "invalid-token"; + +export class AuthFailure extends Error { + constructor(readonly reason: AuthFailureReason) { + super(reason); + this.name = "AuthFailure"; + } +} diff --git a/server/src/auth/auth.guard.ts b/server/src/auth/auth.guard.ts index 7a129df..941145c 100644 --- a/server/src/auth/auth.guard.ts +++ b/server/src/auth/auth.guard.ts @@ -7,39 +7,14 @@ import { import { Reflector } from "@nestjs/core"; import type { Request } from "express"; import { AuthService, AuthSession } from "./auth.service"; -import { AUTH_COOKIE_NAME } from "./auth.constants"; +import { requestToken } from "./auth.helpers"; import { IS_PUBLIC_KEY } from "./public.decorator"; +import { AuthFailure } from "./auth.error"; export interface AuthenticatedRequest extends Request { authSession?: AuthSession; } -function cookieToken(header: string | undefined): string | undefined { - if (!header) return undefined; - for (const item of header.split(";")) { - const separator = item.indexOf("="); - if (separator < 0 || item.slice(0, separator).trim() !== AUTH_COOKIE_NAME) { - continue; - } - const value = item.slice(separator + 1).trim(); - try { - return decodeURIComponent(value); - } catch { - return undefined; - } - } - return undefined; -} - -function requestToken(request: Request): string | undefined { - const authorization = request.get("authorization"); - if (authorization) { - const match = /^Bearer\s+(.+)$/i.exec(authorization); - return match?.[1].trim(); - } - return cookieToken(request.get("cookie")); -} - @Injectable() export class AuthGuard implements CanActivate { constructor( @@ -55,9 +30,14 @@ export class AuthGuard implements CanActivate { if (isPublic || !this.auth.enabled) return true; const request = context.switchToHttp().getRequest(); - const token = requestToken(request); + const token = requestToken(request, this.auth.cookieName); if (!token) throw new UnauthorizedException(); - request.authSession = await this.auth.authenticate(token); + try { + request.authSession = await this.auth.authenticate(token); + } catch (error) { + if (error instanceof AuthFailure) throw new UnauthorizedException(); + throw error; + } return true; } } diff --git a/server/src/auth/auth.helpers.ts b/server/src/auth/auth.helpers.ts new file mode 100644 index 0000000..2271cb0 --- /dev/null +++ b/server/src/auth/auth.helpers.ts @@ -0,0 +1,74 @@ +import type { Request } from "express"; +import { AUTH_COOKIE_NAME } from "./auth.constants"; +import type { AuthSession, SafeUser } from "./auth.service"; + +export function isHttps(request: Request): boolean { + const forwarded = request.get("x-forwarded-proto")?.split(",")[0].trim(); + return request.secure || forwarded === "https"; +} + +export function sessionCookie( + request: Request, + session: AuthSession, + cookieName = AUTH_COOKIE_NAME, +): string { + const maxAge = Math.max( + 0, + Math.floor((session.expiresAt.getTime() - Date.now()) / 1000), + ); + const options = ["Path=/", "HttpOnly", "SameSite=Strict"]; + if (isHttps(request)) options.push("Secure"); + options.push( + `Max-Age=${maxAge}`, + `Expires=${session.expiresAt.toUTCString()}`, + ); + return `${cookieName}=${encodeURIComponent(session.token)}; ${options.join("; ")}`; +} + +export function clearedSessionCookie( + request: Request, + cookieName = AUTH_COOKIE_NAME, +): string { + const options = ["Path=/", "HttpOnly", "SameSite=Strict"]; + if (isHttps(request)) options.push("Secure"); + options.push("Max-Age=0", "Expires=Thu, 01 Jan 1970 00:00:00 GMT"); + return `${cookieName}=; ${options.join("; ")}`; +} + +export function loginResponse(user: SafeUser): { user: SafeUser } { + return { user }; +} + +export function sessionUser(session: AuthSession): SafeUser { + return session.user; +} + +export function cookieToken( + header: string | undefined, + cookieName = AUTH_COOKIE_NAME, +): string | undefined { + if (!header) return undefined; + for (const item of header.split(";")) { + const separator = item.indexOf("="); + if (separator < 0 || item.slice(0, separator).trim() !== cookieName) { + continue; + } + try { + return decodeURIComponent(item.slice(separator + 1).trim()); + } catch { + return undefined; + } + } + return undefined; +} + +export function requestToken( + request: Request, + cookieName = AUTH_COOKIE_NAME, +): string | undefined { + const authorization = request.get("authorization"); + if (authorization) { + return /^Bearer\s+(.+)$/i.exec(authorization)?.[1].trim(); + } + return cookieToken(request.get("cookie"), cookieName); +} diff --git a/server/src/auth/auth.service.ts b/server/src/auth/auth.service.ts index 6e77eb5..0028152 100644 --- a/server/src/auth/auth.service.ts +++ b/server/src/auth/auth.service.ts @@ -1,16 +1,14 @@ -import { - Injectable, - NotFoundException, - UnauthorizedException, -} from "@nestjs/common"; +import { Injectable } from "@nestjs/common"; import { ConfigService } from "@nestjs/config"; import { InjectRepository } from "@nestjs/typeorm"; -import { createHash, createHmac, timingSafeEqual } from "node:crypto"; import { Repository } from "typeorm"; -import { AppConfig, authDurationSeconds } from "../config/app.config"; +import { AppConfig } from "../config/app.config"; +import { durationSeconds } from "../common/interval"; import { PasswordService } from "./password.service"; import { RevokedTokenEntity } from "./revoked-token.entity"; import { UserEntity } from "./user.entity"; +import { AuthFailure } from "./auth.error"; +import { issueJwt, safeUser, tokenHash, verifyJwt } from "./jwt.helpers"; export interface SafeUser { id: string; @@ -25,20 +23,6 @@ export interface AuthSession { expiresAt: Date; } -interface JwtPayload { - sub: string; - iat: number; - exp: number; -} - -function base64UrlJson(value: unknown): string { - return Buffer.from(JSON.stringify(value)).toString("base64url"); -} - -export function tokenHash(token: string): string { - return createHash("sha256").update(token).digest("hex"); -} - @Injectable() export class AuthService { constructor( @@ -54,16 +38,20 @@ export class AuthService { return this.config.get("AUTH_ENABLED"); } + get cookieName(): string { + return this.config.get("AUTH_COOKIE_NAME"); + } + async login(username: string, password: string): Promise { if (!this.enabled) { - throw new NotFoundException("Authentication is disabled."); + throw new AuthFailure("disabled"); } const user = await this.users.findOneBy({ username }); const valid = user ? await this.passwords.verify(password, user.passwordHash) : false; if (!user || !valid) { - throw new UnauthorizedException("Invalid username or password."); + throw new AuthFailure("invalid-credentials"); } return this.issueToken(user); } @@ -72,38 +60,34 @@ export class AuthService { user: Pick, ): AuthSession { if (!this.enabled) { - throw new NotFoundException("Authentication is disabled."); + throw new AuthFailure("disabled"); } - const issuedAt = Math.floor(Date.now() / 1000); - const expiresIn = authDurationSeconds( - this.config.get("AUTH_JWT_EXPIRES_IN"), - ); + const expiresIn = durationSeconds(this.config.get("AUTH_JWT_EXPIRES_IN")); if (expiresIn === null) { throw new Error("AUTH_JWT_EXPIRES_IN is not a valid positive duration."); } - const payload: JwtPayload = { - sub: user.id, - iat: issuedAt, - exp: issuedAt + expiresIn, - }; - const unsigned = `${base64UrlJson({ alg: "HS256", typ: "JWT" })}.${base64UrlJson(payload)}`; + const { token, expiresAt } = issueJwt( + user.id, + expiresIn, + this.config.get("AUTH_JWT_SECRET"), + ); return { - user: this.safeUser(user as UserEntity), - token: `${unsigned}.${this.sign(unsigned)}`, - expiresAt: new Date(payload.exp * 1000), + user: safeUser(user), + token, + expiresAt, }; } async authenticate(token: string): Promise { - const payload = this.verify(token); + const payload = verifyJwt(token, this.config.get("AUTH_JWT_SECRET")); const digest = tokenHash(token); if (await this.revokedTokens.findOneBy({ tokenHash: digest })) { - throw new UnauthorizedException(); + throw new AuthFailure("invalid-token"); } const user = await this.users.findOneBy({ id: payload.sub }); - if (!user) throw new UnauthorizedException(); + if (!user) throw new AuthFailure("invalid-token"); return { - user: this.safeUser(user), + user: safeUser(user), token, expiresAt: new Date(payload.exp * 1000), }; @@ -115,73 +99,4 @@ export class AuthService { expiresAt: session.expiresAt, }); } - - private sign(unsigned: string): string { - return createHmac("sha256", this.config.get("AUTH_JWT_SECRET")) - .update(unsigned) - .digest("base64url"); - } - - private verify(token: string): JwtPayload { - const parts = token.split("."); - if (parts.length !== 3 || parts.some((part) => part.length === 0)) { - throw new UnauthorizedException(); - } - - const [encodedHeader, encodedPayload, encodedSignature] = parts; - let header: unknown; - let payload: unknown; - let supplied: Buffer; - try { - header = JSON.parse( - Buffer.from(encodedHeader, "base64url").toString("utf8"), - ); - payload = JSON.parse( - Buffer.from(encodedPayload, "base64url").toString("utf8"), - ); - supplied = Buffer.from(encodedSignature, "base64url"); - } catch { - throw new UnauthorizedException(); - } - if ( - !header || - typeof header !== "object" || - (header as { alg?: unknown }).alg !== "HS256" - ) { - throw new UnauthorizedException(); - } - - const unsigned = `${encodedHeader}.${encodedPayload}`; - const expected = Buffer.from(this.sign(unsigned), "base64url"); - if ( - expected.length !== supplied.length || - !timingSafeEqual(expected, supplied) - ) { - throw new UnauthorizedException(); - } - if (!payload || typeof payload !== "object") { - throw new UnauthorizedException(); - } - const claims = payload as Partial; - const now = Math.floor(Date.now() / 1000); - if ( - typeof claims.sub !== "string" || - !claims.sub || - !Number.isSafeInteger(claims.iat) || - !Number.isSafeInteger(claims.exp) || - (claims.exp as number) <= now - ) { - throw new UnauthorizedException(); - } - return claims as JwtPayload; - } - - private safeUser(user: UserEntity): SafeUser { - return { - id: user.id, - username: user.username, - createdAt: user.createdAt, - updatedAt: user.updatedAt, - }; - } } diff --git a/server/src/auth/dto/auth-response.dto.ts b/server/src/auth/dto/auth-response.dto.ts new file mode 100644 index 0000000..65599b8 --- /dev/null +++ b/server/src/auth/dto/auth-response.dto.ts @@ -0,0 +1,20 @@ +import { ApiProperty } from "@nestjs/swagger"; + +export class SafeUserDto { + @ApiProperty() + id!: string; + + @ApiProperty() + username!: string; + + @ApiProperty({ type: String, format: "date-time" }) + createdAt!: Date; + + @ApiProperty({ type: String, format: "date-time" }) + updatedAt!: Date; +} + +export class LoginResponseDto { + @ApiProperty({ type: SafeUserDto }) + user!: SafeUserDto; +} diff --git a/server/src/auth/dto/login.dto.ts b/server/src/auth/dto/login.dto.ts new file mode 100644 index 0000000..cabacad --- /dev/null +++ b/server/src/auth/dto/login.dto.ts @@ -0,0 +1,13 @@ +import { IsNotEmpty, IsString, MaxLength } from "class-validator"; + +export class LoginDto { + @IsString() + @IsNotEmpty() + @MaxLength(250) + username!: string; + + @IsString() + @IsNotEmpty() + @MaxLength(1024) + password!: string; +} diff --git a/server/src/auth/jwt.helpers.ts b/server/src/auth/jwt.helpers.ts new file mode 100644 index 0000000..9502ce9 --- /dev/null +++ b/server/src/auth/jwt.helpers.ts @@ -0,0 +1,98 @@ +import { createHash, createHmac, timingSafeEqual } from "node:crypto"; +import { AuthFailure } from "./auth.error"; +import { SafeUser } from "./auth.service"; +import { UserEntity } from "./user.entity"; + +export interface JwtPayload { + sub: string; + iat: number; + exp: number; +} + +export function safeUser( + user: Pick, +): SafeUser { + return { + id: user.id, + username: user.username, + createdAt: user.createdAt, + updatedAt: user.updatedAt, + }; +} + +export function tokenHash(token: string): string { + return createHash("sha256").update(token).digest("hex"); +} + +function base64UrlJson(value: unknown): string { + return Buffer.from(JSON.stringify(value)).toString("base64url"); +} + +function sign(unsigned: string, secret: string): string { + return createHmac("sha256", secret).update(unsigned).digest("base64url"); +} + +export function issueJwt( + userId: string, + expiresIn: number, + secret: string, +): { token: string; expiresAt: Date } { + const issuedAt = Math.floor(Date.now() / 1000); + const payload: JwtPayload = { + sub: userId, + iat: issuedAt, + exp: issuedAt + expiresIn, + }; + const unsigned = `${base64UrlJson({ alg: "HS256", typ: "JWT" })}.${base64UrlJson(payload)}`; + return { + token: `${unsigned}.${sign(unsigned, secret)}`, + expiresAt: new Date(payload.exp * 1000), + }; +} + +export function verifyJwt(token: string, secret: string): JwtPayload { + const parts = token.split("."); + if (parts.length !== 3 || parts.some((part) => part.length === 0)) + throw new AuthFailure("invalid-token"); + const [encodedHeader, encodedPayload, encodedSignature] = parts; + let header: unknown; + let payload: unknown; + let supplied: Buffer; + try { + header = JSON.parse( + Buffer.from(encodedHeader, "base64url").toString("utf8"), + ); + payload = JSON.parse( + Buffer.from(encodedPayload, "base64url").toString("utf8"), + ); + supplied = Buffer.from(encodedSignature, "base64url"); + } catch { + throw new AuthFailure("invalid-token"); + } + if ( + !header || + typeof header !== "object" || + (header as { alg?: unknown }).alg !== "HS256" + ) + throw new AuthFailure("invalid-token"); + const unsigned = `${encodedHeader}.${encodedPayload}`; + const expected = Buffer.from(sign(unsigned, secret), "base64url"); + if ( + expected.length !== supplied.length || + !timingSafeEqual(expected, supplied) + ) + throw new AuthFailure("invalid-token"); + if (!payload || typeof payload !== "object") + throw new AuthFailure("invalid-token"); + const claims = payload as Partial; + const now = Math.floor(Date.now() / 1000); + if ( + typeof claims.sub !== "string" || + !claims.sub || + !Number.isSafeInteger(claims.iat) || + !Number.isSafeInteger(claims.exp) || + (claims.exp as number) <= now + ) + throw new AuthFailure("invalid-token"); + return claims as JwtPayload; +} diff --git a/server/src/auth/password.service.ts b/server/src/auth/password.service.ts index 7ebfe31..c7741bc 100644 --- a/server/src/auth/password.service.ts +++ b/server/src/auth/password.service.ts @@ -1,10 +1,14 @@ import { randomBytes, scrypt, timingSafeEqual } from "node:crypto"; import { Injectable } from "@nestjs/common"; +// N=2^14 is the baseline scrypt CPU/memory cost; verify permits bounded future upgrades. const SCRYPT_N = 16384; +// r=8 and p=1 are the standard scrypt block size and parallelization for this cost. const SCRYPT_R = 8; const SCRYPT_P = 1; +// A 128-bit random salt prevents practical salt collisions across stored passwords. const SALT_BYTES = 16; +// 512-bit output gives ample margin for password verification. const HASH_BYTES = 64; function derive( diff --git a/server/src/auth/public.decorator.ts b/server/src/auth/public.decorator.ts index 7beff6f..2ac9963 100644 --- a/server/src/auth/public.decorator.ts +++ b/server/src/auth/public.decorator.ts @@ -1,4 +1,4 @@ import { SetMetadata } from "@nestjs/common"; -export const IS_PUBLIC_KEY = "isPublic"; +export const IS_PUBLIC_KEY = Symbol("isPublic"); export const Public = () => SetMetadata(IS_PUBLIC_KEY, true); diff --git a/server/src/common/interval.ts b/server/src/common/interval.ts new file mode 100644 index 0000000..984b7a5 --- /dev/null +++ b/server/src/common/interval.ts @@ -0,0 +1,11 @@ +/** Parse a positive duration (seconds, minutes, hours, or days) into seconds. */ +export function durationSeconds(value: string): number | null { + const match = /^(\d+)(s|m|h|d)$/.exec(value); + if (!match) return null; + const amount = Number(match[1]); + const multiplier = { s: 1, m: 60, h: 3600, d: 86400 }[ + match[2] as "s" | "m" | "h" | "d" + ]; + const seconds = amount * multiplier; + return Number.isSafeInteger(seconds) && seconds > 0 ? seconds : null; +} diff --git a/server/src/config/app.config.ts b/server/src/config/app.config.ts index 3d5f882..ad7b278 100644 --- a/server/src/config/app.config.ts +++ b/server/src/config/app.config.ts @@ -12,16 +12,7 @@ import { import { appPackage } from "../common/app-package"; -export function authDurationSeconds(value: string): number | null { - const match = /^(\d+)(s|m|h|d)$/.exec(value); - if (!match) return null; - const amount = Number(match[1]); - const multiplier = { s: 1, m: 60, h: 3600, d: 86400 }[ - match[2] as "s" | "m" | "h" | "d" - ]; - const seconds = amount * multiplier; - return Number.isSafeInteger(seconds) && seconds > 0 ? seconds : null; -} +import { durationSeconds } from "../common/interval"; export enum TraceMode { On = "on", @@ -96,6 +87,10 @@ export class AppConfig { @IsString() AUTH_JWT_SECRET: string = ""; + /** Cookie name used for browser sessions. */ + @IsString() + AUTH_COOKIE_NAME: string = "liqa_auth"; + @IsString() AUTH_JWT_EXPIRES_IN: string = "24h"; @@ -130,7 +125,7 @@ export function validateAppConfig(config: Record): AppConfig { } if ( validated.AUTH_ENABLED && - authDurationSeconds(validated.AUTH_JWT_EXPIRES_IN) === null + durationSeconds(validated.AUTH_JWT_EXPIRES_IN) === null ) { throw new Error( "AUTH_JWT_EXPIRES_IN must be a positive duration such as 30m, 1h, or 24h.", diff --git a/server/src/manifest/manifest.dto.ts b/server/src/manifest/manifest.dto.ts index 2ac738a..1b73709 100644 --- a/server/src/manifest/manifest.dto.ts +++ b/server/src/manifest/manifest.dto.ts @@ -29,7 +29,7 @@ export class ManifestDto { version!: string; @ApiProperty({ - description: "Whether optional account authentication is enabled.", + description: "Whether account authentication is enabled.", type: "object", properties: { enabled: { type: "boolean", example: false } }, }) diff --git a/server/test/auth-config.spec.ts b/server/test/auth-config.spec.ts index 83ab381..4e19c7d 100644 --- a/server/test/auth-config.spec.ts +++ b/server/test/auth-config.spec.ts @@ -1,8 +1,6 @@ import "reflect-metadata"; -import { - authDurationSeconds, - validateAppConfig, -} from "../src/config/app.config"; +import { validateAppConfig } from "../src/config/app.config"; +import { durationSeconds } from "../src/common/interval"; describe("Authentication configuration", () => { it("defaults authentication off with a 24-hour token lifetime and cleanup schedule", () => { @@ -10,6 +8,7 @@ describe("Authentication configuration", () => { expect(config.AUTH_ENABLED).toBe(false); expect(config.AUTH_JWT_EXPIRES_IN).toBe("24h"); + expect(config.AUTH_COOKIE_NAME).toBe("liqa_auth"); expect(config.AUTH_REVOKED_TOKEN_CLEANUP_CRON).toBe("0 3 * * *"); }); @@ -46,9 +45,9 @@ describe("Authentication configuration", () => { expect(() => validateAppConfig({ AUTH_ENABLED: "yes" })).toThrow( "AUTH_ENABLED must be either true or false", ); - expect(authDurationSeconds("30m")).toBe(1800); - expect(authDurationSeconds("24h")).toBe(86400); - expect(authDurationSeconds("2d")).toBe(172800); - expect(authDurationSeconds("0s")).toBeNull(); + expect(durationSeconds("30m")).toBe(1800); + expect(durationSeconds("24h")).toBe(86400); + expect(durationSeconds("2d")).toBe(172800); + expect(durationSeconds("0s")).toBeNull(); }); }); diff --git a/server/test/auth-disabled.spec.ts b/server/test/auth-disabled.spec.ts index 262079a..929ebba 100644 --- a/server/test/auth-disabled.spec.ts +++ b/server/test/auth-disabled.spec.ts @@ -31,4 +31,11 @@ describe("authentication disabled", () => { .expect(200); expect(manifest.body.auth).toEqual({ enabled: false }); }); + + it("returns not found for login while authentication is disabled", async () => { + await request(app.getHttpServer()) + .post("/auth/login") + .send({ username: "nobody", password: "synthetic" }) + .expect(404); + }); }); diff --git a/server/test/auth-helpers.spec.ts b/server/test/auth-helpers.spec.ts new file mode 100644 index 0000000..4b09588 --- /dev/null +++ b/server/test/auth-helpers.spec.ts @@ -0,0 +1,57 @@ +import { AuthSession } from "../src/auth/auth.service"; +import { + clearedSessionCookie, + cookieToken, + requestToken, + sessionCookie, +} from "../src/auth/auth.helpers"; +import { Public, IS_PUBLIC_KEY } from "../src/auth/public.decorator"; + +describe("authentication helpers", () => { + const request = { + secure: false, + get: (name: string) => + name === "x-forwarded-proto" ? undefined : undefined, + } as never; + const session: AuthSession = { + user: { + id: "u", + username: "user", + createdAt: new Date(0), + updatedAt: new Date(0), + }, + token: "a.token.value", + expiresAt: new Date(Date.now() + 60_000), + }; + + it("sets and clears a configurable cookie name", () => { + expect(sessionCookie(request, session, "custom_session")).toContain( + "custom_session=a.token.value", + ); + expect(clearedSessionCookie(request, "custom_session")).toContain( + "custom_session=;", + ); + }); + + it("reads only the selected cookie and supports bearer credentials", () => { + expect( + cookieToken("other=x; custom_session=encoded%20value", "custom_session"), + ).toBe("encoded value"); + expect( + requestToken( + { + get: (name: string) => + name === "authorization" ? "Bearer token" : undefined, + } as never, + "x", + ), + ).toBe("token"); + }); + + it("stores public-route metadata under a Symbol key", () => { + class PublicController {} + Public()(PublicController); + expect(typeof IS_PUBLIC_KEY).toBe("symbol"); + expect(Reflect.getMetadata(IS_PUBLIC_KEY, PublicController)).toBe(true); + }); +}); diff --git a/server/test/auth.spec.ts b/server/test/auth.spec.ts index 8dd3c73..4f45eca 100644 --- a/server/test/auth.spec.ts +++ b/server/test/auth.spec.ts @@ -4,7 +4,7 @@ import request from "supertest"; import { Repository } from "typeorm"; import { filter, firstValueFrom, timeout } from "rxjs"; import { AuthService } from "../src/auth/auth.service"; -import { tokenHash } from "../src/auth/auth.service"; +import { tokenHash } from "../src/auth/jwt.helpers"; import { PasswordService } from "../src/auth/password.service"; import { RevokedTokenEntity } from "../src/auth/revoked-token.entity"; import { EnvironmentService } from "../src/environment/environment.service"; diff --git a/server/test/manifest.spec.ts b/server/test/manifest.spec.ts index 3b12513..cbe91b8 100644 --- a/server/test/manifest.spec.ts +++ b/server/test/manifest.spec.ts @@ -1,9 +1,22 @@ import { INestApplication } from "@nestjs/common"; import request from "supertest"; import { appPackage } from "../src/common/app-package"; +import { ManifestDto } from "../src/manifest/manifest.dto"; import { buildTestApp } from "./app.harness"; describe("GET /manifest.json", () => { + it("describes the manifest auth flag without describing authentication as optional", () => { + const authProperty = Reflect.getMetadata( + "swagger/apiModelProperties", + ManifestDto.prototype, + "auth", + ) as { description: string }; + expect(authProperty.description).toBe( + "Whether account authentication is enabled.", + ); + expect(authProperty.description).not.toContain("optional"); + }); + let app: INestApplication; afterEach(async () => {