VR-MEDIA / src /lib /auth.ts
Zero124's picture
VR Media Server 2.0 — latest build (custom Blomp thumbnail auto-detection + full pipeline)
5c0175e
Raw History Blame Contribute Delete
10 kB
// Authentication primitives — Edge-safe (no Node built-ins, no Prisma).
//
// Two ways to sign in, both fully supported:
//
// 1. A key configured as a Space Secret / environment variable
// (APP_API_KEY, legacy APP_PASSWORD, or your OFFCLOUD_API_KEY).
// 2. A key set from the sign-in page / Settings, stored in the database.
// Database keys cannot be read from Edge middleware, so a successful login
// issues an HMAC-signed session cookie that middleware CAN verify.
//
// Anything Node-only (reading the stored key, DEOVR ?token= checks) lives in
// auth-server.ts.
import { readEnv } from "./env";
export const FALLBACK_API_KEY = "vr-media-server";
export const AUTH_COOKIE = "vrms_auth";
/** Session lifetime in seconds (30 days). */
export const AUTH_MAX_AGE = 60 * 60 * 24 * 30;
const SESSION_PREFIX = "s1";
const SESSION_PREFIX_V2 = "s2";
// ---------------------------------------------------------------------------
// Environment keys
// ---------------------------------------------------------------------------
function clean(value: string | undefined): string | null {
if (!value) return null;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
}
/** Every key accepted from the environment, in priority order. */
export function getValidApiKeys(): string[] {
const keys: string[] = [];
const push = (k: string | null) => {
if (k && !keys.includes(k)) keys.push(k);
};
// Read through readEnv() so the values are resolved at RUNTIME. Direct
// process.env.X access is inlined at build time in the middleware bundle,
// where HF Space secrets do not exist yet.
push(readEnv("APP_API_KEY"));
push(readEnv("APP_PASSWORD")); // legacy name
if (readEnv("ALLOW_OFFCLOUD_KEY_LOGIN") !== "false") {
push(readEnv("OFFCLOUD_API_KEY"));
}
if (keys.length === 0) keys.push(FALLBACK_API_KEY);
return keys;
}
/** The key shown in generated DEOVR URLs. */
export function getPrimaryApiKey(): string {
return getValidApiKeys()[0];
}
/** True when no key was configured and the insecure default is in play. */
export function isUsingFallbackKey(): boolean {
const keys = getValidApiKeys();
return keys.length === 1 && keys[0] === FALLBACK_API_KEY;
}
function safeEqual(a: string, b: string): boolean {
if (a.length !== b.length) return false;
let diff = 0;
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
return diff === 0;
}
/** Verify a candidate against the environment-configured keys only. */
export function verifyApiKey(candidate: string | null | undefined): boolean {
if (!candidate) return false;
return getValidApiKeys().some((k) => safeEqual(candidate, k));
}
// Legacy aliases kept so older imports keep compiling.
export const verifyPassword = verifyApiKey;
export const getAppPassword = getPrimaryApiKey;
export function maskApiKey(key: string): string {
if (key.length <= 6) return "•".repeat(key.length);
return `${key.slice(0, 3)}${"•".repeat(Math.min(10, key.length - 6))}${key.slice(-3)}`;
}
// ---------------------------------------------------------------------------
// Signed session tokens (verifiable in Edge middleware)
// ---------------------------------------------------------------------------
function sessionSecret(): string {
return readEnv("AUTH_SECRET") ?? `vrms:${getPrimaryApiKey()}`;
}
/**
* Where the session-signing secret comes from.
*
* "env" - AUTH_SECRET is set, so every runtime signs identically.
* "derived" - computed from the API key. That only stays consistent while
* every runtime can see the same key, which is why the
* entrypoint now generates and persists an AUTH_SECRET.
*/
export function authSecretSource(): "env" | "derived" {
return readEnv("AUTH_SECRET") ? "env" : "derived";
}
/**
* Short, non-reversible fingerprint of a key. Two runtimes reporting the
* same fingerprint are provably using the same key; different fingerprints
* mean one of them cannot see the secret.
*/
export async function keyFingerprint(key: string = getPrimaryApiKey()): Promise<string> {
const data = new TextEncoder().encode(`vrms-fp:${key}`);
const digest = await crypto.subtle.digest("SHA-256", data);
return Array.from(new Uint8Array(digest))
.slice(0, 4)
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
}
async function hmacHex(message: string): Promise<string> {
const enc = new TextEncoder();
const key = await crypto.subtle.importKey(
"raw",
enc.encode(sessionSecret()),
{ name: "HMAC", hash: "SHA-256" },
false,
["sign"]
);
const sig = await crypto.subtle.sign("HMAC", key, enc.encode(message));
return Array.from(new Uint8Array(sig))
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
}
/**
* How far a session has got through sign-in.
*
* "key" - the API key was accepted. Enough for DEOVR / PLAY'A media URLs.
* "full" - the password step is also done (or no password is configured).
* Required for the web UI and the admin APIs.
*/
export type SessionLevel = "key" | "full";
/** Mint a session token at `level`, valid for `ttlSeconds`. */
export async function createSessionToken(
level: SessionLevel = "full",
ttlSeconds = AUTH_MAX_AGE
): Promise<string> {
const expires = Math.floor(Date.now() / 1000) + ttlSeconds;
const body = `${SESSION_PREFIX_V2}.${expires}.${level}`;
return `${body}.${await hmacHex(body)}`;
}
/** Verify a session token and report the level it was issued at. */
export async function readSessionToken(
token: string | null | undefined
): Promise<{ ok: boolean; level: SessionLevel | null }> {
const deny = { ok: false, level: null } as const;
if (!token) return deny;
const parts = token.split(".");
// Current format: s2.<expiry>.<level>.<signature>
if (parts[0] === SESSION_PREFIX_V2 && parts.length === 4) {
const [, expiresRaw, levelRaw, signature] = parts;
if (levelRaw !== "key" && levelRaw !== "full") return deny;
const expires = Number(expiresRaw);
if (!Number.isFinite(expires) || expires * 1000 < Date.now()) return deny;
const expected = await hmacHex(`${SESSION_PREFIX_V2}.${expiresRaw}.${levelRaw}`);
if (!safeEqual(signature, expected)) return deny;
return { ok: true, level: levelRaw };
}
// Legacy format: s1.<expiry>.<signature>. Treated as key-level, so a session
// minted before the password existed cannot skip the password step.
if (parts[0] === SESSION_PREFIX && parts.length === 3) {
const [, expiresRaw, signature] = parts;
const expires = Number(expiresRaw);
if (!Number.isFinite(expires) || expires * 1000 < Date.now()) return deny;
const expected = await hmacHex(`${SESSION_PREFIX}.${expiresRaw}`);
if (!safeEqual(signature, expected)) return deny;
return { ok: true, level: "key" };
}
return deny;
}
/** Signature/expiry only - ignores the level. */
export async function verifySessionToken(token: string | null | undefined): Promise<boolean> {
return (await readSessionToken(token)).ok;
}
// ---------------------------------------------------------------------------
// Credential extraction
// ---------------------------------------------------------------------------
type HeaderBag = { get(name: string): string | null };
export type CredentialSource = { headers: HeaderBag; url?: string };
export function readKeyFromCookieHeader(header: string | null): string | null {
if (!header) return null;
const match = /(?:^|;\s*)vrms_auth=([^;]+)/.exec(header);
if (!match) return null;
try {
return decodeURIComponent(match[1]);
} catch {
return match[1];
}
}
/** Cookie value, ?token=, Authorization: Bearer, or X-API-Key. */
export function extractCredential(req: CredentialSource): string | null {
const cookie = readKeyFromCookieHeader(req.headers.get("cookie"));
if (cookie) return cookie;
if (req.url) {
try {
const token = new URL(req.url).searchParams.get("token");
if (token) return token;
} catch {
// Not an absolute URL — ignore.
}
}
const authorization = req.headers.get("authorization");
if (authorization?.toLowerCase().startsWith("bearer ")) {
return authorization.slice(7).trim();
}
const headerKey = req.headers.get("x-api-key");
if (headerKey) return headerKey.trim();
return null;
}
export type AuthVerdict = {
ok: boolean;
via: "session" | "env-key" | null;
credential: string | null;
/** Session level, or "key" for a raw API key: a bare key never unlocks the UI. */
level: SessionLevel | null;
};
/**
* Edge-safe verification: a signed session cookie, or a raw environment key
* passed as cookie/token/header. A key stored in the database can only be
* verified by auth-server.ts.
*/
export async function verifyRequest(req: CredentialSource): Promise<AuthVerdict> {
const credential = extractCredential(req);
if (!credential) return { ok: false, via: null, credential: null, level: null };
const session = await readSessionToken(credential);
if (session.ok) {
return { ok: true, via: "session", credential, level: session.level };
}
if (verifyApiKey(credential)) {
// A raw key is machine-grade: good for media URLs, not for the web UI.
return { ok: true, via: "env-key", credential, level: "key" };
}
return { ok: false, via: null, credential, level: null };
}
/** Convenience boolean form. */
export async function isAuthenticated(req: CredentialSource): Promise<boolean> {
return (await verifyRequest(req)).ok;
}
export function addTokenToUrl(url: string, key = getPrimaryApiKey()): string {
const separator = url.includes("?") ? "&" : "?";
return `${url}${separator}token=${encodeURIComponent(key)}`;
}