Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 1 addition & 6 deletions config/quality/eslint-suppressions.json
Original file line number Diff line number Diff line change
Expand Up @@ -1797,11 +1797,6 @@
"count": 6
}
},
"tests/unit/provider-scoped-models-route.test.ts": {
"@typescript-eslint/no-explicit-any": {
"count": 7
}
},
"tests/unit/provider-validation-hardening.test.ts": {
"@typescript-eslint/no-explicit-any": {
"count": 6
Expand Down Expand Up @@ -2322,4 +2317,4 @@
"count": 5
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/**
* Provider Exposure toggle for CLIProxyAPI.
* Persists the `providerExpose` field via POST /api/services/cliproxy/provider-expose.
* When enabled, CLIProxyAPI models appear as `cliproxyapi/...` in OmniRoute's model selection.
*/
"use client";

import { useState } from "react";
import { Card, Toggle } from "@/shared/components";
import { useServiceStatus } from "../hooks/useServiceStatus";

const NAME = "cliproxy";

export function CliproxyProviderExposureCard() {
const { data, mutate } = useServiceStatus(NAME);
const [pending, setPending] = useState(false);
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);

async function handleToggle(enabled: boolean) {
setPending(true);
setMsg(null);
try {
const res = await fetch(`/api/services/${NAME}/provider-expose`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ enabled }),
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
const errorMsg =
body?.error?.message ?? body?.message ?? `Failed to update (HTTP ${res.status})`;
setMsg({ ok: false, text: errorMsg });
return;
}
setMsg(null);
mutate();
} catch {
setMsg({ ok: false, text: "Network error — could not update provider exposure setting" });
} finally {
setPending(false);
}
}

return (
<Card padding="md">
<div className="flex items-center gap-3 mb-3">
<div className="size-8 rounded-lg flex items-center justify-center bg-sky-500/10">
<span className="material-symbols-outlined text-sky-500 text-xl">hub</span>
</div>
<div>
<h3 className="font-medium text-sm">Provider Exposure</h3>
<p className="text-xs text-text-muted">
Expose CLIProxyAPI models as a routing target under the{" "}
<code className="font-mono bg-bg-subtle px-1 rounded">cliproxyapi/</code> prefix.
</p>
</div>
</div>

{msg && (
<div
className={`flex items-center gap-1.5 mb-3 px-2 py-1.5 rounded text-xs ${
msg.ok
? "bg-green-500/10 text-green-600 dark:text-green-400"
: "bg-red-500/10 text-red-600 dark:text-red-400"
}`}
>
<span className="material-symbols-outlined text-[12px]">
{msg.ok ? "check_circle" : "error"}
</span>
{msg.text}
</div>
)}

<div className="flex items-center justify-between">
<div>
<p className="text-sm">
Expose as{" "}
<code className="font-mono bg-bg-subtle px-1 rounded text-xs">cliproxyapi/...</code>
</p>
<p className="text-xs text-text-muted mt-0.5">
When enabled, discovered models appear in provider selects across OmniRoute.
</p>
</div>
<Toggle checked={data?.providerExpose ?? false} onChange={handleToggle} disabled={pending || !data} />
</div>
</Card>
);
}

Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { ServiceLogsPanel } from "../components/ServiceLogsPanel";
import { CliproxyModelMappingEditor } from "../components/CliproxyModelMappingEditor";
import { AutoStartToggle } from "../components/AutoStartToggle";
import { CliproxyConnectionPanel } from "../components/CliproxyConnectionPanel";
import { CliproxyProviderExposureCard } from "../components/CliproxyProviderExposureCard";

const NAME = "cliproxy";

