This commit is contained in:
Tom Chien (IQ-AS)
2026-09-08 17:46:28 +08:00
commit e25c995560
55 changed files with 6928 additions and 0 deletions
+55
View File
@@ -0,0 +1,55 @@
import fs from "node:fs";
import path from "node:path";
// Role model for the app. Access is either full "admin" or read-only "user".
// NOTE: this module uses node:fs and MUST only be imported from Node runtime
// code (src/auth.ts / server components / API routes) — never from the edge
// middleware, or the edge bundle will fail to compile.
export type Role = "admin" | "user";
// Resolve a user's role from the hand-edited allowlist at config/users.json.
// Emails are matched case-insensitively. This is FAIL CLOSED: a missing file,
// invalid JSON, or an email that is not listed all return null (access denied).
export function lookupRole(email: string | null | undefined): Role | null {
if (!email) return null;
let raw: string;
try {
raw = fs.readFileSync(
path.join(process.cwd(), "config", "users.json"),
"utf8"
);
} catch {
// File missing/unreadable -> deny everyone (local admin is the break-glass).
return null;
}
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch {
return null;
}
if (!parsed || typeof parsed !== "object") return null;
// Lowercase every key so the lookup is case-insensitive.
const table: Record<string, Role> = {};
for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) {
if (value === "admin" || value === "user") {
table[key.toLowerCase()] = value;
}
}
return table[email.toLowerCase()] ?? null;
}
// Constant-time string comparison to avoid leaking secrets via timing.
// Pure JS (no node:crypto) so this stays cheap and dependency-free.
export function safeEqual(a: string, b: string): boolean {
if (a.length !== b.length) return false;
let mismatch = 0;
for (let i = 0; i < a.length; i++) {
mismatch |= a.charCodeAt(i) ^ b.charCodeAt(i);
}
return mismatch === 0;
}