2026-04-26 03:02:31 -03:00
|
|
|
// Edge-compatible — no Node.js imports here (used in middleware)
|
|
|
|
|
|
|
|
|
|
export const AUTH_ENABLED = !!(process.env.AUTH_USER && process.env.AUTH_PASS)
|
|
|
|
|
export const COOKIE_NAME = "ds_session"
|
|
|
|
|
|
2026-04-27 10:41:23 -03:00
|
|
|
// Cached promise — token is deterministic (env vars never change at runtime)
|
|
|
|
|
let _tokenCache: Promise<string> | null = null
|
|
|
|
|
|
2026-04-26 03:02:31 -03:00
|
|
|
// HMAC-SHA256(user, key=pass) — deterministic, no in-memory state, survives restarts
|
|
|
|
|
// Works in both Edge (SubtleCrypto) and Node.js runtime
|
2026-04-27 10:41:23 -03:00
|
|
|
export function computeSessionToken(): Promise<string> {
|
|
|
|
|
if (_tokenCache) return _tokenCache
|
2026-04-26 03:02:31 -03:00
|
|
|
const user = process.env.AUTH_USER ?? ""
|
|
|
|
|
const pass = process.env.AUTH_PASS ?? ""
|
|
|
|
|
const enc = new TextEncoder()
|
2026-04-27 10:41:23 -03:00
|
|
|
_tokenCache = globalThis.crypto.subtle
|
|
|
|
|
.importKey("raw", enc.encode(pass), { name: "HMAC", hash: "SHA-256" }, false, ["sign"])
|
|
|
|
|
.then(key => globalThis.crypto.subtle.sign("HMAC", key, enc.encode(user)))
|
|
|
|
|
.then(sig => Array.from(new Uint8Array(sig), b => b.toString(16).padStart(2, "0")).join(""))
|
|
|
|
|
return _tokenCache
|
2026-04-26 03:02:31 -03:00
|
|
|
}
|