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
+25
-110
@@ -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<AuthSession> {
|
||||
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<UserEntity, "id" | "username" | "createdAt" | "updatedAt">,
|
||||
): 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<AuthSession> {
|
||||
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<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,
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user