62 lines
2.1 KiB
TypeScript
62 lines
2.1 KiB
TypeScript
import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
import type { Clock } from '#lib/server/sync/core/ports.ts';
|
|
|
|
export const SESSION_COOKIE = 'admin_session';
|
|
|
|
export interface AdminAuthConfig {
|
|
username?: string;
|
|
password?: string;
|
|
/** Signs session tokens. If omitted, a random one is used and sessions end on restart. */
|
|
sessionSecret?: string;
|
|
sessionTtlMs: number;
|
|
clock: Clock;
|
|
}
|
|
|
|
/** The single admin account from env, with stateless signed session tokens. */
|
|
export class AdminAuth {
|
|
private readonly secret: string;
|
|
|
|
constructor(private readonly config: AdminAuthConfig) {
|
|
this.secret = config.sessionSecret || randomBytes(32).toString('hex');
|
|
}
|
|
|
|
get enabled(): boolean {
|
|
return Boolean(this.config.username && this.config.password);
|
|
}
|
|
|
|
get sessionTtlSeconds(): number {
|
|
return Math.floor(this.config.sessionTtlMs / 1000);
|
|
}
|
|
|
|
checkCredentials(username: string, password: string): boolean {
|
|
if (!this.enabled) return false;
|
|
// Evaluate both so timing doesn't reveal which one was wrong.
|
|
const userOk = safeEqual(username, this.config.username!);
|
|
const passwordOk = safeEqual(password, this.config.password!);
|
|
return userOk && passwordOk;
|
|
}
|
|
|
|
/** A token of the form `<expiresAtMs>.<signature>`. */
|
|
issueToken(): string {
|
|
const expiresAt = String(this.config.clock().getTime() + this.config.sessionTtlMs);
|
|
return `${expiresAt}.${this.sign(expiresAt)}`;
|
|
}
|
|
|
|
verifyToken(token: string | undefined): boolean {
|
|
if (!this.enabled || !token) return false;
|
|
const [expiresAt, signature] = token.split('.');
|
|
if (!expiresAt || !signature || !safeEqual(signature, this.sign(expiresAt))) return false;
|
|
return Number(expiresAt) > this.config.clock().getTime();
|
|
}
|
|
|
|
private sign(value: string): string {
|
|
return createHmac('sha256', this.secret).update(value).digest('base64url');
|
|
}
|
|
}
|
|
|
|
/** Constant-time comparison that also hides length differences. */
|
|
function safeEqual(a: string, b: string): boolean {
|
|
const digest = (value: string) => createHash('sha256').update(value).digest();
|
|
return timingSafeEqual(digest(a), digest(b));
|
|
}
|