VR-MEDIA / src /lib /password.ts
Zero124's picture
VR Media Server 2.0 — latest build (custom Blomp thumbnail auto-detection + full pipeline)
5c0175e
Raw History Blame Contribute Delete
4.18 kB
// Password primitives - Edge-safe (WebCrypto only, no Node built-ins, no DB).
//
// Sign-in has two layers:
// Layer 1 - API key: unlocks machine access (DEOVR / PLAY'A feeds, streams,
// thumbnails) and is the first step of the web sign-in.
// Layer 2 - password: additionally required for the web UI. Headsets cannot
// type a password, which is exactly why the layers are separate.
import { readEnv, readEnvFlag } from "./env";
/** Iteration count for NEW hashes. Each hash stores the count it was made with. */
export const PBKDF2_ITERATIONS = 210000;
export const MIN_PASSWORD_LENGTH = 8;
function bytesToHex(bytes: Uint8Array): string {
return Array.from(bytes)
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
}
function hexToBytes(hex: string): Uint8Array {
const clean = hex.length % 2 === 0 ? hex : `0${hex}`;
const out = new Uint8Array(clean.length / 2);
for (let i = 0; i < out.length; i++) {
out[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);
}
return out;
}
/** Constant-time comparison - no early exit on the first differing byte. */
export function safeEqualStrings(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;
}
async function derive(password: string, salt: Uint8Array, iterations: number): Promise<string> {
const material = await crypto.subtle.importKey(
"raw",
new TextEncoder().encode(password),
"PBKDF2",
false,
["deriveBits"]
);
const bits = await crypto.subtle.deriveBits(
{ name: "PBKDF2", hash: "SHA-256", salt: salt as BufferSource, iterations },
material,
256
);
return bytesToHex(new Uint8Array(bits));
}
/** Format: pbkdf2$<iterations>$<saltHex>$<hashHex>. Plaintext is never stored. */
export async function hashPassword(password: string): Promise<string> {
const salt = crypto.getRandomValues(new Uint8Array(16));
const hash = await derive(password, salt, PBKDF2_ITERATIONS);
return `pbkdf2$${PBKDF2_ITERATIONS}$${bytesToHex(salt)}$${hash}`;
}
export async function verifyPasswordAgainstHash(password: string, stored: string): Promise<boolean> {
const parts = stored.split("$");
if (parts.length !== 4 || parts[0] !== "pbkdf2") return false;
const iterations = Number(parts[1]);
if (!Number.isFinite(iterations) || iterations < 1000) return false;
const hash = await derive(password, hexToBytes(parts[2]), iterations);
return safeEqualStrings(hash, parts[3]);
}
/** Password supplied as a Space secret. Always wins over the stored one. */
export function envLoginPassword(): string | null {
return readEnv("APP_LOGIN_PASSWORD");
}
/** Escape hatch: RESET_LOGIN_PASSWORD=true drops the password stored in the app. */
export function shouldResetStoredPassword(): boolean {
return readEnvFlag("RESET_LOGIN_PASSWORD", false);
}
/** Failed-attempt policy for the sign-in guard. */
export function lockoutPolicy(): { maxAttempts: number; windowMinutes: number } {
const attempts = Number(readEnv("LOGIN_MAX_ATTEMPTS") ?? "5");
const minutes = Number(readEnv("LOGIN_LOCKOUT_MINUTES") ?? "15");
return {
maxAttempts: Number.isFinite(attempts) && attempts >= 1 ? Math.min(attempts, 50) : 5,
windowMinutes: Number.isFinite(minutes) && minutes >= 1 ? Math.min(minutes, 1440) : 15,
};
}
// ---------------------------------------------------------------------------
// Username - this is a single-user server, so there is exactly one account
// ---------------------------------------------------------------------------
/** Used when neither APP_USERNAME nor an in-app username is set. */
export const DEFAULT_USERNAME = "admin";
/** Username supplied as a Space secret. Wins over the in-app one. */
export function envUsername(): string | null {
return readEnv("APP_USERNAME");
}
/** Usernames are compared trimmed and case-insensitively. */
export function normalizeUsername(value: string): string {
return value.trim().toLowerCase();
}