building out next phase of sync

This commit is contained in:
C-West8
2026-10-22 22:42:07 -05:00
parent db4abbeefb
commit 42a1ce7d30
34 changed files with 934 additions and 107 deletions

View File

@@ -0,0 +1,57 @@
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 | undefined;
password: string | undefined;
/** Signs session tokens. If omitted, a random one is used and sessions end on restart. */
sessionSecret: string | undefined;
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);
}
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));
}