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(auth): enforce dashboard sessions for management routes

diegosouzapw8cf78ddf0050
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index 93e916306c..941e8a4eba 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -750,6 +750,70 @@ paths:
"200":
description: Updated settings
+ /api/settings/payload-rules:
+ get:
+ tags: [Settings]
+ summary: Get payload rules configuration
+ description: |
+ Returns the current payload rules used to mutate outgoing request payloads before they
+ are sent upstream.
+
+ Requires a dashboard management session cookie when management auth is enabled.
+ security:
+ - ManagementSessionAuth: []
+ responses:
+ "200":
+ description: Current payload rules configuration
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/PayloadRulesConfig"
+ "401":
+ $ref: "#/components/responses/ManagementAuthenticationRequired"
+ "403":
+ $ref: "#/components/responses/ManagementInvalidToken"
+ "500":
+ description: Failed to read payload rules configuration
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiErrorResponse"
+ put:
+ tags: [Settings]
+ summary: Update payload rules configuration
+ description: |
+ Persists and hot reloads payload rules. The legacy input field `default-raw` is accepted
+ on writes and normalized to `defaultRaw` in responses/runtime state.
+
+ Requires a dashboard management session cookie when management auth is enabled.
+ security:
+ - ManagementSessionAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/UpdatePayloadRulesRequest"
+ responses:
+ "200":
+ description: Updated payload rules configuration
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/PayloadRulesConfig"
+ "400":
+ $ref: "#/components/responses/ValidationError"
+ "401":
+ $ref: "#/components/responses/ManagementAuthenticationRequired"
+ "403":
+ $ref: "#/components/responses/ManagementInvalidToken"
+ "500":
+ description: Failed to update payload rules configuration
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiErrorResponse"
+
/api/settings/combo-defaults:
get:
tags: [Settings]
@@ -1997,6 +2061,11 @@ components:
type: http
scheme: bearer
description: API key obtained from the OmniRoute dashboard
+ ManagementSessionAuth:
+ type: apiKey
+ in: cookie
+ name: auth_token
+ description: Dashboard management session cookie for protected management routes
parameters:
ResourceId:
@@ -2017,8 +2086,171 @@ components:
error:
type: string
example: Unauthorized
+ ManagementAuthenticationRequired:
+ description: Authentication required for management routes
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiErrorResponse"
+ example:
+ error:
+ message: Authentication required
+ type: invalid_request
+ requestId: 3f9f6f5a-509a-4b35-b0a7-2d2d99d73a01
+ ManagementInvalidToken:
+ description: Bearer tokens are not accepted for management routes
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ApiErrorResponse"
+ example:
+ error:
+ message: Invalid management token
+ type: invalid_request
+ requestId: 1b6a6ff8-d60c-4900-8d0a-25f81749f0a3
+ ValidationError:
+ description: Request body failed validation
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ValidationErrorResponse"
schemas:
+ ApiErrorResponse:
+ type: object
+ properties:
+ error:
+ type: object
+ properties:
+ message:
+ type: string
+ type:
+ type: string
+ details:
+ description: Optional additional error details
+ requestId:
+ type: string
+ format: uuid
+
+ ValidationErrorResponse:
+ type: object
+ properties:
+ error:
+ type: object
+ required: [message, details]
+ properties:
+ message:
+ type: string
+ example: Invalid request
+ details:
+ type: array
+ items:
+ type: object
+ required: [field, message]
+ properties:
+ field:
+ type: string
+ message:
+ type: string
+
+ PayloadRuleModelSpec:
+ type: object
+ additionalProperties: false
+ required: [name]
+ properties:
+ name:
+ type: string
+ minLength: 1
+ protocol:
+ type: string
+ minLength: 1
+
+ PayloadMutationRule:
+ type: object
+ additionalProperties: false
+ required: [models, params]
+ properties:
+ models:
+ type: array
+ minItems: 1
+ items:
+ $ref: "#/components/schemas/PayloadRuleModelSpec"
+ params:
+ type: object
+ minProperties: 1
+ additionalProperties: true
+
+ PayloadFilterRule:
+ type: object
+ additionalProperties: false
+ required: [models, params]
+ properties:
+ models:
+ type: array
+ minItems: 1
+ items:
+ $ref: "#/components/schemas/PayloadRuleModelSpec"
+ params:
+ type: array
+ minItems: 1
+ items:
+ type: string
+ minLength: 1
+
+ PayloadRulesConfig:
+ type: object
+ additionalProperties: false
+ required: [default, override, filter, defaultRaw]
+ properties:
+ default:
+ type: array
+ items:
+ $ref: "#/components/schemas/PayloadMutationRule"
+ override:
+ type: array
+ items:
+ $ref: "#/components/schemas/PayloadMutationRule"
+ filter:
+ type: array
+ items:
+ $ref: "#/components/schemas/PayloadFilterRule"
+ defaultRaw:
+ type: array
+ items:
+ $ref: "#/components/schemas/PayloadMutationRule"
+
+ UpdatePayloadRulesRequest:
+ type: object
+ additionalProperties: false
+ description: At least one payload-rules section must be present in the request body.
+ properties:
+ default:
+ type: array
+ items:
+ $ref: "#/components/schemas/PayloadMutationRule"
+ override:
+ type: array
+ items:
+ $ref: "#/components/schemas/PayloadMutationRule"
+ filter:
+ type: array
+ items:
+ $ref: "#/components/schemas/PayloadFilterRule"
+ defaultRaw:
+ type: array
+ items:
+ $ref: "#/components/schemas/PayloadMutationRule"
+ default-raw:
+ type: array
+ items:
+ $ref: "#/components/schemas/PayloadMutationRule"
+ anyOf:
+ - required: [default]
+ - required: [override]
+ - required: [filter]
+ - required: [defaultRaw]
+ - required: [default-raw]
+
ChatCompletionRequest:
type: object
required: [model, messages]
diff --git a/scripts/build-next-isolated.mjs b/scripts/build-next-isolated.mjs
index 52fa1dcaeb..4bfa6b744d 100644
--- a/scripts/build-next-isolated.mjs
+++ b/scripts/build-next-isolated.mjs
@@ -15,18 +15,26 @@ import { pathToFileURL } from "node:url";
const projectRoot = process.cwd();
const backupRoot = path.join(os.tmpdir(), `omniroute-build-isolated-${process.pid}-${Date.now()}`);
-const transientBuildPaths = [
- {
- label: "legacy app snapshot",
- sourcePath: path.join(projectRoot, "app"),
- backupPath: path.join(backupRoot, "app"),
- },
- {
- label: "task planning workspace",
- sourcePath: path.join(projectRoot, "_tasks"),
- backupPath: path.join(backupRoot, "_tasks"),
- },
-];
+
+export function getTransientBuildPaths(rootDir = projectRoot, env = process.env) {
+ const paths = [
+ {
+ label: "legacy app snapshot",
+ sourcePath: path.join(rootDir, "app"),
+ backupPath: path.join(backupRoot, "app"),
+ },
+ ];
+
+ if (env.OMNIROUTE_BUILD_MOVE_TASKS === "1") {
+ paths.push({
+ label: "task planning workspace",
+ sourcePath: path.join(rootDir, "_tasks"),
+ backupPath: path.join(backupRoot, "_tasks"),
+ });
+ }
+
+ return paths;
+}
async function exists(targetPath) {
try {
@@ -38,7 +46,8 @@ async function exists(targetPath) {
}
export async function movePath(sourcePath, destinationPath, fsImpl = fs) {
- await fsImpl.mkdir(path.dirname(destinationPath), { recursive: true });
+ const mkdir = typeof fsImpl.mkdir === "function" ? fsImpl.mkdir.bind(fsImpl) : fs.mkdir.bind(fs);
+ await mkdir(path.dirname(destinationPath), { recursive: true });
try {
await fsImpl.rename(sourcePath, destinationPath);
@@ -95,8 +104,22 @@ export function resolveNextBuildEnv(baseEnv = process.env) {
};
}
+export async function pruneStandaloneArtifacts(rootDir = projectRoot, fsImpl = fs) {
+ const standaloneRoot = path.join(rootDir, ".next", "standalone");
+ const pruneTargets = [path.join(standaloneRoot, "_tasks")];
+
+ for (const targetPath of pruneTargets) {
+ if (!(await exists(targetPath))) continue;
+ await fsImpl.rm(targetPath, { recursive: true, force: true });
+ console.log(
+ `[build-next-isolated] Pruned standalone artifact: ${path.relative(rootDir, targetPath)}`
+ );
+ }
+}
+
export async function main() {
const movedPaths = [];
+ const transientBuildPaths = getTransientBuildPaths();
try {
for (const entry of transientBuildPaths) {
@@ -122,6 +145,15 @@ export async function main() {
} catch (copyErr) {
console.warn("[build-next-isolated] Non-fatal error copying static assets:", copyErr);
}
+
+ try {
+ await pruneStandaloneArtifacts(projectRoot);
+ } catch (pruneErr) {
+ console.warn(
+ "[build-next-isolated] Non-fatal error pruning standalone artifacts:",
+ pruneErr
+ );
+ }
}
process.exitCode = result.code;
} catch (error) {
diff --git a/src/app/(dashboard)/dashboard/agents/page.tsx b/src/app/(dashboard)/dashboard/agents/page.tsx
index 85354278cf..5714e2b250 100644
--- a/src/app/(dashboard)/dashboard/agents/page.tsx
+++ b/src/app/(dashboard)/dashboard/agents/page.tsx
@@ -5,7 +5,7 @@ import Link from "next/link";
import { Card, Button, Input } from "@/shared/components";
import ProviderIcon from "@/shared/components/ProviderIcon";
import { useTranslations } from "next-intl";
-import { AI_PROVIDERS } from "@/shared/constants/config";
+import { AI_PROVIDERS } from "@/shared/constants/providers";
import { CLI_COMPAT_PROVIDER_IDS } from "@/shared/constants/cliCompatProviders";
interface AgentInfo {
diff --git a/src/app/(dashboard)/dashboard/providers/[id]/page.tsx b/src/app/(dashboard)/dashboard/providers/[id]/page.tsx
index 7d839277e0..55056e3fbb 100644
--- a/src/app/(dashboard)/dashboard/providers/[id]/page.tsx
+++ b/src/app/(dashboard)/dashboard/providers/[id]/page.tsx
@@ -23,9 +23,6 @@ import {
ProxyConfigModal,
} from "@/shared/components";
import {
- FREE_PROVIDERS,
- OAUTH_PROVIDERS,
- APIKEY_PROVIDERS,
getProviderAlias,
isOpenAICompatibleProvider,
isAnthropicCompatibleProvider,
@@ -52,6 +49,7 @@ import { maskEmail, pickMaskedDisplayValue, pickDisplayValue } from "@/shared/ut
import useEmailPrivacyStore from "@/store/emailPrivacyStore";
import EmailPrivacyToggle from "@/shared/components/EmailPrivacyToggle";
import { getCodexRequestDefaults as _getCodexRequestDefaults } from "@/lib/providers/requestDefaults";
+import { resolveDashboardProviderInfo } from "../providerPageUtils";
type CompatByProtocolMap = Partial<
Record<
@@ -990,35 +988,16 @@ export default function ProviderDetailPage() {
const isCompatible = isOpenAICompatible || isAnthropicCompatible || isCcCompatible;
const isAnthropicProtocolCompatible = isAnthropicCompatible || isCcCompatible;
- const providerInfo = providerNode
- ? {
- id: providerNode.id,
- name:
- providerNode.name ||
- (isCcCompatible
- ? CC_COMPATIBLE_LABEL
- : providerNode.type === "anthropic-compatible"
- ? t("anthropicCompatibleName")
- : t("openaiCompatibleName")),
- color: isCcCompatible
- ? "#B45309"
- : providerNode.type === "anthropic-compatible"
- ? "#D97757"
- : "#10A37F",
- textIcon: isCcCompatible
- ? "CC"
- : providerNode.type === "anthropic-compatible"
- ? "AC"
- : "OC",
- apiType: providerNode.apiType,
- baseUrl: providerNode.baseUrl,
- type: providerNode.type,
- }
- : (FREE_PROVIDERS as any)[providerId] ||
- (OAUTH_PROVIDERS as any)[providerId] ||
- (APIKEY_PROVIDERS as any)[providerId];
+ const providerInfo = resolveDashboardProviderInfo(providerId, {
+ providerNode,
+ compatibleLabels: {
+ ccCompatibleName: CC_COMPATIBLE_LABEL,
+ anthropicCompatibleName: t("anthropicCompatibleName"),
+ openAiCompatibleName: t("openaiCompatibleName"),
+ },
+ });
const providerSupportsOAuth =
- !!(FREE_PROVIDERS as any)[providerId] || !!(OAUTH_PROVIDERS as any)[providerId];
+ providerInfo?.toggleAuthType === "oauth" || providerInfo?.toggleAuthType === "free";
const providerSupportsPat = supportsApiKeyOnFreeProvider(providerId);
const isOAuth = providerSupportsOAuth && !providerSupportsPat;
const registryModels = getModelsByProviderId(providerId);
@@ -1052,6 +1031,7 @@ export default function ProviderDetailPage() {
const providerAlias = getProviderAlias(providerId);
const isManagedAvailableModelsProvider = isCompatible || providerId === "openrouter";
const isSearchProvider = providerId.endsWith("-search");
+ const isUpstreamProxyProvider = providerInfo?.category === "upstream-proxy";
const compatibleSupportsModelImport = compatibleProviderSupportsModelImport(providerId);
const providerStorageAlias = isCompatible ? providerId : providerAlias;
@@ -2658,294 +2638,341 @@ export default function ProviderDetailPage() {
)}
{/* Connections */}
- <Card>
- <div className="flex items-center justify-between mb-4">
- <div className="flex items-center gap-3">
- <h2 className="text-lg font-semibold">{t("connections")}</h2>
- {/* Provider-level proxy indicator/button */}
- <button
- onClick={() =>
- setProxyTarget({
- level: "provider",
- id: providerId,
- label: providerInfo?.name || providerId,
- })
- }
- className={`inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium transition-all ${
- proxyConfig?.providers?.[providerId]
- ? "bg-amber-500/15 text-amber-500 hover:bg-amber-500/25"
- : "bg-black/[0.03] dark:bg-white/[0.03] text-text-muted/50 hover:text-text-muted hover:bg-black/[0.06] dark:hover:bg-white/[0.06]"
- }`}
- title={
- proxyConfig?.providers?.[providerId]
- ? t("providerProxyTitleConfigured", {
- host: proxyConfig.providers[providerId].host || t("configured"),
- })
- : t("providerProxyConfigureHint")
- }
- >
- <span className="material-symbols-outlined text-[14px]">vpn_lock</span>
- {proxyConfig?.providers?.[providerId]
- ? proxyConfig.providers[providerId].host || t("providerProxy")
- : t("providerProxy")}
- </button>
- </div>
- {connections.length > 1 && (
- <button
- onClick={handleBatchTestAll}
- disabled={batchTesting || !!retestingId}
- className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium border transition-colors ${
- batchTesting
- ? "bg-primary/20 border-primary/40 text-primary animate-pulse"
- : "bg-bg-subtle border-border text-text-muted hover:text-text-primary hover:border-primary/40"
- }`}
- title={t("testAll")}
- aria-label={t("testAll")}
- >
- <span className="material-symbols-outlined text-[14px]">
- {batchTesting ? "sync" : "play_arrow"}
- </span>
- {batchTesting ? t("testing") : t("testAll")}
- </button>
- )}
- {!isCompatible ? (
- <div className="flex items-center gap-2">
- <Button size="sm" icon="add" onClick={openPrimaryAddFlow}>
- {providerSupportsPat ? "Add PAT" : t("add")}
- </Button>
- {providerId === "qoder" && (
- <Button size="sm" variant="secondary" onClick={() => setShowOAuthModal(true)}>
- Experimental OAuth
- </Button>
- )}
- </div>
- ) : (
- connections.length === 0 && (
- <Button size="sm" icon="add" onClick={() => setShowAddApiKeyModal(true)}>
- {t("add")}
- </Button>
- )
- )}
- </div>
-
- {connections.length === 0 ? (
- <div className="text-center py-12">
- <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-primary/10 text-primary mb-4">
- <span className="material-symbols-outlined text-[32px]">
- {isOAuth ? "lock" : "key"}
- </span>
+ {!isUpstreamProxyProvider && (
+ <Card>
+ <div className="flex items-center justify-between mb-4">
+ <div className="flex items-center gap-3">
+ <h2 className="text-lg font-semibold">{t("connections")}</h2>
+ {/* Provider-level proxy indicator/button */}
+ <button
+ onClick={() =>
+ setProxyTarget({
+ level: "provider",
+ id: providerId,
+ label: providerInfo?.name || providerId,
+ })
+ }
+ className={`inline-flex items-center gap-1 px-2 py-1 rounded text-xs font-medium transition-all ${
+ proxyConfig?.providers?.[providerId]
+ ? "bg-amber-500/15 text-amber-500 hover:bg-amber-500/25"
+ : "bg-black/[0.03] dark:bg-white/[0.03] text-text-muted/50 hover:text-text-muted hover:bg-black/[0.06] dark:hover:bg-white/[0.06]"
+ }`}
+ title={
+ proxyConfig?.providers?.[providerId]
+ ? t("providerProxyTitleConfigured", {
+ host: proxyConfig.providers[providerId].host || t("configured"),
+ })
+ : t("providerProxyConfigureHint")
+ }
+ >
+ <span className="material-symbols-outlined text-[14px]">vpn_lock</span>
+ {proxyConfig?.providers?.[providerId]
+ ? proxyConfig.providers[providerId].host || t("providerProxy")
+ : t("providerProxy")}
+ </button>
</div>
- <p className="text-text-main font-medium mb-1">{t("noConnectionsYet")}</p>
- <p className="text-sm text-text-muted mb-4">{t("addFirstConnectionHint")}</p>
- {!isCompatible && (
- <div className="flex items-center justify-center gap-2">
- <Button icon="add" onClick={openPrimaryAddFlow}>
- {providerSupportsPat ? "Add PAT" : t("addConnection")}
+ {connections.length > 1 && (
+ <button
+ onClick={handleBatchTestAll}
+ disabled={batchTesting || !!retestingId}
+ className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium border transition-colors ${
+ batchTesting
+ ? "bg-primary/20 border-primary/40 text-primary animate-pulse"
+ : "bg-bg-subtle border-border text-text-muted hover:text-text-primary hover:border-primary/40"
+ }`}
+ title={t("testAll")}
+ aria-label={t("testAll")}
+ >
+ <span className="material-symbols-outlined text-[14px]">
+ {batchTesting ? "sync" : "play_arrow"}
+ </span>
+ {batchTesting ? t("testing") : t("testAll")}
+ </button>
+ )}
+ {!isCompatible ? (
+ <div className="flex items-center gap-2">
+ <Button size="sm" icon="add" onClick={openPrimaryAddFlow}>
+ {providerSupportsPat ? "Add PAT" : t("add")}
</Button>
{providerId === "qoder" && (
- <Button variant="secondary" onClick={() => setShowOAuthModal(true)}>
+ <Button size="sm" variant="secondary" onClick={() => setShowOAuthModal(true)}>
Experimental OAuth
</Button>
)}
</div>
+ ) : (
+ connections.length === 0 && (
+ <Button size="sm" icon="add" onClick={() => setShowAddApiKeyModal(true)}>
+ {t("add")}
+ </Button>
+ )
)}
</div>
- ) : (
- (() => {
- // Group connections by tag (providerSpecificData.tag)
- const sorted = [...connections].sort((a, b) => (a.priority || 0) - (b.priority || 0));
- const hasAnyTag = sorted.some((c) => c.providerSpecificData?.tag as string | undefined);
- if (!hasAnyTag) {
- // No tags — render flat list as before
- return (
- <div className="flex flex-col divide-y divide-black/[0.03] dark:divide-white/[0.03]">
- {sorted.map((conn, index) => (
- <ConnectionRow
- key={conn.id}
- connection={conn}
- isOAuth={conn.authType === "oauth"}
- isFirst={index === 0}
- isLast={index === sorted.length - 1}
- onMoveUp={() => handleSwapPriority(conn, sorted[index - 1])}
- onMoveDown={() => handleSwapPriority(conn, sorted[index + 1])}
- onToggleActive={(isActive) => handleUpdateConnectionStatus(conn.id, isActive)}
- onToggleRateLimit={(enabled) => handleToggleRateLimit(conn.id, enabled)}
- isCodex={providerId === "codex"}
- isCcCompatible={isCcCompatible}
- cliproxyapiEnabled={cpaProviderEnabled}
- onToggleCliproxyapiMode={(enabled) =>
- handleToggleCliproxyapiMode(conn.id, enabled)
- }
- onToggleCodex5h={(enabled) =>
- handleToggleCodexLimit(conn.id, "use5h", enabled)
- }
- onToggleCodexWeekly={(enabled) =>
- handleToggleCodexLimit(conn.id, "useWeekly", enabled)
- }
- onRetest={() => handleRetestConnection(conn.id)}
- isRetesting={retestingId === conn.id}
- onEdit={() => {
- setSelectedConnection(conn);
- setShowEditModal(true);
- }}
- onDelete={() => handleDelete(conn.id)}
- onReauth={
- conn.authType === "oauth" ? () => setShowOAuthModal(true) : undefined
- }
- onRefreshToken={
- conn.authType === "oauth" ? () => handleRefreshToken(conn.id) : undefined
- }
- isRefreshing={refreshingId === conn.id}
- onApplyCodexAuthLocal={
- providerId === "codex"
- ? () => handleApplyCodexAuthLocal(conn.id)
- : undefined
- }
- isApplyingCodexAuthLocal={applyingCodexAuthId === conn.id}
- onExportCodexAuthFile={
- providerId === "codex"
- ? () => handleExportCodexAuthFile(conn.id)
- : undefined
- }
- isExportingCodexAuthFile={exportingCodexAuthId === conn.id}
- onProxy={() =>
- setProxyTarget({
- level: "key",
- id: conn.id,
- label: pickDisplayValue([conn.name, conn.email], emailsVisible, conn.id),
- })
- }
- hasProxy={!!connProxyMap[conn.id]?.proxy}
- proxySource={connProxyMap[conn.id]?.level || null}
- proxyHost={connProxyMap[conn.id]?.proxy?.host || null}
- />
- ))}
+ {connections.length === 0 ? (
+ <div className="text-center py-12">
+ <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-primary/10 text-primary mb-4">
+ <span className="material-symbols-outlined text-[32px]">
+ {isOAuth ? "lock" : "key"}
+ </span>
+ </div>
+ <p className="text-text-main font-medium mb-1">{t("noConnectionsYet")}</p>
+ <p className="text-sm text-text-muted mb-4">{t("addFirstConnectionHint")}</p>
+ {!isCompatible && (
+ <div className="flex items-center justify-center gap-2">
+ <Button icon="add" onClick={openPrimaryAddFlow}>
+ {providerSupportsPat ? "Add PAT" : t("addConnection")}
+ </Button>
+ {providerId === "qoder" && (
+ <Button variant="secondary" onClick={() => setShowOAuthModal(true)}>
+ Experimental OAuth
+ </Button>
+ )}
</div>
+ )}
+ </div>
+ ) : (
+ (() => {
+ // Group connections by tag (providerSpecificData.tag)
+ const sorted = [...connections].sort((a, b) => (a.priority || 0) - (b.priority || 0));
+ const hasAnyTag = sorted.some(
+ (c) => c.providerSpecificData?.tag as string | undefined
);
- }
- // Build ordered tag groups: untagged first, then alphabetically
- const groupMap = new Map<string, typeof sorted>();
- for (const conn of sorted) {
- const tag = (conn.providerSpecificData?.tag as string | undefined)?.trim() || "";
- if (!groupMap.has(tag)) groupMap.set(tag, []);
- groupMap.get(tag)!.push(conn);
- }
- const groupKeys = Array.from(groupMap.keys()).sort((a, b) => {
- if (a === "") return -1;
- if (b === "") return 1;
- return a.localeCompare(b);
- });
+ if (!hasAnyTag) {
+ // No tags — render flat list as before
+ return (
+ <div className="flex flex-col divide-y divide-black/[0.03] dark:divide-white/[0.03]">
+ {sorted.map((conn, index) => (
+ <ConnectionRow
+ key={conn.id}
+ connection={conn}
+ isOAuth={conn.authType === "oauth"}
+ isFirst={index === 0}
+ isLast={index === sorted.length - 1}
+ onMoveUp={() => handleSwapPriority(conn, sorted[index - 1])}
+ onMoveDown={() => handleSwapPriority(conn, sorted[index + 1])}
+ onToggleActive={(isActive) =>
+ handleUpdateConnectionStatus(conn.id, isActive)
+ }
+ onToggleRateLimit={(enabled) => handleToggleRateLimit(conn.id, enabled)}
+ isCodex={providerId === "codex"}
+ isCcCompatible={isCcCompatible}
+ cliproxyapiEnabled={cpaProviderEnabled}
+ onToggleCliproxyapiMode={(enabled) =>
+ handleToggleCliproxyapiMode(conn.id, enabled)
+ }
+ onToggleCodex5h={(enabled) =>
+ handleToggleCodexLimit(conn.id, "use5h", enabled)
+ }
+ onToggleCodexWeekly={(enabled) =>
+ handleToggleCodexLimit(conn.id, "useWeekly", enabled)
+ }
+ onRetest={() => handleRetestConnection(conn.id)}
+ isRetesting={retestingId === conn.id}
+ onEdit={() => {
+ setSelectedConnection(conn);
+ setShowEditModal(true);
+ }}
+ onDelete={() => handleDelete(conn.id)}
+ onReauth={
+ conn.authType === "oauth" ? () => setShowOAuthModal(true) : undefined
+ }
+ onRefreshToken={
+ conn.authType === "oauth" ? () => handleRefreshToken(conn.id) : undefined
+ }
+ isRefreshing={refreshingId === conn.id}
+ onApplyCodexAuthLocal={
+ providerId === "codex"
+ ? () => handleApplyCodexAuthLocal(conn.id)
+ : undefined
+ }
+ isApplyingCodexAuthLocal={applyingCodexAuthId === conn.id}
+ onExportCodexAuthFile={
+ providerId === "codex"
+ ? () => handleExportCodexAuthFile(conn.id)
+ : undefined
+ }
+ isExportingCodexAuthFile={exportingCodexAuthId === conn.id}
+ onProxy={() =>
+ setProxyTarget({
+ level: "key",
+ id: conn.id,
+ label: pickDisplayValue(
+ [conn.name, conn.email],
+ emailsVisible,
+ conn.id
+ ),
+ })
+ }
+ hasProxy={!!connProxyMap[conn.id]?.proxy}
+ proxySource={connProxyMap[conn.id]?.level || null}
+ proxyHost={connProxyMap[conn.id]?.proxy?.host || null}
+ />
+ ))}
+ </div>
+ );
+ }
- return (
- <div className="flex flex-col gap-0">
- {groupKeys.map((tag, gi) => {
- const groupConns = groupMap.get(tag)!;
- return (
- <div
- key={tag || "__untagged__"}
- className={
- gi > 0
- ? "border-t border-black/[0.06] dark:border-white/[0.06] mt-1 pt-1"
- : ""
- }
- >
- {tag && (
- <div className="flex items-center gap-2 px-3 pt-2 pb-1">
- <span className="material-symbols-outlined text-[13px] text-text-muted/50">
- label
- </span>
- <span className="text-[11px] font-semibold uppercase tracking-widest text-text-muted/60 select-none">
- {tag}
- </span>
- <div className="flex-1 h-px bg-black/[0.04] dark:bg-white/[0.04]" />
- <span className="text-[10px] text-text-muted/40">
- {groupConns.length}
- </span>
+ // Build ordered tag groups: untagged first, then alphabetically
+ const groupMap = new Map<string, typeof sorted>();
+ for (const conn of sorted) {
+ const tag = (conn.providerSpecificData?.tag as string | undefined)?.trim() || "";
+ if (!groupMap.has(tag)) groupMap.set(tag, []);
+ groupMap.get(tag)!.push(conn);
+ }
+ const groupKeys = Array.from(groupMap.keys()).sort((a, b) => {
+ if (a === "") return -1;
+ if (b === "") return 1;
+ return a.localeCompare(b);
+ });
+
+ return (
+ <div className="flex flex-col gap-0">
+ {groupKeys.map((tag, gi) => {
+ const groupConns = groupMap.get(tag)!;
+ return (
+ <div
+ key={tag || "__untagged__"}
+ className={
+ gi > 0
+ ? "border-t border-black/[0.06] dark:border-white/[0.06] mt-1 pt-1"
+ : ""
+ }
+ >
+ {tag && (
+ <div className="flex items-center gap-2 px-3 pt-2 pb-1">
+ <span className="material-symbols-outlined text-[13px] text-text-muted/50">
+ label
+ </span>
+ <span className="text-[11px] font-semibold uppercase tracking-widest text-text-muted/60 select-none">
+ {tag}
+ </span>
+ <div className="flex-1 h-px bg-black/[0.04] dark:bg-white/[0.04]" />
+ <span className="text-[10px] text-text-muted/40">
+ {groupConns.length}
+ </span>
+ </div>
+ )}
+ <div className="flex flex-col divide-y divide-black/[0.03] dark:divide-white/[0.03]">
+ {groupConns.map((conn, index) => (
+ <ConnectionRow
+ key={conn.id}
+ connection={conn}
+ isOAuth={conn.authType === "oauth"}
+ isFirst={gi === 0 && index === 0}
+ isLast={
+ gi === groupKeys.length - 1 && index === groupConns.length - 1
+ }
+ onMoveUp={() =>
+ handleSwapPriority(conn, sorted[sorted.indexOf(conn) - 1])
+ }
+ onMoveDown={() =>
+ handleSwapPriority(conn, sorted[sorted.indexOf(conn) + 1])
+ }
+ onToggleActive={(isActive) =>
+ handleUpdateConnectionStatus(conn.id, isActive)
+ }
+ onToggleRateLimit={(enabled) =>
+ handleToggleRateLimit(conn.id, enabled)
+ }
+ isCodex={providerId === "codex"}
+ onToggleCodex5h={(enabled) =>
+ handleToggleCodexLimit(conn.id, "use5h", enabled)
+ }
+ onToggleCodexWeekly={(enabled) =>
+ handleToggleCodexLimit(conn.id, "useWeekly", enabled)
+ }
+ onRetest={() => handleRetestConnection(conn.id)}
+ isRetesting={retestingId === conn.id}
+ onEdit={() => {
+ setSelectedConnection(conn);
+ setShowEditModal(true);
+ }}
+ onDelete={() => handleDelete(conn.id)}
+ onReauth={
+ conn.authType === "oauth"
+ ? () => setShowOAuthModal(true)
+ : undefined
+ }
+ onRefreshToken={
+ conn.authType === "oauth"
+ ? () => handleRefreshToken(conn.id)
+ : undefined
+ }
+ isRefreshing={refreshingId === conn.id}
+ onApplyCodexAuthLocal={
+ providerId === "codex"
+ ? () => handleApplyCodexAuthLocal(conn.id)
+ : undefined
+ }
+ isApplyingCodexAuthLocal={applyingCodexAuthId === conn.id}
+ onExportCodexAuthFile={
+ providerId === "codex"
+ ? () => handleExportCodexAuthFile(conn.id)
+ : undefined
+ }
+ isExportingCodexAuthFile={exportingCodexAuthId === conn.id}
+ onProxy={() =>
+ setProxyTarget({
+ level: "key",
+ id: conn.id,
+ label: pickDisplayValue(
+ [conn.name, conn.email],
+ emailsVisible,
+ conn.id
+ ),
+ })
+ }
+ hasProxy={!!connProxyMap[conn.id]?.proxy}
+ proxySource={connProxyMap[conn.id]?.level || null}
+ proxyHost={connProxyMap[conn.id]?.proxy?.host || null}
+ />
+ ))}
</div>
- )}
- <div className="flex flex-col divide-y divide-black/[0.03] dark:divide-white/[0.03]">
- {groupConns.map((conn, index) => (
- <ConnectionRow
- key={conn.id}
- connection={conn}
- isOAuth={conn.authType === "oauth"}
- isFirst={gi === 0 && index === 0}
- isLast={gi === groupKeys.length - 1 && index === groupConns.length - 1}
- onMoveUp={() =>
- handleSwapPriority(conn, sorted[sorted.indexOf(conn) - 1])
- }
- onMoveDown={() =>
- handleSwapPriority(conn, sorted[sorted.indexOf(conn) + 1])
- }
- onToggleActive={(isActive) =>
- handleUpdateConnectionStatus(conn.id, isActive)
- }
- onToggleRateLimit={(enabled) => handleToggleRateLimit(conn.id, enabled)}
- isCodex={providerId === "codex"}
- onToggleCodex5h={(enabled) =>
- handleToggleCodexLimit(conn.id, "use5h", enabled)
- }
- onToggleCodexWeekly={(enabled) =>
- handleToggleCodexLimit(conn.id, "useWeekly", enabled)
- }
- onRetest={() => handleRetestConnection(conn.id)}
- isRetesting={retestingId === conn.id}
- onEdit={() => {
- setSelectedConnection(conn);
- setShowEditModal(true);
- }}
- onDelete={() => handleDelete(conn.id)}
- onReauth={
- conn.authType === "oauth" ? () => setShowOAuthModal(true) : undefined
- }
- onRefreshToken={
- conn.authType === "oauth"
- ? () => handleRefreshToken(conn.id)
- : undefined
- }
- isRefreshing={refreshingId === conn.id}
- onApplyCodexAuthLocal={
- providerId === "codex"
- ? () => handleApplyCodexAuthLocal(conn.id)
- : undefined
- }
- isApplyingCodexAuthLocal={applyingCodexAuthId === conn.id}
- onExportCodexAuthFile={
- providerId === "codex"
- ? () => handleExportCodexAuthFile(conn.id)
- : undefined
- }
- isExportingCodexAuthFile={exportingCodexAuthId === conn.id}
- onProxy={() =>
- setProxyTarget({
- level: "key",
- id: conn.id,
- label: pickDisplayValue(
- [conn.name, conn.email],
- emailsVisible,
- conn.id
- ),
- })
- }
- hasProxy={!!connProxyMap[conn.id]?.proxy}
- proxySource={connProxyMap[conn.id]?.level || null}
- proxyHost={connProxyMap[conn.id]?.proxy?.host || null}
- />
- ))}
</div>
- </div>
- );
- })}
- </div>
- );
- })()
- )}
- </Card>
+ );
+ })}
+ </div>
+ );
+ })()
+ )}
+ </Card>
+ )}
+
+ {isUpstreamProxyProvider && (
+ <Card>
+ <div className="flex flex-col gap-3">
+ <div>
+ <h2 className="text-lg font-semibold">Managed via Upstream Proxy Settings</h2>
+ <p className="text-sm text-text-muted mt-1">
+ CLIProxyAPI is configured as an upstream proxy layer, not as a direct provider
+ connection. Manage the binary/runtime in CLI Tools and enable proxy routing on each
+ provider via the provider proxy controls.
+ </p>
+ </div>
+ <div className="flex flex-wrap gap-2">
+ <Link
+ href="/dashboard/cli-tools"
+ className="inline-flex items-center gap-2 rounded-lg border border-border px-3 py-2 text-sm text-text-main hover:border-primary/40 hover:text-text-primary transition-colors"
+ >
+ <span className="material-symbols-outlined text-base">terminal</span>
+ Open CLI Tools
+ </Link>
+ <Link
+ href="/dashboard/settings"
+ className="inline-flex items-center gap-2 rounded-lg border border-border px-3 py-2 text-sm text-text-main hover:border-primary/40 hover:text-text-primary transition-colors"
+ >
+ <span className="material-symbols-outlined text-base">settings</span>
+ Open Settings
+ </Link>
+ </div>
+ </div>
+ </Card>
+ )}
{/* Models — hidden for search providers (they don't have models) */}
- {!isSearchProvider && (
+ {!isSearchProvider && !isUpstreamProxyProvider && (
<Card>
<h2 className="text-lg font-semibold mb-4">{t("availableModels")}</h2>
{renderModelsSection()}
@@ -3007,51 +3034,56 @@ export default function ProviderDetailPage() {
)}
{/* Modals */}
- {providerId === "kiro" ? (
- <KiroOAuthWrapper
- isOpen={showOAuthModal}
- providerInfo={providerInfo}
- onSuccess={handleOAuthSuccess}
- onClose={() => {
- setShowOAuthModal(false);
- }}
- />
- ) : providerId === "cursor" ? (
- <CursorAuthModal
- isOpen={showOAuthModal}
- onSuccess={handleOAuthSuccess}
- onClose={() => {
- setShowOAuthModal(false);
- }}
- />
- ) : (
- <OAuthModal
- isOpen={showOAuthModal}
+ {!isUpstreamProxyProvider &&
+ (providerId === "kiro" ? (
+ <KiroOAuthWrapper
+ isOpen={showOAuthModal}
+ providerInfo={providerInfo}
+ onSuccess={handleOAuthSuccess}
+ onClose={() => {
+ setShowOAuthModal(false);
+ }}
+ />
+ ) : providerId === "cursor" ? (
+ <CursorAuthModal
+ isOpen={showOAuthModal}
+ onSuccess={handleOAuthSuccess}
+ onClose={() => {
+ setShowOAuthModal(false);
+ }}
+ />
+ ) : (
+ <OAuthModal
+ isOpen={showOAuthModal}
+ provider={providerId}
+ providerInfo={providerInfo}
+ onSuccess={handleOAuthSuccess}
+ onClose={() => {
+ setShowOAuthModal(false);
+ }}
+ />
+ ))}
+ {!isUpstreamProxyProvider && (
+ <AddApiKeyModal
+ isOpen={showAddApiKeyModal}
provider={providerId}
- providerInfo={providerInfo}
- onSuccess={handleOAuthSuccess}
- onClose={() => {
- setShowOAuthModal(false);
- }}
+ providerName={providerInfo.name}
+ isCompatible={isCompatible}
+ isAnthropic={isAnthropicProtocolCompatible}
+ isCcCompatible={isCcCompatible}
+ onSave={handleSaveApiKey}
+ onClose={() => setShowAddApiKeyModal(false)}
+ />
+ )}
+ {!isUpstreamProxyProvider && (
+ <EditConnectionModal
+ isOpen={showEditModal}
+ connection={selectedConnection}
+ onSave={handleUpdateConnection}
+ onClose={() => setShowEditModal(false)}
/>
)}
- <AddApiKeyModal
- isOpen={showAddApiKeyModal}
- provider={providerId}
- providerName={providerInfo.name}
- isCompatible={isCompatible}
- isAnthropic={isAnthropicProtocolCompatible}
- isCcCompatible={isCcCompatible}
- onSave={handleSaveApiKey}
- onClose={() => setShowAddApiKeyModal(false)}
- />
- <EditConnectionModal
- isOpen={showEditModal}
- connection={selectedConnection}
- onSave={handleUpdateConnection}
- onClose={() => setShowEditModal(false)}
- />
- {isCompatible && (
+ {!isUpstreamProxyProvider && isCompatible && (
<EditCompatibleNodeModal
isOpen={showEditNodeModal}
node={providerNode}
@@ -5338,6 +5370,9 @@ function AddApiKeyModal({
const isCloudflare = provider === "cloudflare-ai";
const isSearxng = provider === "searxng-search";
const isGooglePse = provider === "google-pse-search";
+ const isGrokWeb = provider === "grok-web";
+ const isPerplexityWeb = provider === "perplexity-web";
+ const isWebSessionProvider = isGrokWeb || isPerplexityWeb;
const apiKeyOptional = isSearxng;
const [formData, setFormData] = useState({
@@ -5501,9 +5536,11 @@ function AddApiKeyModal({
label={
isQoder
? "Personal Access Token"
- : isSearxng
- ? "API Key (optional)"
- : t("apiKeyLabel")
+ : isWebSessionProvider
+ ? "Session Cookie"
+ : isSearxng
+ ? "API Key (optional)"
+ : t("apiKeyLabel")
}
type="password"
value={formData.apiKey}
@@ -5512,18 +5549,26 @@ function AddApiKeyModal({
placeholder={
isVertex
? "Cole o Service Account JSON aqui"
- : isSearxng
- ? "Optional"
- : isQoder
- ? "Paste your Qoder Personal Access Token"
- : undefined
+ : isGrokWeb
+ ? "Paste your sso cookie value from grok.com"
+ : isPerplexityWeb
+ ? "Paste your __Secure-next-auth.session-token value"
+ : isSearxng
+ ? "Optional"
+ : isQoder
+ ? "Paste your Qoder Personal Access Token"
+ : undefined
}
hint={
isQoder
? "Supported path: PAT via qodercli. Browser OAuth remains experimental."
- : isSearxng
- ? "Optional. Leave blank if your SearXNG instance does not require authentication."
- : undefined
+ : isGrokWeb
+ ? "Paste the sso cookie from grok.com. A full 'sso=...' value also works."
+ : isPerplexityWeb
+ ? "Paste the __Secure-next-auth.session-token cookie from perplexity.ai."
+ : isSearxng
+ ? "Optional. Leave blank if your SearXNG instance does not require authentication."
+ : undefined
}
/>
<div className="pt-6">
diff --git a/src/app/(dashboard)/dashboard/providers/new/page.tsx b/src/app/(dashboard)/dashboard/providers/new/page.tsx
index 8dadb07130..819133ea07 100644
--- a/src/app/(dashboard)/dashboard/providers/new/page.tsx
+++ b/src/app/(dashboard)/dashboard/providers/new/page.tsx
@@ -1,217 +1,5 @@
-"use client";
-
-import { useState } from "react";
-import { useRouter } from "next/navigation";
-import Link from "next/link";
-import { Card, Button, Input, Select, Toggle } from "@/shared/components";
-import { AI_PROVIDERS, AUTH_METHODS } from "@/shared/constants/config";
-import { useTranslations } from "next-intl";
-
-const providerOptions = Object.values(AI_PROVIDERS).map((p) => ({
- value: p.id,
- label: p.name,
-}));
-
-const authMethodOptions = Object.values(AUTH_METHODS).map((m) => ({
- value: m.id,
- label: m.name,
-}));
+import { redirect } from "next/navigation";
export default function NewProviderPage() {
- const router = useRouter();
- const [loading, setLoading] = useState(false);
- const t = useTranslations("providers");
- const [formData, setFormData] = useState({
- provider: "",
- authMethod: "api_key",
- apiKey: "",
- displayName: "",
- isActive: true,
- });
- const [errors, setErrors] = useState<any>({});
-
- const handleChange = (field, value) => {
- setFormData((prev) => ({ ...prev, [field]: value }));
- if (errors[field]) {
- setErrors((prev) => ({ ...prev, [field]: null }));
- }
- };
-
- const validate = () => {
- const newErrors: any = {};
- if (!formData.provider) newErrors.provider = t("selectProvider");
- if (formData.authMethod === "api_key" && !formData.apiKey) {
- newErrors.apiKey = t("apiKeyRequired");
- }
- setErrors(newErrors);
- return Object.keys(newErrors).length === 0;
- };
-
- const handleSubmit = async (e) => {
- e.preventDefault();
- if (!validate()) return;
-
- setLoading(true);
- try {
- const response = await fetch("/api/providers", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(formData),
- });
-
- if (response.ok) {
- router.push("/dashboard/providers");
- } else {
- const data = await response.json();
- setErrors({ submit: data.error || t("failedCreate") });
- }
- } catch (error) {
- setErrors({ submit: t("errorOccurred") });
- } finally {
- setLoading(false);
- }
- };
-
- const selectedProvider = (AI_PROVIDERS as any)[formData.provider];
-
- return (
- <div className="max-w-2xl mx-auto min-w-0">
- {/* Header */}
- <div className="mb-8">
- <Link
- href="/dashboard/providers"
- className="inline-flex items-center gap-1 text-sm text-text-muted hover:text-primary transition-colors mb-4"
- >
- <span className="material-symbols-outlined text-lg">arrow_back</span>
- {t("backToProviders")}
- </Link>
- <h1 className="text-2xl sm:text-3xl font-semibold tracking-tight break-words">
- {t("addNewProvider")}
- </h1>
- <p className="text-text-muted mt-2">{t("configureNewProvider")}</p>
- </div>
-
- {/* Form */}
- <Card>
- <form onSubmit={handleSubmit} className="flex flex-col gap-6">
- {/* Provider Selection */}
- <Select
- label={t("providerLabel")}
- options={providerOptions}
- value={formData.provider}
- onChange={(e) => handleChange("provider", e.target.value)}
- placeholder={t("selectProvider")}
- error={errors.provider as string}
- required
- />
-
- {/* Provider Info */}
- {selectedProvider && (
- <Card.Section className="flex items-center gap-3">
- <div className="size-10 rounded-lg flex items-center justify-center bg-bg border border-border">
- <span
- className="material-symbols-outlined text-xl"
- style={{ color: selectedProvider.color }}
- >
- {selectedProvider.icon}
- </span>
- </div>
- <div>
- <p className="font-medium">{selectedProvider.name}</p>
- <p className="text-sm text-text-muted">{t("selectedProvider")}</p>
- </div>
- </Card.Section>
- )}
-
- {/* Auth Method */}
- <div className="flex flex-col gap-3">
- <label className="text-sm font-medium">
- {t("authMethod")} <span className="text-red-500">*</span>
- </label>
- <div className="flex flex-col sm:flex-row gap-3">
- {authMethodOptions.map((method) => (
- <button
- key={method.value}
- type="button"
- onClick={() => handleChange("authMethod", method.value)}
- className={`flex-1 min-w-0 flex items-center justify-center gap-2 p-4 rounded-lg border transition-all ${
- formData.authMethod === method.value
- ? "border-primary bg-primary/5 text-primary"
- : "border-border hover:border-primary/50"
- }`}
- >
- <span className="material-symbols-outlined">
- {method.value === "api_key" ? "key" : "lock"}
- </span>
- <span className="font-medium text-center break-words">
- {method.value === "api_key" ? t("apiKeyLabel") : t("oauth2Label")}
- </span>
- </button>
- ))}
- </div>
- </div>
-
- {/* API Key Input */}
- {formData.authMethod === "api_key" && (
- <Input
- label={t("apiKeyLabel")}
- type="password"
- placeholder={t("enterApiKey")}
- value={formData.apiKey}
- onChange={(e) => handleChange("apiKey", e.target.value)}
- error={errors.apiKey as string}
- hint={t("apiKeySecure")}
- required
- />
- )}
-
- {/* OAuth2 Button */}
- {formData.authMethod === "oauth2" && (
- <Card.Section className="">
- <p className="text-sm text-text-muted mb-4">{t("oauth2Desc")}</p>
- <Button type="button" variant="secondary" icon="link">
- {t("oauth2Connect")}
- </Button>
- </Card.Section>
- )}
-
- {/* Display Name */}
- <Input
- label={t("displayName")}
- placeholder={t("displayNamePlaceholder")}
- value={formData.displayName}
- onChange={(e) => handleChange("displayName", e.target.value)}
- hint={t("displayNameHint")}
- />
-
- {/* Active Toggle */}
- <Toggle
- checked={formData.isActive}
- onChange={(checked) => handleChange("isActive", checked)}
- label={t("active")}
- description={t("activeDescription")}
- />
-
- {/* Error Message */}
- {errors.submit && (
- <div className="p-4 rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 text-red-600 dark:text-red-400 text-sm">
- {errors.submit as string}
- </div>
- )}
-
- {/* Actions */}
- <div className="flex flex-col sm:flex-row gap-3 pt-4 border-t border-border">
- <Link href="/dashboard/providers" className="flex-1">
- <Button type="button" variant="ghost" fullWidth>
- {t("cancel")}
- </Button>
- </Link>
- <Button type="submit" loading={loading} fullWidth className="flex-1">
- {t("createProvider")}
- </Button>
- </div>
- </form>
- </Card>
- </div>
- );
+ redirect("/dashboard/providers");
}
diff --git a/src/app/(dashboard)/dashboard/providers/page.tsx b/src/app/(dashboard)/dashboard/providers/page.tsx
index dbe260d0ae..de86e770cb 100644
--- a/src/app/(dashboard)/dashboard/providers/page.tsx
+++ b/src/app/(dashboard)/dashboard/providers/page.tsx
@@ -14,15 +14,9 @@ import {
Select,
Toggle,
} from "@/shared/components";
-import {
- OAUTH_PROVIDERS,
- APIKEY_PROVIDERS,
- WEB_COOKIE_PROVIDERS,
- SEARCH_PROVIDERS,
- AUDIO_ONLY_PROVIDERS,
-} from "@/shared/constants/config";
import {
FREE_PROVIDERS,
+ OAUTH_PROVIDERS,
isAnthropicCompatibleProvider,
isClaudeCodeCompatibleProvider,
isOpenAICompatibleProvider,
@@ -36,7 +30,7 @@ import ModelAvailabilityBadge from "./components/ModelAvailabilityBadge";
import { useTranslations } from "next-intl";
import {
buildMergedOAuthProviderEntries,
- buildProviderEntries,
+ buildStaticProviderEntries,
filterConfiguredProviderEntries,
} from "./providerPageUtils";
import { readConfiguredOnlyPreference, writeConfiguredOnlyPreference } from "./providerPageStorage";
@@ -403,22 +397,22 @@ export default function ProvidersPage() {
);
const apiKeyProviderEntries = filterConfiguredProviderEntries(
- buildProviderEntries(APIKEY_PROVIDERS, "apikey", "apikey", getProviderStats),
+ buildStaticProviderEntries("apikey", getProviderStats),
showConfiguredOnly
);
const webCookieProviderEntries = filterConfiguredProviderEntries(
- buildProviderEntries(WEB_COOKIE_PROVIDERS, "apikey", "apikey", getProviderStats),
+ buildStaticProviderEntries("web-cookie", getProviderStats),
showConfiguredOnly
);
const searchProviderEntries = filterConfiguredProviderEntries(
- buildProviderEntries(SEARCH_PROVIDERS, "apikey", "apikey", getProviderStats),
+ buildStaticProviderEntries("search", getProviderStats),
showConfiguredOnly
);
const audioProviderEntries = filterConfiguredProviderEntries(
- buildProviderEntries(AUDIO_ONLY_PROVIDERS, "apikey", "apikey", getProviderStats),
+ buildStaticProviderEntries("audio", getProviderStats),
showConfiguredOnly
);
diff --git a/src/app/(dashboard)/dashboard/providers/providerPageUtils.ts b/src/app/(dashboard)/dashboard/providers/providerPageUtils.ts
index 55cd0fd77b..d2f75617db 100644
--- a/src/app/(dashboard)/dashboard/providers/providerPageUtils.ts
+++ b/src/app/(dashboard)/dashboard/providers/providerPageUtils.ts
@@ -1,3 +1,13 @@
+import {
+ getStaticProviderCatalogGroup,
+ resolveProviderCatalogEntry,
+ type CompatibleProviderLabels,
+ type CompatibleProviderNodeLike,
+ type ProviderCatalogMetadata,
+ type ResolvedProviderCatalogEntry,
+ type StaticProviderCatalogCategory,
+} from "@/lib/providers/catalog";
+
export interface ProviderStatsSnapshot {
total?: number;
[key: string]: unknown;
@@ -44,6 +54,19 @@ export function buildMergedOAuthProviderEntries<TProvider = Record<string, unkno
];
}
+export function buildStaticProviderEntries(
+ category: StaticProviderCatalogCategory,
+ getProviderStats: GetProviderStats
+): ProviderEntry<ProviderCatalogMetadata>[] {
+ const group = getStaticProviderCatalogGroup(category);
+ return buildProviderEntries(
+ group.providers,
+ group.displayAuthType,
+ group.toggleAuthType,
+ getProviderStats
+ );
+}
+
export function filterConfiguredProviderEntries<TProvider>(
entries: ProviderEntry<TProvider>[],
showConfiguredOnly: boolean
@@ -52,3 +75,13 @@ export function filterConfiguredProviderEntries<TProvider>(
return entries.filter((entry) => Number(entry.stats?.total || 0) > 0);
}
+
+export function resolveDashboardProviderInfo(
+ providerId: string,
+ options?: {
+ providerNode?: CompatibleProviderNodeLike | null;
+ compatibleLabels?: CompatibleProviderLabels | null;
+ }
+): ResolvedProviderCatalogEntry | null {
+ return resolveProviderCatalogEntry(providerId, options);
+}
diff --git a/src/app/(dashboard)/dashboard/settings/components/PayloadRulesTab.tsx b/src/app/(dashboard)/dashboard/settings/components/PayloadRulesTab.tsx
new file mode 100644
index 0000000000..31af651749
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/settings/components/PayloadRulesTab.tsx
@@ -0,0 +1,282 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { Card, Button } from "@/shared/components";
+
+const EMPTY_PAYLOAD_RULES_TEMPLATE = {
+ default: [],
+ override: [],
+ filter: [],
+ defaultRaw: [],
+};
+
+const EMPTY_PAYLOAD_RULES_TEXT = JSON.stringify(EMPTY_PAYLOAD_RULES_TEMPLATE, null, 2);
+
+type StatusMessage = {
+ type: "success" | "error" | "info";
+ text: string;
+};
+
+function isObjectRecord(value: unknown): value is Record<string, unknown> {
+ return !!value && typeof value === "object" && !Array.isArray(value);
+}
+
+function getRuleSectionCount(value: unknown, keys: string[]): number {
+ for (const key of keys) {
+ if (isObjectRecord(value) && Array.isArray(value[key])) {
+ return value[key].length;
+ }
+ }
+ return 0;
+}
+
+function getErrorMessage(payload: unknown): string {
+ if (!isObjectRecord(payload)) return "Failed to save payload rules";
+
+ const nestedError = payload.error;
+ if (typeof nestedError === "string" && nestedError.trim()) {
+ return nestedError;
+ }
+
+ if (isObjectRecord(nestedError)) {
+ if (typeof nestedError.message === "string" && nestedError.message.trim()) {
+ return nestedError.message;
+ }
+
+ if (Array.isArray(nestedError.details) && nestedError.details.length > 0) {
+ const detail = nestedError.details[0];
+ if (isObjectRecord(detail) && typeof detail.message === "string" && detail.message.trim()) {
+ return detail.message;
+ }
+ }
+ }
+
+ return "Failed to save payload rules";
+}
+
+export default function PayloadRulesTab() {
+ const [editorValue, setEditorValue] = useState(EMPTY_PAYLOAD_RULES_TEXT);
+ const [loading, setLoading] = useState(true);
+ const [saving, setSaving] = useState(false);
+ const [message, setMessage] = useState<StatusMessage | null>(null);
+
+ const parsedEditor = useMemo(() => {
+ try {
+ const parsed = JSON.parse(editorValue);
+ if (!isObjectRecord(parsed)) {
+ return { value: null, error: "Payload rules must be a JSON object." };
+ }
+ return { value: parsed, error: null };
+ } catch (error) {
+ return {
+ value: null,
+ error: error instanceof Error ? error.message : "Invalid JSON payload.",
+ };
+ }
+ }, [editorValue]);
+
+ const summary = useMemo(() => {
+ const source = parsedEditor.value;
+ return {
+ default: getRuleSectionCount(source, ["default"]),
+ override: getRuleSectionCount(source, ["override"]),
+ filter: getRuleSectionCount(source, ["filter"]),
+ defaultRaw: getRuleSectionCount(source, ["defaultRaw", "default-raw"]),
+ };
+ }, [parsedEditor.value]);
+
+ const loadConfig = useCallback(async () => {
+ setLoading(true);
+ setMessage(null);
+ try {
+ const response = await fetch("/api/settings/payload-rules");
+ const payload = await response.json();
+ if (!response.ok) {
+ throw new Error(getErrorMessage(payload));
+ }
+
+ setEditorValue(JSON.stringify(payload, null, 2));
+ } catch (error) {
+ setMessage({
+ type: "error",
+ text: error instanceof Error ? error.message : "Failed to load payload rules",
+ });
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ loadConfig();
+ }, [loadConfig]);
+
+ const handleReset = () => {
+ setEditorValue(EMPTY_PAYLOAD_RULES_TEXT);
+ setMessage({
+ type: "info",
+ text: "Editor reset to the neutral template. Save to apply it.",
+ });
+ };
+
+ const handleSave = async () => {
+ if (parsedEditor.error || !parsedEditor.value) {
+ setMessage({
+ type: "error",
+ text: parsedEditor.error || "Payload rules must be valid JSON before saving.",
+ });
+ return;
+ }
+
+ setSaving(true);
+ setMessage(null);
+ try {
+ const response = await fetch("/api/settings/payload-rules", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(parsedEditor.value),
+ });
+ const payload = await response.json();
+ if (!response.ok) {
+ throw new Error(getErrorMessage(payload));
+ }
+
+ setEditorValue(JSON.stringify(payload, null, 2));
+ setMessage({ type: "success", text: "Payload rules saved and hot reloaded." });
+ } catch (error) {
+ setMessage({
+ type: "error",
+ text: error instanceof Error ? error.message : "Failed to save payload rules",
+ });
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return (
+ <Card>
+ <div className="flex flex-col gap-5">
+ <div className="flex items-start gap-3">
+ <div className="p-2 rounded-lg bg-indigo-500/10 text-indigo-500">
+ <span className="material-symbols-outlined text-[20px]" aria-hidden="true">
+ data_object
+ </span>
+ </div>
+ <div className="flex-1">
+ <h3 className="text-lg font-semibold">Payload Rules</h3>
+ <p className="text-sm text-text-muted mt-1">
+ Configure request payload mutations by model and protocol. Changes are persisted in
+ settings and hot reloaded into the runtime immediately after save.
+ </p>
+ </div>
+ </div>
+
+ <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-3">
+ <div className="rounded-lg border border-border bg-bg-secondary/40 p-3">
+ <p className="text-sm font-medium">default</p>
+ <p className="text-xs text-text-muted mt-1">
+ Applies params only when the target path is missing from the outgoing payload.
+ </p>
+ </div>
+ <div className="rounded-lg border border-border bg-bg-secondary/40 p-3">
+ <p className="text-sm font-medium">override</p>
+ <p className="text-xs text-text-muted mt-1">
+ Forces values onto the payload, replacing anything already present at that path.
+ </p>
+ </div>
+ <div className="rounded-lg border border-border bg-bg-secondary/40 p-3">
+ <p className="text-sm font-medium">filter</p>
+ <p className="text-xs text-text-muted mt-1">
+ Removes blocked params from the payload before the upstream request is sent.
+ </p>
+ </div>
+ <div className="rounded-lg border border-border bg-bg-secondary/40 p-3">
+ <p className="text-sm font-medium">defaultRaw</p>
+ <p className="text-xs text-text-muted mt-1">
+ Like <code>default</code>, but string values are parsed as JSON first when possible.
+ The legacy input alias <code>default-raw</code> is also accepted on save.
+ </p>
+ </div>
+ </div>
+
+ <div className="flex flex-wrap items-center gap-2 text-xs text-text-muted">
+ <span className="rounded-full border border-border px-2.5 py-1">
+ default: {summary.default}
+ </span>
+ <span className="rounded-full border border-border px-2.5 py-1">
+ override: {summary.override}
+ </span>
+ <span className="rounded-full border border-border px-2.5 py-1">
+ filter: {summary.filter}
+ </span>
+ <span className="rounded-full border border-border px-2.5 py-1">
+ defaultRaw: {summary.defaultRaw}
+ </span>
+ </div>
+
+ {message && (
+ <div
+ className={`flex items-center gap-2 px-3 py-2 rounded-lg text-sm ${
+ message.type === "success"
+ ? "bg-green-500/10 text-green-600 dark:text-green-400"
+ : message.type === "info"
+ ? "bg-blue-500/10 text-blue-600 dark:text-blue-400"
+ : "bg-red-500/10 text-red-600 dark:text-red-400"
+ }`}
+ >
+ <span className="material-symbols-outlined text-[16px]">
+ {message.type === "success"
+ ? "check_circle"
+ : message.type === "info"
+ ? "info"
+ : "error"}
+ </span>
+ {message.text}
+ </div>
+ )}
+
+ <div className="rounded-xl border border-border overflow-hidden">
+ <div className="flex items-center justify-between px-4 py-3 border-b border-border bg-bg-secondary/30">
+ <div>
+ <p className="text-sm font-medium">Editor</p>
+ <p className="text-xs text-text-muted">
+ Use the runtime schema shape: <code>default</code>, <code>override</code>,{" "}
+ <code>filter</code>, <code>defaultRaw</code>. The API also accepts the legacy input
+ key <code>default-raw</code>.
+ </p>
+ </div>
+ <div className="text-xs text-text-muted">{loading ? "Loading..." : "Ready"}</div>
+ </div>
+ <textarea
+ value={editorValue}
+ onChange={(event) => {
+ setEditorValue(event.target.value);
+ if (message?.type === "error") setMessage(null);
+ }}
+ spellCheck={false}
+ rows={22}
+ className="w-full px-4 py-4 bg-transparent text-sm font-mono leading-6 text-text-main resize-y min-h-[420px] focus:outline-none"
+ disabled={loading || saving}
+ />
+ </div>
+
+ {parsedEditor.error && (
+ <p className="text-sm text-red-500">
+ JSON parse error: <span className="font-medium">{parsedEditor.error}</span>
+ </p>
+ )}
+
+ <div className="flex flex-wrap gap-2">
+ <Button variant="secondary" onClick={loadConfig} disabled={loading || saving}>
+ Reload
+ </Button>
+ <Button variant="secondary" onClick={handleReset} disabled={loading || saving}>
+ Reset Template
+ </Button>
+ <Button onClick={handleSave} disabled={loading || saving || !!parsedEditor.error}>
+ {saving ? "Saving..." : "Save Payload Rules"}
+ </Button>
+ </div>
+ </div>
+ </Card>
+ );
+}
diff --git a/src/app/(dashboard)/dashboard/settings/page.tsx b/src/app/(dashboard)/dashboard/settings/page.tsx
index 2d62d6a3ae..ca3d97282a 100644
--- a/src/app/(dashboard)/dashboard/settings/page.tsx
+++ b/src/app/(dashboard)/dashboard/settings/page.tsx
@@ -3,7 +3,7 @@
import { useState } from "react";
import { useSearchParams } from "next/navigation";
import { cn } from "@/shared/utils/cn";
-import { APP_CONFIG } from "@/shared/constants/config";
+import { APP_CONFIG } from "@/shared/constants/appConfig";
import { useTranslations } from "next-intl";
import SystemStorageTab from "./components/SystemStorageTab";
import SecurityTab from "./components/SecurityTab";
@@ -20,6 +20,7 @@ import MemorySkillsTab from "./components/MemorySkillsTab";
import ModelsDevSyncTab from "./components/ModelsDevSyncTab";
import ResilienceTab from "./components/ResilienceTab";
import CliproxyapiSettingsTab from "./components/CliproxyapiSettingsTab";
+import PayloadRulesTab from "./components/PayloadRulesTab";
import ModelRoutingSection from "@/shared/components/ModelRoutingSection";
const tabs = [
@@ -115,6 +116,7 @@ export default function SettingsPage() {
{activeTab === "advanced" && (
<div className="flex flex-col gap-6">
+ <PayloadRulesTab />
<ProxyTab />
<CliproxyapiSettingsTab />
</div>
diff --git a/src/app/api/init/route.ts b/src/app/api/init/route.ts
index 2630babfae..1167f48dec 100644
--- a/src/app/api/init/route.ts
+++ b/src/app/api/init/route.ts
@@ -1,7 +1,7 @@
-// Auto-initialize cloud sync when server starts
-import "@/lib/initCloudSync";
+import { ensureCloudSyncInitialized } from "@/lib/initCloudSync";
// This API route is called automatically to initialize sync
export async function GET() {
- return new Response("Initialized", { status: 200 });
+ const initialized = await ensureCloudSyncInitialized();
+ return Response.json({ initialized });
}
diff --git a/src/app/api/models/alias/route.ts b/src/app/api/models/alias/route.ts
index a690de5186..84480424c3 100644
--- a/src/app/api/models/alias/route.ts
+++ b/src/app/api/models/alias/route.ts
@@ -2,7 +2,6 @@ import { NextResponse } from "next/server";
import { getModelAliases, setModelAlias, deleteModelAlias, isCloudEnabled } from "@/models";
import { getConsistentMachineId } from "@/shared/utils/machineId";
import { syncToCloud } from "@/lib/cloudSync";
-import { isAuthenticated } from "@/shared/utils/apiAuth";
import { cloudModelAliasUpdateSchema } from "@/shared/validation/schemas";
import { isValidationFailure, validateBody } from "@/shared/validation/helpers";
import {
@@ -10,20 +9,19 @@ import {
getCatalogDiagnosticsHeaders,
resolveModelAliasLookup,
} from "@/lib/modelMetadataRegistry";
+import { requireManagementAuth } from "@/lib/api/requireManagementAuth";
// GET /api/models/alias - Get all aliases
export async function GET(request) {
const alias = new URL(request.url).searchParams.get("alias");
try {
- // Require authentication for security
- if (!(await isAuthenticated(request))) {
- return NextResponse.json(
- { error: "Authentication required" },
- {
- status: 401,
- headers: getCatalogDiagnosticsHeaders({ request }),
- }
- );
+ const authError = await requireManagementAuth(request);
+ if (authError) {
+ const headers = getCatalogDiagnosticsHeaders({ request, resolvedAlias: alias });
+ for (const [key, value] of Object.entries(headers)) {
+ authError.headers.set(key, value);
+ }
+ return authError;
}
if (alias) {
@@ -113,12 +111,12 @@ export async function PUT(request) {
}
try {
- // Require authentication for security
- if (!(await isAuthenticated(request))) {
- return NextResponse.json(
- { error: "Authentication required" },
- { status: 401, headers: diagnosticHeaders }
- );
+ const authError = await requireManagementAuth(request);
+ if (authError) {
+ for (const [key, value] of Object.entries(diagnosticHeaders)) {
+ authError.headers.set(key, value);
+ }
+ return authError;
}
const validation = validateBody(cloudModelAliasUpdateSchema, rawBody);
@@ -157,12 +155,12 @@ export async function PUT(request) {
export async function DELETE(request) {
const diagnosticHeaders = getCatalogDiagnosticsHeaders({ request });
try {
- // Require authentication for security
- if (!(await isAuthenticated(request))) {
- return NextResponse.json(
- { error: "Authentication required" },
- { status: 401, headers: diagnosticHeaders }
- );
+ const authError = await requireManagementAuth(request);
+ if (authError) {
+ for (const [key, value] of Object.entries(diagnosticHeaders)) {
+ authError.headers.set(key, value);
+ }
+ return authError;
}
const { searchParams } = new URL(request.url);
diff --git a/src/app/api/providers/[id]/route.ts b/src/app/api/providers/[id]/route.ts
index 57c236c4bd..88ee650319 100644
--- a/src/app/api/providers/[id]/route.ts
+++ b/src/app/api/providers/[id]/route.ts
@@ -15,6 +15,7 @@ import { syncToCloud } from "@/lib/cloudSync";
import { updateProviderConnectionSchema } from "@/shared/validation/schemas";
import { isValidationFailure, validateBody } from "@/shared/validation/helpers";
import { normalizeProviderSpecificData } from "@/lib/providers/requestDefaults";
+import { requireManagementAuth } from "@/lib/api/requireManagementAuth";
function normalizeCodexLimitPolicy(
incoming: unknown,
@@ -42,6 +43,9 @@ function normalizeCodexLimitPolicy(
// GET /api/providers/[id] - Get single connection
export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {
+ const authError = await requireManagementAuth(request);
+ if (authError) return authError;
+
try {
const { id } = await params;
const connection = await getProviderConnectionById(id);
@@ -69,6 +73,9 @@ export async function GET(request: Request, { params }: { params: Promise<{ id:
// PUT /api/providers/[id] - Update connection
export async function PUT(request: Request, { params }: { params: Promise<{ id: string }> }) {
+ const authError = await requireManagementAuth(request);
+ if (authError) return authError;
+
const auditContext = getAuditRequestContext(request);
let rawBody;
try {
@@ -196,6 +203,9 @@ export async function PUT(request: Request, { params }: { params: Promise<{ id:
// DELETE /api/providers/[id] - Delete connection
export async function DELETE(request: Request, { params }: { params: Promise<{ id: string }> }) {
+ const authError = await requireManagementAuth(request);
+ if (authError) return authError;
+
const auditContext = getAuditRequestContext(request);
try {
diff --git a/src/app/api/providers/route.ts b/src/app/api/providers/route.ts
index 1faeb25ab6..99c9906ad3 100644
--- a/src/app/api/providers/route.ts
+++ b/src/app/api/providers/route.ts
@@ -10,7 +10,6 @@ import {
getProviderNodeById,
isCloudEnabled,
} from "@/models";
-import { APIKEY_PROVIDERS, SEARCH_PROVIDERS } from "@/shared/constants/config";
import {
isClaudeCodeCompatibleProvider,
isOpenAICompatibleProvider,
@@ -22,9 +21,14 @@ import { createProviderSchema } from "@/shared/validation/schemas";
import { isValidationFailure, validateBody } from "@/shared/validation/helpers";
import { normalizeQoderPatProviderData } from "@omniroute/open-sse/services/qoderCli";
import { normalizeProviderSpecificData } from "@/lib/providers/requestDefaults";
+import { requireManagementAuth } from "@/lib/api/requireManagementAuth";
+import { isManagedProviderConnectionId } from "@/lib/providers/catalog";
// GET /api/providers - List all connections
-export async function GET() {
+export async function GET(request: Request) {
+ const authError = await requireManagementAuth(request);
+ if (authError) return authError;
+
try {
const connections = await getProviderConnections();
@@ -52,6 +56,9 @@ export async function GET() {
// POST /api/providers - Create new connection (API Key only, OAuth via separate flow)
export async function POST(request: Request) {
+ const authError = await requireManagementAuth(request);
+ if (authError) return authError;
+
const auditContext = getAuditRequestContext(request);
try {
@@ -75,9 +82,7 @@ export async function POST(request: Request) {
// Business validation
const isValidProvider =
- APIKEY_PROVIDERS[provider] ||
- SEARCH_PROVIDERS[provider] ||
- provider === "qoder" ||
+ isManagedProviderConnectionId(provider) ||
isOpenAICompatibleProvider(provider) ||
isAnthropicCompatibleProvider(provider);
diff --git a/src/app/api/providers/test-batch/route.ts b/src/app/api/providers/test-batch/route.ts
index 28e24916e6..d4b72bda31 100644
--- a/src/app/api/providers/test-batch/route.ts
+++ b/src/app/api/providers/test-batch/route.ts
@@ -15,6 +15,7 @@ import {
import { testSingleConnection } from "../[id]/test/route";
import { providersBatchTestSchema } from "@/shared/validation/schemas";
import { isValidationFailure, validateBody } from "@/shared/validation/helpers";
+import { requireManagementAuth } from "@/lib/api/requireManagementAuth";
// Determine auth type group for a provider id
function getAuthGroup(providerId) {
@@ -43,6 +44,9 @@ function isCompatibleProvider(providerId) {
// POST /api/providers/test-batch - Test multiple connections by group
export async function POST(request) {
+ const authError = await requireManagementAuth(request);
+ if (authError) return authError;
+
let rawBody;
try {
rawBody = await request.json();
diff --git a/src/app/api/settings/payload-rules/route.ts b/src/app/api/settings/payload-rules/route.ts
index 77d8b7413d..8a1a5a7bcd 100644
--- a/src/app/api/settings/payload-rules/route.ts
+++ b/src/app/api/settings/payload-rules/route.ts
@@ -2,12 +2,16 @@ import { NextResponse } from "next/server";
import { updateSettings } from "@/lib/localDb";
import {
getPayloadRulesConfig,
- setPayloadRulesConfig,
+ normalizePayloadRulesConfig,
} from "@omniroute/open-sse/services/payloadRules.ts";
import { updatePayloadRulesSchema } from "@/shared/validation/schemas";
import { isValidationFailure, validateBody } from "@/shared/validation/helpers";
+import { requireManagementAuth } from "@/lib/api/requireManagementAuth";
+
+export async function GET(request: Request) {
+ const authError = await requireManagementAuth(request);
+ if (authError) return authError;
-export async function GET() {
try {
return NextResponse.json(await getPayloadRulesConfig());
} catch (error) {
@@ -17,6 +21,9 @@ export async function GET() {
}
export async function PUT(request: Request) {
+ const authError = await requireManagementAuth(request);
+ if (authError) return authError;
+
let rawBody: unknown;
try {
rawBody = await request.json();
@@ -38,11 +45,10 @@ export async function PUT(request: Request) {
return NextResponse.json({ error: validation.error }, { status: 400 });
}
- setPayloadRulesConfig(validation.data);
- const currentConfig = await getPayloadRulesConfig();
- await updateSettings({ payloadRules: currentConfig });
+ const normalizedConfig = normalizePayloadRulesConfig(validation.data);
+ await updateSettings({ payloadRules: normalizedConfig });
- return NextResponse.json(currentConfig);
+ return NextResponse.json(normalizedConfig);
} catch (error) {
console.error("Error updating payload rules config:", error);
return NextResponse.json({ error: "Failed to update payload rules config" }, { status: 500 });
diff --git a/src/app/api/settings/route.ts b/src/app/api/settings/route.ts
index e34bc6cafa..403a2a6ff2 100644
--- a/src/app/api/settings/route.ts
+++ b/src/app/api/settings/route.ts
@@ -12,8 +12,12 @@ import {
hashManagementPassword,
verifyManagementPassword,
} from "@/lib/auth/managementPassword";
+import { requireManagementAuth } from "@/lib/api/requireManagementAuth";
+
+export async function GET(request: Request) {
+ const authError = await requireManagementAuth(request);
+ if (authError) return authError;
-export async function GET() {
try {
const settings = await getSettings();
const { password, ...safeSettings } = settings;
@@ -38,7 +42,10 @@ export async function GET() {
}
}
-export async function PATCH(request) {
+export async function PATCH(request: Request) {
+ const authError = await requireManagementAuth(request);
+ if (authError) return authError;
+
try {
const rawBody = await request.json();
diff --git a/src/app/layout.tsx b/src/app/layout.tsx
index c184aa720b..1d1d54a7cc 100644
--- a/src/app/layout.tsx
+++ b/src/app/layout.tsx
@@ -1,7 +1,6 @@
import { Inter } from "next/font/google";
import "./globals.css";
import { ThemeProvider } from "@/shared/components/ThemeProvider";
-import "@/lib/initCloudSync"; // Auto-initialize cloud sync
import { NextIntlClientProvider } from "next-intl";
import { getMessages, getLocale } from "next-intl/server";
import { RTL_LOCALES } from "@/i18n/config";
diff --git a/src/app/page.tsx b/src/app/page.tsx
index 53ac0287f7..d594875903 100644
--- a/src/app/page.tsx
+++ b/src/app/page.tsx
@@ -1,5 +1,3 @@
-// Auto-initialize cloud sync when server starts
-import "@/lib/initCloudSync";
import { redirect } from "next/navigation";
export default function InitPage() {
diff --git a/src/instrumentation-node.ts b/src/instrumentation-node.ts
index cff466f700..d67092f262 100755
--- a/src/instrumentation-node.ts
+++ b/src/instrumentation-node.ts
@@ -87,6 +87,7 @@ export async function registerNodejs(): Promise<void> {
{ initGracefulShutdown },
{ initApiBridgeServer },
{ startBackgroundRefresh },
+ { ensureCloudSyncInitialized },
{ startProviderLimitsSyncScheduler },
{ getSettings },
{ applyRuntimeSettings },
@@ -100,6 +101,7 @@ export async function registerNodejs(): Promise<void> {
import("@/lib/gracefulShutdown"),
import("@/lib/apiBridgeServer"),
import("@/domain/quotaCache"),
+ import("@/lib/initCloudSync"),
import("@/shared/services/providerLimitsSyncScheduler"),
import("@/lib/db/settings"),
import("@/lib/config/runtimeSettings"),
@@ -124,6 +126,10 @@ export async function registerNodejs(): Promise<void> {
console.log("[STARTUP] Quota cache background refresh started");
startProviderLimitsSyncScheduler();
console.log("[STARTUP] Provider limits sync scheduler started");
+ const cloudSyncInitialized = await ensureCloudSyncInitialized();
+ console.log(
+ `[STARTUP] Cloud/model sync background bootstrap ${cloudSyncInitialized ? "initialized" : "skipped"}`
+ );
}
try {
diff --git a/src/lib/api/requireManagementAuth.ts b/src/lib/api/requireManagementAuth.ts
index 55820964e3..8d2b8b0809 100644
--- a/src/lib/api/requireManagementAuth.ts
+++ b/src/lib/api/requireManagementAuth.ts
@@ -1,35 +1,12 @@
-import { isAuthRequired } from "@/shared/utils/apiAuth";
+import { isAuthRequired, isDashboardSessionAuthenticated } from "@/shared/utils/apiAuth";
import { createErrorResponse } from "@/lib/api/errorResponse";
-import { jwtVerify } from "jose";
-import { cookies } from "next/headers";
-
-/**
- * Checks if the request is authenticated strictly via a Dashboard Session (JWT Cookie).
- * Standard Bearer API keys are rejected for management routes to prevent privilege escalation.
- */
-async function isDashboardSessionAuthenticated(): Promise<boolean> {
- if (process.env.JWT_SECRET) {
- try {
- const cookieStore = await cookies();
- const token = cookieStore.get("auth_token")?.value;
- if (token) {
- const secret = new TextEncoder().encode(process.env.JWT_SECRET);
- await jwtVerify(token, secret);
- return true;
- }
- } catch {
- // Invalid/expired token
- }
- }
- return false;
-}
export async function requireManagementAuth(request: Request): Promise<Response | null> {
if (!(await isAuthRequired())) {
return null;
}
- if (await isDashboardSessionAuthenticated()) {
+ if (await isDashboardSessionAuthenticated(request)) {
return null;
}
diff --git a/src/lib/config/runtimeSettings.ts b/src/lib/config/runtimeSettings.ts
index df9f41e53f..ef5e2ccc6c 100644
--- a/src/lib/config/runtimeSettings.ts
+++ b/src/lib/config/runtimeSettings.ts
@@ -46,6 +46,15 @@ const DEFAULT_RUNTIME_SETTINGS_SNAPSHOT: RuntimeSettingsSnapshot = {
let lastAppliedSnapshot: RuntimeSettingsSnapshot | null = null;
+function isAutomatedTestProcess(): boolean {
+ return (
+ typeof process !== "undefined" &&
+ (process.env.NODE_ENV === "test" ||
+ process.env.VITEST !== undefined ||
+ process.argv.some((arg) => arg.includes("test")))
+ );
+}
+
function toRecord(value: unknown): JsonRecord {
return value && typeof value === "object" && !Array.isArray(value) ? (value as JsonRecord) : {};
}
@@ -240,6 +249,14 @@ async function applyModelsDevSyncSection(
force: boolean
) {
const { startPeriodicSync, stopPeriodicSync } = await import("@/lib/modelsDevSync");
+ const skipBackgroundSyncInTests =
+ isAutomatedTestProcess() && process.env.OMNIROUTE_ENABLE_RUNTIME_BACKGROUND_TASKS !== "1";
+
+ if (skipBackgroundSyncInTests) {
+ stopPeriodicSync();
+ return;
+ }
+
const wasEnabled = previousSnapshot.modelsDevSyncEnabled === true;
const isEnabled = currentSnapshot.modelsDevSyncEnabled === true;
const intervalChanged =
diff --git a/src/lib/dataPaths.js b/src/lib/dataPaths.js
index ad9d20a6bf..6f9b0b626f 100644
--- a/src/lib/dataPaths.js
+++ b/src/lib/dataPaths.js
@@ -1,59 +1,69 @@
-"use strict";
-var __importDefault =
- (this && this.__importDefault) ||
- function (mod) {
- return mod && mod.__esModule ? mod : { default: mod };
- };
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.APP_NAME = void 0;
-exports.getLegacyDotDataDir = getLegacyDotDataDir;
-exports.getDefaultDataDir = getDefaultDataDir;
-exports.resolveDataDir = resolveDataDir;
-exports.isSamePath = isSamePath;
-const path_1 = __importDefault(require("path"));
-const os_1 = __importDefault(require("os"));
-exports.APP_NAME = "omniroute";
+import os from "os";
+import path from "path";
+
+export const APP_NAME = "omniroute";
+
+function fallbackHomeDir() {
+ const envHome = process.env.HOME || process.env.USERPROFILE;
+ if (typeof envHome === "string" && envHome.trim().length > 0) {
+ return path.resolve(envHome);
+ }
+
+ return os.tmpdir();
+}
+
function safeHomeDir() {
try {
- return os_1.default.homedir();
+ return os.homedir();
} catch {
- return process.cwd();
+ return fallbackHomeDir();
}
}
+
function normalizeConfiguredPath(dir) {
if (typeof dir !== "string") return null;
const trimmed = dir.trim();
if (!trimmed) return null;
- return path_1.default.resolve(trimmed);
+ return path.resolve(trimmed);
}
-function getLegacyDotDataDir() {
- return path_1.default.join(safeHomeDir(), `.${exports.APP_NAME}`);
+
+export function getLegacyDotDataDir() {
+ return path.join(safeHomeDir(), `.${APP_NAME}`);
}
-function getDefaultDataDir() {
+
+export function getDefaultDataDir() {
const homeDir = safeHomeDir();
+
if (process.platform === "win32") {
- const appData = process.env.APPDATA || path_1.default.join(homeDir, "AppData", "Roaming");
- return path_1.default.join(appData, exports.APP_NAME);
+ const appData = process.env.APPDATA || path.join(homeDir, "AppData", "Roaming");
+ return path.join(appData, APP_NAME);
}
- // Support XDG on Linux/macOS when explicitly configured.
+
const xdgConfigHome = normalizeConfiguredPath(process.env.XDG_CONFIG_HOME);
if (xdgConfigHome) {
- return path_1.default.join(xdgConfigHome, exports.APP_NAME);
+ return path.join(xdgConfigHome, APP_NAME);
}
+
return getLegacyDotDataDir();
}
-function resolveDataDir({ isCloud = false } = {}) {
+
+export function resolveDataDir({ isCloud = false } = {}) {
if (isCloud) return "/tmp";
+
const configured = normalizeConfiguredPath(process.env.DATA_DIR);
if (configured) return configured;
+
return getDefaultDataDir();
}
-function isSamePath(a, b) {
+
+export function isSamePath(a, b) {
if (!a || !b) return false;
- const normalizedA = path_1.default.resolve(a);
- const normalizedB = path_1.default.resolve(b);
+ const normalizedA = path.resolve(a);
+ const normalizedB = path.resolve(b);
+
if (process.platform === "win32") {
return normalizedA.toLowerCase() === normalizedB.toLowerCase();
}
+
return normalizedA === normalizedB;
}
diff --git a/src/lib/dataPaths.ts b/src/lib/dataPaths.ts
index 60a6dc2835..24e7e8338a 100644
--- a/src/lib/dataPaths.ts
+++ b/src/lib/dataPaths.ts
@@ -3,11 +3,20 @@ import os from "os";
export const APP_NAME = "omniroute";
+function fallbackHomeDir() {
+ const envHome = process.env.HOME || process.env.USERPROFILE;
+ if (typeof envHome === "string" && envHome.trim().length > 0) {
+ return path.resolve(envHome);
+ }
+
+ return os.tmpdir();
+}
+
function safeHomeDir() {
try {
return os.homedir();
} catch {
- return process.cwd();
+ return fallbackHomeDir();
}
}
diff --git a/src/lib/db/backup.ts b/src/lib/db/backup.ts
index 3ca0f16d53..da4f6782a1 100644
--- a/src/lib/db/backup.ts
+++ b/src/lib/db/backup.ts
@@ -222,17 +222,20 @@ export function backupDbFile(reason = "auto") {
const backupDir = getBackupDir();
if (!fs.existsSync(backupDir)) fs.mkdirSync(backupDir, { recursive: true });
- // Shrink check vs latest backup
- const existingBackups = fs
- .readdirSync(backupDir)
- .filter((f) => f.startsWith("db_") && f.endsWith(".sqlite"))
- .sort();
- if (existingBackups.length > 0) {
- const latestBackup = existingBackups[existingBackups.length - 1];
- const latestStat = fs.statSync(path.join(backupDir, latestBackup));
- if (latestStat.size > 4096 && stat.size < latestStat.size * 0.5) {
- console.warn(`[DB] Backup SKIPPED — DB shrank from ${latestStat.size}B to ${stat.size}B`);
- return null;
+ if (reason !== "manual" && reason !== "pre-restore") {
+ // Shrink detection is useful for automatic safety backups, but it should
+ // never block an explicit operator action like manual backup or pre-restore.
+ const existingBackups = fs
+ .readdirSync(backupDir)
+ .filter((f) => f.startsWith("db_") && f.endsWith(".sqlite"))
+ .sort();
+ if (existingBackups.length > 0) {
+ const latestBackup = existingBackups[existingBackups.length - 1];
+ const latestStat = fs.statSync(path.join(backupDir, latestBackup));
+ if (latestStat.size > 4096 && stat.size < latestStat.size * 0.5) {
+ console.warn(`[DB] Backup SKIPPED — DB shrank from ${latestStat.size}B to ${stat.size}B`);
+ return null;
+ }
}
}
diff --git a/src/lib/db/core.ts b/src/lib/db/core.ts
index d1036943ef..7e85dcafae 100644
--- a/src/lib/db/core.ts
+++ b/src/lib/db/core.ts
@@ -20,6 +20,30 @@ import {
type SqliteDatabase = import("better-sqlite3").Database;
type JsonRecord = Record<string, unknown>;
type CheckpointMode = "PASSIVE" | "FULL" | "RESTART" | "TRUNCATE";
+type PreservedTableSnapshot = {
+ table: string;
+ rowCount: number;
+ maxRows: number;
+ columns: string[];
+ rows: JsonRecord[];
+};
+type SkippedTableSnapshot = {
+ table: string;
+ rowCount: number;
+ maxRows: number;
+ reason: string;
+};
+type PreservedCriticalDbState = {
+ captureSucceeded: boolean;
+ captureError: string | null;
+ preservedTables: PreservedTableSnapshot[];
+ skippedTables: SkippedTableSnapshot[];
+};
+type CriticalTableSpec = {
+ table: string;
+ maxRows?: number;
+ readRows?: (db: SqliteDatabase) => JsonRecord[];
+};
// ──────────────── Environment Detection ────────────────
@@ -34,6 +58,34 @@ const LEGACY_DATA_DIR = isCloud ? null : getLegacyDotDataDir();
export const SQLITE_FILE = isCloud ? null : path.join(DATA_DIR, "storage.sqlite");
const JSON_DB_FILE = isCloud ? null : path.join(DATA_DIR, "db.json");
export const DB_BACKUPS_DIR = isCloud ? null : path.join(DATA_DIR, "db_backups");
+const DEFAULT_CRITICAL_TABLE_ROW_LIMIT = 10_000;
+const SKIP_PRESERVE_NAMESPACES = new Set(["syncedAvailableModels", "providerLimitsCache", "lkgp"]);
+const CRITICAL_DB_TABLES: CriticalTableSpec[] = [
+ {
+ table: "key_value",
+ maxRows: 10_000,
+ readRows(db) {
+ return (
+ (db.prepare("SELECT namespace, key, value FROM key_value").all() as JsonRecord[]) ?? []
+ ).filter(
+ (row) => typeof row.namespace !== "string" || !SKIP_PRESERVE_NAMESPACES.has(row.namespace)
+ );
+ },
+ },
+ { table: "provider_connections", maxRows: 5_000 },
+ { table: "provider_nodes", maxRows: 5_000 },
+ { table: "combos", maxRows: 5_000 },
+ { table: "api_keys", maxRows: 5_000 },
+ { table: "proxy_registry", maxRows: 5_000 },
+ { table: "proxy_assignments", maxRows: 10_000 },
+ { table: "model_combo_mappings", maxRows: 5_000 },
+ { table: "sync_tokens", maxRows: 5_000 },
+ { table: "registered_keys", maxRows: 10_000 },
+ { table: "provider_key_limits", maxRows: 10_000 },
+ { table: "account_key_limits", maxRows: 10_000 },
+ { table: "upstream_proxy_config", maxRows: 5_000 },
+ { table: "webhooks", maxRows: 5_000 },
+];
// Ensure data directory exists — with fallback for restricted home directories (#133)
if (!isCloud && !fs.existsSync(DATA_DIR)) {
@@ -524,6 +576,159 @@ function hasTable(db: SqliteDatabase, tableName: string): boolean {
);
}
+function quoteIdentifier(identifier: string): string {
+ return `"${identifier.replace(/"/g, '""')}"`;
+}
+
+function getTableColumns(db: SqliteDatabase, tableName: string): string[] {
+ return (
+ db.prepare(`PRAGMA table_info(${quoteIdentifier(tableName)})`).all() as Array<{ name?: string }>
+ )
+ .map((column) => String(column.name ?? ""))
+ .filter((column) => column.length > 0);
+}
+
+function summarizePreservedTables(tables: PreservedTableSnapshot[]): string {
+ if (tables.length === 0) return "none";
+ return tables.map((table) => `${table.table}(${table.rowCount})`).join(", ");
+}
+
+function summarizeSkippedTables(tables: SkippedTableSnapshot[]): string {
+ if (tables.length === 0) return "none";
+ return tables
+ .map((table) => `${table.table}(${table.rowCount}/${table.maxRows}: ${table.reason})`)
+ .join(", ");
+}
+
+function listProbeFailureBackups(sqliteFile: string): string[] {
+ const directory = path.dirname(sqliteFile);
+ const baseName = path.basename(sqliteFile);
+ if (!fs.existsSync(directory)) return [];
+
+ return fs
+ .readdirSync(directory)
+ .filter((name) => name.startsWith(`${baseName}.probe-failed-`))
+ .map((name) => path.join(directory, name))
+ .sort((left, right) => {
+ const leftMtime = fs.statSync(left).mtimeMs;
+ const rightMtime = fs.statSync(right).mtimeMs;
+ return rightMtime - leftMtime;
+ });
+}
+
+function captureCriticalDbState(sqliteFile: string): PreservedCriticalDbState {
+ const snapshot: PreservedCriticalDbState = {
+ captureSucceeded: false,
+ captureError: null,
+ preservedTables: [],
+ skippedTables: [],
+ };
+
+ if (!fs.existsSync(sqliteFile)) {
+ snapshot.captureSucceeded = true;
+ return snapshot;
+ }
+
+ let probe: SqliteDatabase | null = null;
+ try {
+ probe = new Database(sqliteFile, { readonly: true });
+
+ for (const tableSpec of CRITICAL_DB_TABLES) {
+ if (!hasTable(probe, tableSpec.table)) continue;
+
+ const maxRows = tableSpec.maxRows ?? DEFAULT_CRITICAL_TABLE_ROW_LIMIT;
+ const rows = (tableSpec.readRows?.(probe) ??
+ (probe
+ .prepare(`SELECT * FROM ${quoteIdentifier(tableSpec.table)}`)
+ .all() as JsonRecord[])) as JsonRecord[];
+ const rowCount = rows.length;
+
+ if (rowCount === 0) continue;
+
+ if (rowCount > maxRows) {
+ snapshot.skippedTables.push({
+ table: tableSpec.table,
+ rowCount,
+ maxRows,
+ reason: "row_limit_exceeded",
+ });
+ continue;
+ }
+
+ snapshot.preservedTables.push({
+ table: tableSpec.table,
+ rowCount,
+ maxRows,
+ columns: getTableColumns(probe, tableSpec.table),
+ rows,
+ });
+ }
+
+ snapshot.captureSucceeded = true;
+ return snapshot;
+ } catch (error: unknown) {
+ snapshot.captureError = error instanceof Error ? error.message : String(error);
+ return snapshot;
+ } finally {
+ try {
+ probe?.close();
+ } catch {
+ /* ignore */
+ }
+ }
+}
+
+function restoreCriticalDbState(
+ db: SqliteDatabase,
+ snapshot: PreservedCriticalDbState
+): PreservedTableSnapshot[] {
+ const restoredTables: PreservedTableSnapshot[] = [];
+
+ const restore = db.transaction(() => {
+ for (const table of snapshot.preservedTables) {
+ if (table.rows.length === 0) continue;
+ if (!hasTable(db, table.table)) {
+ throw new Error(`Current schema is missing preserved table "${table.table}"`);
+ }
+
+ const currentColumns = new Set(getTableColumns(db, table.table));
+ const restoreColumns = table.columns.filter((column) => currentColumns.has(column));
+ if (restoreColumns.length === 0) {
+ throw new Error(`No compatible columns remain for preserved table "${table.table}"`);
+ }
+
+ const sql = `INSERT OR REPLACE INTO ${quoteIdentifier(table.table)} (${restoreColumns
+ .map((column) => quoteIdentifier(column))
+ .join(", ")}) VALUES (${restoreColumns.map(() => "?").join(", ")})`;
+ const insert = db.prepare(sql);
+
+ for (const row of table.rows) {
+ insert.run(...restoreColumns.map((column) => row[column] ?? null));
+ }
+
+ restoredTables.push(table);
+ }
+ });
+
+ restore();
+ return restoredTables;
+}
+
+function cleanupRecreatedSqliteFiles(sqliteFile: string) {
+ for (const filePath of [
+ sqliteFile,
+ `${sqliteFile}-wal`,
+ `${sqliteFile}-shm`,
+ `${sqliteFile}-journal`,
+ ]) {
+ try {
+ if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
+ } catch {
+ /* ignore */
+ }
+ }
+}
+
function parseLegacyError(value: unknown): unknown {
if (typeof value !== "string" || value.trim().length === 0) return null;
try {
@@ -789,54 +994,45 @@ export function getDbInstance(): SqliteDatabase {
throw new Error("SQLITE_FILE is unavailable for local mode");
}
const jsonDbFile = JSON_DB_FILE;
+ const probeFailureBackups = listProbeFailureBackups(sqliteFile);
+ if (!fs.existsSync(sqliteFile) && probeFailureBackups.length > 0) {
+ throw new Error(
+ `[DB] Manual recovery required before startup. ` +
+ `Detected preserved database from a previous probe failure: ${probeFailureBackups[0]}. ` +
+ `Restore the preserved file or another backup to ${sqliteFile} before restarting.`
+ );
+ }
- // ── key_value Preservation Guard (#1332) ──
- // Before any potential DB file rename/recreation, read all key_value data
- // so it can be restored if the DB is recreated from scratch (e.g., schema
- // mismatch, probe failure, or npm update wiping the file).
- const SKIP_PRESERVE_NAMESPACES = new Set([
- "syncedAvailableModels",
- "providerLimitsCache",
- "lkgp",
- ]);
- const KEY_VALUE_PRESERVE_LIMIT = 10_000;
- let preservedKeyValue: Array<{ namespace: string; key: string; value: string }> = [];
-
- if (!isCloud && SQLITE_FILE && fs.existsSync(sqliteFile)) {
- try {
- const kvProbe = new Database(sqliteFile, { readonly: true });
- try {
- const hasKv = kvProbe
- .prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='key_value'")
- .get();
- if (hasKv) {
- const rowCount = (
- kvProbe.prepare("SELECT COUNT(*) AS c FROM key_value").get() as { c: number }
- ).c;
- if (rowCount > KEY_VALUE_PRESERVE_LIMIT) {
- console.warn(
- `[DB] key_value has ${rowCount} rows (limit ${KEY_VALUE_PRESERVE_LIMIT}), skipping preservation`
- );
- } else {
- preservedKeyValue = kvProbe
- .prepare("SELECT namespace, key, value FROM key_value")
- .all() as Array<{ namespace: string; key: string; value: string }>;
- preservedKeyValue = preservedKeyValue.filter(
- (row) => !SKIP_PRESERVE_NAMESPACES.has(row.namespace)
- );
- if (preservedKeyValue.length > 0) {
- console.log(
- `[DB] Preserved ${preservedKeyValue.length} key_value entries before potential recreation`
- );
- }
- }
- }
- } finally {
- kvProbe.close();
+ let preservedCriticalState: PreservedCriticalDbState = {
+ captureSucceeded: true,
+ captureError: null,
+ preservedTables: [],
+ skippedTables: [],
+ };
+ let failedProbePath: string | null = null;
+ let failedProbeMessage: string | null = null;
+
+ if (fs.existsSync(sqliteFile)) {
+ preservedCriticalState = captureCriticalDbState(sqliteFile);
+ if (preservedCriticalState.captureSucceeded) {
+ if (preservedCriticalState.preservedTables.length > 0) {
+ console.log(
+ `[DB] Preserved critical DB state before potential recreation: ${summarizePreservedTables(
+ preservedCriticalState.preservedTables
+ )}`
+ );
}
- } catch (e: unknown) {
- const message = e instanceof Error ? e.message : String(e);
- console.warn(`[DB] Could not preserve key_value: ${message}`);
+ if (preservedCriticalState.skippedTables.length > 0) {
+ console.warn(
+ `[DB] Critical DB tables skipped during preservation: ${summarizeSkippedTables(
+ preservedCriticalState.skippedTables
+ )}`
+ );
+ }
+ } else if (preservedCriticalState.captureError) {
+ console.warn(
+ `[DB] Could not preserve critical DB state before recreation: ${preservedCriticalState.captureError}`
+ );
}
}
@@ -918,12 +1114,30 @@ export function getDbInstance(): SqliteDatabase {
try {
fs.renameSync(sqliteFile, failedPath);
console.warn(`[DB] Renamed corrupt DB to ${path.basename(failedPath)}`);
+ failedProbePath = failedPath;
+ failedProbeMessage = message;
} catch {
/* ok */
}
}
}
+ if (failedProbePath) {
+ const hasUnsafeSkippedTables = preservedCriticalState.skippedTables.length > 0;
+ const missingSnapshot = !preservedCriticalState.captureSucceeded;
+ if (hasUnsafeSkippedTables || missingSnapshot) {
+ const details = missingSnapshot
+ ? `snapshot_failed=${preservedCriticalState.captureError || "unknown"}`
+ : `skipped_tables=${summarizeSkippedTables(preservedCriticalState.skippedTables)}`;
+ throw new Error(
+ `[DB] Manual recovery required after probe failure. ` +
+ `Preserved database: ${failedProbePath}. ` +
+ `Automatic recovery was aborted because ${details}. ` +
+ `Original probe error: ${failedProbeMessage || "unknown"}.`
+ );
+ }
+ }
+
const db = new Database(sqliteFile);
db.pragma("journal_mode = WAL");
db.pragma("busy_timeout = 5000");
@@ -1029,21 +1243,28 @@ export function getDbInstance(): SqliteDatabase {
migrateFromJson(db, jsonDbFile);
}
- // ── key_value Restoration (#1332) ──
- // Restore preserved key_value data that was read before potential DB recreation.
- // Uses INSERT OR IGNORE so fresh defaults seeded by migrations are not overwritten.
- if (preservedKeyValue.length > 0) {
- const insertKv = db.prepare(
- "INSERT OR IGNORE INTO key_value (namespace, key, value) VALUES (?, ?, ?)"
- );
- const restoreKv = db.transaction(() => {
- for (const row of preservedKeyValue) {
- insertKv.run(row.namespace, row.key, row.value);
+ if (failedProbePath && preservedCriticalState.preservedTables.length > 0) {
+ try {
+ const restoredTables = restoreCriticalDbState(db, preservedCriticalState);
+ console.log(
+ `[DB] Restored preserved critical DB state after probe failure: ${summarizePreservedTables(
+ restoredTables
+ )}`
+ );
+ } catch (error: unknown) {
+ const message = error instanceof Error ? error.message : String(error);
+ try {
+ if (db.open) db.close();
+ } catch {
+ /* ignore */
}
- });
- restoreKv();
- console.log(`[DB] Restored ${preservedKeyValue.length} preserved key_value entries`);
- preservedKeyValue = [];
+ cleanupRecreatedSqliteFiles(sqliteFile);
+ throw new Error(
+ `[DB] Automatic recovery aborted after probe failure. ` +
+ `Preserved database: ${failedProbePath}. ` +
+ `Restore failure: ${message}.`
+ );
+ }
}
// Store schema version
diff --git a/src/lib/db/migrationRunner.ts b/src/lib/db/migrationRunner.ts
index 65198f49ba..f434d304cc 100644
--- a/src/lib/db/migrationRunner.ts
+++ b/src/lib/db/migrationRunner.ts
@@ -25,17 +25,25 @@ import type Database from "better-sqlite3";
* `file://` URL, causing `fileURLToPath` to throw `ERR_INVALID_FILE_URL_PATH`.
*/
function resolveMigrationsDir(): string {
+ const configuredDir = process.env.OMNIROUTE_MIGRATIONS_DIR;
+ if (typeof configuredDir === "string" && configuredDir.trim().length > 0) {
+ return path.resolve(configuredDir);
+ }
+
try {
- const metaUrl = import.meta.url;
- if (metaUrl && metaUrl.startsWith("file://")) {
- const __filename = fileURLToPath(metaUrl);
- return path.join(path.dirname(__filename), "migrations");
- }
+ return path.join(path.dirname(fileURLToPath(import.meta.url)), "migrations");
} catch {
- // fileURLToPath failed (e.g. Windows global install) — use fallback
+ // Fall through to a more defensive URL parse below.
}
- // Fallback: resolve relative to cwd (works for both dev and global installs)
- return path.join(process.cwd(), "src", "lib", "db", "migrations");
+
+ const metaUrl = import.meta.url;
+ if (typeof metaUrl === "string" && metaUrl.startsWith("file://")) {
+ return path.join(path.dirname(fileURLToPath(metaUrl)), "migrations");
+ }
+
+ throw new Error(
+ "[Migration] Could not resolve migrations directory. Set OMNIROUTE_MIGRATIONS_DIR."
+ );
}
const MIGRATIONS_DIR = resolveMigrationsDir();
diff --git a/src/lib/initCloudSync.ts b/src/lib/initCloudSync.ts
index 7b834b517c..78b26e89bf 100644
--- a/src/lib/initCloudSync.ts
+++ b/src/lib/initCloudSync.ts
@@ -1,23 +1,43 @@
import initializeCloudSync from "@/shared/services/initializeCloudSync";
import { startBudgetResetJob } from "@/lib/jobs/budgetResetJob";
import { startModelSyncScheduler } from "@/shared/services/modelSyncScheduler";
-import "@/lib/tokenHealthCheck"; // Proactive token health-check scheduler
-// Initialize background sync services when this module is imported
+// Initialize runtime background sync services once per server process.
let initialized = false;
-function isBackgroundServicesDisabled(): boolean {
- const raw = process.env.OMNIROUTE_DISABLE_BACKGROUND_SERVICES;
- if (!raw) return false;
- return new Set(["1", "true", "yes", "on"]).has(raw.trim().toLowerCase());
+function isAutomatedTestProcess(
+ env: NodeJS.ProcessEnv = process.env,
+ argv: string[] = process.argv
+): boolean {
+ return (
+ env.NODE_ENV === "test" || env.VITEST !== undefined || argv.some((arg) => arg.includes("test"))
+ );
+}
+
+export function shouldSkipCloudSyncInitialization(
+ env: NodeJS.ProcessEnv = process.env,
+ argv: string[] = process.argv
+): boolean {
+ if (env.NEXT_PHASE === "phase-production-build") {
+ return true;
+ }
+
+ const raw = env.OMNIROUTE_DISABLE_BACKGROUND_SERVICES;
+ if (raw && new Set(["1", "true", "yes", "on"]).has(raw.trim().toLowerCase())) {
+ return true;
+ }
+
+ return isAutomatedTestProcess(env, argv) && env.OMNIROUTE_ENABLE_RUNTIME_BACKGROUND_TASKS !== "1";
}
export async function ensureCloudSyncInitialized() {
- if (isBackgroundServicesDisabled()) {
+ if (shouldSkipCloudSyncInitialization()) {
return false;
}
if (!initialized) {
try {
+ const { initTokenHealthCheck } = await import("@/lib/tokenHealthCheck");
+ initTokenHealthCheck();
await initializeCloudSync();
startModelSyncScheduler();
startBudgetResetJob();
@@ -29,7 +49,4 @@ export async function ensureCloudSyncInitialized() {
return initialized;
}
-// Auto-initialize when module loads
-ensureCloudSyncInitialized().catch((err) => console.error("[CloudSync] ensure failed:", err));
-
export default ensureCloudSyncInitialized;
diff --git a/src/lib/localHealthCheck.ts b/src/lib/localHealthCheck.ts
index 01b92b1591..e61a35aac4 100644
--- a/src/lib/localHealthCheck.ts
+++ b/src/lib/localHealthCheck.ts
@@ -33,6 +33,19 @@ const INITIAL_DELAY_MS = 15_000; // Wait for server boot before first sweep
const LOG_PREFIX = "[LocalHealthCheck]";
const TRUE_ENV_VALUES = new Set(["1", "true", "yes", "on"]);
+function isBuildProcess(): boolean {
+ return typeof process !== "undefined" && process.env.NEXT_PHASE === "phase-production-build";
+}
+
+function isAutomatedTestProcess(): boolean {
+ return (
+ typeof process !== "undefined" &&
+ (process.env.NODE_ENV === "test" ||
+ process.env.VITEST !== undefined ||
+ process.argv.some((arg) => arg.includes("test")))
+ );
+}
+
// ── State (globalThis survives HMR re-evaluation) ───────────────────────
declare global {
@@ -69,7 +82,11 @@ function isEnvFlagEnabled(name: string): boolean {
}
function isLocalHealthCheckDisabled(): boolean {
- return isEnvFlagEnabled("OMNIROUTE_DISABLE_LOCAL_HEALTHCHECK") || process.env.NODE_ENV === "test";
+ return (
+ isEnvFlagEnabled("OMNIROUTE_DISABLE_LOCAL_HEALTHCHECK") ||
+ isBuildProcess() ||
+ isAutomatedTestProcess()
+ );
}
function isLocalhostUrl(baseUrl: string): boolean {
diff --git a/src/lib/modelsDevSync.ts b/src/lib/modelsDevSync.ts
index 8623100d7b..263e0918e1 100644
--- a/src/lib/modelsDevSync.ts
+++ b/src/lib/modelsDevSync.ts
@@ -202,6 +202,9 @@ export function mapProviderId(modelsDevProviderId: string): string[] {
// ─── Periodic sync state ─────────────────────────────────
let syncTimer: ReturnType<typeof setInterval> | null = null;
+let activeSyncAbortController: AbortController | null = null;
+let activeSyncPromise: Promise<SyncResult> | null = null;
+let activePeriodicSyncToken: { stopped: boolean } | null = null;
let lastSyncTime: string | null = null;
let lastSyncModelCount = 0;
let lastSyncCapabilityCount = 0;
@@ -211,6 +214,48 @@ let cacheTime = 0;
const CACHE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
let cachedCapabilities: CapabilitiesByProvider | null = null;
let cachedCapabilitiesLoadedAll = false;
+const MODELS_DEV_ABORT_ERROR = "AbortError";
+
+function createAbortError(): Error {
+ const error = new Error("models.dev sync aborted");
+ error.name = MODELS_DEV_ABORT_ERROR;
+ return error;
+}
+
+function isAbortError(error: unknown): boolean {
+ return error instanceof Error && error.name === MODELS_DEV_ABORT_ERROR;
+}
+
+function createAbortedSyncResult(dryRun: boolean): SyncResult {
+ return {
+ success: false,
+ modelCount: 0,
+ providerCount: 0,
+ capabilityCount: 0,
+ dryRun,
+ error: "aborted",
+ };
+}
+
+async function sleepWithAbort(ms: number, signal?: AbortSignal): Promise<void> {
+ if (signal?.aborted) {
+ throw createAbortError();
+ }
+
+ await new Promise<void>((resolve, reject) => {
+ const timeout = setTimeout(() => {
+ signal?.removeEventListener("abort", onAbort);
+ resolve();
+ }, ms);
+
+ const onAbort = () => {
+ clearTimeout(timeout);
+ reject(createAbortError());
+ };
+
+ signal?.addEventListener("abort", onAbort, { once: true });
+ });
+}
// ─── Core: Fetch ─────────────────────────────────────────
@@ -218,14 +263,14 @@ let cachedCapabilitiesLoadedAll = false;
* Fetch raw data from models.dev API.
* Uses in-memory cache with 24h TTL to avoid repeated fetches.
*/
-export async function fetchModelsDev(): Promise<ModelsDevData> {
+export async function fetchModelsDev(signal?: AbortSignal): Promise<ModelsDevData> {
// Return cached data if still fresh
if (cachedData && Date.now() - cacheTime < CACHE_TTL_MS) {
return cachedData;
}
const response = await fetch(MODELS_DEV_API_URL, {
- signal: AbortSignal.timeout(30000),
+ signal: signal ?? AbortSignal.timeout(30000),
});
if (!response.ok) {
throw new Error(`models.dev fetch failed [${response.status}]: ${response.statusText}`);
@@ -599,16 +644,22 @@ export async function syncModelsDev(opts?: {
dryRun?: boolean;
syncCapabilities?: boolean;
maxRetries?: number;
+ signal?: AbortSignal;
}): Promise<SyncResult> {
const dryRun = opts?.dryRun ?? false;
const syncCapabilities = opts?.syncCapabilities ?? true;
const maxRetries = opts?.maxRetries ?? 3;
+ const signal = opts?.signal;
let lastError: Error | null = null;
for (let attempt = 0; attempt <= maxRetries; attempt++) {
+ if (signal?.aborted) {
+ return createAbortedSyncResult(dryRun);
+ }
+
try {
- const raw = await fetchModelsDev();
+ const raw = await fetchModelsDev(signal);
const pricing = transformModelsDevToPricing(raw);
const capabilities = syncCapabilities ? transformModelsDevToCapabilities(raw) : {};
@@ -621,6 +672,10 @@ export async function syncModelsDev(opts?: {
? Object.values(capabilities).reduce((sum, models) => sum + Object.keys(models).length, 0)
: 0;
+ if (signal?.aborted) {
+ return createAbortedSyncResult(dryRun);
+ }
+
if (!dryRun) {
saveModelsDevPricing(pricing);
if (syncCapabilities) {
@@ -641,6 +696,10 @@ export async function syncModelsDev(opts?: {
...(dryRun ? { data: { pricing, capabilities } } : {}),
};
} catch (err) {
+ if (signal?.aborted || isAbortError(err)) {
+ return createAbortedSyncResult(dryRun);
+ }
+
lastError = err instanceof Error ? err : new Error(String(err));
if (attempt < maxRetries) {
@@ -649,7 +708,14 @@ export async function syncModelsDev(opts?: {
`[MODELS_DEV] Sync attempt ${attempt + 1} failed, retrying in ${delayMs}ms:`,
lastError.message
);
- await new Promise((resolve) => setTimeout(resolve, delayMs));
+ try {
+ await sleepWithAbort(delayMs, signal);
+ } catch (sleepError) {
+ if (signal?.aborted || isAbortError(sleepError)) {
+ return createAbortedSyncResult(dryRun);
+ }
+ throw sleepError;
+ }
}
}
}
@@ -676,10 +742,33 @@ export function startPeriodicSync(intervalMs?: number): void {
const interval = intervalMs ?? SYNC_INTERVAL_MS;
activeSyncIntervalMs = interval;
+ const syncToken = { stopped: false };
+ activePeriodicSyncToken = syncToken;
console.log(`[MODELS_DEV] Starting periodic sync every ${interval / 1000}s`);
+ const launchSync = () => {
+ if (syncToken.stopped) {
+ return Promise.resolve(createAbortedSyncResult(false));
+ }
+
+ if (activeSyncPromise) return activeSyncPromise;
+
+ const controller = new AbortController();
+ activeSyncAbortController = controller;
+ const promise = syncModelsDev({ signal: controller.signal }).finally(() => {
+ if (activeSyncAbortController === controller) {
+ activeSyncAbortController = null;
+ }
+ if (activeSyncPromise === promise) {
+ activeSyncPromise = null;
+ }
+ });
+ activeSyncPromise = promise;
+ return promise;
+ };
+
// Initial sync (non-blocking)
- syncModelsDev()
+ launchSync()
.then((result) => {
if (result.success) {
console.log(
@@ -692,7 +781,7 @@ export function startPeriodicSync(intervalMs?: number): void {
});
syncTimer = setInterval(() => {
- syncModelsDev()
+ launchSync()
.then((result) => {
if (result.success) {
console.log(`[MODELS_DEV] Periodic sync complete: ${result.modelCount} pricing entries`);
@@ -712,6 +801,16 @@ export function startPeriodicSync(intervalMs?: number): void {
* Stop periodic sync and cleanup timer.
*/
export function stopPeriodicSync(): void {
+ if (activePeriodicSyncToken) {
+ activePeriodicSyncToken.stopped = true;
+ activePeriodicSyncToken = null;
+ }
+
+ if (activeSyncAbortController) {
+ activeSyncAbortController.abort();
+ activeSyncAbortController = null;
+ }
+
if (syncTimer) {
clearInterval(syncTimer);
syncTimer = null;
diff --git a/src/lib/providers/catalog.ts b/src/lib/providers/catalog.ts
new file mode 100644
index 0000000000..2f182309b2
--- /dev/null
+++ b/src/lib/providers/catalog.ts
@@ -0,0 +1,228 @@
+import {
+ APIKEY_PROVIDERS,
+ AUDIO_ONLY_PROVIDERS,
+ FREE_PROVIDERS,
+ OAUTH_PROVIDERS,
+ SEARCH_PROVIDERS,
+ UPSTREAM_PROXY_PROVIDERS,
+ WEB_COOKIE_PROVIDERS,
+ isClaudeCodeCompatibleProvider,
+ supportsApiKeyOnFreeProvider,
+} from "@/shared/constants/providers";
+
+export type ProviderDisplayAuthType = "oauth" | "apikey" | "compatible";
+export type ProviderToggleAuthType = "oauth" | "free" | "apikey";
+export type StaticProviderCatalogCategory =
+ | "free"
+ | "oauth"
+ | "web-cookie"
+ | "search"
+ | "audio"
+ | "upstream-proxy"
+ | "apikey";
+
+export interface ProviderCatalogMetadata {
+ id: string;
+ name: string;
+ color: string;
+ alias?: string;
+ icon?: string;
+ textIcon?: string;
+ website?: string;
+ authHint?: string;
+ apiHint?: string;
+ passthroughModels?: boolean;
+ apiType?: string;
+ baseUrl?: string;
+ [key: string]: unknown;
+}
+
+type ProviderRecord = Record<string, ProviderCatalogMetadata>;
+
+export interface StaticProviderCatalogGroup {
+ category: StaticProviderCatalogCategory;
+ providers: ProviderRecord;
+ displayAuthType: Exclude<ProviderDisplayAuthType, "compatible">;
+ toggleAuthType: ProviderToggleAuthType;
+}
+
+export interface CompatibleProviderNodeLike {
+ id: string;
+ name?: string | null;
+ type?: string | null;
+ apiType?: string | null;
+ baseUrl?: string | null;
+}
+
+export interface CompatibleProviderLabels {
+ ccCompatibleName: string;
+ anthropicCompatibleName: string;
+ openAiCompatibleName: string;
+}
+
+export interface ResolvedStaticProviderCatalogEntry extends ProviderCatalogMetadata {
+ category: StaticProviderCatalogCategory;
+ displayAuthType: Exclude<ProviderDisplayAuthType, "compatible">;
+ toggleAuthType: ProviderToggleAuthType;
+ isCompatible: false;
+}
+
+export interface ResolvedCompatibleProviderCatalogEntry extends ProviderCatalogMetadata {
+ category: "compatible";
+ displayAuthType: "compatible";
+ toggleAuthType: "apikey";
+ isCompatible: true;
+ type?: string | null;
+}
+
+export type ResolvedProviderCatalogEntry =
+ | ResolvedStaticProviderCatalogEntry
+ | ResolvedCompatibleProviderCatalogEntry;
+
+export const STATIC_PROVIDER_CATALOG_GROUPS: Record<
+ StaticProviderCatalogCategory,
+ StaticProviderCatalogGroup
+> = {
+ free: {
+ category: "free",
+ providers: FREE_PROVIDERS as ProviderRecord,
+ displayAuthType: "oauth",
+ toggleAuthType: "free",
+ },
+ oauth: {
+ category: "oauth",
+ providers: OAUTH_PROVIDERS as ProviderRecord,
+ displayAuthType: "oauth",
+ toggleAuthType: "oauth",
+ },
+ "web-cookie": {
+ category: "web-cookie",
+ providers: WEB_COOKIE_PROVIDERS as ProviderRecord,
+ displayAuthType: "apikey",
+ toggleAuthType: "apikey",
+ },
+ search: {
+ category: "search",
+ providers: SEARCH_PROVIDERS as ProviderRecord,
+ displayAuthType: "apikey",
+ toggleAuthType: "apikey",
+ },
+ audio: {
+ category: "audio",
+ providers: AUDIO_ONLY_PROVIDERS as ProviderRecord,
+ displayAuthType: "apikey",
+ toggleAuthType: "apikey",
+ },
+ "upstream-proxy": {
+ category: "upstream-proxy",
+ providers: UPSTREAM_PROXY_PROVIDERS as ProviderRecord,
+ displayAuthType: "apikey",
+ toggleAuthType: "apikey",
+ },
+ apikey: {
+ category: "apikey",
+ providers: APIKEY_PROVIDERS as ProviderRecord,
+ displayAuthType: "apikey",
+ toggleAuthType: "apikey",
+ },
+};
+
+export const STATIC_PROVIDER_CATALOG_RESOLUTION_ORDER: StaticProviderCatalogCategory[] = [
+ "free",
+ "oauth",
+ "web-cookie",
+ "search",
+ "audio",
+ "upstream-proxy",
+ "apikey",
+];
+
+const MANAGED_PROVIDER_CONNECTION_CATEGORIES = new Set<StaticProviderCatalogCategory>([
+ "apikey",
+ "web-cookie",
+ "search",
+ "audio",
+]);
+
+export function getStaticProviderCatalogGroup(
+ category: StaticProviderCatalogCategory
+): StaticProviderCatalogGroup {
+ return STATIC_PROVIDER_CATALOG_GROUPS[category];
+}
+
+export function getStaticProviderCategories(providerId: string): StaticProviderCatalogCategory[] {
+ const categories: StaticProviderCatalogCategory[] = [];
+ for (const category of STATIC_PROVIDER_CATALOG_RESOLUTION_ORDER) {
+ if (STATIC_PROVIDER_CATALOG_GROUPS[category].providers[providerId]) {
+ categories.push(category);
+ }
+ }
+ return categories;
+}
+
+export function resolveStaticProviderCatalogEntry(
+ providerId: string
+): ResolvedStaticProviderCatalogEntry | null {
+ for (const category of STATIC_PROVIDER_CATALOG_RESOLUTION_ORDER) {
+ const group = STATIC_PROVIDER_CATALOG_GROUPS[category];
+ const provider = group.providers[providerId];
+ if (!provider) continue;
+ return {
+ ...provider,
+ category,
+ displayAuthType: group.displayAuthType,
+ toggleAuthType: group.toggleAuthType,
+ isCompatible: false,
+ };
+ }
+ return null;
+}
+
+export function isManagedProviderConnectionId(providerId: string): boolean {
+ if (supportsApiKeyOnFreeProvider(providerId)) return true;
+
+ const entry = resolveStaticProviderCatalogEntry(providerId);
+ return !!(entry && MANAGED_PROVIDER_CONNECTION_CATEGORIES.has(entry.category));
+}
+
+export function resolveCompatibleProviderCatalogEntry(
+ providerNode: CompatibleProviderNodeLike,
+ labels: CompatibleProviderLabels
+): ResolvedCompatibleProviderCatalogEntry {
+ const isCcCompatible = isClaudeCodeCompatibleProvider(providerNode.id);
+ const isAnthropicCompatible = providerNode.type === "anthropic-compatible" && !isCcCompatible;
+
+ return {
+ id: providerNode.id,
+ name:
+ providerNode.name ||
+ (isCcCompatible
+ ? labels.ccCompatibleName
+ : isAnthropicCompatible
+ ? labels.anthropicCompatibleName
+ : labels.openAiCompatibleName),
+ color: isCcCompatible ? "#B45309" : isAnthropicCompatible ? "#D97757" : "#10A37F",
+ textIcon: isCcCompatible ? "CC" : isAnthropicCompatible ? "AC" : "OC",
+ apiType: providerNode.apiType || undefined,
+ baseUrl: providerNode.baseUrl || undefined,
+ type: providerNode.type,
+ category: "compatible",
+ displayAuthType: "compatible",
+ toggleAuthType: "apikey",
+ isCompatible: true,
+ };
+}
+
+export function resolveProviderCatalogEntry(
+ providerId: string,
+ options?: {
+ providerNode?: CompatibleProviderNodeLike | null;
+ compatibleLabels?: CompatibleProviderLabels | null;
+ }
+): ResolvedProviderCatalogEntry | null {
+ if (options?.providerNode && options.compatibleLabels) {
+ return resolveCompatibleProviderCatalogEntry(options.providerNode, options.compatibleLabels);
+ }
+
+ return resolveStaticProviderCatalogEntry(providerId);
+}
diff --git a/src/lib/providers/validation.ts b/src/lib/providers/validation.ts
index 55824b5235..d1af78a9b6 100644
--- a/src/lib/providers/validation.ts
+++ b/src/lib/providers/validation.ts
@@ -1171,6 +1171,86 @@ async function validateGrokWebProvider({ apiKey, providerSpecificData = {} }: an
}
}
+async function validatePerplexityWebProvider({ apiKey, providerSpecificData = {} }: any) {
+ try {
+ let sessionToken = apiKey;
+ let bearerToken: string | null = null;
+
+ if (sessionToken.startsWith("__Secure-next-auth.session-token=")) {
+ sessionToken = sessionToken.slice("__Secure-next-auth.session-token=".length);
+ } else if (/^bearer\s+/i.test(sessionToken)) {
+ bearerToken = sessionToken.replace(/^bearer\s+/i, "").trim();
+ sessionToken = "";
+ }
+
+ const timezone =
+ typeof Intl !== "undefined" ? Intl.DateTimeFormat().resolvedOptions().timeZone : "UTC";
+ const headers = applyCustomUserAgent(
+ {
+ "Content-Type": "application/json",
+ Accept: "text/event-stream",
+ Origin: "https://www.perplexity.ai",
+ Referer: "https://www.perplexity.ai/",
+ "User-Agent":
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
+ "X-App-ApiClient": "default",
+ "X-App-ApiVersion": "client-1.11.0",
+ ...(bearerToken
+ ? { Authorization: `Bearer ${bearerToken}` }
+ : sessionToken
+ ? { Cookie: `__Secure-next-auth.session-token=${sessionToken}` }
+ : {}),
+ },
+ providerSpecificData
+ );
+
+ const response = await validationWrite("https://www.perplexity.ai/rest/sse/perplexity_ask", {
+ method: "POST",
+ headers,
+ body: JSON.stringify({
+ query_str: "test",
+ params: {
+ query_str: "test",
+ search_focus: "internet",
+ mode: "concise",
+ model_preference: "default",
+ sources: ["web"],
+ attachments: [],
+ frontend_uuid: crypto.randomUUID(),
+ frontend_context_uuid: crypto.randomUUID(),
+ version: "client-1.11.0",
+ language: "en-US",
+ timezone,
+ search_recency_filter: null,
+ is_incognito: true,
+ use_schematized_api: true,
+ last_backend_uuid: null,
+ },
+ }),
+ });
+
+ if (response.status === 401 || response.status === 403) {
+ return {
+ valid: false,
+ error:
+ "Invalid Perplexity session cookie — re-paste __Secure-next-auth.session-token from perplexity.ai",
+ };
+ }
+
+ if (response.ok || (response.status >= 400 && response.status < 500)) {
+ return { valid: true, error: null };
+ }
+
+ if (response.status >= 500) {
+ return { valid: false, error: `Perplexity unavailable (${response.status})` };
+ }
+
+ return { valid: false, error: `Validation failed: ${response.status}` };
+ } catch (error: any) {
+ return toValidationErrorResult(error);
+ }
+}
+
export async function validateProviderApiKey({ provider, apiKey, providerSpecificData = {} }: any) {
const requiresApiKey = provider !== "searxng-search";
if (!provider || (requiresApiKey && !apiKey)) {
@@ -1211,6 +1291,7 @@ export async function validateProviderApiKey({ provider, apiKey, providerSpecifi
snowflake: validateSnowflakeProvider,
gigachat: validateGigachatProvider,
"grok-web": validateGrokWebProvider,
+ "perplexity-web": validatePerplexityWebProvider,
vertex: async ({ apiKey }: any) => {
try {
const { parseSAFromApiKey, getAccessToken } =
diff --git a/src/lib/tokenHealthCheck.ts b/src/lib/tokenHealthCheck.ts
index 4522aa38a8..9f62d90cea 100644
--- a/src/lib/tokenHealthCheck.ts
+++ b/src/lib/tokenHealthCheck.ts
@@ -31,6 +31,19 @@ const EXPIRED_RETRY_BACKOFF_MIN = 5; // backoff between expired retries (minutes
const LOG_PREFIX = "[HealthCheck]";
const TRUE_ENV_VALUES = new Set(["1", "true", "yes", "on"]);
+function isBuildProcess(): boolean {
+ return typeof process !== "undefined" && process.env.NEXT_PHASE === "phase-production-build";
+}
+
+function isAutomatedTestProcess(): boolean {
+ return (
+ typeof process !== "undefined" &&
+ (process.env.NODE_ENV === "test" ||
+ process.env.VITEST !== undefined ||
+ process.argv.some((arg) => arg.includes("test")))
+ );
+}
+
function getConnectionLogLabel(conn: { name?: string; email?: string; id?: string }): string {
return pickMaskedDisplayValue([conn.name, conn.email], conn.id || "-");
}
@@ -74,7 +87,11 @@ function isEnvFlagEnabled(name: string): boolean {
}
function isHealthCheckDisabled(): boolean {
- return isEnvFlagEnabled("OMNIROUTE_DISABLE_TOKEN_HEALTHCHECK") || process.env.NODE_ENV === "test";
+ return (
+ isEnvFlagEnabled("OMNIROUTE_DISABLE_TOKEN_HEALTHCHECK") ||
+ isBuildProcess() ||
+ isAutomatedTestProcess()
+ );
}
// ── Logging helper ───────────────────────────────────────────────────────────
@@ -84,7 +101,11 @@ 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") {
+ if (
+ isEnvFlagEnabled("OMNIROUTE_HIDE_HEALTHCHECK_LOGS") ||
+ isBuildProcess() ||
+ isAutomatedTestProcess()
+ ) {
return true;
}
diff --git a/src/proxy.ts b/src/proxy.ts
index 34fab99a1f..ffc4f92b7c 100644
--- a/src/proxy.ts
+++ b/src/proxy.ts
@@ -100,6 +100,7 @@ export async function proxy(request: any) {
// Verify authentication (JWT cookie or Bearer API key)
const authError = await verifyAuth(request);
if (authError) {
+ const status = authError === "Invalid management token" ? 403 : 401;
return NextResponse.json(
{
error: {
@@ -108,7 +109,7 @@ export async function proxy(request: any) {
correlation_id: requestId,
},
},
- { status: 401 }
+ { status }
);
}
}
diff --git a/src/shared/components/Footer.tsx b/src/shared/components/Footer.tsx
index fa98f22bc9..722b5cc7cc 100644
--- a/src/shared/components/Footer.tsx
+++ b/src/shared/components/Footer.tsx
@@ -3,7 +3,7 @@
import { useTranslations } from "next-intl";
import Link from "next/link";
-import { APP_CONFIG } from "@/shared/constants/config";
+import { APP_CONFIG } from "@/shared/constants/appConfig";
const footerLinks = {
product: [
diff --git a/src/shared/components/ProviderIcon.tsx b/src/shared/components/ProviderIcon.tsx
index eddf45fcf8..ef561fb77d 100644
--- a/src/shared/components/ProviderIcon.tsx
+++ b/src/shared/components/ProviderIcon.tsx
@@ -33,8 +33,10 @@ const LOBEHUB_PROVIDER_MAP: Record<string, string> = {
cohere: "cohere",
perplexity: "perplexity",
"perplexity-search": "perplexity",
+ "perplexity-web": "perplexity",
xai: "xai",
grok: "xai",
+ "grok-web": "xai",
together: "together",
fireworks: "fireworks",
"fireworks-ai": "fireworks",
diff --git a/src/shared/components/Sidebar.tsx b/src/shared/components/Sidebar.tsx
index 098878eb98..5e59ff549b 100644
--- a/src/shared/components/Sidebar.tsx
+++ b/src/shared/components/Sidebar.tsx
@@ -6,7 +6,7 @@ import Link from "next/link";
import { usePathname } from "next/navigation";
import { cn } from "@/shared/utils/cn";
import { getActiveSidebarHref } from "@/shared/utils/sidebarRouteMatch";
-import { APP_CONFIG } from "@/shared/constants/config";
+import { APP_CONFIG } from "@/shared/constants/appConfig";
import OmniRouteLogo from "./OmniRouteLogo";
import Button from "./Button";
import { ConfirmModal } from "./Modal";
diff --git a/src/shared/constants/appConfig.ts b/src/shared/constants/appConfig.ts
new file mode 100644
index 0000000000..f73868a70e
--- /dev/null
+++ b/src/shared/constants/appConfig.ts
@@ -0,0 +1,12 @@
+import pkg from "../../../package.json" with { type: "json" };
+
+export const APP_CONFIG = {
+ name: "OmniRoute",
+ description: "AI Gateway for Multi-Provider LLMs",
+ version: pkg.version,
+};
+
+export const THEME_CONFIG = {
+ storageKey: "theme",
+ defaultTheme: "system",
+};
diff --git a/src/shared/constants/config.ts b/src/shared/constants/config.ts
index 4d156c78fd..9b5df09757 100644
--- a/src/shared/constants/config.ts
+++ b/src/shared/constants/config.ts
@@ -1,17 +1,4 @@
-import pkg from "../../../package.json" with { type: "json" };
-
-// App configuration
-export const APP_CONFIG = {
- name: "OmniRoute",
- description: "AI Gateway for Multi-Provider LLMs",
- version: pkg.version,
-};
-
-// Theme configuration
-export const THEME_CONFIG = {
- storageKey: "theme",
- defaultTheme: "system", // "light" | "dark" | "system"
-};
+export { APP_CONFIG, THEME_CONFIG } from "./appConfig";
// Subscription
export const SUBSCRIPTION_CONFIG = {
diff --git a/src/shared/constants/providers.ts b/src/shared/constants/providers.ts
index d8497fea38..82f480a507 100644
--- a/src/shared/constants/providers.ts
+++ b/src/shared/constants/providers.ts
@@ -75,6 +75,16 @@ export const WEB_COOKIE_PROVIDERS = {
authHint: "Paste your sso= cookie value from grok.com",
passthroughModels: true,
},
+ "perplexity-web": {
+ id: "perplexity-web",
+ alias: "pplx-web",
+ name: "Perplexity Web (Pro/Max)",
+ icon: "search",
+ color: "#20808D",
+ textIcon: "PW",
+ website: "https://www.perplexity.ai",
+ authHint: "Paste your __Secure-next-auth.session-token cookie value from perplexity.ai",
+ },
};
// API Key Providers
@@ -239,17 +249,6 @@ export const APIKEY_PROVIDERS = {
textIcon: "XA",
website: "https://x.ai",
},
- "grok-web": {
- id: "grok-web",
- alias: "grok-web",
- name: "Grok Web (Subscription)",
- icon: "auto_awesome",
- color: "#1DA1F2",
- textIcon: "GW",
- website: "https://grok.com",
- authHint:
- "Paste your sso cookie value from grok.com (found in browser DevTools → Cookies → sso)",
- },
mistral: {
id: "mistral",
alias: "mistral",
diff --git a/src/shared/services/cloudSyncScheduler.ts b/src/shared/services/cloudSyncScheduler.ts
index 84becf0ae1..d56e5cd237 100644
--- a/src/shared/services/cloudSyncScheduler.ts
+++ b/src/shared/services/cloudSyncScheduler.ts
@@ -44,9 +44,10 @@ export class CloudSyncScheduler {
await this.initializeMachineId();
// Delay first sync by 30 seconds to ensure server is ready
- setTimeout(() => {
+ const startupTimer = setTimeout(() => {
this.syncWithRetry().catch(() => {});
}, 30000);
+ startupTimer.unref?.();
// Then sync periodically
this.intervalId = setInterval(
@@ -55,6 +56,7 @@ export class CloudSyncScheduler {
},
this.intervalMinutes * 60 * 1000
);
+ this.intervalId.unref?.();
}
/**
diff --git a/src/shared/utils/apiAuth.ts b/src/shared/utils/apiAuth.ts
index 92055d8a28..c5c5038a45 100644
--- a/src/shared/utils/apiAuth.ts
+++ b/src/shared/utils/apiAuth.ts
@@ -1,8 +1,8 @@
/**
- * API Authentication Guard — Shared utility for protecting management API routes.
+ * API Authentication Guard — Shared utility for protecting 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.
+ * Management APIs require a dashboard session, while client-facing APIs may still
+ * accept Bearer API keys. Route scope is inferred from the request pathname.
*
* @module shared/utils/apiAuth
*/
@@ -12,41 +12,156 @@ import { cookies } from "next/headers";
import { getSettings } from "@/lib/localDb";
import { isPublicApiRoute } from "@/shared/constants/publicApiRoutes";
+type RequestLike = {
+ cookies?: {
+ get?: (name: string) => { value?: string } | undefined;
+ };
+ headers?: Headers;
+ method?: string;
+ nextUrl?: { pathname?: string | null } | null;
+ url?: string;
+};
+
+function getRequestPathname(request: RequestLike | Request | null | undefined): string | null {
+ const nextPathname =
+ request &&
+ typeof request === "object" &&
+ "nextUrl" in request &&
+ request.nextUrl &&
+ typeof request.nextUrl.pathname === "string"
+ ? request.nextUrl.pathname
+ : null;
+
+ if (nextPathname) return nextPathname;
+
+ const rawUrl =
+ request && typeof request === "object" && "url" in request && typeof request.url === "string"
+ ? request.url
+ : "";
+
+ if (!rawUrl) return null;
+
+ try {
+ return new URL(rawUrl, "http://localhost").pathname;
+ } catch {
+ return null;
+ }
+}
+
+function getRequestMethod(request: RequestLike | Request | null | undefined): string {
+ if (
+ request &&
+ typeof request === "object" &&
+ "method" in request &&
+ typeof request.method === "string"
+ ) {
+ return request.method.toUpperCase();
+ }
+ return "GET";
+}
+
+function getCookieValueFromHeader(headers: Headers | undefined, name: string): string | null {
+ const cookieHeader = headers?.get("cookie") || headers?.get("Cookie");
+ if (!cookieHeader) return null;
+
+ for (const segment of cookieHeader.split(";")) {
+ const [rawKey, ...rawValue] = segment.split("=");
+ if (!rawKey || rawValue.length === 0) continue;
+ if (rawKey.trim() !== name) continue;
+ return rawValue.join("=").trim();
+ }
+
+ return null;
+}
+
+function getBearerToken(request: RequestLike | Request | null | undefined): string | null {
+ const headers =
+ request && typeof request === "object" && "headers" in request ? request.headers : undefined;
+ const authHeader = headers?.get("authorization") || headers?.get("Authorization");
+ if (typeof authHeader !== "string") return null;
+
+ const trimmedHeader = authHeader.trim();
+ if (!trimmedHeader.toLowerCase().startsWith("bearer ")) return null;
+ return trimmedHeader.slice(7).trim() || null;
+}
+
+async function validateBearerApiKey(apiKey: string | null): Promise<boolean> {
+ if (!apiKey) return false;
+
+ try {
+ const { validateApiKey } = await import("@/lib/db/apiKeys");
+ return await validateApiKey(apiKey);
+ } catch {
+ return false;
+ }
+}
+
+export function isManagementApiRequest(request: RequestLike | Request): boolean {
+ const pathname = getRequestPathname(request);
+ if (!pathname?.startsWith("/api/")) return false;
+ if (pathname.startsWith("/api/v1/")) return false;
+ return !isPublicApiRoute(pathname, getRequestMethod(request));
+}
+
+export async function isDashboardSessionAuthenticated(
+ request?: RequestLike | Request | null
+): Promise<boolean> {
+ if (!process.env.JWT_SECRET) return false;
+
+ let token =
+ request &&
+ typeof request === "object" &&
+ "cookies" in request &&
+ request.cookies?.get?.("auth_token")?.value
+ ? request.cookies.get("auth_token")?.value || null
+ : null;
+
+ const requestHeaders =
+ request && typeof request === "object" && "headers" in request ? request.headers : undefined;
+
+ if (!token) {
+ token = getCookieValueFromHeader(requestHeaders, "auth_token");
+ }
+
+ if (!token) {
+ try {
+ const cookieStore = await cookies();
+ token = cookieStore.get("auth_token")?.value || null;
+ } catch {
+ token = null;
+ }
+ }
+
+ if (!token) return false;
+
+ try {
+ const secret = new TextEncoder().encode(process.env.JWT_SECRET);
+ await jwtVerify(token, secret);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
// ──────────────── Auth Verification ────────────────
/**
- * Check if a request is authenticated via JWT cookie or Bearer API key.
+ * Check if a request is authenticated.
*
* @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
- }
+ if (await isDashboardSessionAuthenticated(request)) {
+ return null;
}
- // 2. Check Bearer API key
- const authHeader = request.headers.get("authorization") || request.headers.get("Authorization");
- if (typeof authHeader === "string") {
- const trimmedHeader = authHeader.trim();
- if (trimmedHeader.toLowerCase().startsWith("bearer ")) {
- const apiKey = trimmedHeader.slice(7).trim();
- 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
- }
- }
+ const bearerToken = getBearerToken(request);
+ if (isManagementApiRequest(request)) {
+ return bearerToken ? "Invalid management token" : "Authentication required";
+ }
+
+ if (await validateBearerApiKey(bearerToken)) {
+ return null;
}
return "Authentication required";
@@ -66,37 +181,16 @@ export async function isAuthenticated(request: Request): Promise<boolean> {
if (!(await isAuthRequired())) {
return true;
}
- // 1. Check API key (for external clients)
- const authHeader = request.headers.get("authorization") || request.headers.get("Authorization");
- if (typeof authHeader === "string") {
- const trimmedHeader = authHeader.trim();
- if (trimmedHeader.toLowerCase().startsWith("bearer ")) {
- const apiKey = trimmedHeader.slice(7).trim();
- try {
- const { validateApiKey } = await import("@/lib/db/apiKeys");
- if (await validateApiKey(apiKey)) return true;
- } catch {
- // DB not ready or import error
- }
- }
+
+ if (await isDashboardSessionAuthenticated(request)) {
+ return true;
}
- // 2. Check JWT cookie (for dashboard session)
- if (process.env.JWT_SECRET) {
- try {
- const cookieStore = await cookies();
- const token = cookieStore.get("auth_token")?.value;
- if (token) {
- const secret = new TextEncoder().encode(process.env.JWT_SECRET);
- await jwtVerify(token, secret);
- return true;
- }
- } catch {
- // Invalid/expired token or cookies not available
- }
+ if (isManagementApiRequest(request)) {
+ return false;
}
- return false;
+ return validateBearerApiKey(getBearerToken(request));
}
/**
diff --git a/src/store/themeStore.ts b/src/store/themeStore.ts
index 9262707f42..fee84b30e5 100644
--- a/src/store/themeStore.ts
+++ b/src/store/themeStore.ts
@@ -2,7 +2,7 @@
import { create } from "zustand";
import { persist } from "zustand/middleware";
-import { THEME_CONFIG } from "@/shared/constants/config";
+import { THEME_CONFIG } from "@/shared/constants/appConfig";
interface ThemeState {
theme: string;
diff --git a/tests/helpers/managementSession.ts b/tests/helpers/managementSession.ts
new file mode 100644
index 0000000000..98899fbd7f
--- /dev/null
+++ b/tests/helpers/managementSession.ts
@@ -0,0 +1,64 @@
+import { SignJWT } from "jose";
+
+export const TEST_MANAGEMENT_JWT_SECRET = "test-management-jwt-secret";
+
+function appendCookie(existingCookieHeader: string | null, cookie: string): string {
+ if (!existingCookieHeader) return cookie;
+ return `${existingCookieHeader}; ${cookie}`;
+}
+
+export async function createManagementSessionToken(
+ secret = process.env.JWT_SECRET || TEST_MANAGEMENT_JWT_SECRET
+): Promise<string> {
+ process.env.JWT_SECRET = secret;
+
+ return new SignJWT({ authenticated: true })
+ .setProtectedHeader({ alg: "HS256" })
+ .setIssuedAt()
+ .setExpirationTime("1h")
+ .sign(new TextEncoder().encode(secret));
+}
+
+export async function createManagementSessionHeaders(headers?: HeadersInit): Promise<Headers> {
+ const requestHeaders = new Headers(headers);
+ const token = await createManagementSessionToken();
+ requestHeaders.set("cookie", appendCookie(requestHeaders.get("cookie"), `auth_token=${token}`));
+ return requestHeaders;
+}
+
+export async function makeManagementSessionRequest(
+ url: string,
+ options: {
+ method?: string;
+ token?: string;
+ headers?: HeadersInit;
+ body?: BodyInit | Record<string, unknown> | unknown[] | number | boolean | null;
+ } = {}
+): Promise<Request> {
+ const { method = "GET", token, headers, body } = options;
+ const requestHeaders = await createManagementSessionHeaders(headers);
+
+ if (token) {
+ requestHeaders.set("authorization", `Bearer ${token}`);
+ }
+
+ const isFormData = typeof FormData !== "undefined" && body instanceof FormData;
+ const isUrlSearchParams =
+ typeof URLSearchParams !== "undefined" && body instanceof URLSearchParams;
+ const isStringBody = typeof body === "string";
+ const shouldSerializeJson =
+ body !== undefined && !isFormData && !isUrlSearchParams && !isStringBody;
+
+ if (body !== undefined && !requestHeaders.has("content-type") && !isFormData) {
+ requestHeaders.set(
+ "content-type",
+ isUrlSearchParams ? "application/x-www-form-urlencoded;charset=UTF-8" : "application/json"
+ );
+ }
+
+ return new Request(url, {
+ method,
+ headers: requestHeaders,
+ body: shouldSerializeJson ? JSON.stringify(body) : body,
+ });
+}
diff --git a/tests/integration/api-keys.test.ts b/tests/integration/api-keys.test.ts
index 960c310e83..706f7dc1c1 100644
--- a/tests/integration/api-keys.test.ts
+++ b/tests/integration/api-keys.test.ts
@@ -3,6 +3,7 @@ import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
+import { makeManagementSessionRequest } from "../helpers/managementSession.ts";
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-api-keys-route-"));
process.env.DATA_DIR = TEST_DATA_DIR;
@@ -109,11 +110,10 @@ test("API keys POST also requires management auth when login protection is enabl
test("POST /api/keys creates a key, preserves special characters, and persists noLog", async () => {
await enableManagementAuth();
- const authKey = await createManagementKey();
+ await createManagementKey();
const response = await listRoute.POST(
- makeRequest("http://localhost/api/keys", {
+ await makeManagementSessionRequest("http://localhost/api/keys", {
method: "POST",
- token: authKey.key,
body: { name: "Key / Prod #1", noLog: true },
})
);
@@ -130,19 +130,17 @@ test("POST /api/keys creates a key, preserves special characters, and persists n
test("POST /api/keys validates missing and oversized names", async () => {
await enableManagementAuth();
- const authKey = await createManagementKey();
+ await createManagementKey();
const missingName = await listRoute.POST(
- makeRequest("http://localhost/api/keys", {
+ await makeManagementSessionRequest("http://localhost/api/keys", {
method: "POST",
- token: authKey.key,
body: {},
})
);
const oversizedName = await listRoute.POST(
- makeRequest("http://localhost/api/keys", {
+ await makeManagementSessionRequest("http://localhost/api/keys", {
method: "POST",
- token: authKey.key,
body: { name: "x".repeat(201) },
})
);
@@ -153,15 +151,12 @@ test("POST /api/keys validates missing and oversized names", async () => {
test("POST /api/keys returns a server error for malformed JSON payloads", async () => {
await enableManagementAuth();
- const authKey = await createManagementKey();
+ await createManagementKey();
const response = await listRoute.POST(
- new Request("http://localhost/api/keys", {
+ await makeManagementSessionRequest("http://localhost/api/keys", {
method: "POST",
- headers: {
- authorization: `Bearer ${authKey.key}`,
- "content-type": "application/json",
- },
+ headers: { "content-type": "application/json" },
body: "{",
})
);
@@ -173,17 +168,15 @@ test("POST /api/keys returns a server error for malformed JSON payloads", async
test("GET /api/keys lists masked keys with pagination and GET /api/keys/[id] stays masked", async () => {
await enableManagementAuth();
- const authKey = await createManagementKey();
+ await createManagementKey();
const createdA = await apiKeysDb.createApiKey("Alpha", MACHINE_ID);
const createdB = await apiKeysDb.createApiKey("Beta", MACHINE_ID);
const listResponse = await listRoute.GET(
- makeRequest("http://localhost/api/keys?limit=1&offset=1", {
- token: authKey.key,
- })
+ await makeManagementSessionRequest("http://localhost/api/keys?limit=1&offset=1")
);
const getResponse = await keyRoute.GET(
- makeRequest(`http://localhost/api/keys/${createdB.id}`, { token: authKey.key }),
+ await makeManagementSessionRequest(`http://localhost/api/keys/${createdB.id}`),
{ params: Promise.resolve({ id: createdB.id }) }
);
@@ -205,14 +198,12 @@ test("GET /api/keys lists masked keys with pagination and GET /api/keys/[id] sta
test("GET /api/keys falls back to default pagination for invalid query params", async () => {
await enableManagementAuth();
- const authKey = await createManagementKey();
+ await createManagementKey();
await apiKeysDb.createApiKey("Alpha", MACHINE_ID);
await apiKeysDb.createApiKey("Beta", MACHINE_ID);
const response = await listRoute.GET(
- makeRequest("http://localhost/api/keys?limit=0&offset=-25", {
- token: authKey.key,
- })
+ await makeManagementSessionRequest("http://localhost/api/keys?limit=0&offset=-25")
);
const body = await response.json();
@@ -224,14 +215,12 @@ test("GET /api/keys falls back to default pagination for invalid query params",
test("GET /api/keys treats non-numeric pagination params as defaults", async () => {
await enableManagementAuth();
- const authKey = await createManagementKey();
+ await createManagementKey();
await apiKeysDb.createApiKey("Alpha", MACHINE_ID);
await apiKeysDb.createApiKey("Beta", MACHINE_ID);
const response = await listRoute.GET(
- makeRequest("http://localhost/api/keys?limit=abc&offset=xyz", {
- token: authKey.key,
- })
+ await makeManagementSessionRequest("http://localhost/api/keys?limit=abc&offset=xyz")
);
const body = await response.json();
@@ -252,9 +241,7 @@ test("GET /api/keys uses default pagination when query params are absent and rep
const createdB = await apiKeysDb.createApiKey("Beta", MACHINE_ID);
const response = await listRoute.GET(
- makeRequest("http://localhost/api/keys", {
- token: authKey.key,
- })
+ await makeManagementSessionRequest("http://localhost/api/keys")
);
const body = await response.json();
@@ -272,7 +259,7 @@ test("GET /api/keys uses default pagination when query params are absent and rep
test("POST /api/keys triggers cloud sync when cloud mode is enabled", async () => {
await enableManagementAuth();
await localDb.updateSettings({ cloudEnabled: true });
- const authKey = await createManagementKey();
+ await createManagementKey();
const originalFetch = globalThis.fetch;
const calls = [];
globalThis.fetch = async (url, options = {}) => {
@@ -282,9 +269,8 @@ test("POST /api/keys triggers cloud sync when cloud mode is enabled", async () =
try {
const response = await listRoute.POST(
- makeRequest("http://localhost/api/keys", {
+ await makeManagementSessionRequest("http://localhost/api/keys", {
method: "POST",
- token: authKey.key,
body: { name: "Cloud Synced Key" },
})
);
@@ -338,7 +324,7 @@ test("GET /api/keys returns 500 when the key store throws unexpectedly", async (
test("POST /api/keys still succeeds when cloud sync fails after creation", async () => {
await enableManagementAuth();
await localDb.updateSettings({ cloudEnabled: true });
- const authKey = await createManagementKey();
+ await createManagementKey();
const originalFetch = globalThis.fetch;
let syncAttempts = 0;
@@ -349,9 +335,8 @@ test("POST /api/keys still succeeds when cloud sync fails after creation", async
try {
const response = await listRoute.POST(
- makeRequest("http://localhost/api/keys", {
+ await makeManagementSessionRequest("http://localhost/api/keys", {
method: "POST",
- token: authKey.key,
body: { name: "Cloud Failure Tolerated" },
})
);
@@ -369,21 +354,21 @@ test("POST /api/keys still succeeds when cloud sync fails after creation", async
test("GET /api/keys/[id] returns 404 for an unknown key and reveal is gated by the feature flag", async () => {
await enableManagementAuth();
- const authKey = await createManagementKey();
+ await createManagementKey();
const created = await apiKeysDb.createApiKey("Reveal Target", MACHINE_ID);
const missingResponse = await keyRoute.GET(
- makeRequest("http://localhost/api/keys/missing", { token: authKey.key }),
+ await makeManagementSessionRequest("http://localhost/api/keys/missing"),
{ params: Promise.resolve({ id: "missing" }) }
);
const revealDisabled = await revealRoute.GET(
- makeRequest(`http://localhost/api/keys/${created.id}/reveal`, { token: authKey.key }),
+ await makeManagementSessionRequest(`http://localhost/api/keys/${created.id}/reveal`),
{ params: Promise.resolve({ id: created.id }) }
);
process.env.ALLOW_API_KEY_REVEAL = "true";
const revealEnabled = await revealRoute.GET(
- makeRequest(`http://localhost/api/keys/${created.id}/reveal`, { token: authKey.key }),
+ await makeManagementSessionRequest(`http://localhost/api/keys/${created.id}/reveal`),
{ params: Promise.resolve({ id: created.id }) }
);
@@ -401,12 +386,11 @@ test("GET /api/keys/[id] returns 404 for an unknown key and reveal is gated by t
test("PATCH /api/keys/[id] updates permissions and rejects invalid payloads", async () => {
await enableManagementAuth();
- const authKey = await createManagementKey();
+ await createManagementKey();
const created = await apiKeysDb.createApiKey("Mutable", MACHINE_ID);
const patchResponse = await keyRoute.PATCH(
- makeRequest(`http://localhost/api/keys/${created.id}`, {
+ await makeManagementSessionRequest(`http://localhost/api/keys/${created.id}`, {
method: "PATCH",
- token: authKey.key,
body: {
noLog: true,
allowedModels: ["gpt-4.1-mini"],
@@ -418,20 +402,16 @@ test("PATCH /api/keys/[id] updates permissions and rejects invalid payloads", as
{ params: Promise.resolve({ id: created.id }) }
);
const invalidJsonResponse = await keyRoute.PATCH(
- new Request(`http://localhost/api/keys/${created.id}`, {
+ await makeManagementSessionRequest(`http://localhost/api/keys/${created.id}`, {
method: "PATCH",
- headers: {
- authorization: `Bearer ${authKey.key}`,
- "content-type": "application/json",
- },
+ headers: { "content-type": "application/json" },
body: "{",
}),
{ params: Promise.resolve({ id: created.id }) }
);
const missingKeyResponse = await keyRoute.PATCH(
- makeRequest("http://localhost/api/keys/missing", {
+ await makeManagementSessionRequest("http://localhost/api/keys/missing", {
method: "PATCH",
- token: authKey.key,
body: { noLog: false },
}),
{ params: Promise.resolve({ id: "missing" }) }
@@ -457,20 +437,18 @@ test("PATCH /api/keys/[id] updates permissions and rejects invalid payloads", as
test("DELETE /api/keys/[id] removes keys and reports missing resources", async () => {
await enableManagementAuth();
- const authKey = await createManagementKey();
+ await createManagementKey();
const created = await apiKeysDb.createApiKey("Disposable", MACHINE_ID);
const deleteResponse = await keyRoute.DELETE(
- makeRequest(`http://localhost/api/keys/${created.id}`, {
+ await makeManagementSessionRequest(`http://localhost/api/keys/${created.id}`, {
method: "DELETE",
- token: authKey.key,
}),
{ params: Promise.resolve({ id: created.id }) }
);
const missingDeleteResponse = await keyRoute.DELETE(
- makeRequest("http://localhost/api/keys/missing", {
+ await makeManagementSessionRequest("http://localhost/api/keys/missing", {
method: "DELETE",
- token: authKey.key,
}),
{ params: Promise.resolve({ id: "missing" }) }
);
diff --git a/tests/integration/api-routes-critical.test.ts b/tests/integration/api-routes-critical.test.ts
index fb5846d8e3..a1f3a184e9 100644
--- a/tests/integration/api-routes-critical.test.ts
+++ b/tests/integration/api-routes-critical.test.ts
@@ -3,6 +3,7 @@ import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
+import { makeManagementSessionRequest } from "../helpers/managementSession.ts";
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-api-critical-routes-"));
process.env.DATA_DIR = TEST_DATA_DIR;
@@ -62,7 +63,7 @@ test.after(async () => {
test("critical routes: v1 management proxies covers auth, lookup, where-used, patch, and delete branches", async () => {
await enableManagementAuth();
- const authKey = await createManagementKey();
+ await createManagementKey();
const unauthenticated = await proxiesRoute.GET(
new Request("http://localhost/api/v1/management/proxies")
@@ -73,9 +74,8 @@ test("critical routes: v1 management proxies covers auth, lookup, where-used, pa
})
);
const createResponse = await proxiesRoute.POST(
- makeRequest("http://localhost/api/v1/management/proxies", {
+ await makeManagementSessionRequest("http://localhost/api/v1/management/proxies", {
method: "POST",
- token: authKey.key,
body: {
name: "Branch Proxy",
type: "http",
@@ -89,59 +89,57 @@ test("critical routes: v1 management proxies covers auth, lookup, where-used, pa
await localDb.assignProxyToScope("provider", "openai", created.id);
const getById = await proxiesRoute.GET(
- makeRequest(`http://localhost/api/v1/management/proxies?id=${created.id}`, {
- token: authKey.key,
- })
+ await makeManagementSessionRequest(
+ `http://localhost/api/v1/management/proxies?id=${created.id}`
+ )
);
const whereUsed = await proxiesRoute.GET(
- makeRequest(`http://localhost/api/v1/management/proxies?id=${created.id}&where_used=1`, {
- token: authKey.key,
- })
+ await makeManagementSessionRequest(
+ `http://localhost/api/v1/management/proxies?id=${created.id}&where_used=1`
+ )
);
const missingGet = await proxiesRoute.GET(
- makeRequest("http://localhost/api/v1/management/proxies?id=missing", { token: authKey.key })
+ await makeManagementSessionRequest("http://localhost/api/v1/management/proxies?id=missing")
);
const invalidJsonPatch = await proxiesRoute.PATCH(
- new Request("http://localhost/api/v1/management/proxies", {
+ await makeManagementSessionRequest("http://localhost/api/v1/management/proxies", {
method: "PATCH",
- headers: {
- authorization: `Bearer ${authKey.key}`,
- "content-type": "application/json",
- },
+ headers: { "content-type": "application/json" },
body: "{",
})
);
const invalidPatch = await proxiesRoute.PATCH(
- makeRequest("http://localhost/api/v1/management/proxies", {
+ await makeManagementSessionRequest("http://localhost/api/v1/management/proxies", {
method: "PATCH",
- token: authKey.key,
body: {},
})
);
const validPatch = await proxiesRoute.PATCH(
- makeRequest("http://localhost/api/v1/management/proxies", {
+ await makeManagementSessionRequest("http://localhost/api/v1/management/proxies", {
method: "PATCH",
- token: authKey.key,
body: { id: created.id, host: "patched.local", notes: "updated" },
})
);
const missingDelete = await proxiesRoute.DELETE(
- makeRequest("http://localhost/api/v1/management/proxies", {
+ await makeManagementSessionRequest("http://localhost/api/v1/management/proxies", {
method: "DELETE",
- token: authKey.key,
})
);
const conflictDelete = await proxiesRoute.DELETE(
- makeRequest(`http://localhost/api/v1/management/proxies?id=${created.id}`, {
- method: "DELETE",
- token: authKey.key,
- })
+ await makeManagementSessionRequest(
+ `http://localhost/api/v1/management/proxies?id=${created.id}`,
+ {
+ method: "DELETE",
+ }
+ )
);
const forcedDelete = await proxiesRoute.DELETE(
- makeRequest(`http://localhost/api/v1/management/proxies?id=${created.id}&force=1`, {
- method: "DELETE",
- token: authKey.key,
- })
+ await makeManagementSessionRequest(
+ `http://localhost/api/v1/management/proxies?id=${created.id}&force=1`,
+ {
+ method: "DELETE",
+ }
+ )
);
const unauthenticatedBody = await unauthenticated.json();
@@ -183,22 +181,18 @@ test("critical routes: v1 management proxies covers auth, lookup, where-used, pa
test("critical routes: v1 management proxies validates create payloads and clamps pagination", async () => {
await enableManagementAuth();
- const authKey = await createManagementKey();
+ await createManagementKey();
const invalidJsonPost = await proxiesRoute.POST(
- new Request("http://localhost/api/v1/management/proxies", {
+ await makeManagementSessionRequest("http://localhost/api/v1/management/proxies", {
method: "POST",
- headers: {
- authorization: `Bearer ${authKey.key}`,
- "content-type": "application/json",
- },
+ headers: { "content-type": "application/json" },
body: "{",
})
);
const invalidPost = await proxiesRoute.POST(
- makeRequest("http://localhost/api/v1/management/proxies", {
+ await makeManagementSessionRequest("http://localhost/api/v1/management/proxies", {
method: "POST",
- token: authKey.key,
body: {},
})
);
@@ -206,9 +200,8 @@ test("critical routes: v1 management proxies validates create payloads and clamp
const createdIds = [];
for (let index = 0; index < 3; index += 1) {
const createResponse = await proxiesRoute.POST(
- makeRequest("http://localhost/api/v1/management/proxies", {
+ await makeManagementSessionRequest("http://localhost/api/v1/management/proxies", {
method: "POST",
- token: authKey.key,
body: {
name: `Paged Proxy ${index + 1}`,
type: index % 2 === 0 ? "http" : "https",
@@ -223,21 +216,19 @@ test("critical routes: v1 management proxies validates create payloads and clamp
}
const pagedList = await proxiesRoute.GET(
- makeRequest("http://localhost/api/v1/management/proxies?limit=999&offset=-5", {
- token: authKey.key,
- })
+ await makeManagementSessionRequest(
+ "http://localhost/api/v1/management/proxies?limit=999&offset=-5"
+ )
);
const missingPatch = await proxiesRoute.PATCH(
- makeRequest("http://localhost/api/v1/management/proxies", {
+ await makeManagementSessionRequest("http://localhost/api/v1/management/proxies", {
method: "PATCH",
- token: authKey.key,
body: { id: "missing", host: "absent.local" },
})
);
const missingDelete = await proxiesRoute.DELETE(
- makeRequest("http://localhost/api/v1/management/proxies?id=missing", {
+ await makeManagementSessionRequest("http://localhost/api/v1/management/proxies?id=missing", {
method: "DELETE",
- token: authKey.key,
})
);
diff --git a/tests/integration/integration-wiring.test.ts b/tests/integration/integration-wiring.test.ts
index 18e64ef55c..a9e99a6809 100644
--- a/tests/integration/integration-wiring.test.ts
+++ b/tests/integration/integration-wiring.test.ts
@@ -216,6 +216,37 @@ describe("API Routes — T09 /v1 catalog consistency", () => {
});
});
+describe("Dashboard Wiring — T05 payload rules", () => {
+ const settingsPageSrc = readProjectFile("src/app/(dashboard)/dashboard/settings/page.tsx");
+ const payloadRulesTabSrc = readProjectFile(
+ "src/app/(dashboard)/dashboard/settings/components/PayloadRulesTab.tsx"
+ );
+ const openapiSrc = readProjectFile("docs/openapi.yaml");
+
+ it("settings page should surface payload rules inside advanced settings", () => {
+ assert.ok(settingsPageSrc, "settings page source should exist");
+ assert.match(settingsPageSrc, /import PayloadRulesTab from "\.\/components\/PayloadRulesTab"/);
+ assert.match(settingsPageSrc, /activeTab === "advanced"/);
+ assert.match(settingsPageSrc, /<PayloadRulesTab\s*\/>/);
+ });
+
+ it("payload rules tab should read and write through the dedicated settings endpoint", () => {
+ assert.ok(payloadRulesTabSrc, "payload rules tab source should exist");
+ assert.match(payloadRulesTabSrc, /fetch\("\/api\/settings\/payload-rules"\)/);
+ assert.match(payloadRulesTabSrc, /fetch\("\/api\/settings\/payload-rules",\s*\{/);
+ assert.match(payloadRulesTabSrc, /method:\s*"PUT"/);
+ assert.match(payloadRulesTabSrc, /default-raw/);
+ });
+
+ it("openapi should document the payload rules management surface", () => {
+ assert.ok(openapiSrc, "docs/openapi.yaml should exist");
+ assert.match(openapiSrc, /\/api\/settings\/payload-rules:/);
+ assert.match(openapiSrc, /summary:\s+Get payload rules configuration/);
+ assert.match(openapiSrc, /ManagementSessionAuth:/);
+ assert.match(openapiSrc, /PayloadRulesConfig:/);
+ });
+});
+
// ─── Barrel Exports ─────────────────────────────────
describe("Barrel Exports — shared/components", () => {
@@ -374,4 +405,37 @@ describe("Page Integration — provider test results privacy", () => {
/pickDisplayValue\(\s*\[r\.connectionName\],\s*emailsVisible,\s*r\.connectionName\s*\)/
);
});
+
+ it("should resolve provider detail metadata through the shared dashboard catalog", () => {
+ assert.ok(
+ providerDetailSrc,
+ "src/app/(dashboard)/dashboard/providers/[id]/page.tsx should exist"
+ );
+ assert.match(providerDetailSrc, /resolveDashboardProviderInfo/);
+ });
+
+ it("should treat upstream proxy entries as a dedicated management surface", () => {
+ assert.ok(
+ providerDetailSrc,
+ "src/app/(dashboard)/dashboard/providers/[id]/page.tsx should exist"
+ );
+ assert.match(providerDetailSrc, /isUpstreamProxyProvider/);
+ assert.match(providerDetailSrc, /Managed via Upstream Proxy Settings/);
+ });
+});
+
+describe("Page Integration — legacy provider create route retirement", () => {
+ const legacyProviderNewSrc = readProjectFile(
+ "src/app/(dashboard)/dashboard/providers/new/page.tsx"
+ );
+
+ it("should redirect legacy /dashboard/providers/new to the canonical providers flow", () => {
+ assert.ok(
+ legacyProviderNewSrc,
+ "src/app/(dashboard)/dashboard/providers/new/page.tsx should exist"
+ );
+ assert.match(legacyProviderNewSrc, /redirect\("\/dashboard\/providers"\)/);
+ assert.doesNotMatch(legacyProviderNewSrc, /authMethod:\s*"api_key"/);
+ assert.doesNotMatch(legacyProviderNewSrc, /displayName/);
+ });
});
diff --git a/tests/unit/admin-audit-events.test.ts b/tests/unit/admin-audit-events.test.ts
index 6e3d9056f5..073f6d6bf8 100644
--- a/tests/unit/admin-audit-events.test.ts
+++ b/tests/unit/admin-audit-events.test.ts
@@ -3,6 +3,7 @@ import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
+import { makeManagementSessionRequest } from "../helpers/managementSession.ts";
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-admin-audit-"));
process.env.DATA_DIR = TEST_DATA_DIR;
@@ -122,19 +123,18 @@ test("auth login route records failed password attempts", async () => {
test("provider create/update/delete routes emit sanitized credential audit events", async () => {
const createResponse = await providersRoute.POST(
- new Request("http://localhost/api/providers", {
+ await makeManagementSessionRequest("http://localhost/api/providers", {
method: "POST",
headers: {
- "content-type": "application/json",
"x-forwarded-for": "203.0.113.10",
"x-request-id": "req-provider-create",
},
- body: JSON.stringify({
+ body: {
provider: "openai",
apiKey: "sk-secret-provider-key",
name: "Primary OpenAI",
defaultModel: "gpt-4o-mini",
- }),
+ },
})
);
@@ -144,18 +144,17 @@ test("provider create/update/delete routes emit sanitized credential audit event
assert.equal(typeof connectionId, "string");
const updateResponse = await providerByIdRoute.PUT(
- new Request(`http://localhost/api/providers/${connectionId}`, {
+ await makeManagementSessionRequest(`http://localhost/api/providers/${connectionId}`, {
method: "PUT",
headers: {
- "content-type": "application/json",
"x-forwarded-for": "203.0.113.10",
"x-request-id": "req-provider-update",
},
- body: JSON.stringify({
+ body: {
name: "Primary OpenAI Updated",
defaultModel: "gpt-4.1-mini",
isActive: false,
- }),
+ },
}),
{ params: Promise.resolve({ id: connectionId }) }
);
@@ -163,7 +162,7 @@ test("provider create/update/delete routes emit sanitized credential audit event
assert.equal(updateResponse.status, 200);
const deleteResponse = await providerByIdRoute.DELETE(
- new Request(`http://localhost/api/providers/${connectionId}`, {
+ await makeManagementSessionRequest(`http://localhost/api/providers/${connectionId}`, {
method: "DELETE",
headers: {
"x-forwarded-for": "203.0.113.10",
diff --git a/tests/unit/api-auth.test.ts b/tests/unit/api-auth.test.ts
index 1c1432724a..4b1ec7540b 100644
--- a/tests/unit/api-auth.test.ts
+++ b/tests/unit/api-auth.test.ts
@@ -90,6 +90,7 @@ test("verifyAuth falls back to bearer API key validation after a bad JWT", async
},
},
headers: new Headers({ authorization: `Bearer ${key.key}` }),
+ url: "https://example.com/api/v1/models",
};
const result = await apiAuth.verifyAuth(request);
@@ -97,6 +98,21 @@ test("verifyAuth falls back to bearer API key validation after a bad JWT", async
assert.equal(result, null);
});
+test("verifyAuth rejects bearer API keys on management routes", async () => {
+ const key = await apiKeysDb.createApiKey("integration", "machine1234567890");
+ const result = await apiAuth.verifyAuth({
+ cookies: {
+ get() {
+ return undefined;
+ },
+ },
+ headers: new Headers({ authorization: `Bearer ${key.key}` }),
+ url: "https://example.com/api/providers",
+ });
+
+ assert.equal(result, "Invalid management token");
+});
+
test("verifyAuth rejects requests without valid credentials", async () => {
const result = await apiAuth.verifyAuth({
cookies: {
@@ -105,14 +121,15 @@ test("verifyAuth rejects requests without valid credentials", async () => {
},
},
headers: new Headers({ authorization: "Bearer sk-invalid" }),
+ url: "https://example.com/api/v1/models",
});
assert.equal(result, "Authentication required");
});
-test("isAuthenticated accepts bearer API keys", async () => {
+test("isAuthenticated accepts bearer API keys on client-facing routes", async () => {
const key = await apiKeysDb.createApiKey("integration", "machine1234567890");
- const request = new Request("https://example.com/api/providers", {
+ const request = new Request("https://example.com/api/v1/models", {
headers: { authorization: `Bearer ${key.key}` },
});
@@ -121,6 +138,20 @@ test("isAuthenticated accepts bearer API keys", async () => {
assert.equal(result, true);
});
+test("isAuthenticated rejects bearer API keys on management routes", async () => {
+ process.env.INITIAL_PASSWORD = "bootstrap-password";
+ await localDb.updateSettings({ requireLogin: true, password: "" });
+
+ const key = await apiKeysDb.createApiKey("integration", "machine1234567890");
+ const request = new Request("https://example.com/api/providers", {
+ headers: { authorization: `Bearer ${key.key}` },
+ });
+
+ const result = await apiAuth.isAuthenticated(request);
+
+ assert.equal(result, false);
+});
+
test("isAuthenticated returns false when auth is required without valid credentials", async () => {
// Force requireLogin to be active
process.env.INITIAL_PASSWORD = "bootstrap-password";
diff --git a/tests/unit/bailian-coding-plan-provider.test.ts b/tests/unit/bailian-coding-plan-provider.test.ts
index 6229cf5c52..b071511f51 100644
--- a/tests/unit/bailian-coding-plan-provider.test.ts
+++ b/tests/unit/bailian-coding-plan-provider.test.ts
@@ -260,8 +260,7 @@ test("getStaticModelsForProvider returns models with correct structure", () => {
});
test("getStaticModelsForProvider returns undefined for non-static providers", () => {
- // Test with providers that are NOT in STATIC_MODEL_PROVIDERS
- const nonStaticProviders = ["openai", "anthropic", "deepseek", "groq", "unknown-provider"];
+ const nonStaticProviders = ["anthropic", "deepseek", "groq", "unknown-provider"];
for (const provider of nonStaticProviders) {
const models = getStaticModelsForProvider(provider);
@@ -269,6 +268,16 @@ test("getStaticModelsForProvider returns undefined for non-static providers", ()
}
});
+test("getStaticModelsForProvider returns local image catalogs for image-capable providers", () => {
+ const models = getStaticModelsForProvider("openai");
+
+ assert.ok(models, "OpenAI should expose local image models");
+ assert.deepEqual(
+ models.map((model) => model.id),
+ ["gpt-image-1", "dall-e-3", "dall-e-2"]
+ );
+});
+
test("getStaticModelsForProvider returns models for other static providers", () => {
// Verify other static providers still work
const staticProviders = ["deepgram", "assemblyai", "nanobanana", "perplexity"];
diff --git a/tests/unit/build-next-isolated.test.ts b/tests/unit/build-next-isolated.test.ts
index 7b0cdda836..ef372eb8c6 100644
--- a/tests/unit/build-next-isolated.test.ts
+++ b/tests/unit/build-next-isolated.test.ts
@@ -5,7 +5,8 @@ import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
-const { movePath, resolveNextBuildEnv } = await import("../../scripts/build-next-isolated.mjs");
+const { getTransientBuildPaths, movePath, pruneStandaloneArtifacts, resolveNextBuildEnv } =
+ await import("../../scripts/build-next-isolated.mjs");
async function withTempDir(fn) {
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "omniroute-build-next-isolated-"));
@@ -101,3 +102,37 @@ test("resolveNextBuildEnv forces stable build worker mode unless already provide
assert.equal(preservedEnv.NEXT_PRIVATE_BUILD_WORKER, "1");
assert.equal(preservedEnv.NODE_ENV, "production");
});
+
+test("getTransientBuildPaths leaves _tasks in place by default", () => {
+ const paths = getTransientBuildPaths("/repo", {});
+
+ assert.deepEqual(
+ paths.map((entry) => entry.label),
+ ["legacy app snapshot"]
+ );
+ assert.equal(
+ paths.some((entry) => entry.sourcePath === "/repo/_tasks"),
+ false
+ );
+});
+
+test("getTransientBuildPaths only moves _tasks when explicitly enabled", () => {
+ const paths = getTransientBuildPaths("/repo", { OMNIROUTE_BUILD_MOVE_TASKS: "1" });
+
+ assert.equal(
+ paths.some((entry) => entry.sourcePath === "/repo/_tasks"),
+ true
+ );
+});
+
+test("pruneStandaloneArtifacts removes traced _tasks from standalone output", async () => {
+ await withTempDir(async (tempDir) => {
+ const tracedTaskFile = path.join(tempDir, ".next", "standalone", "_tasks", "plan.md");
+ await fs.mkdir(path.dirname(tracedTaskFile), { recursive: true });
+ await fs.writeFile(tracedTaskFile, "transient planning artifact");
+
+ await pruneStandaloneArtifacts(tempDir);
+
+ assert.equal(fsSync.existsSync(path.join(tempDir, ".next", "standalone", "_tasks")), false);
+ });
+});
diff --git a/tests/unit/db-core-init.test.ts b/tests/unit/db-core-init.test.ts
index 9e843689ee..599ccf0205 100644
--- a/tests/unit/db-core-init.test.ts
+++ b/tests/unit/db-core-init.test.ts
@@ -203,6 +203,125 @@ function createLegacyCallLogsDb(sqliteFile) {
seedDb.close();
}
+function createRecoverableDb(sqliteFile) {
+ const seedDb = new Database(sqliteFile);
+ const now = new Date().toISOString();
+ seedDb.exec(`
+ CREATE TABLE provider_connections (
+ id TEXT PRIMARY KEY,
+ provider TEXT NOT NULL,
+ auth_type TEXT,
+ name TEXT,
+ is_active INTEGER DEFAULT 1,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL
+ );
+
+ CREATE TABLE provider_nodes (
+ id TEXT PRIMARY KEY,
+ type TEXT NOT NULL,
+ name TEXT NOT NULL,
+ prefix TEXT,
+ api_type TEXT,
+ base_url TEXT,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL
+ );
+
+ CREATE TABLE key_value (
+ namespace TEXT NOT NULL,
+ key TEXT NOT NULL,
+ value TEXT NOT NULL,
+ PRIMARY KEY (namespace, key)
+ );
+
+ CREATE TABLE combos (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL UNIQUE,
+ data TEXT NOT NULL,
+ sort_order INTEGER NOT NULL DEFAULT 0,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL
+ );
+
+ CREATE TABLE api_keys (
+ id TEXT PRIMARY KEY,
+ 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
+ );
+ `);
+
+ seedDb
+ .prepare(
+ "INSERT INTO provider_connections (id, provider, auth_type, name, is_active, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)"
+ )
+ .run("recover-openai", "openai", "apikey", "Recover Me", 1, now, now);
+ seedDb
+ .prepare(
+ "INSERT INTO provider_nodes (id, type, name, prefix, api_type, base_url, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
+ )
+ .run(
+ "recover-node",
+ "custom",
+ "Recover Node",
+ "recover",
+ "openai",
+ "https://example.com",
+ now,
+ now
+ );
+ seedDb
+ .prepare("INSERT INTO key_value (namespace, key, value) VALUES (?, ?, ?)")
+ .run("settings", "globalFallbackModel", JSON.stringify("openai/gpt-4o-mini"));
+ seedDb
+ .prepare("INSERT INTO key_value (namespace, key, value) VALUES (?, ?, ?)")
+ .run("modelAliases", "fast-default", JSON.stringify("openai/gpt-4o-mini"));
+ seedDb
+ .prepare(
+ "INSERT INTO combos (id, name, data, sort_order, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)"
+ )
+ .run(
+ "recover-combo",
+ "Recover Combo",
+ JSON.stringify({
+ id: "recover-combo",
+ name: "Recover Combo",
+ models: ["openai/gpt-4o-mini"],
+ }),
+ 1,
+ now,
+ now
+ );
+ seedDb
+ .prepare(
+ "INSERT INTO api_keys (id, name, key, machine_id, allowed_models, no_log, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)"
+ )
+ .run(
+ "recover-key",
+ "Recover Key",
+ "sk-recover-key",
+ "machine-recover",
+ JSON.stringify(["openai/gpt-4o-mini"]),
+ 1,
+ now
+ );
+ seedDb.close();
+}
+
+function listProbeFailedBackups(sqliteFile) {
+ const directory = path.dirname(sqliteFile);
+ const prefix = `${path.basename(sqliteFile)}.probe-failed-`;
+ return fs
+ .readdirSync(directory)
+ .filter((name) => name.startsWith(prefix))
+ .map((name) => path.join(directory, name))
+ .sort();
+}
+
test.beforeEach(() => {
restoreEnv();
cleanupGlobalDb();
@@ -572,36 +691,119 @@ test(
seedDb.close();
try {
- await withEnv(
- { DATA_DIR: dataDir, DISABLE_SQLITE_AUTO_BACKUP: "true" },
- async () => {
- const core = await importFresh("src/lib/db/core.ts");
- const db = core.getDbInstance();
-
- assert.ok(
- db.prepare("SELECT version FROM _omniroute_migrations WHERE version = ?").get("022")
- );
- assert.ok(
- db.prepare("SELECT version FROM _omniroute_migrations WHERE version = ?").get("023")
- );
- assert.ok(
- db.prepare("SELECT version FROM _omniroute_migrations WHERE version = ?").get("026")
- );
- assert.equal(
- db
- .prepare("SELECT version FROM _omniroute_migrations WHERE version = ? AND name = ?")
- .get("022", "call_logs_cache_source"),
- undefined
- );
- assert.deepEqual(db.prepare("SELECT memory_id FROM memories").get(), { memory_id: 1 });
- assert.deepEqual(db.prepare("SELECT rowid, content FROM memory_fts").get(), {
- rowid: 1,
- content: "memory content",
- });
-
- core.resetDbInstance();
+ await withEnv({ DATA_DIR: dataDir, DISABLE_SQLITE_AUTO_BACKUP: "true" }, async () => {
+ const core = await importFresh("src/lib/db/core.ts");
+ const db = core.getDbInstance();
+
+ assert.ok(
+ db.prepare("SELECT version FROM _omniroute_migrations WHERE version = ?").get("022")
+ );
+ assert.ok(
+ db.prepare("SELECT version FROM _omniroute_migrations WHERE version = ?").get("023")
+ );
+ assert.ok(
+ db.prepare("SELECT version FROM _omniroute_migrations WHERE version = ?").get("026")
+ );
+ assert.equal(
+ db
+ .prepare("SELECT version FROM _omniroute_migrations WHERE version = ? AND name = ?")
+ .get("022", "call_logs_cache_source"),
+ undefined
+ );
+ assert.deepEqual(db.prepare("SELECT memory_id FROM memories").get(), { memory_id: 1 });
+ assert.deepEqual(db.prepare("SELECT rowid, content FROM memory_fts").get(), {
+ rowid: 1,
+ content: "memory content",
+ });
+
+ core.resetDbInstance();
+ });
+ } finally {
+ removePath(dataDir);
+ }
+ }
+);
+
+test(
+ "probe failures restore preserved critical state instead of booting with an empty database",
+ serial,
+ async () => {
+ const dataDir = makeTempDir("omniroute-db-probe-recover-");
+ const sqliteFile = path.join(dataDir, "storage.sqlite");
+ createRecoverableDb(sqliteFile);
+
+ const originalPrepare = Database.prototype.prepare;
+
+ try {
+ Database.prototype.prepare = function patchedPrepare(sql, ...args) {
+ if (String(sql).includes("schema_migrations")) {
+ throw new Error("forced probe failure");
}
- );
+ return originalPrepare.call(this, sql, ...args);
+ };
+
+ await withEnv({ DATA_DIR: dataDir }, async () => {
+ const core = await importFresh("src/lib/db/core.ts");
+ const db = core.getDbInstance();
+
+ assert.deepEqual(
+ db
+ .prepare("SELECT id, provider, name FROM provider_connections WHERE id = ?")
+ .get("recover-openai"),
+ { id: "recover-openai", provider: "openai", name: "Recover Me" }
+ );
+ assert.deepEqual(
+ db.prepare("SELECT id, name FROM provider_nodes WHERE id = ?").get("recover-node"),
+ { id: "recover-node", name: "Recover Node" }
+ );
+ assert.deepEqual(
+ db.prepare("SELECT id, name FROM combos WHERE id = ?").get("recover-combo"),
+ { id: "recover-combo", name: "Recover Combo" }
+ );
+ assert.deepEqual(
+ db.prepare("SELECT id, name, no_log FROM api_keys WHERE id = ?").get("recover-key"),
+ { id: "recover-key", name: "Recover Key", no_log: 1 }
+ );
+ assert.deepEqual(
+ db
+ .prepare("SELECT value FROM key_value WHERE namespace = 'settings' AND key = ?")
+ .get("globalFallbackModel"),
+ { value: JSON.stringify("openai/gpt-4o-mini") }
+ );
+ assert.equal(listProbeFailedBackups(sqliteFile).length >= 1, true);
+
+ core.resetDbInstance();
+ });
+ } finally {
+ Database.prototype.prepare = originalPrepare;
+ removePath(dataDir);
+ }
+ }
+);
+
+test(
+ "probe failures without a safe snapshot abort startup and keep manual recovery explicit",
+ serial,
+ async () => {
+ const dataDir = makeTempDir("omniroute-db-probe-abort-");
+ const sqliteFile = path.join(dataDir, "storage.sqlite");
+ fs.writeFileSync(sqliteFile, "not-a-valid-sqlite-database");
+
+ try {
+ await withEnv({ DATA_DIR: dataDir }, async () => {
+ const core = await importFresh("src/lib/db/core.ts");
+
+ assert.throws(() => core.getDbInstance(), /Manual recovery required after probe failure/i);
+ assert.equal(fs.existsSync(sqliteFile), false);
+ assert.equal(listProbeFailedBackups(sqliteFile).length >= 1, true);
+
+ const restartedCore = await importFresh("src/lib/db/core.ts");
+ assert.throws(
+ () => restartedCore.getDbInstance(),
+ /Manual recovery required before startup/i
+ );
+ assert.equal(fs.existsSync(sqliteFile), false);
+ });
} finally {
removePath(dataDir);
}
diff --git a/tests/unit/db-migration-runner.test.ts b/tests/unit/db-migration-runner.test.ts
index 2445598ebf..3f7746979f 100644
--- a/tests/unit/db-migration-runner.test.ts
+++ b/tests/unit/db-migration-runner.test.ts
@@ -70,6 +70,15 @@ const REAL_023_FIX_MEMORY_FTS_UUID_SQL = fs.readFileSync(
"utf8"
);
+test("migration infrastructure avoids cwd-based repo tracing fallbacks", () => {
+ const runnerSource = fs.readFileSync(path.resolve("src/lib/db/migrationRunner.ts"), "utf8");
+ const dataPathsSource = fs.readFileSync(path.resolve("src/lib/dataPaths.ts"), "utf8");
+
+ assert.doesNotMatch(runnerSource, /process\.cwd\(\)/);
+ assert.doesNotMatch(dataPathsSource, /process\.cwd\(\)/);
+ assert.match(runnerSource, /fileURLToPath\(import\.meta\.url\)/);
+});
+
test("runMigrations applies pending files sequentially in version order", serial, async () => {
const runner = await importFresh("src/lib/db/migrationRunner.ts");
const db = createDb();
@@ -524,14 +533,15 @@ test(
db.prepare("SELECT version FROM _omniroute_migrations ORDER BY version").all(),
[{ version: "021" }, { version: "022" }, { version: "023" }]
);
- assert.deepEqual(
- db.prepare("SELECT memory_id, content FROM memories").get(),
- { memory_id: 1, content: "memory content" }
- );
- assert.deepEqual(
- db.prepare("SELECT rowid, content, key FROM memory_fts").get(),
- { rowid: 1, content: "memory content", key: "topic" }
- );
+ assert.deepEqual(db.prepare("SELECT memory_id, content FROM memories").get(), {
+ memory_id: 1,
+ content: "memory content",
+ });
+ assert.deepEqual(db.prepare("SELECT rowid, content, key FROM memory_fts").get(), {
+ rowid: 1,
+ content: "memory content",
+ key: "topic",
+ });
} finally {
db.close();
}
diff --git a/tests/unit/model-alias-route.test.ts b/tests/unit/model-alias-route.test.ts
index c76f2dd722..b3b512e654 100644
--- a/tests/unit/model-alias-route.test.ts
+++ b/tests/unit/model-alias-route.test.ts
@@ -3,6 +3,7 @@ import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
+import { makeManagementSessionRequest } from "../helpers/managementSession.ts";
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-model-alias-route-"));
process.env.DATA_DIR = TEST_DATA_DIR;
@@ -10,11 +11,13 @@ process.env.JWT_SECRET = process.env.JWT_SECRET || "model-alias-route-jwt";
const core = await import("../../src/lib/db/core.ts");
const modelsDb = await import("../../src/lib/db/models.ts");
+const localDb = await import("../../src/lib/localDb.ts");
const route = await import("../../src/app/api/models/alias/route.ts");
const catalogRoute = await import("../../src/app/api/models/catalog/route.ts");
const v1Catalog = await import("../../src/app/api/v1/models/catalog.ts");
async function resetStorage() {
+ delete process.env.INITIAL_PASSWORD;
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
@@ -33,7 +36,7 @@ test("model alias route resolves a stored alias and emits diagnostics headers",
await modelsDb.setModelAlias("fast-default", "openai/gpt-4o-mini");
const response = await route.GET(
- new Request("http://localhost/api/models/alias?alias=fast-default", {
+ await makeManagementSessionRequest("http://localhost/api/models/alias?alias=fast-default", {
headers: { "x-request-id": "req-model-alias-1" },
})
);
@@ -49,7 +52,7 @@ test("model alias route resolves a stored alias and emits diagnostics headers",
test("model alias route returns typed ambiguity errors for ambiguous aliases", async () => {
const response = await route.GET(
- new Request("http://localhost/api/models/alias?alias=claude-sonnet-4-6")
+ await makeManagementSessionRequest("http://localhost/api/models/alias?alias=claude-sonnet-4-6")
);
const body = await response.json();
@@ -59,6 +62,29 @@ test("model alias route returns typed ambiguity errors for ambiguous aliases", a
assert.equal(response.headers.get("X-Model-Alias-Resolved"), "claude-sonnet-4-6");
});
+test("model alias route requires a dashboard session when management auth is enabled", async () => {
+ process.env.INITIAL_PASSWORD = "bootstrap-password";
+ await localDb.updateSettings({ requireLogin: true, password: "" });
+
+ const unauthenticated = await route.GET(
+ new Request("http://localhost/api/models/alias?alias=fast-default")
+ );
+ const invalidToken = await route.GET(
+ new Request("http://localhost/api/models/alias?alias=fast-default", {
+ headers: { authorization: "Bearer sk-invalid" },
+ })
+ );
+
+ const unauthenticatedBody = await unauthenticated.json();
+ const invalidTokenBody = await invalidToken.json();
+
+ assert.equal(unauthenticated.status, 401);
+ assert.equal(unauthenticatedBody.error.message, "Authentication required");
+ assert.equal(invalidToken.status, 403);
+ assert.equal(invalidTokenBody.error.message, "Invalid management token");
+ assert.match(unauthenticated.headers.get("X-Model-Catalog-Version") || "", /^model-metadata-v1:/);
+});
+
test("api models catalog route reuses the unified catalog diagnostics headers", async () => {
const response = await catalogRoute.GET(
new Request("http://localhost/api/models/catalog", {
diff --git a/tests/unit/model-sync-scheduler.test.ts b/tests/unit/model-sync-scheduler.test.ts
index 12e040702c..547e7dbf26 100644
--- a/tests/unit/model-sync-scheduler.test.ts
+++ b/tests/unit/model-sync-scheduler.test.ts
@@ -10,6 +10,7 @@ process.env.DATA_DIR = TEST_DATA_DIR;
const coreDb = await import("../../src/lib/db/core.ts");
const providersDb = await import("../../src/lib/db/providers.ts");
+const initCloudSync = await import("../../src/lib/initCloudSync.ts");
async function resetStorage() {
coreDb.resetDbInstance();
@@ -136,6 +137,40 @@ test("initCloudSync: startup initialization also starts model sync scheduler", (
assert.match(source, /startModelSyncScheduler\s*\(/);
});
+test("cloud sync bootstrap is wired to server startup, not app layout imports", () => {
+ const layoutSource = fs.readFileSync(path.join(process.cwd(), "src/app/layout.tsx"), "utf8");
+ const instrumentationSource = fs.readFileSync(
+ path.join(process.cwd(), "src/instrumentation-node.ts"),
+ "utf8"
+ );
+
+ assert.doesNotMatch(layoutSource, /initCloudSync/);
+ assert.match(instrumentationSource, /ensureCloudSyncInitialized/);
+});
+
+test("initCloudSync skips auto initialization during build and test processes unless explicitly re-enabled", () => {
+ assert.equal(
+ initCloudSync.shouldSkipCloudSyncInitialization({ NEXT_PHASE: "phase-production-build" }, [
+ "node",
+ ]),
+ true
+ );
+ assert.equal(
+ initCloudSync.shouldSkipCloudSyncInitialization({ NODE_ENV: "test" }, ["node", "--test"]),
+ true
+ );
+ assert.equal(
+ initCloudSync.shouldSkipCloudSyncInitialization(
+ {
+ NODE_ENV: "test",
+ OMNIROUTE_ENABLE_RUNTIME_BACKGROUND_TASKS: "1",
+ },
+ ["node", "--test"]
+ ),
+ false
+ );
+});
+
test("proxy: internal model sync token is only allowed for provider model sync routes", () => {
const filePath = path.join(process.cwd(), "src/proxy.ts");
const source = fs.readFileSync(filePath, "utf8");
diff --git a/tests/unit/modelsDevSync-extended.test.ts b/tests/unit/modelsDevSync-extended.test.ts
index 3bb1422e62..aac461f652 100644
--- a/tests/unit/modelsDevSync-extended.test.ts
+++ b/tests/unit/modelsDevSync-extended.test.ts
@@ -473,6 +473,31 @@ test("syncModelsDev string failures are normalized into an error payload", async
assert.equal(failed.dryRun, true);
});
+test("syncModelsDev honors abort signals during retry backoff", async () => {
+ const modelsDev = await importFresh("sync-abort");
+ const warnings = [];
+ const originalWarn = console.warn;
+ console.warn = (...args) => warnings.push(args.map((arg) => String(arg)).join(" "));
+ globalThis.fetch = async () => {
+ throw new Error("network down");
+ };
+
+ try {
+ const controller = new AbortController();
+ const pending = modelsDev.syncModelsDev({ signal: controller.signal, maxRetries: 3 });
+ const warned = await waitFor(() => warnings.length > 0, 100);
+ assert.ok(warned, "expected the first retry warning before aborting");
+
+ controller.abort();
+ const aborted = await pending;
+ assert.equal(aborted.success, false);
+ assert.equal(aborted.error, "aborted");
+ assert.equal(warnings.length, 1);
+ } finally {
+ console.warn = originalWarn;
+ }
+});
+
test("startPeriodicSync, stopPeriodicSync, getSyncStatus, and initModelsDevSync honor settings and avoid duplicate timers", async () => {
const modelsDev = await importFresh("periodic-sync");
mockFetchWith(MOCK_MODELS_DEV_DATA);
@@ -513,3 +538,30 @@ test("startPeriodicSync, stopPeriodicSync, getSyncStatus, and initModelsDevSync
assert.equal(enabled.getSyncStatus().intervalMs, 15);
await waitFor(() => enabled.getSyncStatus().lastSync, 300);
});
+
+test("stopPeriodicSync aborts the in-flight initial sync", async () => {
+ const modelsDev = await importFresh("periodic-stop-abort");
+ let aborted = false;
+
+ globalThis.fetch = async (_url, init) =>
+ await new Promise((_resolve, reject) => {
+ const signal = init?.signal;
+ const onAbort = () => {
+ aborted = true;
+ const error = new Error("aborted");
+ error.name = "AbortError";
+ reject(error);
+ };
+
+ signal?.addEventListener("abort", onAbort, { once: true });
+ });
+
+ modelsDev.startPeriodicSync(25);
+ await waitFor(() => modelsDev.getSyncStatus().enabled, 50);
+ modelsDev.stopPeriodicSync();
+
+ const stopped = await waitFor(() => aborted, 200);
+ assert.equal(stopped, true);
+ assert.equal(modelsDev.getSyncStatus().enabled, false);
+ assert.equal(modelsDev.getSyncStatus().lastSync, null);
+});
diff --git a/tests/unit/payload-rules-route.test.ts b/tests/unit/payload-rules-route.test.ts
new file mode 100644
index 0000000000..a846c1e441
--- /dev/null
+++ b/tests/unit/payload-rules-route.test.ts
@@ -0,0 +1,194 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { makeManagementSessionRequest } from "../helpers/managementSession.ts";
+
+const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-payload-rules-route-"));
+const ORIGINAL_DATA_DIR = process.env.DATA_DIR;
+const ORIGINAL_INITIAL_PASSWORD = process.env.INITIAL_PASSWORD;
+const ORIGINAL_JWT_SECRET = process.env.JWT_SECRET;
+
+process.env.DATA_DIR = TEST_DATA_DIR;
+
+const core = await import("../../src/lib/db/core.ts");
+const settingsDb = await import("../../src/lib/db/settings.ts");
+const route = await import("../../src/app/api/settings/payload-rules/route.ts");
+const payloadRulesService = await import("../../open-sse/services/payloadRules.ts");
+
+async function resetStorage() {
+ core.resetDbInstance();
+ payloadRulesService.resetPayloadRulesConfigForTests();
+ delete process.env.INITIAL_PASSWORD;
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+ fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
+}
+
+async function enableManagementAuth() {
+ process.env.INITIAL_PASSWORD = "bootstrap-password";
+ await settingsDb.updateSettings({ requireLogin: true, password: "" });
+}
+
+test.beforeEach(async () => {
+ await resetStorage();
+});
+
+test.after(async () => {
+ await resetStorage();
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+
+ if (ORIGINAL_DATA_DIR === undefined) {
+ delete process.env.DATA_DIR;
+ } else {
+ process.env.DATA_DIR = ORIGINAL_DATA_DIR;
+ }
+
+ if (ORIGINAL_INITIAL_PASSWORD === undefined) {
+ delete process.env.INITIAL_PASSWORD;
+ } else {
+ process.env.INITIAL_PASSWORD = ORIGINAL_INITIAL_PASSWORD;
+ }
+
+ if (ORIGINAL_JWT_SECRET === undefined) {
+ delete process.env.JWT_SECRET;
+ } else {
+ process.env.JWT_SECRET = ORIGINAL_JWT_SECRET;
+ }
+});
+
+test("payload rules route returns the neutral config by default", async () => {
+ const response = await route.GET(new Request("http://localhost/api/settings/payload-rules"));
+ const body = await response.json();
+
+ assert.equal(response.status, 200);
+ assert.deepEqual(body, {
+ default: [],
+ override: [],
+ filter: [],
+ defaultRaw: [],
+ });
+});
+
+test("payload rules route requires a dashboard session when management auth is enabled", async () => {
+ await enableManagementAuth();
+
+ const unauthenticated = await route.GET(
+ new Request("http://localhost/api/settings/payload-rules")
+ );
+ const invalidToken = await route.GET(
+ new Request("http://localhost/api/settings/payload-rules", {
+ headers: { authorization: "Bearer sk-invalid" },
+ })
+ );
+ const authenticated = await route.GET(
+ await makeManagementSessionRequest("http://localhost/api/settings/payload-rules")
+ );
+
+ const unauthenticatedBody = await unauthenticated.json();
+ const invalidTokenBody = await invalidToken.json();
+ const authenticatedBody = await authenticated.json();
+
+ assert.equal(unauthenticated.status, 401);
+ assert.equal(unauthenticatedBody.error.message, "Authentication required");
+ assert.equal(invalidToken.status, 403);
+ assert.equal(invalidTokenBody.error.message, "Invalid management token");
+ assert.equal(authenticated.status, 200);
+ assert.deepEqual(authenticatedBody, {
+ default: [],
+ override: [],
+ filter: [],
+ defaultRaw: [],
+ });
+});
+
+test("payload rules route persists normalized config and hot reloads the runtime", async () => {
+ await enableManagementAuth();
+
+ const requestBody = {
+ default: [
+ {
+ models: [{ name: "gpt-*" }],
+ params: { temperature: 0.2 },
+ },
+ ],
+ override: [
+ {
+ models: [{ name: "claude-*", protocol: "anthropic" }],
+ params: { max_tokens: 512 },
+ },
+ ],
+ filter: [
+ {
+ models: [{ name: "*", protocol: "openai" }],
+ params: ["metadata.internal"],
+ },
+ ],
+ "default-raw": [
+ {
+ models: [{ name: "gpt-4o-mini" }],
+ params: {
+ response_format: '{"type":"json_schema"}',
+ },
+ },
+ ],
+ };
+
+ const response = await route.PUT(
+ await makeManagementSessionRequest("http://localhost/api/settings/payload-rules", {
+ method: "PUT",
+ body: requestBody,
+ })
+ );
+ const body = await response.json();
+ const settings = await settingsDb.getSettings();
+ const runtimeConfig = await payloadRulesService.getPayloadRulesConfig();
+
+ assert.equal(response.status, 200);
+ assert.deepEqual(body, {
+ default: requestBody.default,
+ override: requestBody.override,
+ filter: requestBody.filter,
+ defaultRaw: requestBody["default-raw"],
+ });
+ assert.deepEqual(settings.payloadRules, body);
+ assert.deepEqual(runtimeConfig, body);
+});
+
+test("payload rules route rejects malformed and schema-invalid payloads", async () => {
+ await enableManagementAuth();
+
+ const invalidJson = await route.PUT(
+ await makeManagementSessionRequest("http://localhost/api/settings/payload-rules", {
+ method: "PUT",
+ headers: { "content-type": "application/json" },
+ body: "{",
+ })
+ );
+ const invalidSchema = await route.PUT(
+ await makeManagementSessionRequest("http://localhost/api/settings/payload-rules", {
+ method: "PUT",
+ body: {},
+ })
+ );
+
+ const invalidJsonBody = await invalidJson.json();
+ const invalidSchemaBody = await invalidSchema.json();
+ const runtimeConfig = await payloadRulesService.getPayloadRulesConfig();
+
+ assert.equal(invalidJson.status, 400);
+ assert.equal(invalidJsonBody.error.message, "Invalid request");
+ assert.deepEqual(invalidJsonBody.error.details, [
+ { field: "body", message: "Invalid JSON body" },
+ ]);
+
+ assert.equal(invalidSchema.status, 400);
+ assert.equal(invalidSchemaBody.error.message, "Invalid request");
+ assert.match(invalidSchemaBody.error.details[0].message, /No valid fields to update/);
+ assert.deepEqual(runtimeConfig, {
+ default: [],
+ override: [],
+ filter: [],
+ defaultRaw: [],
+ });
+});
diff --git a/tests/unit/provider-validation-specialty.test.ts b/tests/unit/provider-validation-specialty.test.ts
index 44a6fa7470..f0c401c562 100644
--- a/tests/unit/provider-validation-specialty.test.ts
+++ b/tests/unit/provider-validation-specialty.test.ts
@@ -83,6 +83,57 @@ test("specialty providers surface network failures and non-auth upstream failure
assert.equal(longcat.error, "longcat offline");
});
+test("web-cookie provider validators accept valid Grok and Perplexity session cookies", async () => {
+ const calls = [];
+ globalThis.fetch = async (url, init = {}) => {
+ const target = String(url);
+ calls.push({ url: target, init });
+
+ if (target.includes("grok.com/rest/app-chat/conversations/new")) {
+ return new Response(JSON.stringify({ ok: true }), { status: 400 });
+ }
+ if (target.includes("perplexity.ai/rest/sse/perplexity_ask")) {
+ return new Response(JSON.stringify({ ok: true }), { status: 200 });
+ }
+
+ throw new Error(`unexpected fetch: ${target}`);
+ };
+
+ const grok = await validateProviderApiKey({ provider: "grok-web", apiKey: "sso=grok-cookie" });
+ const perplexity = await validateProviderApiKey({
+ provider: "perplexity-web",
+ apiKey: "__Secure-next-auth.session-token=pplx-cookie",
+ });
+
+ assert.equal(grok.valid, true);
+ assert.equal(perplexity.valid, true);
+ assert.equal(calls[0].init.headers.Cookie, "sso=grok-cookie");
+ assert.equal(calls[1].init.headers.Cookie, "__Secure-next-auth.session-token=pplx-cookie");
+});
+
+test("web-cookie provider validators surface auth failures for expired session cookies", async () => {
+ globalThis.fetch = async (url) => {
+ const target = String(url);
+ if (target.includes("grok.com/rest/app-chat/conversations/new")) {
+ return new Response(JSON.stringify({ error: "unauthorized" }), { status: 401 });
+ }
+ if (target.includes("perplexity.ai/rest/sse/perplexity_ask")) {
+ return new Response(JSON.stringify({ error: "forbidden" }), { status: 403 });
+ }
+
+ throw new Error(`unexpected fetch: ${target}`);
+ };
+
+ const grok = await validateProviderApiKey({ provider: "grok-web", apiKey: "grok-cookie" });
+ const perplexity = await validateProviderApiKey({
+ provider: "perplexity-web",
+ apiKey: "pplx-cookie",
+ });
+
+ assert.match(grok.error || "", /Invalid SSO cookie/i);
+ assert.match(perplexity.error || "", /Invalid Perplexity session cookie/i);
+});
+
test("search provider validators cover success, client errors, server errors and custom user agent injection", async () => {
const calls = [];
globalThis.fetch = async (url, init = {}) => {
diff --git a/tests/unit/providers-page-utils.test.ts b/tests/unit/providers-page-utils.test.ts
index b1b89bd1d5..11bf8e49fc 100644
--- a/tests/unit/providers-page-utils.test.ts
+++ b/tests/unit/providers-page-utils.test.ts
@@ -6,6 +6,7 @@ const providerPageUtils =
const providerPageStorage =
await import("../../src/app/(dashboard)/dashboard/providers/providerPageStorage.ts");
const providers = await import("../../src/shared/constants/providers.ts");
+const providerCatalog = await import("../../src/lib/providers/catalog.ts");
test("merged OAuth providers keep free-tier providers in the OAuth section", () => {
const statsCalls = [];
@@ -106,3 +107,85 @@ test("configured-only preference storage round-trips correctly", () => {
assert.equal(storage.has(providerPageStorage.SHOW_CONFIGURED_ONLY_STORAGE_KEY), false);
assert.equal(providerPageStorage.readConfiguredOnlyPreference(mockStorage), false);
});
+
+test("static catalog entries resolve search, audio, web-cookie and upstream providers", () => {
+ const searchProvider = providerPageUtils.resolveDashboardProviderInfo("brave-search");
+ const audioProvider = providerPageUtils.resolveDashboardProviderInfo("assemblyai");
+ const webCookieProvider = providerPageUtils.resolveDashboardProviderInfo("grok-web");
+ const perplexityWebProvider = providerPageUtils.resolveDashboardProviderInfo("perplexity-web");
+ const upstreamProvider = providerPageUtils.resolveDashboardProviderInfo("cliproxyapi");
+
+ assert.equal(searchProvider?.category, "search");
+ assert.equal(searchProvider?.name, providers.SEARCH_PROVIDERS["brave-search"].name);
+
+ assert.equal(audioProvider?.category, "audio");
+ assert.equal(audioProvider?.name, providers.AUDIO_ONLY_PROVIDERS.assemblyai.name);
+
+ assert.equal(webCookieProvider?.category, "web-cookie");
+ assert.equal(webCookieProvider?.name, providers.WEB_COOKIE_PROVIDERS["grok-web"].name);
+
+ assert.equal(perplexityWebProvider?.category, "web-cookie");
+ assert.equal(perplexityWebProvider?.name, providers.WEB_COOKIE_PROVIDERS["perplexity-web"].name);
+
+ assert.equal(upstreamProvider?.category, "upstream-proxy");
+ assert.equal(
+ upstreamProvider?.name,
+ providerCatalog.STATIC_PROVIDER_CATALOG_GROUPS["upstream-proxy"].providers.cliproxyapi.name
+ );
+});
+
+test("managed provider connection ids include supported static categories and exclude upstream proxy", () => {
+ assert.equal(providerCatalog.isManagedProviderConnectionId("qoder"), true);
+ assert.equal(providerCatalog.isManagedProviderConnectionId("assemblyai"), true);
+ assert.equal(providerCatalog.isManagedProviderConnectionId("grok-web"), true);
+ assert.equal(providerCatalog.isManagedProviderConnectionId("perplexity-web"), true);
+ assert.equal(providerCatalog.isManagedProviderConnectionId("brave-search"), true);
+ assert.equal(providerCatalog.isManagedProviderConnectionId("cliproxyapi"), false);
+ assert.equal(providerCatalog.isManagedProviderConnectionId("claude"), false);
+});
+
+test("grok-web taxonomy stays web-cookie only and does not leak into api-key entries", () => {
+ assert.equal("grok-web" in providers.APIKEY_PROVIDERS, false);
+ assert.equal("grok-web" in providers.WEB_COOKIE_PROVIDERS, true);
+
+ const apiKeyEntries = providerPageUtils.buildStaticProviderEntries("apikey", () => ({
+ total: 0,
+ }));
+ const webCookieEntries = providerPageUtils.buildStaticProviderEntries("web-cookie", () => ({
+ total: 0,
+ }));
+
+ assert.equal(
+ apiKeyEntries.some((entry) => entry.providerId === "grok-web"),
+ false
+ );
+ assert.equal(
+ webCookieEntries.some((entry) => entry.providerId === "grok-web"),
+ true
+ );
+});
+
+test("compatible catalog entries keep dynamic compatible metadata", () => {
+ const compatibleProvider = providerPageUtils.resolveDashboardProviderInfo(
+ "openai-compatible-lab",
+ {
+ providerNode: {
+ id: "openai-compatible-lab",
+ type: "openai-compatible",
+ apiType: "responses",
+ baseUrl: "https://example.test",
+ },
+ compatibleLabels: {
+ ccCompatibleName: "CC Compatible",
+ anthropicCompatibleName: "Anthropic Compatible",
+ openAiCompatibleName: "OpenAI Compatible",
+ },
+ }
+ );
+
+ assert.equal(compatibleProvider?.category, "compatible");
+ assert.equal(compatibleProvider?.displayAuthType, "compatible");
+ assert.equal(compatibleProvider?.toggleAuthType, "apikey");
+ assert.equal(compatibleProvider?.apiType, "responses");
+ assert.equal(compatibleProvider?.baseUrl, "https://example.test");
+});
diff --git a/tests/unit/providers-route-managed-catalog.test.ts b/tests/unit/providers-route-managed-catalog.test.ts
new file mode 100644
index 0000000000..7268e537a8
--- /dev/null
+++ b/tests/unit/providers-route-managed-catalog.test.ts
@@ -0,0 +1,112 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { makeManagementSessionRequest } from "../helpers/managementSession.ts";
+
+const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-providers-managed-"));
+process.env.DATA_DIR = TEST_DATA_DIR;
+process.env.JWT_SECRET = "test-jwt-secret-for-managed-providers";
+process.env.INITIAL_PASSWORD = "admin-secret";
+
+const core = await import("../../src/lib/db/core.ts");
+const providersRoute = await import("../../src/app/api/providers/route.ts");
+
+function resetDb() {
+ core.resetDbInstance();
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+ fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
+}
+
+test.beforeEach(() => {
+ resetDb();
+});
+
+test.after(() => {
+ core.resetDbInstance();
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+});
+
+test("providers route accepts managed audio, web-cookie and search providers", async () => {
+ const cases = [
+ {
+ provider: "assemblyai",
+ body: {
+ provider: "assemblyai",
+ apiKey: "aa-key",
+ name: "AssemblyAI Primary",
+ },
+ },
+ {
+ provider: "grok-web",
+ body: {
+ provider: "grok-web",
+ apiKey: "sso=grok-cookie",
+ name: "Grok Web Session",
+ },
+ },
+ {
+ provider: "perplexity-web",
+ body: {
+ provider: "perplexity-web",
+ apiKey: "__Secure-next-auth.session-token=pplx-cookie",
+ name: "Perplexity Web Session",
+ },
+ },
+ {
+ provider: "google-pse-search",
+ body: {
+ provider: "google-pse-search",
+ apiKey: "google-key",
+ name: "Google PSE",
+ providerSpecificData: {
+ cx: "engine-id-123",
+ },
+ },
+ },
+ {
+ provider: "searxng-search",
+ body: {
+ provider: "searxng-search",
+ name: "Local SearXNG",
+ providerSpecificData: {
+ baseUrl: "http://localhost:8888/search",
+ },
+ },
+ },
+ ];
+
+ for (const entry of cases) {
+ const response = await providersRoute.POST(
+ await makeManagementSessionRequest("http://localhost/api/providers", {
+ method: "POST",
+ body: entry.body,
+ })
+ );
+
+ assert.equal(
+ response.status,
+ 201,
+ `${entry.provider} should be accepted by POST /api/providers`
+ );
+ const payload = await response.json();
+ assert.equal(payload.connection.provider, entry.provider);
+ }
+});
+
+test("providers route rejects upstream proxy tools as direct provider connections", async () => {
+ const response = await providersRoute.POST(
+ await makeManagementSessionRequest("http://localhost/api/providers", {
+ method: "POST",
+ body: {
+ provider: "cliproxyapi",
+ apiKey: "cpa-key",
+ name: "CLIProxyAPI",
+ },
+ })
+ );
+
+ assert.equal(response.status, 400);
+ assert.deepEqual(await response.json(), { error: "Invalid provider" });
+});
diff --git a/tests/unit/proxy-login-bootstrap-auth.test.ts b/tests/unit/proxy-login-bootstrap-auth.test.ts
index bbe8246b20..b43c403632 100644
--- a/tests/unit/proxy-login-bootstrap-auth.test.ts
+++ b/tests/unit/proxy-login-bootstrap-auth.test.ts
@@ -22,7 +22,7 @@ async function resetStorage() {
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
}
-function makeRequest(pathname, method = "GET") {
+function makeRequest(pathname, method = "GET", headers) {
return {
nextUrl: {
pathname,
@@ -34,7 +34,7 @@ function makeRequest(pathname, method = "GET") {
return undefined;
},
},
- headers: new Headers(),
+ headers: new Headers(headers),
url: `http://localhost:20128${pathname}`,
};
}
@@ -82,6 +82,25 @@ test("proxy requires auth for POST /api/settings/require-login after setup", asy
assert.equal(body.error.code, "AUTH_001");
});
+test("proxy rejects bearer tokens for POST /api/settings/require-login after setup", async () => {
+ await settingsDb.updateSettings({
+ requireLogin: true,
+ password: "hashed-password",
+ setupComplete: true,
+ });
+
+ const { proxy } = await importFreshProxy();
+ const response = await proxy(
+ makeRequest("/api/settings/require-login", "POST", {
+ authorization: "Bearer sk-invalid",
+ })
+ );
+ const body = await response.json();
+
+ assert.equal(response.status, 403);
+ assert.equal(body.error.code, "AUTH_001");
+});
+
test("proxy still allows POST /api/settings/require-login during bootstrap", async () => {
const { proxy } = await importFreshProxy();
const response = await proxy(makeRequest("/api/settings/require-login", "POST"));
diff --git a/tests/unit/route-edge-coverage.test.ts b/tests/unit/route-edge-coverage.test.ts
index 2e962c2bb2..e966536189 100644
--- a/tests/unit/route-edge-coverage.test.ts
+++ b/tests/unit/route-edge-coverage.test.ts
@@ -3,6 +3,7 @@ import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
+import { makeManagementSessionRequest } from "../helpers/managementSession.ts";
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-route-edges-"));
process.env.DATA_DIR = TEST_DATA_DIR;
@@ -139,7 +140,7 @@ test("api keys route covers auth, create, masking, pagination fallback and cloud
headers: { authorization: "Bearer sk-invalid" },
})
);
- const managementKey = await createManagementKey();
+ await createManagementKey();
const originalFetch = globalThis.fetch;
const fetchCalls = [];
@@ -152,9 +153,8 @@ test("api keys route covers auth, create, masking, pagination fallback and cloud
await localDb.updateSettings({ cloudEnabled: true });
const created = await listKeysRoute.POST(
- makeRequest("http://localhost/api/keys", {
+ await makeManagementSessionRequest("http://localhost/api/keys", {
method: "POST",
- token: managementKey.key,
body: { name: "Key / Prod #1", noLog: true },
})
);
@@ -165,9 +165,7 @@ test("api keys route covers auth, create, masking, pagination fallback and cloud
await apiKeysDb.createApiKey("Beta", MACHINE_ID);
const paged = await listKeysRoute.GET(
- makeRequest("http://localhost/api/keys?limit=0&offset=-25", {
- token: managementKey.key,
- })
+ await makeManagementSessionRequest("http://localhost/api/keys?limit=0&offset=-25")
);
const unauthenticatedBody = await unauthenticated.json();
@@ -199,23 +197,19 @@ test("api keys route covers auth, create, masking, pagination fallback and cloud
test("api keys route rejects invalid payloads and malformed JSON", async () => {
await enableManagementAuth();
- const managementKey = await createManagementKey();
+ await createManagementKey();
const missingName = await listKeysRoute.POST(
- makeRequest("http://localhost/api/keys", {
+ await makeManagementSessionRequest("http://localhost/api/keys", {
method: "POST",
- token: managementKey.key,
body: {},
})
);
const malformed = await listKeysRoute.POST(
- new Request("http://localhost/api/keys", {
+ await makeManagementSessionRequest("http://localhost/api/keys", {
method: "POST",
- headers: {
- authorization: `Bearer ${managementKey.key}`,
- "content-type": "application/json",
- },
+ headers: { "content-type": "application/json" },
body: "{",
})
);
@@ -502,7 +496,7 @@ test("settings proxy route covers default types, null maps, registry fallback, a
test("management proxies route covers auth, pagination, lookup, where-used, patch and delete flows", async () => {
await enableManagementAuth();
- const managementKey = await createManagementKey();
+ await createManagementKey();
const unauthenticated = await managementProxiesRoute.GET(
new Request("http://localhost/api/v1/management/proxies")
@@ -514,9 +508,8 @@ test("management proxies route covers auth, pagination, lookup, where-used, patc
);
const createdResponse = await managementProxiesRoute.POST(
- makeRequest("http://localhost/api/v1/management/proxies", {
+ await makeManagementSessionRequest("http://localhost/api/v1/management/proxies", {
method: "POST",
- token: managementKey.key,
body: {
name: "Branch Proxy",
type: "http",
@@ -529,66 +522,62 @@ test("management proxies route covers auth, pagination, lookup, where-used, patc
await localDb.assignProxyToScope("provider", "openai", created.id);
const pagedList = await managementProxiesRoute.GET(
- makeRequest("http://localhost/api/v1/management/proxies?limit=999&offset=-5", {
- token: managementKey.key,
- })
+ await makeManagementSessionRequest(
+ "http://localhost/api/v1/management/proxies?limit=999&offset=-5"
+ )
);
const byId = await managementProxiesRoute.GET(
- makeRequest(`http://localhost/api/v1/management/proxies?id=${created.id}`, {
- token: managementKey.key,
- })
+ await makeManagementSessionRequest(
+ `http://localhost/api/v1/management/proxies?id=${created.id}`
+ )
);
const whereUsed = await managementProxiesRoute.GET(
- makeRequest(`http://localhost/api/v1/management/proxies?id=${created.id}&where_used=1`, {
- token: managementKey.key,
- })
+ await makeManagementSessionRequest(
+ `http://localhost/api/v1/management/proxies?id=${created.id}&where_used=1`
+ )
);
const missingGet = await managementProxiesRoute.GET(
- makeRequest("http://localhost/api/v1/management/proxies?id=missing", {
- token: managementKey.key,
- })
+ await makeManagementSessionRequest("http://localhost/api/v1/management/proxies?id=missing")
);
const invalidJsonPatch = await managementProxiesRoute.PATCH(
- new Request("http://localhost/api/v1/management/proxies", {
+ await makeManagementSessionRequest("http://localhost/api/v1/management/proxies", {
method: "PATCH",
- headers: {
- authorization: `Bearer ${managementKey.key}`,
- "content-type": "application/json",
- },
+ headers: { "content-type": "application/json" },
body: "{",
})
);
const invalidPatch = await managementProxiesRoute.PATCH(
- makeRequest("http://localhost/api/v1/management/proxies", {
+ await makeManagementSessionRequest("http://localhost/api/v1/management/proxies", {
method: "PATCH",
- token: managementKey.key,
body: {},
})
);
const patched = await managementProxiesRoute.PATCH(
- makeRequest("http://localhost/api/v1/management/proxies", {
+ await makeManagementSessionRequest("http://localhost/api/v1/management/proxies", {
method: "PATCH",
- token: managementKey.key,
body: { id: created.id, host: "patched.local", notes: "updated" },
})
);
const missingDelete = await managementProxiesRoute.DELETE(
- makeRequest("http://localhost/api/v1/management/proxies", {
+ await makeManagementSessionRequest("http://localhost/api/v1/management/proxies", {
method: "DELETE",
- token: managementKey.key,
})
);
const conflictDelete = await managementProxiesRoute.DELETE(
- makeRequest(`http://localhost/api/v1/management/proxies?id=${created.id}`, {
- method: "DELETE",
- token: managementKey.key,
- })
+ await makeManagementSessionRequest(
+ `http://localhost/api/v1/management/proxies?id=${created.id}`,
+ {
+ method: "DELETE",
+ }
+ )
);
const forcedDelete = await managementProxiesRoute.DELETE(
- makeRequest(`http://localhost/api/v1/management/proxies?id=${created.id}&force=1`, {
- method: "DELETE",
- token: managementKey.key,
- })
+ await makeManagementSessionRequest(
+ `http://localhost/api/v1/management/proxies?id=${created.id}&force=1`,
+ {
+ method: "DELETE",
+ }
+ )
);
const unauthenticatedBody = await unauthenticated.json();
diff --git a/tests/unit/settings-api.test.ts b/tests/unit/settings-api.test.ts
index f636e97e40..27f7160d4e 100644
--- a/tests/unit/settings-api.test.ts
+++ b/tests/unit/settings-api.test.ts
@@ -1,5 +1,6 @@
import { describe, test } from "node:test";
import assert from "node:assert/strict";
+import { makeManagementSessionRequest } from "../helpers/managementSession.ts";
import { getSettings, updateSettings } from "../../src/lib/db/settings.ts";
const settingsRoute = await import("../../src/app/api/settings/route.ts");
@@ -81,10 +82,9 @@ describe("Settings API - debugMode and hiddenSidebarItems", () => {
test("PUT /api/settings reuses the PATCH update flow", async () => {
const response = await settingsRoute.PUT(
- new Request("http://localhost/api/settings", {
+ await makeManagementSessionRequest("http://localhost/api/settings", {
method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ antigravitySignatureCacheMode: "bypass" }),
+ body: { antigravitySignatureCacheMode: "bypass" },
})
);
const body = await response.json();
diff --git a/tests/unit/settings-route-password.test.ts b/tests/unit/settings-route-password.test.ts
index d8a030cb9c..8576d4cc86 100644
--- a/tests/unit/settings-route-password.test.ts
+++ b/tests/unit/settings-route-password.test.ts
@@ -3,6 +3,7 @@ import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
+import { makeManagementSessionRequest } from "../helpers/managementSession.ts";
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-settings-route-password-"));
process.env.DATA_DIR = TEST_DATA_DIR;
@@ -39,13 +40,12 @@ test("settings route password update requires the current INITIAL_PASSWORD after
process.env.INITIAL_PASSWORD = "bootstrap-secret";
const response = await settingsRoute.PATCH(
- new Request("http://localhost/api/settings", {
+ await makeManagementSessionRequest("http://localhost/api/settings", {
method: "PATCH",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({
+ body: {
currentPassword: "bootstrap-secret",
newPassword: "rotated-secret",
- }),
+ },
})
);
const settings = await settingsDb.getSettings();
@@ -66,13 +66,12 @@ test("settings route password update rejects the wrong current password after mi
process.env.INITIAL_PASSWORD = "bootstrap-secret";
const response = await settingsRoute.PATCH(
- new Request("http://localhost/api/settings", {
+ await makeManagementSessionRequest("http://localhost/api/settings", {
method: "PATCH",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({
+ body: {
currentPassword: "wrong-secret",
newPassword: "rotated-secret",
- }),
+ },
})
);
diff --git a/tests/unit/sync-routes.test.ts b/tests/unit/sync-routes.test.ts
index 4b1cbe9c4f..3bc1f09efa 100644
--- a/tests/unit/sync-routes.test.ts
+++ b/tests/unit/sync-routes.test.ts
@@ -3,6 +3,7 @@ import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
+import { makeManagementSessionRequest } from "../helpers/managementSession.ts";
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-sync-routes-"));
const ORIGINAL_DATA_DIR = process.env.DATA_DIR;
@@ -73,15 +74,14 @@ test("sync token routes issue, list, use and revoke dedicated tokens", async ()
const managementKey = await apiKeysDb.createApiKey("Management", "machine-sync-routes");
const createResponse = await syncTokensRoute.POST(
- new Request("http://localhost/api/sync/tokens", {
+ await makeManagementSessionRequest("http://localhost/api/sync/tokens", {
method: "POST",
+ token: managementKey.key,
headers: {
- "content-type": "application/json",
- authorization: `Bearer ${managementKey.key}`,
"x-request-id": "req-sync-token-create",
"x-forwarded-for": "198.51.100.30",
},
- body: JSON.stringify({ name: "Desktop client" }),
+ body: { name: "Desktop client" },
})
);
@@ -92,8 +92,8 @@ test("sync token routes issue, list, use and revoke dedicated tokens", async ()
assert.equal(createdBody.syncToken.syncApiKeyId, managementKey.id);
const listResponse = await syncTokensRoute.GET(
- new Request("http://localhost/api/sync/tokens", {
- headers: { authorization: `Bearer ${managementKey.key}` },
+ await makeManagementSessionRequest("http://localhost/api/sync/tokens", {
+ token: managementKey.key,
})
);
assert.equal(listResponse.status, 200);
@@ -118,8 +118,8 @@ test("sync token routes issue, list, use and revoke dedicated tokens", async ()
assert.equal(typeof bundlePayload.bundle, "object");
const secondListResponse = await syncTokensRoute.GET(
- new Request("http://localhost/api/sync/tokens", {
- headers: { authorization: `Bearer ${managementKey.key}` },
+ await makeManagementSessionRequest("http://localhost/api/sync/tokens", {
+ token: managementKey.key,
})
);
const secondListBody = await secondListResponse.json();
@@ -136,14 +136,17 @@ test("sync token routes issue, list, use and revoke dedicated tokens", async ()
assert.equal(notModifiedResponse.status, 304);
const revokeResponse = await syncTokenByIdRoute.DELETE(
- new Request(`http://localhost/api/sync/tokens/${createdBody.syncToken.id}`, {
- method: "DELETE",
- headers: {
- authorization: `Bearer ${managementKey.key}`,
- "x-request-id": "req-sync-token-revoke",
- "x-forwarded-for": "198.51.100.30",
- },
- }),
+ await makeManagementSessionRequest(
+ `http://localhost/api/sync/tokens/${createdBody.syncToken.id}`,
+ {
+ method: "DELETE",
+ token: managementKey.key,
+ headers: {
+ "x-request-id": "req-sync-token-revoke",
+ "x-forwarded-for": "198.51.100.30",
+ },
+ }
+ ),
{ params: Promise.resolve({ id: createdBody.syncToken.id }) }
);