Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

feat: add error pages, harden DB layer and compliance module

diegosouzapw85c6b63c8f6c
diff --git a/src/app/.well-known/agent.json/route.ts b/src/app/.well-known/agent.json/route.ts
new file mode 100644
index 0000000000..9ae88e92aa
--- /dev/null
+++ b/src/app/.well-known/agent.json/route.ts
@@ -0,0 +1,105 @@
+/**
+ * Agent Card Endpoint — /.well-known/agent.json
+ *
+ * Serves the OmniRoute A2A Agent Card for discovery by other agents.
+ * Conforms to A2A Protocol v0.3.
+ *
+ * The Agent Card is dynamically generated to include the current version
+ * from package.json and skills based on available combos.
+ */
+
+import { NextResponse } from "next/server";
+
+const PACKAGE_VERSION = process.env.npm_package_version || "1.8.1";
+const BASE_URL = process.env.OMNIROUTE_BASE_URL || "http://localhost:20128";
+
+/**
+ * GET /.well-known/agent.json
+ *
+ * Returns the OmniRoute Agent Card that describes this gateway's
+ * capabilities as an A2A agent.
+ */
+export async function GET() {
+ const agentCard = {
+ name: "OmniRoute AI Gateway",
+ description:
+ "Intelligent AI routing gateway with 36+ providers, smart fallback, " +
+ "quota tracking, format translation, and auto-managed combos. " +
+ "Routes AI requests to the optimal provider based on cost, latency, " +
+ "quota availability, and task requirements.",
+ url: `${BASE_URL}/a2a`,
+ version: PACKAGE_VERSION,
+ capabilities: {
+ streaming: true,
+ pushNotifications: false,
+ },
+ skills: [
+ {
+ id: "smart-routing",
+ name: "Smart Request Routing",
+ description:
+ "Routes AI requests to the optimal provider based on quota, cost, " +
+ "latency, and reliability. Supports combo-based routing with " +
+ "multiple strategies: priority, weighted, round-robin, cost-optimized.",
+ tags: ["routing", "llm", "optimization", "fallback"],
+ examples: [
+ "Route this coding task to the fastest available model",
+ "Send this review to an analytical model under $0.50 budget",
+ "Find the cheapest provider with available quota",
+ ],
+ },
+ {
+ id: "quota-management",
+ name: "Quota & Cost Management",
+ description:
+ "Tracks and manages API quotas across 36+ providers with " +
+ "auto-fallback when quotas are exhausted. Provides real-time " +
+ "cost tracking and budget enforcement.",
+ tags: ["quota", "cost", "monitoring", "budget"],
+ examples: [
+ "Check remaining quota for all providers",
+ "Which provider has the most available quota?",
+ "Generate a cost report for today",
+ ],
+ },
+ {
+ id: "auto-combo",
+ name: "Auto-Managed Model Combos",
+ description:
+ "Self-healing model chains that dynamically adapt to provider " +
+ "health and quota availability. Uses a scoring function based on " +
+ "quota, health, cost, latency, task fitness, and stability.",
+ tags: ["combo", "auto", "self-healing", "adaptive"],
+ examples: [
+ "Create an auto-managed combo for coding tasks",
+ "Switch to cost-saver mode",
+ "Show the Auto-Combo scoring breakdown",
+ ],
+ },
+ {
+ id: "format-translation",
+ name: "Format Translation",
+ description:
+ "Transparently translates between OpenAI, Claude (Anthropic), " +
+ "Gemini (Google), and Responses API formats. Supports streaming " +
+ "translation for all format pairs.",
+ tags: ["translation", "openai", "claude", "gemini", "responses"],
+ examples: [
+ "Send an OpenAI-format request to Claude",
+ "Translate this Gemini response to OpenAI format",
+ ],
+ },
+ ],
+ authentication: {
+ schemes: ["api-key"],
+ apiKeyHeader: "Authorization",
+ },
+ };
+
+ return NextResponse.json(agentCard, {
+ headers: {
+ "Cache-Control": "public, max-age=3600",
+ "Content-Type": "application/json",
+ },
+ });
+}
diff --git a/src/app/400/page.tsx b/src/app/400/page.tsx
new file mode 100644
index 0000000000..bdef8a9d16
--- /dev/null
+++ b/src/app/400/page.tsx
@@ -0,0 +1,19 @@
+import ErrorPageScaffold from "@/shared/components/ErrorPageScaffold";
+
+export default function BadRequestPage() {
+ return (
+ <ErrorPageScaffold
+ code="400"
+ icon="rule"
+ title="Bad Request"
+ description="The request payload is invalid or incomplete."
+ suggestions={[
+ "Review required fields and payload format before retrying.",
+ "If you are using the API, validate the JSON schema locally.",
+ "If this keeps happening, open the request in Translator Playground to inspect the payload.",
+ ]}
+ primaryAction={{ href: "/docs", label: "Open Documentation" }}
+ secondaryAction={{ href: "/dashboard/translator", label: "Open Translator" }}
+ />
+ );
+}
diff --git a/src/app/401/page.tsx b/src/app/401/page.tsx
new file mode 100644
index 0000000000..299ce4a586
--- /dev/null
+++ b/src/app/401/page.tsx
@@ -0,0 +1,19 @@
+import ErrorPageScaffold from "@/shared/components/ErrorPageScaffold";
+
+export default function UnauthorizedPage() {
+ return (
+ <ErrorPageScaffold
+ code="401"
+ icon="lock"
+ title="Unauthorized"
+ description="Authentication is required to access this resource."
+ suggestions={[
+ "Sign in again and retry the operation.",
+ "For API calls, confirm the Bearer token is present and valid.",
+ "If the token was recently rotated, update your client credentials.",
+ ]}
+ primaryAction={{ href: "/login", label: "Go to Login" }}
+ secondaryAction={{ href: "/dashboard/api-manager", label: "Manage API Keys" }}
+ />
+ );
+}
diff --git a/src/app/403/page.tsx b/src/app/403/page.tsx
new file mode 100644
index 0000000000..8a1cc98d72
--- /dev/null
+++ b/src/app/403/page.tsx
@@ -0,0 +1,22 @@
+import ErrorPageScaffold from "@/shared/components/ErrorPageScaffold";
+
+export default function ForbiddenStatusPage() {
+ return (
+ <ErrorPageScaffold
+ code="403"
+ icon="gpp_bad"
+ title="Forbidden"
+ description="Your request was understood, but access is denied by policy."
+ suggestions={[
+ "Check IP allowlist/blocklist rules in settings.",
+ "Verify model and budget policies assigned to your API key.",
+ "Ask an administrator to grant the required permission scope.",
+ ]}
+ primaryAction={{ href: "/forbidden", label: "Open Access Help" }}
+ secondaryAction={{
+ href: "/dashboard/settings?tab=security",
+ label: "Open Security Settings",
+ }}
+ />
+ );
+}
diff --git a/src/app/408/page.tsx b/src/app/408/page.tsx
new file mode 100644
index 0000000000..2a06ef7f81
--- /dev/null
+++ b/src/app/408/page.tsx
@@ -0,0 +1,19 @@
+import ErrorPageScaffold from "@/shared/components/ErrorPageScaffold";
+
+export default function RequestTimeoutPage() {
+ return (
+ <ErrorPageScaffold
+ code="408"
+ icon="timer_off"
+ title="Request Timeout"
+ description="The server did not receive a complete request in time."
+ suggestions={[
+ "Retry the request with a smaller payload.",
+ "Check your network stability and VPN/proxy latency.",
+ "For long operations, enable streaming or split the request.",
+ ]}
+ primaryAction={{ href: "/dashboard/endpoint", label: "Open Endpoint Guide" }}
+ secondaryAction={{ href: "/status", label: "Check Network Status" }}
+ />
+ );
+}
diff --git a/src/app/429/page.tsx b/src/app/429/page.tsx
new file mode 100644
index 0000000000..c8598b39fa
--- /dev/null
+++ b/src/app/429/page.tsx
@@ -0,0 +1,22 @@
+import ErrorPageScaffold from "@/shared/components/ErrorPageScaffold";
+
+export default function TooManyRequestsPage() {
+ return (
+ <ErrorPageScaffold
+ code="429"
+ icon="hourglass_top"
+ title="Too Many Requests"
+ description="Rate limits were exceeded for this client, key, or provider."
+ suggestions={[
+ "Wait for cooldown and retry after the suggested interval.",
+ "Switch to a combo with fallback providers.",
+ "Tune provider resilience/rate-limit profiles in settings.",
+ ]}
+ primaryAction={{
+ href: "/dashboard/settings?tab=resilience",
+ label: "Open Resilience Settings",
+ }}
+ secondaryAction={{ href: "/dashboard/combos", label: "Open Combos" }}
+ />
+ );
+}
diff --git a/src/app/500/page.tsx b/src/app/500/page.tsx
new file mode 100644
index 0000000000..946b6139d1
--- /dev/null
+++ b/src/app/500/page.tsx
@@ -0,0 +1,19 @@
+import ErrorPageScaffold from "@/shared/components/ErrorPageScaffold";
+
+export default function InternalServerErrorPage() {
+ return (
+ <ErrorPageScaffold
+ code="500"
+ icon="warning"
+ title="Internal Server Error"
+ description="An unexpected server-side error occurred while processing your request."
+ suggestions={[
+ "Retry once in a few seconds.",
+ "Check health telemetry and server logs for correlated request IDs.",
+ "If persistent, report the issue with timestamp and request context.",
+ ]}
+ primaryAction={{ href: "/dashboard/health", label: "Open Health Dashboard" }}
+ secondaryAction={{ href: "/dashboard/logs", label: "Open Logs" }}
+ />
+ );
+}
diff --git a/src/app/502/page.tsx b/src/app/502/page.tsx
new file mode 100644
index 0000000000..ecef0a9e30
--- /dev/null
+++ b/src/app/502/page.tsx
@@ -0,0 +1,19 @@
+import ErrorPageScaffold from "@/shared/components/ErrorPageScaffold";
+
+export default function BadGatewayPage() {
+ return (
+ <ErrorPageScaffold
+ code="502"
+ icon="hub"
+ title="Bad Gateway"
+ description="Upstream provider or gateway integration returned an invalid response."
+ suggestions={[
+ "Retry with another provider or active combo route.",
+ "Check provider credentials and model availability.",
+ "Inspect translator output if format conversion is involved.",
+ ]}
+ primaryAction={{ href: "/dashboard/providers", label: "Open Providers" }}
+ secondaryAction={{ href: "/dashboard/translator", label: "Open Translator" }}
+ />
+ );
+}
diff --git a/src/app/503/page.tsx b/src/app/503/page.tsx
new file mode 100644
index 0000000000..d24c5cc01e
--- /dev/null
+++ b/src/app/503/page.tsx
@@ -0,0 +1,19 @@
+import ErrorPageScaffold from "@/shared/components/ErrorPageScaffold";
+
+export default function ServiceUnavailablePage() {
+ return (
+ <ErrorPageScaffold
+ code="503"
+ icon="build_circle"
+ title="Service Unavailable"
+ description="The service is temporarily unavailable due to maintenance or degraded dependencies."
+ suggestions={[
+ "Wait a moment and retry.",
+ "Check maintenance notices and system status.",
+ "Use fallback providers if your workflow is latency-sensitive.",
+ ]}
+ primaryAction={{ href: "/maintenance", label: "Maintenance Details" }}
+ secondaryAction={{ href: "/status", label: "System Status" }}
+ />
+ );
+}
diff --git a/src/app/maintenance/page.tsx b/src/app/maintenance/page.tsx
new file mode 100644
index 0000000000..4d59d2f266
--- /dev/null
+++ b/src/app/maintenance/page.tsx
@@ -0,0 +1,54 @@
+import Link from "next/link";
+
+export default function MaintenancePage() {
+ return (
+ <main className="min-h-screen bg-bg text-text-main flex items-center justify-center p-6">
+ <section className="w-full max-w-xl rounded-2xl border border-border bg-surface p-8 shadow-soft text-center">
+ <span className="material-symbols-outlined text-5xl text-primary mb-3" aria-hidden="true">
+ construction
+ </span>
+ <h1 className="text-2xl font-semibold">Scheduled Maintenance</h1>
+ <p className="mt-3 text-text-muted leading-relaxed">
+ Some services are temporarily unavailable while maintenance is in progress. Core routing
+ usually remains online, but management features may be degraded.
+ </p>
+
+ <ul className="mt-6 text-sm text-text-muted text-left rounded-xl border border-border bg-bg-alt p-4 space-y-2">
+ <li className="flex items-start gap-2">
+ <span
+ className="material-symbols-outlined text-base text-primary mt-0.5"
+ aria-hidden="true"
+ >
+ info
+ </span>
+ Retry after a few minutes.
+ </li>
+ <li className="flex items-start gap-2">
+ <span
+ className="material-symbols-outlined text-base text-primary mt-0.5"
+ aria-hidden="true"
+ >
+ info
+ </span>
+ Check current health indicators and provider status before retrying.
+ </li>
+ </ul>
+
+ <div className="mt-8 flex flex-col sm:flex-row gap-3">
+ <Link
+ href="/status"
+ className="inline-flex items-center justify-center px-6 py-3 rounded-lg text-white text-sm font-semibold bg-gradient-to-br from-primary to-primary-hover hover:shadow-elevated transition-all duration-200 motion-reduce:transition-none"
+ >
+ View System Status
+ </Link>
+ <Link
+ href="/dashboard/health"
+ className="inline-flex items-center justify-center px-6 py-3 rounded-lg text-sm font-semibold border border-border hover:bg-bg-alt transition-colors duration-200 motion-reduce:transition-none"
+ >
+ Open Health Dashboard
+ </Link>
+ </div>
+ </section>
+ </main>
+ );
+}
diff --git a/src/app/offline/page.tsx b/src/app/offline/page.tsx
new file mode 100644
index 0000000000..045b254fc7
--- /dev/null
+++ b/src/app/offline/page.tsx
@@ -0,0 +1,65 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import Link from "next/link";
+
+export default function OfflinePage() {
+ const [isOnline, setIsOnline] = useState<boolean>(() =>
+ typeof navigator !== "undefined" ? navigator.onLine : true
+ );
+
+ useEffect(() => {
+ const onOnline = () => setIsOnline(true);
+ const onOffline = () => setIsOnline(false);
+
+ window.addEventListener("online", onOnline);
+ window.addEventListener("offline", onOffline);
+ return () => {
+ window.removeEventListener("online", onOnline);
+ window.removeEventListener("offline", onOffline);
+ };
+ }, []);
+
+ return (
+ <main className="min-h-screen bg-bg text-text-main flex items-center justify-center p-6">
+ <section className="w-full max-w-xl rounded-2xl border border-border bg-surface p-8 shadow-soft text-center">
+ <span className="material-symbols-outlined text-5xl text-primary mb-3" aria-hidden="true">
+ wifi_off
+ </span>
+ <h1 className="text-2xl font-semibold">Connectivity Issue</h1>
+ <p className="mt-3 text-text-muted leading-relaxed">
+ OmniRoute cannot reach the network right now. Check your internet, VPN, or proxy settings.
+ </p>
+
+ <div
+ className={`mt-6 inline-flex items-center gap-2 rounded-full px-3 py-1.5 text-sm border ${
+ isOnline
+ ? "border-green-500/30 text-green-600 dark:text-green-400 bg-green-500/10"
+ : "border-amber-500/30 text-amber-600 dark:text-amber-400 bg-amber-500/10"
+ }`}
+ aria-live="polite"
+ >
+ <span className="material-symbols-outlined text-base" aria-hidden="true">
+ {isOnline ? "wifi" : "wifi_off"}
+ </span>
+ <span>{isOnline ? "Connection restored" : "Offline mode detected"}</span>
+ </div>
+
+ <div className="mt-8 flex flex-col sm:flex-row gap-3">
+ <button
+ onClick={() => window.location.reload()}
+ className="inline-flex items-center justify-center px-6 py-3 rounded-lg text-white text-sm font-semibold bg-gradient-to-br from-primary to-primary-hover hover:shadow-elevated transition-all duration-200 motion-reduce:transition-none"
+ >
+ Retry Connection
+ </button>
+ <Link
+ href="/status"
+ className="inline-flex items-center justify-center px-6 py-3 rounded-lg text-sm font-semibold border border-border hover:bg-bg-alt transition-colors duration-200 motion-reduce:transition-none"
+ >
+ Open Status Page
+ </Link>
+ </div>
+ </section>
+ </main>
+ );
+}
diff --git a/src/app/status/page.tsx b/src/app/status/page.tsx
new file mode 100644
index 0000000000..a578caf898
--- /dev/null
+++ b/src/app/status/page.tsx
@@ -0,0 +1,156 @@
+"use client";
+
+import { useEffect, useMemo, useState } from "react";
+import Link from "next/link";
+import { Spinner } from "@/shared/components/Loading";
+
+interface HealthPayload {
+ status?: string;
+ timestamp?: string;
+ system?: {
+ version?: string;
+ uptime?: number;
+ nodeVersion?: string;
+ platform?: string;
+ pid?: number;
+ };
+ providerHealth?: Record<string, { state?: string; failures?: number }>;
+ error?: string;
+}
+
+function formatUptime(seconds?: number) {
+ if (!seconds || seconds <= 0) return "0m";
+ const total = Math.floor(seconds);
+ const hours = Math.floor(total / 3600);
+ const minutes = Math.floor((total % 3600) / 60);
+ if (hours > 0) return `${hours}h ${minutes}m`;
+ return `${minutes}m`;
+}
+
+export default function StatusPage() {
+ const [loading, setLoading] = useState(true);
+ const [health, setHealth] = useState<HealthPayload | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ async function loadHealth() {
+ setLoading(true);
+ setError(null);
+ try {
+ const response = await fetch("/api/monitoring/health", { cache: "no-store" });
+ const data = (await response.json()) as HealthPayload;
+ if (!response.ok) {
+ setError(data.error || "Failed to load system health.");
+ setHealth(null);
+ return;
+ }
+ setHealth(data);
+ } catch {
+ setError("Unable to reach health endpoint. Check connectivity and retry.");
+ setHealth(null);
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ useEffect(() => {
+ void loadHealth();
+ }, []);
+
+ const providerStats = useMemo(() => {
+ const providers = Object.entries(health?.providerHealth || {});
+ const open = providers.filter(([, p]) => p.state === "OPEN").length;
+ const halfOpen = providers.filter(([, p]) => p.state === "HALF_OPEN").length;
+ const closed = providers.filter(([, p]) => p.state === "CLOSED").length;
+ return { total: providers.length, open, halfOpen, closed };
+ }, [health]);
+
+ return (
+ <main className="min-h-screen bg-bg text-text-main p-6 sm:p-10">
+ <section className="max-w-4xl mx-auto space-y-6">
+ <header className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
+ <div>
+ <h1 className="text-3xl font-bold tracking-tight">System Status</h1>
+ <p className="text-text-muted mt-1">
+ Live operational snapshot for OmniRoute core services.
+ </p>
+ </div>
+ <button
+ onClick={() => void loadHealth()}
+ className="inline-flex items-center justify-center px-4 py-2 rounded-lg text-sm font-semibold bg-gradient-to-br from-primary to-primary-hover text-white transition-all duration-200 motion-reduce:transition-none"
+ >
+ Refresh
+ </button>
+ </header>
+
+ {loading && (
+ <div
+ className="rounded-xl border border-border bg-surface p-6 flex items-center gap-3"
+ role="status"
+ aria-live="polite"
+ >
+ <Spinner size="md" />
+ <span className="text-text-muted">Loading health metrics...</span>
+ </div>
+ )}
+
+ {!loading && error && (
+ <div className="rounded-xl border border-red-500/30 bg-red-500/10 p-6" role="alert">
+ <h2 className="text-lg font-semibold text-red-600 dark:text-red-400">
+ Health Check Failed
+ </h2>
+ <p className="mt-2 text-sm text-text-muted">{error}</p>
+ <div className="mt-4 flex flex-wrap gap-2">
+ <Link
+ href="/offline"
+ className="px-3 py-2 rounded-lg border border-border text-sm font-medium hover:bg-bg-alt transition-colors"
+ >
+ Open Connectivity Help
+ </Link>
+ <Link
+ href="/maintenance"
+ className="px-3 py-2 rounded-lg border border-border text-sm font-medium hover:bg-bg-alt transition-colors"
+ >
+ Maintenance Info
+ </Link>
+ </div>
+ </div>
+ )}
+
+ {!loading && health && (
+ <>
+ <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
+ <div className="rounded-xl border border-border bg-surface p-4">
+ <p className="text-xs uppercase tracking-wide text-text-muted">Service</p>
+ <p className="mt-2 text-xl font-semibold">{health.status || "unknown"}</p>
+ </div>
+ <div className="rounded-xl border border-border bg-surface p-4">
+ <p className="text-xs uppercase tracking-wide text-text-muted">Version</p>
+ <p className="mt-2 text-xl font-semibold">{health.system?.version || "n/a"}</p>
+ </div>
+ <div className="rounded-xl border border-border bg-surface p-4">
+ <p className="text-xs uppercase tracking-wide text-text-muted">Uptime</p>
+ <p className="mt-2 text-xl font-semibold">{formatUptime(health.system?.uptime)}</p>
+ </div>
+ <div className="rounded-xl border border-border bg-surface p-4">
+ <p className="text-xs uppercase tracking-wide text-text-muted">Providers Tracked</p>
+ <p className="mt-2 text-xl font-semibold">{providerStats.total}</p>
+ </div>
+ </div>
+
+ <div className="rounded-xl border border-border bg-surface p-6">
+ <h2 className="text-lg font-semibold">Provider Circuit Breaker State</h2>
+ <p className="text-sm text-text-muted mt-1">
+ OPEN: {providerStats.open} · HALF_OPEN: {providerStats.halfOpen} · CLOSED:{" "}
+ {providerStats.closed}
+ </p>
+ <p className="mt-4 text-xs text-text-muted">
+ Last update:{" "}
+ {health.timestamp ? new Date(health.timestamp).toLocaleString() : "n/a"}
+ </p>
+ </div>
+ </>
+ )}
+ </section>
+ </main>
+ );
+}
diff --git a/src/lib/compliance/index.ts b/src/lib/compliance/index.ts
index f3f7013a8f..f5577497a2 100644
--- a/src/lib/compliance/index.ts
+++ b/src/lib/compliance/index.ts
@@ -9,12 +9,15 @@
* @module lib/compliance
*/
-
import { getDbInstance } from "../db/core";
/** @returns {import("better-sqlite3").Database | null} */
function getDb() {
- try { return getDbInstance(); } catch { return null; }
+ try {
+ return getDbInstance();
+ } catch {
+ return null;
+ }
}
const LOG_RETENTION_DAYS = parseInt(process.env.LOG_RETENTION_DAYS || "90", 10);
@@ -51,7 +54,13 @@ export function initAuditLog() {
* @param {Object|string} [entry.details] - Additional details
* @param {string} [entry.ipAddress] - Client IP
*/
-export function logAuditEvent(entry: { action: string; actor?: string; target?: string; details?: unknown; ipAddress?: string }) {
+export function logAuditEvent(entry: {
+ action: string;
+ actor?: string;
+ target?: string;
+ details?: unknown;
+ ipAddress?: string;
+}) {
const db = getDb();
if (!db) return;
@@ -82,7 +91,9 @@ export function logAuditEvent(entry: { action: string; actor?: string; target?:
* @param {number} [filter.offset=0] - Pagination offset
* @returns {Array<{ id: number, timestamp: string, action: string, actor: string, target: string, details: any, ip_address: string }>}
*/
-export function getAuditLog(filter: { action?: string; actor?: string; limit?: number; offset?: number } = {}) {
+export function getAuditLog(
+ filter: { action?: string; actor?: string; limit?: number; offset?: number } = {}
+) {
const db = getDb();
if (!db) return [];
@@ -102,13 +113,12 @@ export function getAuditLog(filter: { action?: string; actor?: string; limit?: n
const limit = filter.limit || 100;
const offset = filter.offset || 0;
- /** @type {any[]} */
const rows = db
.prepare(`SELECT * FROM audit_log ${where} ORDER BY timestamp DESC LIMIT ? OFFSET ?`)
- .all(...params, limit, offset);
+ .all(...params, limit, offset) as Array<Record<string, unknown> & { details?: string | null }>;
return rows.map((row) => ({
- ...row,
+ ...(row as Record<string, unknown>),
details: row.details ? JSON.parse(String(row.details)) : null,
}));
}
@@ -117,6 +127,17 @@ export function getAuditLog(filter: { action?: string; actor?: string; limit?: n
/** @type {Set<string>} API key IDs with logging disabled */
const noLogKeys = new Set();
+const noLogDbCache = new Map<string, { value: boolean; timestamp: number }>();
+let noLogColumnVerified = false;
+let hasNoLogColumn = false;
+const NO_LOG_CACHE_TTL_MS = 30_000;
+const noLogIdsFromEnv = (process.env.NO_LOG_API_KEY_IDS || "")
+ .split(",")
+ .map((value) => value.trim())
+ .filter(Boolean);
+for (const id of noLogIdsFromEnv) {
+ noLogKeys.add(id);
+}
/**
* Set whether an API key opts out of request logging.
@@ -130,6 +151,45 @@ export function setNoLog(apiKeyId: string, noLog: boolean) {
} else {
noLogKeys.delete(apiKeyId);
}
+ noLogDbCache.set(apiKeyId, { value: noLog, timestamp: Date.now() });
+}
+
+function ensureNoLogColumn(db: import("better-sqlite3").Database) {
+ if (noLogColumnVerified) {
+ return hasNoLogColumn;
+ }
+
+ try {
+ const columns = db.prepare("PRAGMA table_info(api_keys)").all() as Array<{ name: string }>;
+ hasNoLogColumn = columns.some((column) => column.name === "no_log");
+ } catch {
+ hasNoLogColumn = false;
+ }
+
+ noLogColumnVerified = true;
+ return hasNoLogColumn;
+}
+
+function readNoLogFromDb(apiKeyId: string): boolean {
+ const db = getDb();
+ if (!db || !apiKeyId) return false;
+ if (!ensureNoLogColumn(db)) return false;
+
+ const cached = noLogDbCache.get(apiKeyId);
+ if (cached && Date.now() - cached.timestamp < NO_LOG_CACHE_TTL_MS) {
+ return cached.value;
+ }
+
+ try {
+ const row = db.prepare("SELECT no_log FROM api_keys WHERE id = ?").get(apiKeyId) as
+ | { no_log?: number }
+ | undefined;
+ const value = Boolean(row && Number(row.no_log) === 1);
+ noLogDbCache.set(apiKeyId, { value, timestamp: Date.now() });
+ return value;
+ } catch {
+ return false;
+ }
}
/**
@@ -139,7 +199,14 @@ export function setNoLog(apiKeyId: string, noLog: boolean) {
* @returns {boolean}
*/
export function isNoLog(apiKeyId: string) {
- return noLogKeys.has(apiKeyId);
+ if (!apiKeyId) return false;
+ if (noLogKeys.has(apiKeyId)) return true;
+
+ const persistedNoLog = readNoLogFromDb(apiKeyId);
+ if (persistedNoLog) {
+ noLogKeys.add(apiKeyId);
+ }
+ return persistedNoLog;
}
// ─── Log Retention / Cleanup ────────────────
diff --git a/src/lib/container.ts b/src/lib/container.ts
index 13a1a5feec..f3aa1af3f8 100644
--- a/src/lib/container.ts
+++ b/src/lib/container.ts
@@ -15,17 +15,17 @@
* @module lib/container
*/
-import { evaluateFirstAllowed, evaluateRequest, PolicyEngine } from "../domain/policyEngine";
-import { getDbInstance } from "./db/core";
+import { evaluateFirstAllowed, evaluateRequest, PolicyEngine } from "../domain/policyEngine.ts";
+import { getDbInstance } from "./db/core.ts";
import {
decrypt,
decryptConnectionFields,
encrypt,
encryptConnectionFields,
-} from "./db/encryption";
-import { getSettings } from "./localDb";
-import { getCircuitBreaker } from "../shared/utils/circuitBreaker";
-import { recordTelemetry, RequestTelemetry } from "../shared/utils/requestTelemetry";
+} from "./db/encryption.ts";
+import { getSettings } from "./localDb.ts";
+import { getCircuitBreaker } from "../shared/utils/circuitBreaker.ts";
+import { recordTelemetry, RequestTelemetry } from "../shared/utils/requestTelemetry.ts";
type Factory<T = any> = () => T;
diff --git a/src/lib/dataPaths.ts b/src/lib/dataPaths.ts
index 4f9619e018..233caf77d7 100644
--- a/src/lib/dataPaths.ts
+++ b/src/lib/dataPaths.ts
@@ -11,7 +11,7 @@ function safeHomeDir() {
}
}
-function normalizeConfiguredPath(dir) {
+function normalizeConfiguredPath(dir: unknown): string | null {
if (typeof dir !== "string") return null;
const trimmed = dir.trim();
if (!trimmed) return null;
@@ -39,7 +39,7 @@ export function getDefaultDataDir() {
return getLegacyDotDataDir();
}
-export function resolveDataDir({ isCloud = false } = {}) {
+export function resolveDataDir({ isCloud = false }: { isCloud?: boolean } = {}): string {
if (isCloud) return "/tmp";
const configured = normalizeConfiguredPath(process.env.DATA_DIR);
@@ -48,7 +48,7 @@ export function resolveDataDir({ isCloud = false } = {}) {
return getDefaultDataDir();
}
-export function isSamePath(a, b) {
+export function isSamePath(a: string | null | undefined, b: string | null | undefined): boolean {
if (!a || !b) return false;
const normalizedA = path.resolve(a);
const normalizedB = path.resolve(b);
diff --git a/src/lib/db/apiKeys.ts b/src/lib/db/apiKeys.ts
index dd9bb0689d..5801cd2c95 100644
--- a/src/lib/db/apiKeys.ts
+++ b/src/lib/db/apiKeys.ts
@@ -5,15 +5,70 @@
import { v4 as uuidv4 } from "uuid";
import { getDbInstance, rowToCamel } from "./core";
import { backupDbFile } from "./backup";
+import { registerDbStateResetter } from "./stateReset";
+import { setNoLog } from "../compliance";
// ──────────────── Performance Optimizations ────────────────
// Schema check memoization - only run once
let _schemaChecked = false;
+type JsonRecord = Record<string, unknown>;
+
+interface CacheEntry<TValue> {
+ timestamp: number;
+ value: TValue;
+}
+
+interface ApiKeyMetadata {
+ id: string;
+ name: string;
+ machineId: string | null;
+ allowedModels: string[];
+ noLog: boolean;
+}
+
+interface ApiKeyRow extends JsonRecord {
+ id?: unknown;
+ name?: unknown;
+ key?: unknown;
+ machine_id?: unknown;
+ machineId?: unknown;
+ allowed_models?: unknown;
+ allowedModels?: unknown;
+ no_log?: unknown;
+ noLog?: unknown;
+}
+
+interface StatementLike<TRow = unknown> {
+ all: (...params: unknown[]) => TRow[];
+ get: (...params: unknown[]) => TRow | undefined;
+ run: (...params: unknown[]) => { changes?: number };
+}
+
+interface ApiKeysDbLike {
+ prepare: <TRow = unknown>(sql: string) => StatementLike<TRow>;
+ exec: (sql: string) => void;
+}
+
+interface ApiKeysStatements {
+ getAllKeys: StatementLike<ApiKeyRow>;
+ getKeyById: StatementLike<ApiKeyRow>;
+ validateKey: StatementLike<JsonRecord>;
+ getKeyMetadata: StatementLike<ApiKeyRow>;
+ insertKey: StatementLike;
+ deleteKey: StatementLike;
+}
+
+interface ApiKeyView extends JsonRecord {
+ id?: string;
+ allowedModels: string[];
+ noLog: boolean;
+}
+
// LRU cache for API key validation (valid keys only)
const _keyValidationCache = new Map<string, { valid: boolean; timestamp: number }>();
-const _keyMetadataCache = new Map<string, { metadata: any; timestamp: number }>();
+const _keyMetadataCache = new Map<string, CacheEntry<ApiKeyMetadata>>();
const CACHE_TTL = 60 * 1000; // 1 minute TTL
const MAX_CACHE_SIZE = 1000;
@@ -24,13 +79,12 @@ const _regexCache = new Map<string, RegExp>();
const _modelPermissionCache = new Map<string, { allowed: boolean; timestamp: number }>();
// Prepared statements cache
-let _stmtGetAllKeys: any = null;
-let _stmtGetKeyById: any = null;
-let _stmtValidateKey: any = null;
-let _stmtGetKeyMetadata: any = null;
-let _stmtInsertKey: any = null;
-let _stmtUpdatePermissions: any = null;
-let _stmtDeleteKey: any = null;
+let _stmtGetAllKeys: ApiKeysStatements["getAllKeys"] | null = null;
+let _stmtGetKeyById: ApiKeysStatements["getKeyById"] | null = null;
+let _stmtValidateKey: ApiKeysStatements["validateKey"] | null = null;
+let _stmtGetKeyMetadata: ApiKeysStatements["getKeyMetadata"] | null = null;
+let _stmtInsertKey: ApiKeysStatements["insertKey"] | null = null;
+let _stmtDeleteKey: ApiKeysStatements["deleteKey"] | null = null;
/**
* Clear all caches (called on key create/update/delete)
@@ -41,10 +95,14 @@ function invalidateCaches() {
_modelPermissionCache.clear();
}
+function toRecord(value: unknown): JsonRecord {
+ return value && typeof value === "object" ? (value as JsonRecord) : {};
+}
+
/**
* LRU eviction for cache
*/
-function evictIfNeeded(cache: Map<any, any>) {
+function evictIfNeeded<TKey, TValue>(cache: Map<TKey, TValue>) {
if (cache.size > MAX_CACHE_SIZE) {
// Remove oldest 20% of entries
const entriesToRemove = Math.floor(MAX_CACHE_SIZE * 0.2);
@@ -74,97 +132,131 @@ function getWildcardRegex(pattern: string): RegExp {
return regex;
}
-// Ensure the allowed_models column exists (memoized)
-function ensureAllowedModelsColumn(db) {
+// Ensure api_keys extension columns exist (memoized)
+function ensureApiKeysColumns(db: ApiKeysDbLike) {
if (_schemaChecked) return;
try {
- const columns = db.prepare("PRAGMA table_info(api_keys)").all();
- const columnNames = new Set(columns.map((column) => column.name));
+ const columns = db.prepare<ApiKeyRow>("PRAGMA table_info(api_keys)").all();
+ const columnNames = new Set(columns.map((column) => String(column.name ?? "")));
if (!columnNames.has("allowed_models")) {
db.exec("ALTER TABLE api_keys ADD COLUMN allowed_models TEXT");
console.log("[DB] Added api_keys.allowed_models column");
}
+ if (!columnNames.has("no_log")) {
+ db.exec("ALTER TABLE api_keys ADD COLUMN no_log INTEGER NOT NULL DEFAULT 0");
+ console.log("[DB] Added api_keys.no_log column");
+ }
_schemaChecked = true;
} catch (error) {
- console.warn("[DB] Failed to verify api_keys schema:", error.message);
+ const message = error instanceof Error ? error.message : String(error);
+ console.warn("[DB] Failed to verify api_keys schema:", message);
}
}
/**
* Initialize prepared statements (lazy initialization)
*/
-function getPreparedStatements(db: any) {
- if (!_stmtGetAllKeys) {
- _stmtGetAllKeys = db.prepare("SELECT * FROM api_keys ORDER BY created_at");
- _stmtGetKeyById = db.prepare("SELECT * FROM api_keys WHERE id = ?");
- _stmtValidateKey = db.prepare("SELECT 1 FROM api_keys WHERE key = ?");
- _stmtGetKeyMetadata = db.prepare(
- "SELECT id, name, machine_id, allowed_models FROM api_keys WHERE key = ?"
+function getPreparedStatements(db: ApiKeysDbLike): ApiKeysStatements {
+ ensureApiKeysColumns(db);
+
+ if (
+ !_stmtGetAllKeys ||
+ !_stmtGetKeyById ||
+ !_stmtValidateKey ||
+ !_stmtGetKeyMetadata ||
+ !_stmtInsertKey ||
+ !_stmtDeleteKey
+ ) {
+ _stmtGetAllKeys = db.prepare<ApiKeyRow>("SELECT * FROM api_keys ORDER BY created_at");
+ _stmtGetKeyById = db.prepare<ApiKeyRow>("SELECT * FROM api_keys WHERE id = ?");
+ _stmtValidateKey = db.prepare<JsonRecord>("SELECT 1 FROM api_keys WHERE key = ?");
+ _stmtGetKeyMetadata = db.prepare<ApiKeyRow>(
+ "SELECT id, name, machine_id, allowed_models, no_log FROM api_keys WHERE key = ?"
);
_stmtInsertKey = db.prepare(
- "INSERT INTO api_keys (id, name, key, machine_id, allowed_models, created_at) VALUES (?, ?, ?, ?, ?, ?)"
+ "INSERT INTO api_keys (id, name, key, machine_id, allowed_models, no_log, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)"
);
- _stmtUpdatePermissions = db.prepare("UPDATE api_keys SET allowed_models = ? WHERE id = ?");
_stmtDeleteKey = db.prepare("DELETE FROM api_keys WHERE id = ?");
}
+
+ if (
+ !_stmtGetAllKeys ||
+ !_stmtGetKeyById ||
+ !_stmtValidateKey ||
+ !_stmtGetKeyMetadata ||
+ !_stmtInsertKey ||
+ !_stmtDeleteKey
+ ) {
+ throw new Error("Failed to initialize API key prepared statements");
+ }
+
return {
getAllKeys: _stmtGetAllKeys,
getKeyById: _stmtGetKeyById,
validateKey: _stmtValidateKey,
getKeyMetadata: _stmtGetKeyMetadata,
insertKey: _stmtInsertKey,
- updatePermissions: _stmtUpdatePermissions,
deleteKey: _stmtDeleteKey,
};
}
export async function getApiKeys() {
- const db = getDbInstance();
- ensureAllowedModelsColumn(db);
+ const db = getDbInstance() as ApiKeysDbLike;
const stmt = getPreparedStatements(db);
- const rows = stmt.getAllKeys.all() as Record<string, any>[];
+ const rows = stmt.getAllKeys.all();
return rows.map((row) => {
- const camelRow = rowToCamel(row) as Record<string, any>;
- // Parse allowed_models from JSON string to array
+ const camelRow = toRecord(rowToCamel(row)) as ApiKeyView;
camelRow.allowedModels = parseAllowedModels(camelRow.allowedModels);
+ camelRow.noLog = parseNoLog(camelRow.noLog);
+ if (typeof camelRow.id === "string" && camelRow.id.length > 0) {
+ setNoLog(camelRow.id, camelRow.noLog === true);
+ }
return camelRow;
});
}
export async function getApiKeyById(id: string) {
- const db = getDbInstance();
- ensureAllowedModelsColumn(db);
+ const db = getDbInstance() as ApiKeysDbLike;
const stmt = getPreparedStatements(db);
- const row = stmt.getKeyById.get(id) as Record<string, any> | undefined;
+ const row = stmt.getKeyById.get(id);
if (!row) return null;
- const camelRow = rowToCamel(row) as Record<string, any>;
+ const camelRow = toRecord(rowToCamel(row)) as ApiKeyView;
camelRow.allowedModels = parseAllowedModels(camelRow.allowedModels);
+ camelRow.noLog = parseNoLog(camelRow.noLog);
+ if (typeof camelRow.id === "string" && camelRow.id.length > 0) {
+ setNoLog(camelRow.id, camelRow.noLog === true);
+ }
return camelRow;
}
/**
* Helper function to safely parse allowed_models JSON
*/
-function parseAllowedModels(value: any): string[] {
+function parseAllowedModels(value: unknown): string[] {
if (!value || typeof value !== "string" || value.trim() === "") {
return [];
}
try {
const parsed = JSON.parse(value);
- return Array.isArray(parsed) ? parsed : [];
+ return Array.isArray(parsed)
+ ? parsed.filter((entry): entry is string => typeof entry === "string")
+ : [];
} catch {
return [];
}
}
-export async function createApiKey(name, machineId) {
+function parseNoLog(value: unknown): boolean {
+ return value === true || value === 1 || value === "1";
+}
+
+export async function createApiKey(name: string, machineId: string) {
if (!machineId) {
throw new Error("machineId is required");
}
- const db = getDbInstance();
- ensureAllowedModelsColumn(db);
+ const db = getDbInstance() as ApiKeysDbLike;
const now = new Date().toISOString();
const { generateApiKeyWithMachine } = await import("@/shared/utils/apiKey");
@@ -176,29 +268,67 @@ export async function createApiKey(name, machineId) {
key: result.key,
machineId: machineId,
allowedModels: [], // Empty array means all models allowed
+ noLog: false,
createdAt: now,
};
const stmt = getPreparedStatements(db);
- stmt.insertKey.run(apiKey.id, apiKey.name, apiKey.key, apiKey.machineId, "[]", apiKey.createdAt);
+ stmt.insertKey.run(
+ apiKey.id,
+ apiKey.name,
+ apiKey.key,
+ apiKey.machineId,
+ "[]",
+ 0,
+ apiKey.createdAt
+ );
+ setNoLog(apiKey.id, false);
backupDbFile("pre-write");
return apiKey;
}
-export async function updateApiKeyPermissions(id, allowedModels) {
- const db = getDbInstance();
- ensureAllowedModelsColumn(db);
+export async function updateApiKeyPermissions(
+ id: string,
+ update: string[] | { allowedModels?: string[]; noLog?: boolean }
+) {
+ const db = getDbInstance() as ApiKeysDbLike;
+ getPreparedStatements(db);
+
+ const normalized =
+ Array.isArray(update) || update === undefined
+ ? { allowedModels: update || [] }
+ : {
+ allowedModels: update.allowedModels,
+ noLog: update.noLog,
+ };
+
+ if (normalized.allowedModels === undefined && normalized.noLog === undefined) {
+ return false;
+ }
- // allowedModels should be an array of model IDs (strings)
- // Empty array means all models are allowed
- const modelsJson = JSON.stringify(allowedModels || []);
+ const updates: string[] = [];
+ const params: { id: string; allowedModels?: string; noLog?: number } = { id };
- const stmt = getPreparedStatements(db);
- const result = stmt.updatePermissions.run(modelsJson, id);
+ if (normalized.allowedModels !== undefined) {
+ // Empty array means all models are allowed
+ updates.push("allowed_models = @allowedModels");
+ params.allowedModels = JSON.stringify(normalized.allowedModels || []);
+ }
+
+ if (normalized.noLog !== undefined) {
+ updates.push("no_log = @noLog");
+ params.noLog = normalized.noLog ? 1 : 0;
+ }
+
+ const result = db.prepare(`UPDATE api_keys SET ${updates.join(", ")} WHERE id = @id`).run(params);
if (result.changes === 0) return false;
+ if (normalized.noLog !== undefined) {
+ setNoLog(id, normalized.noLog);
+ }
+
// Invalidate caches since permissions changed
invalidateCaches();
@@ -206,13 +336,15 @@ export async function updateApiKeyPermissions(id, allowedModels) {
return true;
}
-export async function deleteApiKey(id) {
- const db = getDbInstance();
+export async function deleteApiKey(id: string) {
+ const db = getDbInstance() as ApiKeysDbLike;
const stmt = getPreparedStatements(db);
const result = stmt.deleteKey.run(id);
if (result.changes === 0) return false;
+ setNoLog(id, false);
+
// Invalidate caches since a key was removed
invalidateCaches();
@@ -224,7 +356,7 @@ export async function deleteApiKey(id) {
* Validate API key with caching for performance
* Cached valid keys reduce DB hits on every request
*/
-export async function validateApiKey(key) {
+export async function validateApiKey(key: string | null | undefined) {
if (!key || typeof key !== "string") return false;
const now = Date.now();
@@ -235,7 +367,7 @@ export async function validateApiKey(key) {
return cached.valid;
}
- const db = getDbInstance();
+ const db = getDbInstance() as ApiKeysDbLike;
const stmt = getPreparedStatements(db);
const row = stmt.validateKey.get(key);
const valid = !!row;
@@ -252,7 +384,9 @@ export async function validateApiKey(key) {
/**
* Get API key metadata with caching for performance
*/
-export async function getApiKeyMetadata(key) {
+export async function getApiKeyMetadata(
+ key: string | null | undefined
+): Promise<ApiKeyMetadata | null> {
if (!key || typeof key !== "string") return null;
const now = Date.now();
@@ -260,26 +394,38 @@ export async function getApiKeyMetadata(key) {
// Check cache first
const cached = _keyMetadataCache.get(key);
if (cached && now - cached.timestamp < CACHE_TTL) {
- return cached.metadata;
+ return cached.value;
}
- const db = getDbInstance();
- ensureAllowedModelsColumn(db);
+ const db = getDbInstance() as ApiKeysDbLike;
const stmt = getPreparedStatements(db);
- const row = stmt.getKeyMetadata.get(key) as Record<string, any> | undefined;
+ const row = stmt.getKeyMetadata.get(key);
if (!row) return null;
- const metadata = {
- id: row.id,
- name: row.name,
- machineId: row.machine_id,
- allowedModels: parseAllowedModels(row.allowed_models),
+ const record = toRecord(row) as ApiKeyRow;
+ const metadataId = typeof record.id === "string" ? record.id : "";
+ const metadataName = typeof record.name === "string" ? record.name : "";
+ const machineIdRaw = record.machine_id ?? record.machineId;
+ const metadataMachineId = typeof machineIdRaw === "string" ? machineIdRaw : null;
+
+ const metadata: ApiKeyMetadata = {
+ id: metadataId,
+ name: metadataName,
+ machineId: metadataMachineId,
+ allowedModels: parseAllowedModels(record.allowed_models ?? record.allowedModels),
+ noLog: parseNoLog(record.no_log ?? record.noLog),
};
+ if (!metadata.id) {
+ return null;
+ }
+
+ setNoLog(metadata.id, metadata.noLog === true);
+
// Cache the result
evictIfNeeded(_keyMetadataCache);
- _keyMetadataCache.set(key, { metadata, timestamp: now });
+ _keyMetadataCache.set(key, { value: metadata, timestamp: now });
return metadata;
}
@@ -290,7 +436,10 @@ export async function getApiKeyMetadata(key) {
* @param {string} modelId - The model ID to check
* @returns {boolean} - true if allowed, false if not
*/
-export async function isModelAllowedForKey(key, modelId) {
+export async function isModelAllowedForKey(
+ key: string | null | undefined,
+ modelId: string | null | undefined
+) {
// If no key provided, allow (request may be using different auth method like JWT)
// If no modelId provided, deny (invalid request)
if (!key) return true;
@@ -319,7 +468,7 @@ export async function isModelAllowedForKey(key, modelId) {
let allowed = false;
- // Check if model matches any allowed pattern
+ // Check if model matches each allowed pattern
// Support exact match and prefix match (e.g., "openai/*" allows all OpenAI models)
for (const pattern of allowedModels) {
if (pattern === modelId) {
@@ -361,7 +510,6 @@ function clearPreparedStatementCache() {
_stmtValidateKey = null;
_stmtGetKeyMetadata = null;
_stmtInsertKey = null;
- _stmtUpdatePermissions = null;
_stmtDeleteKey = null;
_schemaChecked = false; // Also reset schema check for new connection
}
@@ -383,3 +531,5 @@ export function resetApiKeyState() {
clearPreparedStatementCache();
clearApiKeyCaches();
}
+
+registerDbStateResetter(resetApiKeyState);
diff --git a/src/lib/db/backup.ts b/src/lib/db/backup.ts
index e9989ed118..e061acf611 100644
--- a/src/lib/db/backup.ts
+++ b/src/lib/db/backup.ts
@@ -14,7 +14,9 @@ import {
DB_BACKUPS_DIR,
DATA_DIR,
} from "./core";
-import { resetApiKeyState } from "./apiKeys";
+import { resetAllDbModuleState } from "./stateReset";
+
+type CountRow = { cnt?: number };
// ──────────────── Backup Config ────────────────
@@ -67,8 +69,9 @@ export function backupDbFile(reason = "auto") {
.then(() => {
console.log(`[DB] Backup created: ${backupFile} (${stat.size} bytes)`);
})
- .catch((err) => {
- console.error("[DB] Backup failed:", err.message);
+ .catch((err: unknown) => {
+ const message = err instanceof Error ? err.message : String(err);
+ console.error("[DB] Backup failed:", message);
});
// Rotation — keep only last N, delete smallest first
@@ -100,8 +103,9 @@ export function backupDbFile(reason = "auto") {
}
return { filename: path.basename(backupFile), size: stat.size };
- } catch (err) {
- console.error("[DB] Backup failed:", err.message);
+ } catch (err: unknown) {
+ const message = err instanceof Error ? err.message : String(err);
+ console.error("[DB] Backup failed:", message);
return null;
}
}
@@ -128,7 +132,9 @@ export async function listDbBackups() {
let connectionCount = 0;
try {
const backupDb = new Database(filePath, { readonly: true });
- const row: any = backupDb.prepare("SELECT COUNT(*) as cnt FROM provider_connections").get();
+ const row = backupDb.prepare("SELECT COUNT(*) as cnt FROM provider_connections").get() as
+ | CountRow
+ | undefined;
connectionCount = row?.cnt || 0;
backupDb.close();
} catch {
@@ -151,7 +157,7 @@ export async function listDbBackups() {
// ──────────────── Restore Backup ────────────────
-export async function restoreDbBackup(backupId) {
+export async function restoreDbBackup(backupId: string) {
const backupDir = DB_BACKUPS_DIR || path.join(DATA_DIR, "db_backups");
const backupPath = path.join(backupDir, backupId);
@@ -165,14 +171,15 @@ export async function restoreDbBackup(backupId) {
// Validate backup integrity
try {
const testDb = new Database(backupPath, { readonly: true });
- const result = testDb.pragma("integrity_check");
+ const result = testDb.pragma("integrity_check") as Array<{ integrity_check?: string }>;
testDb.close();
if (result[0]?.integrity_check !== "ok") {
throw new Error("Backup integrity check failed");
}
- } catch (e) {
- if (e.message === "Backup integrity check failed") throw e;
- throw new Error(`Backup file is corrupt: ${e.message}`);
+ } catch (e: unknown) {
+ if (e instanceof Error && e.message === "Backup integrity check failed") throw e;
+ const message = e instanceof Error ? e.message : String(e);
+ throw new Error(`Backup file is corrupt: ${message}`);
}
// Force pre-restore backup (bypass throttle)
@@ -183,14 +190,19 @@ export async function restoreDbBackup(backupId) {
resetDbInstance();
// Clear all cached prepared statements and other state bound to the old connection
- resetApiKeyState();
+ resetAllDbModuleState();
+
+ const sqliteFile = SQLITE_FILE;
+ if (!sqliteFile) {
+ throw new Error("SQLITE_FILE is unavailable in local backup restore");
+ }
// Remove main file and WAL sidecars to avoid stale frame replay after restore.
const sqliteFilesToReplace = [
- SQLITE_FILE,
- `${SQLITE_FILE}-wal`,
- `${SQLITE_FILE}-shm`,
- `${SQLITE_FILE}-journal`,
+ sqliteFile,
+ `${sqliteFile}-wal`,
+ `${sqliteFile}-shm`,
+ `${sqliteFile}-journal`,
];
for (const filePath of sqliteFilesToReplace) {
if (!filePath) continue;
@@ -200,14 +212,20 @@ export async function restoreDbBackup(backupId) {
}
// Copy backup over current DB
- fs.copyFileSync(backupPath, SQLITE_FILE);
+ fs.copyFileSync(backupPath, sqliteFile);
// Reopen
const db = getDbInstance();
- const connCount = db.prepare("SELECT COUNT(*) as cnt FROM provider_connections").get()?.cnt || 0;
- const nodeCount = db.prepare("SELECT COUNT(*) as cnt FROM provider_nodes").get()?.cnt || 0;
- const comboCount = db.prepare("SELECT COUNT(*) as cnt FROM combos").get()?.cnt || 0;
- const keyCount = db.prepare("SELECT COUNT(*) as cnt FROM api_keys").get()?.cnt || 0;
+ const connCount =
+ (db.prepare("SELECT COUNT(*) as cnt FROM provider_connections").get() as CountRow | undefined)
+ ?.cnt || 0;
+ const nodeCount =
+ (db.prepare("SELECT COUNT(*) as cnt FROM provider_nodes").get() as CountRow | undefined)?.cnt ||
+ 0;
+ const comboCount =
+ (db.prepare("SELECT COUNT(*) as cnt FROM combos").get() as CountRow | undefined)?.cnt || 0;
+ const keyCount =
+ (db.prepare("SELECT COUNT(*) as cnt FROM api_keys").get() as CountRow | undefined)?.cnt || 0;
console.log(`[DB] Restored backup: ${backupId} (${connCount} connections)`);
diff --git a/src/lib/db/cliToolState.ts b/src/lib/db/cliToolState.ts
index 3bf28fd0b5..23f315d7e2 100644
--- a/src/lib/db/cliToolState.ts
+++ b/src/lib/db/cliToolState.ts
@@ -13,6 +13,35 @@
import { getDbInstance, isBuildPhase, isCloud } from "./core";
+type JsonRecord = Record<string, unknown>;
+
+interface StatementLike<TRow = unknown> {
+ all: (...params: unknown[]) => TRow[];
+ get: (...params: unknown[]) => TRow | undefined;
+ run: (...params: unknown[]) => { changes?: number };
+}
+
+interface DbLike {
+ prepare: <TRow = unknown>(sql: string) => StatementLike<TRow>;
+}
+
+interface KeyValueRow {
+ key: string;
+ value: string;
+}
+
+function parseJsonValue(raw: string): unknown {
+ try {
+ return JSON.parse(raw) as unknown;
+ } catch {
+ return null;
+ }
+}
+
+function toRecord(value: unknown): JsonRecord | null {
+ return value && typeof value === "object" && !Array.isArray(value) ? (value as JsonRecord) : null;
+}
+
// ──────────────── Last Configured Timestamp ────────────────
/**
@@ -21,9 +50,9 @@ import { getDbInstance, isBuildPhase, isCloud } from "./core";
export function saveCliToolLastConfigured(
toolId: string,
timestamp: string = new Date().toISOString()
-) {
+): void {
if (isBuildPhase || isCloud) return;
- const db = getDbInstance();
+ const db = getDbInstance() as unknown as DbLike;
db.prepare("INSERT OR REPLACE INTO key_value (namespace, key, value) VALUES (?, ?, ?)").run(
"cliToolLastConfig",
toolId,
@@ -37,11 +66,13 @@ export function saveCliToolLastConfigured(
*/
export function getCliToolLastConfigured(toolId: string): string | null {
if (isBuildPhase || isCloud) return null;
- const db = getDbInstance();
- const row: any = db
+ const db = getDbInstance() as unknown as DbLike;
+ const row = db
.prepare("SELECT value FROM key_value WHERE namespace = ? AND key = ?")
.get("cliToolLastConfig", toolId);
- return row ? JSON.parse(row.value) : null;
+ if (!row) return null;
+ const parsed = parseJsonValue((row as KeyValueRow).value);
+ return typeof parsed === "string" ? parsed : null;
}
/**
@@ -50,13 +81,16 @@ export function getCliToolLastConfigured(toolId: string): string | null {
*/
export function getAllCliToolLastConfigured(): Record<string, string> {
if (isBuildPhase || isCloud) return {};
- const db = getDbInstance();
- const rows: any[] = db
+ const db = getDbInstance() as unknown as DbLike;
+ const rows = db
.prepare("SELECT key, value FROM key_value WHERE namespace = ?")
- .all("cliToolLastConfig");
+ .all("cliToolLastConfig") as KeyValueRow[];
const result: Record<string, string> = {};
for (const row of rows) {
- result[row.key] = JSON.parse(row.value);
+ const parsed = parseJsonValue(row.value);
+ if (typeof parsed === "string") {
+ result[row.key] = parsed;
+ }
}
return result;
}
@@ -64,9 +98,9 @@ export function getAllCliToolLastConfigured(): Record<string, string> {
/**
* Delete last-configured timestamp for a CLI tool.
*/
-export function deleteCliToolLastConfigured(toolId: string) {
+export function deleteCliToolLastConfigured(toolId: string): void {
if (isBuildPhase || isCloud) return;
- const db = getDbInstance();
+ const db = getDbInstance() as unknown as DbLike;
db.prepare("DELETE FROM key_value WHERE namespace = ? AND key = ?").run(
"cliToolLastConfig",
toolId
@@ -80,11 +114,11 @@ export function deleteCliToolLastConfigured(toolId: string) {
* Only saves if no snapshot exists yet (first-time only).
* @returns true if saved, false if snapshot already exists.
*/
-export function saveCliToolInitialConfig(toolId: string, config: Record<string, any>): boolean {
+export function saveCliToolInitialConfig(toolId: string, config: JsonRecord): boolean {
if (isBuildPhase || isCloud) return false;
- const db = getDbInstance();
+ const db = getDbInstance() as unknown as DbLike;
// Only save if not already stored
- const existing: any = db
+ const existing = db
.prepare("SELECT value FROM key_value WHERE namespace = ? AND key = ?")
.get("cliToolInitialConfig", toolId);
if (existing) return false;
@@ -101,21 +135,23 @@ export function saveCliToolInitialConfig(toolId: string, config: Record<string,
* Get the initial config snapshot for a CLI tool.
* @returns Config object or null if no snapshot exists.
*/
-export function getCliToolInitialConfig(toolId: string): Record<string, any> | null {
+export function getCliToolInitialConfig(toolId: string): JsonRecord | null {
if (isBuildPhase || isCloud) return null;
- const db = getDbInstance();
- const row: any = db
+ const db = getDbInstance() as unknown as DbLike;
+ const row = db
.prepare("SELECT value FROM key_value WHERE namespace = ? AND key = ?")
.get("cliToolInitialConfig", toolId);
- return row ? JSON.parse(row.value) : null;
+ if (!row) return null;
+ const parsed = parseJsonValue((row as KeyValueRow).value);
+ return toRecord(parsed);
}
/**
* Delete the initial config snapshot for a CLI tool.
*/
-export function deleteCliToolInitialConfig(toolId: string) {
+export function deleteCliToolInitialConfig(toolId: string): void {
if (isBuildPhase || isCloud) return;
- const db = getDbInstance();
+ const db = getDbInstance() as unknown as DbLike;
db.prepare("DELETE FROM key_value WHERE namespace = ? AND key = ?").run(
"cliToolInitialConfig",
toolId
diff --git a/src/lib/db/core.ts b/src/lib/db/core.ts
index 459ff78932..4a86d91be7 100644
--- a/src/lib/db/core.ts
+++ b/src/lib/db/core.ts
@@ -10,6 +10,9 @@ import fs from "node:fs";
import { resolveDataDir, getLegacyDotDataDir } from "../dataPaths";
import { runMigrations } from "./migrationRunner";
+type SqliteDatabase = import("better-sqlite3").Database;
+type JsonRecord = Record<string, unknown>;
+
// ──────────────── Environment Detection ────────────────
export const isCloud = typeof globalThis.caches === "object" && globalThis.caches !== null;
@@ -114,6 +117,8 @@ const SCHEMA_SQL = `
name TEXT NOT NULL,
key TEXT NOT NULL UNIQUE,
machine_id TEXT,
+ allowed_models TEXT DEFAULT '[]',
+ no_log INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_ak_key ON api_keys(key);
@@ -243,27 +248,27 @@ const SCHEMA_SQL = `
// ──────────────── Column Mapping ────────────────
-export function toSnakeCase(str) {
+export function toSnakeCase(str: string): string {
return str.replace(/([A-Z])/g, "_$1").toLowerCase();
}
-export function toCamelCase(str) {
- return str.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
+export function toCamelCase(str: string): string {
+ return str.replace(/_([a-z])/g, (_: string, c: string) => c.toUpperCase());
}
-export function objToSnake(obj) {
+export function objToSnake(obj: unknown): unknown {
if (!obj || typeof obj !== "object") return obj;
- const result = {};
- for (const [k, v] of Object.entries(obj)) {
+ const result: JsonRecord = {};
+ for (const [k, v] of Object.entries(obj as JsonRecord)) {
result[toSnakeCase(k)] = v;
}
return result;
}
-export function rowToCamel(row) {
+export function rowToCamel(row: unknown): JsonRecord | null {
if (!row) return null;
- const result = {};
- for (const [k, v] of Object.entries(row)) {
+ const result: JsonRecord = {};
+ for (const [k, v] of Object.entries(row as JsonRecord)) {
const camelKey = toCamelCase(k);
if (camelKey === "isActive" || camelKey === "rateLimitProtection") {
result[camelKey] = v === 1 || v === true;
@@ -280,9 +285,9 @@ export function rowToCamel(row) {
return result;
}
-export function cleanNulls(obj) {
- const result = {};
- for (const [k, v] of Object.entries(obj)) {
+export function cleanNulls(obj: unknown): JsonRecord {
+ const result: JsonRecord = {};
+ for (const [k, v] of Object.entries((obj as JsonRecord) || {})) {
if (v !== null && v !== undefined) {
result[k] = v;
}
@@ -292,40 +297,50 @@ export function cleanNulls(obj) {
// ──────────────── Singleton DB Instance ────────────────
-let _db = null;
+let _db: SqliteDatabase | null = null;
-function ensureProviderConnectionsColumns(db) {
+function ensureProviderConnectionsColumns(db: SqliteDatabase) {
try {
- const columns = db.prepare("PRAGMA table_info(provider_connections)").all();
- const columnNames = new Set(columns.map((column) => column.name));
+ const columns = db.prepare("PRAGMA table_info(provider_connections)").all() as Array<{
+ name?: string;
+ }>;
+ const columnNames = new Set(columns.map((column) => String(column.name ?? "")));
if (!columnNames.has("rate_limit_protection")) {
db.exec(
"ALTER TABLE provider_connections ADD COLUMN rate_limit_protection INTEGER DEFAULT 0"
);
console.log("[DB] Added provider_connections.rate_limit_protection column");
}
- } catch (error) {
- console.warn("[DB] Failed to verify provider_connections schema:", error.message);
+ } catch (error: unknown) {
+ const message = error instanceof Error ? error.message : String(error);
+ console.warn("[DB] Failed to verify provider_connections schema:", message);
}
}
-export function getDbInstance() {
+export function getDbInstance(): SqliteDatabase {
if (_db) return _db;
if (isCloud || isBuildPhase) {
if (isBuildPhase) {
console.log("[DB] Build phase detected — using in-memory SQLite (read-only)");
}
- _db = new Database(":memory:");
- _db.pragma("journal_mode = WAL");
- _db.exec(SCHEMA_SQL);
- return _db;
+ const memoryDb = new Database(":memory:");
+ memoryDb.pragma("journal_mode = WAL");
+ memoryDb.exec(SCHEMA_SQL);
+ _db = memoryDb;
+ return memoryDb;
+ }
+
+ const sqliteFile = SQLITE_FILE;
+ if (!sqliteFile) {
+ throw new Error("SQLITE_FILE is unavailable for local mode");
}
+ const jsonDbFile = JSON_DB_FILE;
// Detect and handle old schema format — preserve data when possible (#146)
- if (fs.existsSync(SQLITE_FILE)) {
+ if (fs.existsSync(sqliteFile)) {
try {
- const probe = new Database(SQLITE_FILE, { readonly: true });
+ const probe = new Database(sqliteFile, { readonly: true });
const hasOldSchema = probe
.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='schema_migrations'")
.get();
@@ -337,7 +352,7 @@ export function getDbInstance() {
const count = probe.prepare("SELECT COUNT(*) as c FROM provider_connections").get() as
| { c: number }
| undefined;
- hasData = count && count.c > 0;
+ hasData = Boolean(count && count.c > 0);
} catch {
// Table might not exist at all — truly incompatible
}
@@ -349,26 +364,27 @@ export function getDbInstance() {
console.log(
`[DB] Old schema_migrations table found but data exists — preserving data (#146)`
);
- const fixDb = new Database(SQLITE_FILE);
+ const fixDb = new Database(sqliteFile);
try {
fixDb.exec("DROP TABLE IF EXISTS schema_migrations");
// Clean up WAL/SHM files that might be stale
fixDb.pragma("wal_checkpoint(TRUNCATE)");
- } catch (e) {
- console.warn("[DB] Could not clean up old schema table:", e.message);
+ } catch (e: unknown) {
+ const message = e instanceof Error ? e.message : String(e);
+ console.warn("[DB] Could not clean up old schema table:", message);
} finally {
fixDb.close();
}
} else {
// No data — safe to rename and start fresh
- const oldPath = SQLITE_FILE + ".old-schema";
+ const oldPath = sqliteFile + ".old-schema";
console.log(
`[DB] Old incompatible schema detected (empty) — renaming to ${path.basename(oldPath)}`
);
- fs.renameSync(SQLITE_FILE, oldPath);
+ fs.renameSync(sqliteFile, oldPath);
for (const ext of ["-wal", "-shm"]) {
try {
- if (fs.existsSync(SQLITE_FILE + ext)) fs.unlinkSync(SQLITE_FILE + ext);
+ if (fs.existsSync(sqliteFile + ext)) fs.unlinkSync(sqliteFile + ext);
} catch {
/* ok */
}
@@ -377,27 +393,28 @@ export function getDbInstance() {
} else {
probe.close();
}
- } catch (e) {
- console.warn("[DB] Could not probe existing DB, will create fresh:", e.message);
+ } catch (e: unknown) {
+ const message = e instanceof Error ? e.message : String(e);
+ console.warn("[DB] Could not probe existing DB, will create fresh:", message);
try {
- fs.unlinkSync(SQLITE_FILE);
+ fs.unlinkSync(sqliteFile);
} catch {
/* ok */
}
}
}
- _db = new Database(SQLITE_FILE);
- _db.pragma("journal_mode = WAL");
- _db.pragma("busy_timeout = 5000");
- _db.pragma("synchronous = NORMAL");
- _db.exec(SCHEMA_SQL);
- ensureProviderConnectionsColumns(_db);
+ const db = new Database(sqliteFile);
+ db.pragma("journal_mode = WAL");
+ db.pragma("busy_timeout = 5000");
+ db.pragma("synchronous = NORMAL");
+ db.exec(SCHEMA_SQL);
+ ensureProviderConnectionsColumns(db);
// ── Versioned Migrations ──
// Auto-seed 001 as applied (the inline SCHEMA_SQL already created these tables)
// then run any new migrations (002+)
- _db.exec(`
+ db.exec(`
CREATE TABLE IF NOT EXISTS _omniroute_migrations (
version TEXT PRIMARY KEY,
name TEXT NOT NULL,
@@ -406,21 +423,22 @@ export function getDbInstance() {
INSERT OR IGNORE INTO _omniroute_migrations (version, name)
VALUES ('001', 'initial_schema');
`);
- runMigrations(_db);
+ runMigrations(db);
// Auto-migrate from db.json if exists
- if (JSON_DB_FILE && fs.existsSync(JSON_DB_FILE)) {
- migrateFromJson(_db, JSON_DB_FILE);
+ if (jsonDbFile && fs.existsSync(jsonDbFile)) {
+ migrateFromJson(db, jsonDbFile);
}
// Store schema version
- const versionStmt = _db.prepare(
+ const versionStmt = db.prepare(
"INSERT OR REPLACE INTO db_meta (key, value) VALUES ('schema_version', '1')"
);
versionStmt.run();
- console.log(`[DB] SQLite database ready: ${SQLITE_FILE}`);
- return _db;
+ _db = db;
+ console.log(`[DB] SQLite database ready: ${sqliteFile}`);
+ return db;
}
/**
@@ -435,7 +453,7 @@ export function resetDbInstance() {
// ──────────────── JSON → SQLite Migration ────────────────
-function migrateFromJson(db, jsonPath) {
+function migrateFromJson(db: SqliteDatabase, jsonPath: string) {
try {
const raw = fs.readFileSync(jsonPath, "utf-8");
const data = JSON.parse(raw);
@@ -584,8 +602,8 @@ function migrateFromJson(db, jsonPath) {
// 5. API Keys
const insertKey = db.prepare(`
- INSERT OR REPLACE INTO api_keys (id, name, key, machine_id, created_at)
- VALUES (@id, @name, @key, @machineId, @createdAt)
+ INSERT OR REPLACE INTO api_keys (id, name, key, machine_id, allowed_models, no_log, created_at)
+ VALUES (@id, @name, @key, @machineId, @allowedModels, @noLog, @createdAt)
`);
for (const apiKey of data.apiKeys || []) {
insertKey.run({
@@ -593,6 +611,8 @@ function migrateFromJson(db, jsonPath) {
name: apiKey.name,
key: apiKey.key,
machineId: apiKey.machineId || null,
+ allowedModels: JSON.stringify(apiKey.allowedModels || []),
+ noLog: apiKey.noLog ? 1 : 0,
createdAt: apiKey.createdAt || new Date().toISOString(),
});
}
diff --git a/src/lib/tokenHealthCheck.ts b/src/lib/tokenHealthCheck.ts
index bbe933ada5..a85add7238 100644
--- a/src/lib/tokenHealthCheck.ts
+++ b/src/lib/tokenHealthCheck.ts
@@ -21,6 +21,17 @@ import {
const TICK_MS = 60 * 1000; // sweep interval: every 60 seconds
const DEFAULT_HEALTH_CHECK_INTERVAL_MIN = 60; // default per-connection interval
const LOG_PREFIX = "[HealthCheck]";
+const TRUE_ENV_VALUES = new Set(["1", "true", "yes", "on"]);
+
+function isEnvFlagEnabled(name: string): boolean {
+ const value = process.env[name];
+ if (!value) return false;
+ return TRUE_ENV_VALUES.has(value.trim().toLowerCase());
+}
+
+function isHealthCheckDisabled(): boolean {
+ return isEnvFlagEnabled("OMNIROUTE_DISABLE_TOKEN_HEALTHCHECK") || process.env.NODE_ENV === "test";
+}
// ── Logging helper ───────────────────────────────────────────────────────────
let cachedHideLogs: boolean | null = null;
@@ -29,6 +40,10 @@ let pendingHideLogs: Promise<boolean> | null = null;
const CACHE_TTL = 30_000; // Cache settings for 30 seconds
async function shouldHideLogs(): Promise<boolean> {
+ if (isEnvFlagEnabled("OMNIROUTE_HIDE_HEALTHCHECK_LOGS") || process.env.NODE_ENV === "test") {
+ return true;
+ }
+
const now = Date.now();
// Return cached value if valid
@@ -92,7 +107,7 @@ let intervalHandle = null;
* Start the health-check scheduler (idempotent).
*/
export function initTokenHealthCheck() {
- if (initialized) return;
+ if (initialized || isHealthCheckDisabled()) return;
initialized = true;
log(`${LOG_PREFIX} Starting proactive token health-check (tick every ${TICK_MS / 1000}s)`);