refactor(auth): address server review feedback
- Extract auth DTOs, cookie/JWT helpers and the generic duration parser. - Configure the session cookie and map domain auth failures to HTTP responses. - Add typed Swagger responses and focused regression coverage.
This commit is contained in:
1 parent
72e127888c
commit
1830feb71b
18 files changed
+399
-208
No files matched your search
@@ -15,35 +15,19 @@ import {
|
|||||||
ApiResponse,
|
ApiResponse,
|
||||||
ApiTags,
|
ApiTags,
|
||||||
} from "@nestjs/swagger";
|
} from "@nestjs/swagger";
|
||||||
import { IsNotEmpty, IsString, MaxLength } from "class-validator";
|
|
||||||
import type { Request, Response } from "express";
|
import type { Request, Response } from "express";
|
||||||
import { AUTH_COOKIE_NAME } from "./auth.constants";
|
|
||||||
import { AuthenticatedRequest } from "./auth.guard";
|
import { AuthenticatedRequest } from "./auth.guard";
|
||||||
import { AuthService } from "./auth.service";
|
import { AuthService, AuthSession, SafeUser } from "./auth.service";
|
||||||
import { Public } from "./public.decorator";
|
import { Public } from "./public.decorator";
|
||||||
|
import { LoginDto } from "./dto/login.dto";
|
||||||
export class LoginDto {
|
import {
|
||||||
@IsString()
|
clearedSessionCookie,
|
||||||
@IsNotEmpty()
|
loginResponse,
|
||||||
@MaxLength(250)
|
sessionCookie,
|
||||||
username: string;
|
sessionUser,
|
||||||
|
} from "./auth.helpers";
|
||||||
@IsString()
|
import { AuthFailure } from "./auth.error";
|
||||||
@IsNotEmpty()
|
import { LoginResponseDto, SafeUserDto } from "./dto/auth-response.dto";
|
||||||
@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;
|
|
||||||
}
|
|
||||||
|
|
||||||
@ApiTags("auth")
|
@ApiTags("auth")
|
||||||
@Controller("auth")
|
@Controller("auth")
|
||||||
@@ -54,40 +38,56 @@ export class AuthController {
|
|||||||
@HttpCode(200)
|
@HttpCode(200)
|
||||||
@Public()
|
@Public()
|
||||||
@ApiOperation({ summary: "Sign in and start a browser session" })
|
@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" })
|
@ApiResponse({ status: 401, description: "Invalid username or password" })
|
||||||
async login(
|
async login(
|
||||||
@Body() dto: LoginDto,
|
@Body() dto: LoginDto,
|
||||||
@Req() request: Request,
|
@Req() request: Request,
|
||||||
@Res({ passthrough: true }) response: Response,
|
@Res({ passthrough: true }) response: Response,
|
||||||
) {
|
): Promise<{ user: SafeUser }> {
|
||||||
const session = await this.auth.login(dto.username, dto.password);
|
if (!this.auth.enabled)
|
||||||
const maxAge = Math.max(
|
throw new NotFoundException("Authentication is disabled.");
|
||||||
0,
|
let session: AuthSession;
|
||||||
Math.floor((session.expiresAt.getTime() - Date.now()) / 1000),
|
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(
|
response.setHeader(
|
||||||
"Set-Cookie",
|
"Set-Cookie",
|
||||||
`${AUTH_COOKIE_NAME}=${encodeURIComponent(session.token)}; ${[
|
sessionCookie(request, session, this.auth.cookieName),
|
||||||
...cookieOptions(request),
|
|
||||||
`Max-Age=${maxAge}`,
|
|
||||||
`Expires=${session.expiresAt.toUTCString()}`,
|
|
||||||
].join("; ")}`,
|
|
||||||
);
|
);
|
||||||
return { user: session.user };
|
return loginResponse(session.user);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get("me")
|
@Get("me")
|
||||||
@ApiBearerAuth()
|
@ApiBearerAuth()
|
||||||
@ApiOperation({ summary: "Return the current authenticated user" })
|
@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" })
|
@ApiResponse({ status: 401, description: "Missing or invalid credential" })
|
||||||
me(@Req() request: AuthenticatedRequest) {
|
me(@Req() request: AuthenticatedRequest): SafeUser {
|
||||||
if (!this.auth.enabled) {
|
if (!this.auth.enabled) {
|
||||||
throw new NotFoundException("Authentication is disabled.");
|
throw new NotFoundException("Authentication is disabled.");
|
||||||
}
|
}
|
||||||
if (!request.authSession) throw new UnauthorizedException();
|
if (!request.authSession) throw new UnauthorizedException();
|
||||||
return request.authSession.user;
|
return sessionUser(request.authSession);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post("logout")
|
@Post("logout")
|
||||||
@@ -106,11 +106,7 @@ export class AuthController {
|
|||||||
await this.auth.revoke(request.authSession);
|
await this.auth.revoke(request.authSession);
|
||||||
response.setHeader(
|
response.setHeader(
|
||||||
"Set-Cookie",
|
"Set-Cookie",
|
||||||
`${AUTH_COOKIE_NAME}=; ${[
|
clearedSessionCookie(request, this.auth.cookieName),
|
||||||
...cookieOptions(request),
|
|
||||||
"Max-Age=0",
|
|
||||||
"Expires=Thu, 01 Jan 1970 00:00:00 GMT",
|
|
||||||
].join("; ")}`,
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,39 +7,14 @@ import {
|
|||||||
import { Reflector } from "@nestjs/core";
|
import { Reflector } from "@nestjs/core";
|
||||||
import type { Request } from "express";
|
import type { Request } from "express";
|
||||||
import { AuthService, AuthSession } from "./auth.service";
|
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 { IS_PUBLIC_KEY } from "./public.decorator";
|
||||||
|
import { AuthFailure } from "./auth.error";
|
||||||
|
|
||||||
export interface AuthenticatedRequest extends Request {
|
export interface AuthenticatedRequest extends Request {
|
||||||
authSession?: AuthSession;
|
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()
|
@Injectable()
|
||||||
export class AuthGuard implements CanActivate {
|
export class AuthGuard implements CanActivate {
|
||||||
constructor(
|
constructor(
|
||||||
@@ -55,9 +30,14 @@ export class AuthGuard implements CanActivate {
|
|||||||
if (isPublic || !this.auth.enabled) return true;
|
if (isPublic || !this.auth.enabled) return true;
|
||||||
|
|
||||||
const request = context.switchToHttp().getRequest<AuthenticatedRequest>();
|
const request = context.switchToHttp().getRequest<AuthenticatedRequest>();
|
||||||
const token = requestToken(request);
|
const token = requestToken(request, this.auth.cookieName);
|
||||||
if (!token) throw new UnauthorizedException();
|
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;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
+25
-110
@@ -1,16 +1,14 @@
|
|||||||
import {
|
import { Injectable } from "@nestjs/common";
|
||||||
Injectable,
|
|
||||||
NotFoundException,
|
|
||||||
UnauthorizedException,
|
|
||||||
} from "@nestjs/common";
|
|
||||||
import { ConfigService } from "@nestjs/config";
|
import { ConfigService } from "@nestjs/config";
|
||||||
import { InjectRepository } from "@nestjs/typeorm";
|
import { InjectRepository } from "@nestjs/typeorm";
|
||||||
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
|
|
||||||
import { Repository } from "typeorm";
|
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 { PasswordService } from "./password.service";
|
||||||
import { RevokedTokenEntity } from "./revoked-token.entity";
|
import { RevokedTokenEntity } from "./revoked-token.entity";
|
||||||
import { UserEntity } from "./user.entity";
|
import { UserEntity } from "./user.entity";
|
||||||
|
import { AuthFailure } from "./auth.error";
|
||||||
|
import { issueJwt, safeUser, tokenHash, verifyJwt } from "./jwt.helpers";
|
||||||
|
|
||||||
export interface SafeUser {
|
export interface SafeUser {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -25,20 +23,6 @@ export interface AuthSession {
|
|||||||
expiresAt: Date;
|
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()
|
@Injectable()
|
||||||
export class AuthService {
|
export class AuthService {
|
||||||
constructor(
|
constructor(
|
||||||
@@ -54,16 +38,20 @@ export class AuthService {
|
|||||||
return this.config.get("AUTH_ENABLED");
|
return this.config.get("AUTH_ENABLED");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
get cookieName(): string {
|
||||||
|
return this.config.get("AUTH_COOKIE_NAME");
|
||||||
|
}
|
||||||
|
|
||||||
async login(username: string, password: string): Promise<AuthSession> {
|
async login(username: string, password: string): Promise<AuthSession> {
|
||||||
if (!this.enabled) {
|
if (!this.enabled) {
|
||||||
throw new NotFoundException("Authentication is disabled.");
|
throw new AuthFailure("disabled");
|
||||||
}
|
}
|
||||||
const user = await this.users.findOneBy({ username });
|
const user = await this.users.findOneBy({ username });
|
||||||
const valid = user
|
const valid = user
|
||||||
? await this.passwords.verify(password, user.passwordHash)
|
? await this.passwords.verify(password, user.passwordHash)
|
||||||
: false;
|
: false;
|
||||||
if (!user || !valid) {
|
if (!user || !valid) {
|
||||||
throw new UnauthorizedException("Invalid username or password.");
|
throw new AuthFailure("invalid-credentials");
|
||||||
}
|
}
|
||||||
return this.issueToken(user);
|
return this.issueToken(user);
|
||||||
}
|
}
|
||||||
@@ -72,38 +60,34 @@ export class AuthService {
|
|||||||
user: Pick<UserEntity, "id" | "username" | "createdAt" | "updatedAt">,
|
user: Pick<UserEntity, "id" | "username" | "createdAt" | "updatedAt">,
|
||||||
): AuthSession {
|
): AuthSession {
|
||||||
if (!this.enabled) {
|
if (!this.enabled) {
|
||||||
throw new NotFoundException("Authentication is disabled.");
|
throw new AuthFailure("disabled");
|
||||||
}
|
}
|
||||||
const issuedAt = Math.floor(Date.now() / 1000);
|
const expiresIn = durationSeconds(this.config.get("AUTH_JWT_EXPIRES_IN"));
|
||||||
const expiresIn = authDurationSeconds(
|
|
||||||
this.config.get("AUTH_JWT_EXPIRES_IN"),
|
|
||||||
);
|
|
||||||
if (expiresIn === null) {
|
if (expiresIn === null) {
|
||||||
throw new Error("AUTH_JWT_EXPIRES_IN is not a valid positive duration.");
|
throw new Error("AUTH_JWT_EXPIRES_IN is not a valid positive duration.");
|
||||||
}
|
}
|
||||||
const payload: JwtPayload = {
|
const { token, expiresAt } = issueJwt(
|
||||||
sub: user.id,
|
user.id,
|
||||||
iat: issuedAt,
|
expiresIn,
|
||||||
exp: issuedAt + expiresIn,
|
this.config.get("AUTH_JWT_SECRET"),
|
||||||
};
|
);
|
||||||
const unsigned = `${base64UrlJson({ alg: "HS256", typ: "JWT" })}.${base64UrlJson(payload)}`;
|
|
||||||
return {
|
return {
|
||||||
user: this.safeUser(user as UserEntity),
|
user: safeUser(user),
|
||||||
token: `${unsigned}.${this.sign(unsigned)}`,
|
token,
|
||||||
expiresAt: new Date(payload.exp * 1000),
|
expiresAt,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async authenticate(token: string): Promise<AuthSession> {
|
async authenticate(token: string): Promise<AuthSession> {
|
||||||
const payload = this.verify(token);
|
const payload = verifyJwt(token, this.config.get("AUTH_JWT_SECRET"));
|
||||||
const digest = tokenHash(token);
|
const digest = tokenHash(token);
|
||||||
if (await this.revokedTokens.findOneBy({ tokenHash: digest })) {
|
if (await this.revokedTokens.findOneBy({ tokenHash: digest })) {
|
||||||
throw new UnauthorizedException();
|
throw new AuthFailure("invalid-token");
|
||||||
}
|
}
|
||||||
const user = await this.users.findOneBy({ id: payload.sub });
|
const user = await this.users.findOneBy({ id: payload.sub });
|
||||||
if (!user) throw new UnauthorizedException();
|
if (!user) throw new AuthFailure("invalid-token");
|
||||||
return {
|
return {
|
||||||
user: this.safeUser(user),
|
user: safeUser(user),
|
||||||
token,
|
token,
|
||||||
expiresAt: new Date(payload.exp * 1000),
|
expiresAt: new Date(payload.exp * 1000),
|
||||||
};
|
};
|
||||||
@@ -115,73 +99,4 @@ export class AuthService {
|
|||||||
expiresAt: session.expiresAt,
|
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<JwtPayload>;
|
|
||||||
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,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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<UserEntity, "id" | "username" | "createdAt" | "updatedAt">,
|
||||||
|
): 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<JwtPayload>;
|
||||||
|
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;
|
||||||
|
}
|
||||||
@@ -1,10 +1,14 @@
|
|||||||
import { randomBytes, scrypt, timingSafeEqual } from "node:crypto";
|
import { randomBytes, scrypt, timingSafeEqual } from "node:crypto";
|
||||||
import { Injectable } from "@nestjs/common";
|
import { Injectable } from "@nestjs/common";
|
||||||
|
|
||||||
|
// N=2^14 is the baseline scrypt CPU/memory cost; verify permits bounded future upgrades.
|
||||||
const SCRYPT_N = 16384;
|
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_R = 8;
|
||||||
const SCRYPT_P = 1;
|
const SCRYPT_P = 1;
|
||||||
|
// A 128-bit random salt prevents practical salt collisions across stored passwords.
|
||||||
const SALT_BYTES = 16;
|
const SALT_BYTES = 16;
|
||||||
|
// 512-bit output gives ample margin for password verification.
|
||||||
const HASH_BYTES = 64;
|
const HASH_BYTES = 64;
|
||||||
|
|
||||||
function derive(
|
function derive(
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { SetMetadata } from "@nestjs/common";
|
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);
|
export const Public = () => SetMetadata(IS_PUBLIC_KEY, true);
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -12,16 +12,7 @@ import {
|
|||||||
|
|
||||||
import { appPackage } from "../common/app-package";
|
import { appPackage } from "../common/app-package";
|
||||||
|
|
||||||
export function authDurationSeconds(value: string): number | null {
|
import { durationSeconds } from "../common/interval";
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
export enum TraceMode {
|
export enum TraceMode {
|
||||||
On = "on",
|
On = "on",
|
||||||
@@ -96,6 +87,10 @@ export class AppConfig {
|
|||||||
@IsString()
|
@IsString()
|
||||||
AUTH_JWT_SECRET: string = "";
|
AUTH_JWT_SECRET: string = "";
|
||||||
|
|
||||||
|
/** Cookie name used for browser sessions. */
|
||||||
|
@IsString()
|
||||||
|
AUTH_COOKIE_NAME: string = "liqa_auth";
|
||||||
|
|
||||||
@IsString()
|
@IsString()
|
||||||
AUTH_JWT_EXPIRES_IN: string = "24h";
|
AUTH_JWT_EXPIRES_IN: string = "24h";
|
||||||
|
|
||||||
@@ -130,7 +125,7 @@ export function validateAppConfig(config: Record<string, unknown>): AppConfig {
|
|||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
validated.AUTH_ENABLED &&
|
validated.AUTH_ENABLED &&
|
||||||
authDurationSeconds(validated.AUTH_JWT_EXPIRES_IN) === null
|
durationSeconds(validated.AUTH_JWT_EXPIRES_IN) === null
|
||||||
) {
|
) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
"AUTH_JWT_EXPIRES_IN must be a positive duration such as 30m, 1h, or 24h.",
|
"AUTH_JWT_EXPIRES_IN must be a positive duration such as 30m, 1h, or 24h.",
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ export class ManifestDto {
|
|||||||
version!: string;
|
version!: string;
|
||||||
|
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
description: "Whether optional account authentication is enabled.",
|
description: "Whether account authentication is enabled.",
|
||||||
type: "object",
|
type: "object",
|
||||||
properties: { enabled: { type: "boolean", example: false } },
|
properties: { enabled: { type: "boolean", example: false } },
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
import "reflect-metadata";
|
import "reflect-metadata";
|
||||||
import {
|
import { validateAppConfig } from "../src/config/app.config";
|
||||||
authDurationSeconds,
|
import { durationSeconds } from "../src/common/interval";
|
||||||
validateAppConfig,
|
|
||||||
} from "../src/config/app.config";
|
|
||||||
|
|
||||||
describe("Authentication configuration", () => {
|
describe("Authentication configuration", () => {
|
||||||
it("defaults authentication off with a 24-hour token lifetime and cleanup schedule", () => {
|
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_ENABLED).toBe(false);
|
||||||
expect(config.AUTH_JWT_EXPIRES_IN).toBe("24h");
|
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 * * *");
|
expect(config.AUTH_REVOKED_TOKEN_CLEANUP_CRON).toBe("0 3 * * *");
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -46,9 +45,9 @@ describe("Authentication configuration", () => {
|
|||||||
expect(() => validateAppConfig({ AUTH_ENABLED: "yes" })).toThrow(
|
expect(() => validateAppConfig({ AUTH_ENABLED: "yes" })).toThrow(
|
||||||
"AUTH_ENABLED must be either true or false",
|
"AUTH_ENABLED must be either true or false",
|
||||||
);
|
);
|
||||||
expect(authDurationSeconds("30m")).toBe(1800);
|
expect(durationSeconds("30m")).toBe(1800);
|
||||||
expect(authDurationSeconds("24h")).toBe(86400);
|
expect(durationSeconds("24h")).toBe(86400);
|
||||||
expect(authDurationSeconds("2d")).toBe(172800);
|
expect(durationSeconds("2d")).toBe(172800);
|
||||||
expect(authDurationSeconds("0s")).toBeNull();
|
expect(durationSeconds("0s")).toBeNull();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -31,4 +31,11 @@ describe("authentication disabled", () => {
|
|||||||
.expect(200);
|
.expect(200);
|
||||||
expect(manifest.body.auth).toEqual({ enabled: false });
|
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);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -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);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -4,7 +4,7 @@ import request from "supertest";
|
|||||||
import { Repository } from "typeorm";
|
import { Repository } from "typeorm";
|
||||||
import { filter, firstValueFrom, timeout } from "rxjs";
|
import { filter, firstValueFrom, timeout } from "rxjs";
|
||||||
import { AuthService } from "../src/auth/auth.service";
|
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 { PasswordService } from "../src/auth/password.service";
|
||||||
import { RevokedTokenEntity } from "../src/auth/revoked-token.entity";
|
import { RevokedTokenEntity } from "../src/auth/revoked-token.entity";
|
||||||
import { EnvironmentService } from "../src/environment/environment.service";
|
import { EnvironmentService } from "../src/environment/environment.service";
|
||||||
|
|||||||
@@ -1,9 +1,22 @@
|
|||||||
import { INestApplication } from "@nestjs/common";
|
import { INestApplication } from "@nestjs/common";
|
||||||
import request from "supertest";
|
import request from "supertest";
|
||||||
import { appPackage } from "../src/common/app-package";
|
import { appPackage } from "../src/common/app-package";
|
||||||
|
import { ManifestDto } from "../src/manifest/manifest.dto";
|
||||||
import { buildTestApp } from "./app.harness";
|
import { buildTestApp } from "./app.harness";
|
||||||
|
|
||||||
describe("GET /manifest.json", () => {
|
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;
|
let app: INestApplication;
|
||||||
|
|
||||||
afterEach(async () => {
|
afterEach(async () => {
|
||||||
|
|||||||
Reference in new issue
Block a user