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: Implement API authentication middleware, mask sensitive API keys, integrate prompt injection guard, and enhance onboarding error handling.

diegosouzapw16b72970d721
diff --git a/open-sse/tsconfig.json b/open-sse/tsconfig.json
index bffe1dbf28..e619d74e7e 100644
--- a/open-sse/tsconfig.json
+++ b/open-sse/tsconfig.json
@@ -6,6 +6,7 @@
"allowJs": true,
"checkJs": true,
"noEmit": true,
+ "allowImportingTsExtensions": true,
"skipLibCheck": true,
"esModuleInterop": true,
"strict": false,
@@ -18,8 +19,5 @@
"@omniroute/open-sse/*": ["./open-sse/*"]
}
},
- "include": [
- "**/*.ts",
- "**/*.js"
- ]
+ "include": ["**/*.ts", "**/*.js"]
}
diff --git a/src/app/(dashboard)/dashboard/onboarding/page.tsx b/src/app/(dashboard)/dashboard/onboarding/page.tsx
index d0e8751150..a782f63964 100644
--- a/src/app/(dashboard)/dashboard/onboarding/page.tsx
+++ b/src/app/(dashboard)/dashboard/onboarding/page.tsx
@@ -71,27 +71,35 @@ export default function OnboardingWizard() {
if (step > 0) setStep(step - 1);
};
+ const [errorMessage, setErrorMessage] = useState("");
+
const handleSetPassword = async () => {
if (skipSecurity) {
handleNext();
return;
}
if (password !== confirmPassword) return;
+ setErrorMessage("");
try {
- await fetch("/api/settings/require-login", {
+ const res = await fetch("/api/settings/require-login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ requireLogin: true, password }),
});
+ if (!res.ok) {
+ const data = await res.json().catch(() => ({}));
+ setErrorMessage(data.error || "Failed to set password. Try again.");
+ return;
+ }
handleNext();
} catch {
- // Fallback: skip
- handleNext();
+ setErrorMessage("Connection error. Please try again.");
}
};
const handleAddProvider = async () => {
if (!selectedProvider || !providerKey) return;
+ setErrorMessage("");
try {
const provider = COMMON_PROVIDERS.find((p) => p.id === selectedProvider);
const defaultUrls = {
@@ -102,7 +110,7 @@ export default function OnboardingWizard() {
groq: "https://api.groq.com/openai",
mistral: "https://api.mistral.ai",
};
- await fetch("/api/providers", {
+ const res = await fetch("/api/providers", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
@@ -113,9 +121,14 @@ export default function OnboardingWizard() {
isActive: true,
}),
});
+ if (!res.ok) {
+ const data = await res.json().catch(() => ({}));
+ setErrorMessage(data.error || "Failed to add provider. Try again.");
+ return;
+ }
handleNext();
} catch {
- handleNext();
+ setErrorMessage("Connection error. Please try again.");
}
};
diff --git a/src/app/api/auth/login/route.ts b/src/app/api/auth/login/route.ts
index dd2b2616d9..381ea1a226 100644
--- a/src/app/api/auth/login/route.ts
+++ b/src/app/api/auth/login/route.ts
@@ -5,12 +5,22 @@ import { SignJWT } from "jose";
import { cookies } from "next/headers";
import { loginSchema, validateBody } from "@/shared/validation/schemas";
-const SECRET = new TextEncoder().encode(
- process.env.JWT_SECRET || "omniroute-default-secret-change-me"
-);
+// SECURITY: No hardcoded fallback — JWT_SECRET must be configured.
+if (!process.env.JWT_SECRET) {
+ console.error("[SECURITY] FATAL: JWT_SECRET is not set. Login authentication is disabled.");
+}
+const SECRET = new TextEncoder().encode(process.env.JWT_SECRET || "");
export async function POST(request) {
try {
+ // Fail-fast if JWT_SECRET is not configured
+ if (!process.env.JWT_SECRET) {
+ return NextResponse.json(
+ { error: "Server misconfigured: JWT_SECRET not set. Contact administrator." },
+ { status: 500 }
+ );
+ }
+
const rawBody = await request.json();
// Zod validation
@@ -21,15 +31,20 @@ export async function POST(request) {
const { password } = validation.data;
const settings = await getSettings();
- // Default password is '123456' if not set
const storedHash = settings.password;
let isValid = false;
if (storedHash) {
isValid = await bcrypt.compare(password, storedHash);
} else {
- // Use env var or default
- const initialPassword = process.env.INITIAL_PASSWORD || "123456";
+ // SECURITY: No default password — must be set via env or onboarding
+ if (!process.env.INITIAL_PASSWORD) {
+ return NextResponse.json(
+ { error: "No password configured. Complete onboarding first.", needsSetup: true },
+ { status: 403 }
+ );
+ }
+ const initialPassword = process.env.INITIAL_PASSWORD;
isValid = password === initialPassword;
}
diff --git a/src/app/api/cloud/auth/route.ts b/src/app/api/cloud/auth/route.ts
index 709c65b424..9606c9dac7 100644
--- a/src/app/api/cloud/auth/route.ts
+++ b/src/app/api/cloud/auth/route.ts
@@ -20,13 +20,21 @@ export async function POST(request) {
// Get active provider connections
const connections = await getProviderConnections({ isActive: true });
- // Map connections
+ // Helper to mask sensitive values
+ function maskSecret(value: string | null | undefined): string | null {
+ if (!value) return null;
+ if (value.length <= 8) return "****";
+ return value.slice(0, 4) + "****" + value.slice(-4);
+ }
+
+ // Map connections — NEVER expose raw credentials
const mappedConnections = connections.map((conn) => ({
provider: conn.provider,
authType: conn.authType,
- apiKey: conn.apiKey || null,
- accessToken: conn.accessToken || null,
- refreshToken: conn.refreshToken || null,
+ hasApiKey: !!conn.apiKey,
+ hasAccessToken: !!conn.accessToken,
+ hasRefreshToken: !!conn.refreshToken,
+ maskedApiKey: maskSecret(conn.apiKey),
projectId: conn.projectId || null,
expiresAt: conn.expiresAt,
priority: conn.priority,
diff --git a/src/app/api/db-backups/exportAll/route.ts b/src/app/api/db-backups/exportAll/route.ts
index dc9b8f636e..7404938cbf 100644
--- a/src/app/api/db-backups/exportAll/route.ts
+++ b/src/app/api/db-backups/exportAll/route.ts
@@ -60,7 +60,7 @@ export async function GET() {
try {
const rows = db
.prepare(
- "SELECT id, provider_id, display_name, auth_type, is_enabled, account_email, created_at FROM provider_connections"
+ "SELECT id, provider, name, auth_type, is_active, email, created_at FROM provider_connections"
)
.all();
providers.push(...rows);
@@ -73,7 +73,9 @@ export async function GET() {
const apiKeys: unknown[] = [];
try {
const rows = db
- .prepare("SELECT id, name, prefix, created_at, is_active FROM api_keys")
+ .prepare(
+ "SELECT id, name, substr(key, 1, 8) as prefix, machine_id, created_at FROM api_keys"
+ )
.all();
apiKeys.push(...rows);
} catch {
diff --git a/src/app/api/keys/route.ts b/src/app/api/keys/route.ts
index 8bff3d51ee..2ac585d6f8 100644
--- a/src/app/api/keys/route.ts
+++ b/src/app/api/keys/route.ts
@@ -8,7 +8,12 @@ import { createKeySchema, validateBody } from "@/shared/validation/schemas";
export async function GET() {
try {
const keys = await getApiKeys();
- return NextResponse.json({ keys });
+ // Mask key values — users should never see full keys after creation
+ const maskedKeys = keys.map((k) => ({
+ ...k,
+ key: k.key ? k.key.slice(0, 8) + "****" + k.key.slice(-4) : null,
+ }));
+ return NextResponse.json({ keys: maskedKeys });
} catch (error) {
console.log("Error fetching keys:", error);
return NextResponse.json({ error: "Failed to fetch keys" }, { status: 500 });
diff --git a/src/app/api/settings/require-login/route.ts b/src/app/api/settings/require-login/route.ts
index 1e1a14d680..abd62fe0d8 100644
--- a/src/app/api/settings/require-login/route.ts
+++ b/src/app/api/settings/require-login/route.ts
@@ -1,5 +1,6 @@
import { NextResponse } from "next/server";
-import { getSettings } from "@/lib/localDb";
+import { getSettings, updateSettings } from "@/lib/localDb";
+import bcrypt from "bcryptjs";
export async function GET() {
try {
@@ -10,3 +11,43 @@ export async function GET() {
return NextResponse.json({ requireLogin: true }, { status: 200 });
}
}
+
+/**
+ * POST /api/settings/require-login — Set password and/or toggle requireLogin.
+ * Used by the onboarding wizard security step.
+ */
+export async function POST(request: Request) {
+ try {
+ const body = await request.json();
+ const { requireLogin, password } = body;
+
+ const updates: Record<string, any> = {};
+
+ if (typeof requireLogin === "boolean") {
+ updates.requireLogin = requireLogin;
+ }
+
+ if (password && typeof password === "string" && password.length >= 4) {
+ const hashedPassword = await bcrypt.hash(password, 12);
+ updates.password = hashedPassword;
+ } else if (password) {
+ return NextResponse.json(
+ { error: "Password must be at least 4 characters" },
+ { status: 400 }
+ );
+ }
+
+ if (Object.keys(updates).length === 0) {
+ return NextResponse.json({ error: "No valid fields to update" }, { status: 400 });
+ }
+
+ await updateSettings(updates);
+ return NextResponse.json({ success: true });
+ } catch (error) {
+ console.error("[API] Error updating require-login settings:", error);
+ return NextResponse.json(
+ { error: error instanceof Error ? error.message : "Failed to update settings" },
+ { status: 500 }
+ );
+ }
+}
diff --git a/src/app/api/v1/chat/completions/route.ts b/src/app/api/v1/chat/completions/route.ts
index 26cfced656..1ee1facaf5 100644
--- a/src/app/api/v1/chat/completions/route.ts
+++ b/src/app/api/v1/chat/completions/route.ts
@@ -1,9 +1,13 @@
import { callCloudWithMachineId } from "@/shared/utils/cloud";
import { handleChat } from "@/sse/handlers/chat";
import { initTranslators } from "@omniroute/open-sse/translator/index.ts";
+import { createInjectionGuard } from "@/middleware/promptInjectionGuard";
let initPromise = null;
+// Singleton injection guard instance
+const injectionGuard = createInjectionGuard();
+
/**
* Initialize translators once (Promise-based singleton — no race condition)
*/
@@ -30,8 +34,31 @@ export async function OPTIONS() {
}
export async function POST(request) {
- // Fallback to local handling
await ensureInitialized();
+ // Prompt injection guard — inspect body before forwarding
+ try {
+ const cloned = request.clone();
+ const body = await cloned.json().catch(() => null);
+ if (body) {
+ const { blocked, result } = injectionGuard(body);
+ if (blocked) {
+ return new Response(
+ JSON.stringify({
+ error: {
+ message: "Request blocked: potential prompt injection detected",
+ type: "injection_detected",
+ code: "SECURITY_001",
+ detections: result.detections.length,
+ },
+ }),
+ { status: 400, headers: { "Content-Type": "application/json" } }
+ );
+ }
+ }
+ } catch {
+ // Don't block on guard errors — fail open
+ }
+
return await handleChat(request);
}
diff --git a/src/middleware/promptInjectionGuard.ts b/src/middleware/promptInjectionGuard.ts
index 17ca839931..f4dbaf1a85 100644
--- a/src/middleware/promptInjectionGuard.ts
+++ b/src/middleware/promptInjectionGuard.ts
@@ -38,7 +38,8 @@ export function createInjectionGuard(options: any = {}) {
const result: any = sanitizeRequest(body, logger);
- if (!result.flagged) {
+ // Check if any detections were found (sanitizeRequest returns .detections, NOT .flagged)
+ if (result.detections.length === 0 && result.piiDetections.length === 0) {
return { blocked: false, result };
}
diff --git a/src/proxy.ts b/src/proxy.ts
index e6b4a2b685..2ecabc7f52 100644
--- a/src/proxy.ts
+++ b/src/proxy.ts
@@ -2,6 +2,7 @@ import { NextResponse } from "next/server";
import { jwtVerify } from "jose";
import { generateRequestId } from "./shared/utils/requestId";
import { getSettings } from "./lib/localDb";
+import { isPublicRoute, verifyAuth, isAuthRequired } from "./shared/utils/apiAuth";
// FASE-01: Fail-fast — no hardcoded fallback. Server must have JWT_SECRET configured.
if (!process.env.JWT_SECRET) {
@@ -18,7 +19,36 @@ export async function proxy(request) {
const response = NextResponse.next();
response.headers.set("X-Request-Id", requestId);
- // Protect all dashboard routes (except onboarding)
+ // ──────────────── Protect Management API Routes ────────────────
+ if (pathname.startsWith("/api/") && !pathname.startsWith("/api/v1/")) {
+ // Allow public routes (login, logout, health, etc.)
+ if (isPublicRoute(pathname)) {
+ return response;
+ }
+
+ // Check if auth is required at all (respects requireLogin setting)
+ const authRequired = await isAuthRequired();
+ if (!authRequired) {
+ return response;
+ }
+
+ // Verify authentication (JWT cookie or Bearer API key)
+ const authError = await verifyAuth(request);
+ if (authError) {
+ return NextResponse.json(
+ {
+ error: {
+ code: "AUTH_001",
+ message: authError,
+ correlation_id: requestId,
+ },
+ },
+ { status: 401 }
+ );
+ }
+ }
+
+ // ──────────────── Protect Dashboard Routes ────────────────
if (pathname.startsWith("/dashboard")) {
// Always allow onboarding — it has its own setupComplete guard
if (pathname.startsWith("/dashboard/onboarding")) {
@@ -74,5 +104,5 @@ export async function proxy(request) {
}
export const config = {
- matcher: ["/", "/dashboard/:path*"],
+ matcher: ["/", "/dashboard/:path*", "/api/:path*"],
};
diff --git a/src/shared/utils/apiAuth.ts b/src/shared/utils/apiAuth.ts
new file mode 100644
index 0000000000..71e99b75c4
--- /dev/null
+++ b/src/shared/utils/apiAuth.ts
@@ -0,0 +1,102 @@
+/**
+ * API Authentication Guard — Shared utility for protecting management API routes.
+ *
+ * Provides dual-mode auth: JWT cookie (dashboard session) or Bearer API key.
+ * Used by the middleware (proxy.ts) to guard /api/* management routes.
+ *
+ * @module shared/utils/apiAuth
+ */
+
+import { jwtVerify } from "jose";
+import { getSettings } from "@/lib/localDb";
+
+// ──────────────── Public Routes (No Auth Required) ────────────────
+
+/**
+ * Routes that are ALWAYS accessible without authentication.
+ * Pattern matching: startsWith check against the pathname.
+ */
+const PUBLIC_API_ROUTES = [
+ // Auth flow — must be accessible to unauthenticated users
+ "/api/auth/login",
+ "/api/auth/logout",
+
+ // Settings check — used by login page / onboarding
+ "/api/settings/require-login",
+
+ // Init — first-run setup
+ "/api/init",
+
+ // Health monitoring — probes must work without auth
+ "/api/monitoring/health",
+
+ // LLM proxy routes — use their own API key auth in the SSE layer
+ "/api/v1/",
+
+ // Cloud routes — use Bearer API key auth internally
+ "/api/cloud/",
+
+ // OAuth callback routes — provider redirects back here
+ "/api/oauth/",
+];
+
+// ──────────────── Auth Verification ────────────────
+
+/**
+ * Check if a request is authenticated via JWT cookie or Bearer API key.
+ *
+ * @returns null if authenticated, error message string if not
+ */
+export async function verifyAuth(request: any): Promise<string | null> {
+ // 1. Check JWT cookie (dashboard session)
+ const token = request.cookies.get("auth_token")?.value;
+ if (token && process.env.JWT_SECRET) {
+ try {
+ const secret = new TextEncoder().encode(process.env.JWT_SECRET);
+ await jwtVerify(token, secret);
+ return null; // ✔ Authenticated via cookie
+ } catch {
+ // Invalid/expired token — fall through to API key check
+ }
+ }
+
+ // 2. Check Bearer API key
+ const authHeader = request.headers.get("authorization");
+ if (authHeader?.startsWith("Bearer ")) {
+ const apiKey = authHeader.slice(7);
+ try {
+ // Dynamic import to avoid circular dependencies during build
+ const { validateApiKey } = await import("@/lib/db/apiKeys");
+ const isValid = await validateApiKey(apiKey);
+ if (isValid) return null; // ✔ Authenticated via API key
+ } catch {
+ // DB not ready or import error — deny access
+ }
+ }
+
+ return "Authentication required";
+}
+
+/**
+ * Check if a route is in the public (no-auth) allowlist.
+ */
+export function isPublicRoute(pathname: string): boolean {
+ return PUBLIC_API_ROUTES.some((route) => pathname.startsWith(route));
+}
+
+/**
+ * Check if authentication is required based on settings.
+ * If requireLogin is false AND no password is set, auth is skipped.
+ */
+export async function isAuthRequired(): Promise<boolean> {
+ try {
+ const settings = await getSettings();
+ if (settings.requireLogin === false) return false;
+ // If no password set and no env override, don't require auth (fresh install)
+ if (!settings.password && !process.env.INITIAL_PASSWORD) return false;
+ return true;
+ } catch {
+ // On error, require auth (secure by default)
+ return true;
+ }
+}