Expand All @@ -19,6 +20,7 @@ export function CliproxyServiceTab() {
description="Launch CLIProxyAPI automatically when OmniRoute starts"
/>
<CliproxyConnectionPanel />
<CliproxyProviderExposureCard />
<CliproxyModelMappingEditor />
<ServiceLogsPanel name={NAME} />
</div>
Expand Down
41 changes: 41 additions & 0 deletions src/app/api/services/cliproxy/provider-expose/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/**
* POST /api/services/cliproxy/provider-expose
*
* Toggle provider exposure for the CLIProxy embedded service.
* When enabled, cliproxyapi models are discoverable as `cliproxyapi/...` in
* OmniRoute routing.
*
* Body: { enabled: boolean }
* Response: 204 No Content on success.
*
* Route is under /api/services/ — already classified LOCAL_ONLY in routeGuard.ts.
*/

import { z } from "zod";
import { updateServiceField } from "@/lib/db/versionManager";
import { createErrorResponse } from "@/lib/api/errorResponse";
import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error";

const BodySchema = z.object({ enabled: z.boolean() });

export async function POST(request: Request): Promise<Response> {
let body: unknown;
try {
body = await request.json();
} catch {
return createErrorResponse({ status: 400, message: "Invalid JSON body" });
}

const parsed = BodySchema.safeParse(body);
if (!parsed.success) {
return createErrorResponse({ status: 400, message: parsed.error.message });
}

try {
await updateServiceField("cliproxy", "providerExpose", parsed.data.enabled);
return new Response(null, { status: 204 });
} catch (err) {
const msg = sanitizeErrorMessage(err instanceof Error ? err.message : String(err));
return createErrorResponse({ status: 500, message: msg });
}
}
1 change: 1 addition & 0 deletions src/app/api/services/cliproxy/status/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export async function GET(): Promise<Response> {
latestVersion,
updateAvailable: !!installedVersion && !!latestVersion && installedVersion !== latestVersion,
autoStart: row?.autoStart ?? false,
providerExpose: row?.providerExpose ?? false,
});
} catch (err) {
const msg = sanitizeErrorMessage(err instanceof Error ? err.message : String(err));
Expand Down
3 changes: 2 additions & 1 deletion src/app/api/v1/providers/[provider]/models/route.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { getUnifiedModelsResponse } from "@/app/api/v1/models/catalog";
import { getServiceModels } from "@/lib/db/serviceModels";
import { isServiceBackendPluginId } from "@/lib/services/serviceBackends";
import { getRegistryEntry } from "@omniroute/open-sse/config/providerRegistry.ts";

/**
Expand All @@ -20,7 +21,7 @@ export async function OPTIONS() {
*/
export async function GET(request: Request, { params }: { params: Promise<{ provider: string }> }) {
const { provider: rawProvider } = await params;
if (rawProvider === "cliproxyapi" || rawProvider === "9router") {
if (isServiceBackendPluginId(rawProvider)) {
const models = getServiceModels(rawProvider).filter((model) => model.available !== false);
return Response.json({
object: "list",
Expand Down
54 changes: 54 additions & 0 deletions src/lib/services/serviceBackends.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import type { ProviderPluginManifestEntry } from "@omniroute/open-sse/config/providerPluginManifest.ts";

export const SERVICE_BACKEND_PLUGIN_IDS = ["9router", "cliproxyapi"] as const;

export type ServiceBackendPluginId = (typeof SERVICE_BACKEND_PLUGIN_IDS)[number];

export const SERVICE_BACKEND_EXPOSURE_TOOL_BY_PLUGIN_ID: Record<
ServiceBackendPluginId,
"9router" | "cliproxy"
> = {
"9router": "9router",
cliproxyapi: "cliproxy",
};

export const SERVICE_BACKEND_MANIFEST_TEMPLATE: Record<
ServiceBackendPluginId,
Pick<
ProviderPluginManifestEntry,
"format" | "executor" | "auth" | "endpoints" | "capabilities" | "passthroughModels" | "sidecar"
>
> = {
"9router": {
format: "openai",
executor: "default",
auth: { type: "none", header: "authorization" },
endpoints: { modelsUrl: "/v1/models" },
capabilities: [],
passthroughModels: true,
sidecar: { eligible: false, reasons: ["runtime provider"] },
},
cliproxyapi: {
format: "openai",
executor: "default",
auth: { type: "none", header: "authorization" },
endpoints: { modelsUrl: "/v1/models" },
capabilities: ["passthrough-models"],
passthroughModels: true,
sidecar: { eligible: false, reasons: ["runtime provider"] },
},
};

export function getServiceToolFromPluginId(
pluginId: string
): "9router" | "cliproxy" | undefined {
return SERVICE_BACKEND_EXPOSURE_TOOL_BY_PLUGIN_ID[
pluginId as keyof typeof SERVICE_BACKEND_EXPOSURE_TOOL_BY_PLUGIN_ID
];
}

const SERVICE_BACKEND_PLUGIN_ID_SET = new Set<string>(SERVICE_BACKEND_PLUGIN_IDS);

export function isServiceBackendPluginId(pluginId: string): pluginId is ServiceBackendPluginId {
return SERVICE_BACKEND_PLUGIN_ID_SET.has(pluginId);
}
2 changes: 2 additions & 0 deletions src/mitm/dns/dnsConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ function hasHostEntry(hostsContent: string, hostname: string): boolean {
* invocation so the user gets one UAC prompt instead of one per line.
*/
export async function addDNSEntries(hosts: string[], sudoPassword: string): Promise<void> {
if (process.env.OMNIROUTE_SKIP_DNS_WRITE === "1") return;
Comment thread
HouMinXi marked this conversation as resolved.
Resolved
const hostsContent = readHostsFile();
const missingEntries: string[] = [];

Expand Down Expand Up @@ -178,6 +179,7 @@ fs.writeFileSync(filePath, filtered.join("\\n").replace(/\\n*$/, "\\n"));
* invocation so the user gets one UAC prompt instead of one per host.
*/
export async function removeDNSEntries(hosts: string[], sudoPassword: string): Promise<void> {
if (process.env.OMNIROUTE_SKIP_DNS_WRITE === "1") return;
const hostsContent = readHostsFile();
const presentHosts = hosts.filter((h) => hasHostEntry(hostsContent, h));

Expand Down
13 changes: 13 additions & 0 deletions tests/_cp_mock_hook.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// Loader hook: replaces child_process.spawn with a safe mock.
// Other exports (execFile, execFileSync, etc.) are the real implementations.
// Registered by mitm-dnsConfig.test.ts before any dnsConfig import.
export async function resolve(specifier: string, context: any, nextResolve: Function) {
const bare = specifier.split("?")[0];
if (bare === "child_process") {
return {
shortCircuit: true,
url: new URL("./_cp_mock_module.mts", import.meta.url).href,
};
}
return nextResolve(specifier, context);
}
32 changes: 32 additions & 0 deletions tests/_cp_mock_module.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Mock child_process module — replaces spawn, keeps everything else real.
// Imported by mitm-dnsConfig.test.ts via the loader hook in _cp_mock_hook.mts.
const realCp = await import("node:child_process");

export const execFile = realCp.execFile;
export const execFileSync = realCp.execFileSync;
export const fork = realCp.fork;
export const execSync = realCp.execSync;
export const spawnSync = realCp.spawnSync;

/** All spawn calls recorded as [command, args, options]. */
export const spawnCalls: Array<{ command: string; args: string[] }> = [];

export function spawn(command: string, args?: string[], options?: any) {
spawnCalls.push({ command, args: args ?? [], options });
return {
stdin: { write: () => true, end: () => {} },
stdout: { on: () => {} },
stderr: { on: () => {} },
on: function (ev: string, cb: (code: number) => void) {
if (ev === "close") cb(0);
return this;
},
kill: () => {},
};
}

export function resetSpawnCalls() {
spawnCalls.length = 0;
}

export default { execFile, execFileSync, fork, spawn, execSync, spawnSync };
25 changes: 25 additions & 0 deletions tests/_run_dns_guard_test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#!/usr/bin/env bash
# Wrapper: temporarily inject a test entry into /etc/hosts, run the
# mitm-dnsConfig test, then clean up. The entry lets removeDNSEntries
# exercise the full exec path (host present → spawn sudo → mock intercepts).
set -euo pipefail

TEST_HOST="__dns_guard_test__"
HOSTS_FILE="/etc/hosts"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

cleanup() {
sudo sed -i "/$TEST_HOST/d" "$HOSTS_FILE" 2>/dev/null || true
}
trap cleanup EXIT

# Inject test entries (idempotent — duplicates are harmless).
if ! grep -q "$TEST_HOST" "$HOSTS_FILE" 2>/dev/null; then
echo "127.0.0.1 $TEST_HOST" | sudo tee -a "$HOSTS_FILE" > /dev/null
echo "::1 $TEST_HOST" | sudo tee -a "$HOSTS_FILE" > /dev/null
fi

cd "$REPO_ROOT"
node --import tsx/esm --import ./tests/_setup/isolateDataDir.ts \
--test tests/unit/mitm-dnsConfig.test.ts
4 changes: 4 additions & 0 deletions tests/_setup/isolateDataDir.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,7 @@ if (!process.env.DATA_DIR) {
// baked it into the bundle, breaking ALL system TLS on the VM (2026-07-05).
// installCert/uninstallCert/installTproxyCa/uninstallTproxyCa no-op under this.
process.env.OMNIROUTE_SKIP_SYSTEM_TRUST = "1";

// DNS-write guard: the suite must NEVER mutate /etc/hosts. Tests that exercise
// the real MITM path call addDNSEntries(); this env var makes it a no-op.
process.env.OMNIROUTE_SKIP_DNS_WRITE = "1";
Loading
Loading