- 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.
99 lines
2.9 KiB
TypeScript
99 lines
2.9 KiB
TypeScript
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;
|
|
}
|