import fs from "node:fs"; import { LABELS, normLabel, type Label } from "./store.ts"; export interface AccessConfig { restrict: Partial>; } export interface ModelId { provider: string; id: string; } function globToRegex(glob: string): RegExp { const body = glob .trim() .toLowerCase() .replace(/[.+^${}()|[\]\\]/g, "\\$&") .replace(/\*/g, ".*") .replace(/\?/g, "."); return new RegExp(`^${body}$`); } export function parseAccessConfig(raw: unknown): AccessConfig { const restrict: AccessConfig["restrict"] = {}; const src = (raw as { restrict?: unknown } | undefined)?.restrict; if (src && typeof src === "object") { for (const [key, patterns] of Object.entries(src as Record)) { const label = normLabel(key); if (!label) continue; const list = Array.isArray(patterns) ? patterns : typeof patterns === "string" ? [patterns] : []; restrict[label] = list.map(String).filter((p) => p.trim()); } } return { restrict }; } export function blockedLabels(config: AccessConfig, model: ModelId | undefined): Label[] { if (!model) return []; const names = [`${model.provider}/${model.id}`.toLowerCase(), model.id.toLowerCase()]; return (Object.entries(config.restrict) as [Label, string[]][]) .filter(([, patterns]) => patterns.some((p) => names.some((n) => globToRegex(p).test(n)))) .map(([label]) => label); } export class AccessPolicy { private cached: { mtimeMs: number; config: AccessConfig } | undefined; lastError: string | undefined; private readonly file: string; constructor(file: string) { this.file = file; } config(): AccessConfig { let mtimeMs: number; try { mtimeMs = fs.statSync(this.file).mtimeMs; } catch { this.cached = undefined; return { restrict: {} }; } if (this.cached?.mtimeMs === mtimeMs) return this.cached.config; try { const config = parseAccessConfig(JSON.parse(fs.readFileSync(this.file, "utf8"))); this.cached = { mtimeMs, config }; this.lastError = undefined; return config; } catch (e) { this.lastError = `${this.file}: ${(e as Error).message}`; return this.cached?.config ?? { restrict: Object.fromEntries(LABELS.map((l) => [l, ["*"]])) }; } } blockedFor(model: ModelId | undefined): Label[] { return blockedLabels(this.config(), model); } }