feat(auth): add optional authentication boundary
- Add account, JWT session, revocation, cookie and bearer handling. - Protect server surfaces while preserving public health, manifest and disabled mode. - Add SQLite migration and focused server regression coverage.
This commit is contained in:
1 parent
d4bb274982
commit
de41571b5c
33 files changed
+1083
-20
No files matched your search
@@ -0,0 +1,187 @@
|
||||
import {
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
UnauthorizedException,
|
||||
} 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 { PasswordService } from "./password.service";
|
||||
import { RevokedTokenEntity } from "./revoked-token.entity";
|
||||
import { UserEntity } from "./user.entity";
|
||||
|
||||
export interface SafeUser {
|
||||
id: string;
|
||||
username: string;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
export interface AuthSession {
|
||||
user: SafeUser;
|
||||
token: string;
|
||||
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(
|
||||
@InjectRepository(UserEntity)
|
||||
private readonly users: Repository<UserEntity>,
|
||||
@InjectRepository(RevokedTokenEntity)
|
||||
private readonly revokedTokens: Repository<RevokedTokenEntity>,
|
||||
private readonly config: ConfigService<AppConfig, true>,
|
||||
private readonly passwords: PasswordService,
|
||||
) {}
|
||||
|
||||
get enabled(): boolean {
|
||||
return this.config.get("AUTH_ENABLED");
|
||||
}
|
||||
|
||||
async login(username: string, password: string): Promise<AuthSession> {
|
||||
if (!this.enabled) {
|
||||
throw new NotFoundException("Authentication is 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.");
|
||||
}
|
||||
return this.issueToken(user);
|
||||
}
|
||||
|
||||
issueToken(
|
||||
user: Pick<UserEntity, "id" | "username" | "createdAt" | "updatedAt">,
|
||||
): AuthSession {
|
||||
if (!this.enabled) {
|
||||
throw new NotFoundException("Authentication is disabled.");
|
||||
}
|
||||
const issuedAt = Math.floor(Date.now() / 1000);
|
||||
const expiresIn = authDurationSeconds(
|
||||
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)}`;
|
||||
return {
|
||||
user: this.safeUser(user as UserEntity),
|
||||
token: `${unsigned}.${this.sign(unsigned)}`,
|
||||
expiresAt: new Date(payload.exp * 1000),
|
||||
};
|
||||
}
|
||||
|
||||
async authenticate(token: string): Promise<AuthSession> {
|
||||
const payload = this.verify(token);
|
||||
const digest = tokenHash(token);
|
||||
if (await this.revokedTokens.findOneBy({ tokenHash: digest })) {
|
||||
throw new UnauthorizedException();
|
||||
}
|
||||
const user = await this.users.findOneBy({ id: payload.sub });
|
||||
if (!user) throw new UnauthorizedException();
|
||||
return {
|
||||
user: this.safeUser(user),
|
||||
token,
|
||||
expiresAt: new Date(payload.exp * 1000),
|
||||
};
|
||||
}
|
||||
|
||||
async revoke(session: AuthSession): Promise<void> {
|
||||
await this.revokedTokens.save({
|
||||
tokenHash: tokenHash(session.token),
|
||||
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