- Refines the overall structure of the CLI tools and MITM server functionalities.
- Add buildQwenBaseUrl function to construct URLs for Qwen resources. - Update buildProviderUrl to support Qwen model requests. - Enhance token refresh logic to include provider-specific data for Qwen. - Refactor CLI Tools page to exclude MITM tools and streamline model retrieval. - Introduce new components for MITM server management. - Update API routes to handle Qwen-specific resource URLs and improve error handling.
This commit is contained in:
@@ -3,19 +3,20 @@
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import { Card, CardSkeleton } from "@/shared/components";
|
||||
import { CLI_TOOLS } from "@/shared/constants/cliTools";
|
||||
import { PROVIDER_MODELS, getModelsByProviderId, PROVIDER_ID_TO_ALIAS } from "@/shared/constants/models";
|
||||
import { ClaudeToolCard, CodexToolCard, DroidToolCard, OpenClawToolCard, DefaultToolCard, AntigravityToolCard, OpenCodeToolCard, CopilotToolCard } from "./components";
|
||||
import { getModelsByProviderId, PROVIDER_ID_TO_ALIAS } from "@/shared/constants/models";
|
||||
import { ClaudeToolCard, CodexToolCard, DroidToolCard, OpenClawToolCard, DefaultToolCard, OpenCodeToolCard } from "./components";
|
||||
|
||||
const CLOUD_URL = process.env.NEXT_PUBLIC_CLOUD_URL;
|
||||
|
||||
// MITM tools are now on /dashboard/mitm — exclude from CLI Tools page
|
||||
const MITM_TOOL_IDS = ["antigravity", "copilot"];
|
||||
|
||||
const STATUS_ENDPOINTS = {
|
||||
claude: "/api/cli-tools/claude-settings",
|
||||
codex: "/api/cli-tools/codex-settings",
|
||||
opencode: "/api/cli-tools/opencode-settings",
|
||||
copilot: "/api/cli-tools/copilot-settings",
|
||||
droid: "/api/cli-tools/droid-settings",
|
||||
openclaw: "/api/cli-tools/openclaw-settings",
|
||||
antigravity: "/api/cli-tools/antigravity-mitm",
|
||||
};
|
||||
|
||||
export default function CLIToolsPageClient({ machineId }) {
|
||||
@@ -101,15 +102,12 @@ export default function CLIToolsPageClient({ machineId }) {
|
||||
}
|
||||
};
|
||||
|
||||
const getActiveProviders = () => {
|
||||
return connections.filter(c => c.isActive !== false);
|
||||
};
|
||||
const getActiveProviders = () => connections.filter(c => c.isActive !== false);
|
||||
|
||||
const getAllAvailableModels = () => {
|
||||
const activeProviders = getActiveProviders();
|
||||
const models = [];
|
||||
const seenModels = new Set();
|
||||
|
||||
activeProviders.forEach(conn => {
|
||||
const alias = PROVIDER_ID_TO_ALIAS[conn.provider] || conn.provider;
|
||||
const providerModels = getModelsByProviderId(conn.provider);
|
||||
@@ -117,58 +115,33 @@ export default function CLIToolsPageClient({ machineId }) {
|
||||
const modelValue = `${alias}/${m.id}`;
|
||||
if (!seenModels.has(modelValue)) {
|
||||
seenModels.add(modelValue);
|
||||
models.push({
|
||||
value: modelValue,
|
||||
label: `${alias}/${m.id}`,
|
||||
provider: conn.provider,
|
||||
alias: alias,
|
||||
connectionName: conn.name,
|
||||
modelId: m.id,
|
||||
});
|
||||
models.push({ value: modelValue, label: `${alias}/${m.id}`, provider: conn.provider, alias, connectionName: conn.name, modelId: m.id });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
return models;
|
||||
};
|
||||
|
||||
const handleModelMappingChange = useCallback((toolId, modelAlias, targetModel) => {
|
||||
setModelMappings(prev => {
|
||||
// Prevent unnecessary updates if value hasn't changed
|
||||
if (prev[toolId]?.[modelAlias] === targetModel) {
|
||||
return prev;
|
||||
}
|
||||
return {
|
||||
...prev,
|
||||
[toolId]: {
|
||||
...prev[toolId],
|
||||
[modelAlias]: targetModel,
|
||||
},
|
||||
};
|
||||
if (prev[toolId]?.[modelAlias] === targetModel) return prev;
|
||||
return { ...prev, [toolId]: { ...prev[toolId], [modelAlias]: targetModel } };
|
||||
});
|
||||
}, []);
|
||||
|
||||
const getBaseUrl = () => {
|
||||
if (tunnelEnabled && tunnelUrl) {
|
||||
return tunnelUrl;
|
||||
}
|
||||
if (cloudEnabled && CLOUD_URL) {
|
||||
return CLOUD_URL;
|
||||
}
|
||||
if (typeof window !== "undefined") {
|
||||
return window.location.origin;
|
||||
}
|
||||
if (tunnelEnabled && tunnelUrl) return tunnelUrl;
|
||||
if (cloudEnabled && CLOUD_URL) return CLOUD_URL;
|
||||
if (typeof window !== "undefined") return window.location.origin;
|
||||
return "http://localhost:20128";
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div className="flex flex-col gap-4">
|
||||
<CardSkeleton />
|
||||
<CardSkeleton />
|
||||
<CardSkeleton />
|
||||
</div>
|
||||
<div className="flex flex-col gap-4">
|
||||
<CardSkeleton />
|
||||
<CardSkeleton />
|
||||
<CardSkeleton />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -203,19 +176,17 @@ export default function CLIToolsPageClient({ machineId }) {
|
||||
return <CodexToolCard key={toolId} {...commonProps} activeProviders={getActiveProviders()} cloudEnabled={cloudEnabled} initialStatus={toolStatuses.codex} />;
|
||||
case "opencode":
|
||||
return <OpenCodeToolCard key={toolId} {...commonProps} activeProviders={getActiveProviders()} cloudEnabled={cloudEnabled} initialStatus={toolStatuses.opencode} />;
|
||||
case "copilot":
|
||||
return <CopilotToolCard key={toolId} {...commonProps} activeProviders={getActiveProviders()} cloudEnabled={cloudEnabled} initialStatus={toolStatuses.copilot} />;
|
||||
case "droid":
|
||||
return <DroidToolCard key={toolId} {...commonProps} activeProviders={getActiveProviders()} hasActiveProviders={hasActiveProviders} cloudEnabled={cloudEnabled} initialStatus={toolStatuses.droid} />;
|
||||
case "openclaw":
|
||||
return <OpenClawToolCard key={toolId} {...commonProps} activeProviders={getActiveProviders()} hasActiveProviders={hasActiveProviders} cloudEnabled={cloudEnabled} initialStatus={toolStatuses.openclaw} />;
|
||||
case "antigravity":
|
||||
return <AntigravityToolCard key={toolId} {...commonProps} activeProviders={getActiveProviders()} hasActiveProviders={hasActiveProviders} cloudEnabled={cloudEnabled} initialStatus={toolStatuses.antigravity} />;
|
||||
default:
|
||||
return <DefaultToolCard key={toolId} toolId={toolId} {...commonProps} activeProviders={getActiveProviders()} cloudEnabled={cloudEnabled} tunnelEnabled={tunnelEnabled} />;
|
||||
}
|
||||
};
|
||||
|
||||
const regularTools = Object.entries(CLI_TOOLS).filter(([id]) => !MITM_TOOL_IDS.includes(id));
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
{!hasActiveProviders && (
|
||||
@@ -229,9 +200,8 @@ export default function CLIToolsPageClient({ machineId }) {
|
||||
</div>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<div className="flex flex-col gap-4">
|
||||
{Object.entries(CLI_TOOLS).map(([toolId, tool]) => renderToolCard(toolId, tool))}
|
||||
{regularTools.map(([toolId, tool]) => renderToolCard(toolId, tool))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { Card, Button, Badge, Input } from "@/shared/components";
|
||||
|
||||
/**
|
||||
* Shared MITM infrastructure card — manages SSL cert + server start/stop.
|
||||
* DNS per-tool is handled separately in MitmToolCard.
|
||||
*/
|
||||
export default function MitmServerCard({ apiKeys, cloudEnabled, onStatusChange }) {
|
||||
const [status, setStatus] = useState(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [showPasswordModal, setShowPasswordModal] = useState(false);
|
||||
const [sudoPassword, setSudoPassword] = useState("");
|
||||
const [selectedApiKey, setSelectedApiKey] = useState("");
|
||||
const [message, setMessage] = useState(null);
|
||||
const [pendingAction, setPendingAction] = useState(null); // "start" | "stop"
|
||||
|
||||
const isWindows = typeof navigator !== "undefined" && navigator.userAgent?.includes("Windows");
|
||||
|
||||
useEffect(() => {
|
||||
if (apiKeys?.length > 0 && !selectedApiKey) {
|
||||
setSelectedApiKey(apiKeys[0].key);
|
||||
}
|
||||
}, [apiKeys, selectedApiKey]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchStatus();
|
||||
}, []);
|
||||
|
||||
const fetchStatus = async () => {
|
||||
try {
|
||||
const res = await fetch("/api/cli-tools/antigravity-mitm");
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setStatus(data);
|
||||
onStatusChange?.(data);
|
||||
}
|
||||
} catch {
|
||||
setStatus({ running: false, certExists: false, dnsStatus: {} });
|
||||
}
|
||||
};
|
||||
|
||||
const handleAction = (action) => {
|
||||
if (isWindows || status?.hasCachedPassword) {
|
||||
doAction(action, "");
|
||||
} else {
|
||||
setPendingAction(action);
|
||||
setShowPasswordModal(true);
|
||||
setMessage(null);
|
||||
}
|
||||
};
|
||||
|
||||
const doAction = async (action, password) => {
|
||||
setLoading(true);
|
||||
setMessage(null);
|
||||
try {
|
||||
if (action === "start") {
|
||||
const keyToUse = selectedApiKey?.trim()
|
||||
|| (apiKeys?.length > 0 ? apiKeys[0].key : null)
|
||||
|| (!cloudEnabled ? "sk_9router" : null);
|
||||
|
||||
const res = await fetch("/api/cli-tools/antigravity-mitm", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ apiKey: keyToUse, sudoPassword: password }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (res.ok) {
|
||||
setMessage({ type: "success", text: "Server started" });
|
||||
} else {
|
||||
setMessage({ type: "error", text: data.error || "Failed to start server" });
|
||||
}
|
||||
} else {
|
||||
const res = await fetch("/api/cli-tools/antigravity-mitm", {
|
||||
method: "DELETE",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ sudoPassword: password }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (res.ok) {
|
||||
setMessage({ type: "success", text: "Server stopped — all DNS cleared" });
|
||||
} else {
|
||||
setMessage({ type: "error", text: data.error || "Failed to stop server" });
|
||||
}
|
||||
}
|
||||
setShowPasswordModal(false);
|
||||
setSudoPassword("");
|
||||
await fetchStatus();
|
||||
} catch (error) {
|
||||
setMessage({ type: "error", text: error.message });
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setPendingAction(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleConfirmPassword = () => {
|
||||
if (!sudoPassword.trim()) {
|
||||
setMessage({ type: "error", text: "Sudo password is required" });
|
||||
return;
|
||||
}
|
||||
doAction(pendingAction, sudoPassword);
|
||||
};
|
||||
|
||||
const isRunning = status?.running;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Card padding="sm" className="border-primary/20 bg-primary/5">
|
||||
<div className="flex flex-col gap-3">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="material-symbols-outlined text-primary text-[20px]">security</span>
|
||||
<span className="font-semibold text-sm text-text-main">MITM Server</span>
|
||||
{isRunning ? (
|
||||
<Badge variant="success" size="sm">Running</Badge>
|
||||
) : (
|
||||
<Badge variant="default" size="sm">Stopped</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1 text-xs text-text-muted">
|
||||
{[
|
||||
{ label: "Cert", ok: status?.certExists },
|
||||
{ label: "Server", ok: isRunning },
|
||||
].map(({ label, ok }) => (
|
||||
<span key={label} className={`flex items-center gap-0.5 px-1.5 py-0.5 rounded ${ok ? "text-green-600" : "text-text-muted"}`}>
|
||||
<span className={`material-symbols-outlined text-[12px]`}>
|
||||
{ok ? "check_circle" : "radio_button_unchecked"}
|
||||
</span>
|
||||
{label}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Mechanism explanation */}
|
||||
<div className="px-2 py-2 rounded-lg bg-surface/50 border border-border/50">
|
||||
<p className="text-[11px] text-text-muted leading-relaxed">
|
||||
<span className="font-medium text-text-main">How it works:</span> MITM server runs an HTTPS proxy on port 443.
|
||||
When you enable DNS for a tool, its API domain redirects to localhost.
|
||||
The proxy intercepts requests, applies your model mappings, and forwards to 9Router.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* API Key selector (only when stopped, to pick key for start) */}
|
||||
{!isRunning && (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-text-muted shrink-0">API Key</span>
|
||||
{apiKeys?.length > 0 ? (
|
||||
<select
|
||||
value={selectedApiKey}
|
||||
onChange={(e) => setSelectedApiKey(e.target.value)}
|
||||
className="flex-1 px-2 py-1 bg-surface rounded text-xs border border-border focus:outline-none focus:ring-1 focus:ring-primary/50"
|
||||
>
|
||||
{apiKeys.map((key) => <option key={key.id} value={key.key}>{key.key}</option>)}
|
||||
</select>
|
||||
) : (
|
||||
<span className="text-xs text-text-muted">
|
||||
{cloudEnabled ? "No API keys — create one in Keys page" : "sk_9router (default)"}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{message && (
|
||||
<div className={`flex items-center gap-2 px-2 py-1.5 rounded text-xs ${message.type === "success" ? "bg-green-500/10 text-green-600" : "bg-red-500/10 text-red-600"}`}>
|
||||
<span className="material-symbols-outlined text-[14px]">{message.type === "success" ? "check_circle" : "error"}</span>
|
||||
<span>{message.text}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Action button */}
|
||||
<div className="flex items-center gap-2">
|
||||
{isRunning ? (
|
||||
<button
|
||||
onClick={() => handleAction("stop")}
|
||||
disabled={loading}
|
||||
className="px-4 py-1.5 rounded-lg bg-red-500/10 border border-red-500/30 text-red-500 font-medium text-xs flex items-center gap-1.5 hover:bg-red-500/20 transition-colors disabled:opacity-50"
|
||||
>
|
||||
<span className="material-symbols-outlined text-[16px]">stop_circle</span>
|
||||
Stop Server
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => handleAction("start")}
|
||||
disabled={loading}
|
||||
className="px-4 py-1.5 rounded-lg bg-primary/10 border border-primary/30 text-primary font-medium text-xs flex items-center gap-1.5 hover:bg-primary/20 transition-colors disabled:opacity-50"
|
||||
>
|
||||
<span className="material-symbols-outlined text-[16px]">play_circle</span>
|
||||
Start Server
|
||||
</button>
|
||||
)}
|
||||
{isRunning && (
|
||||
<p className="text-xs text-text-muted">Enable DNS per tool below to activate interception</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Windows admin warning */}
|
||||
{!isRunning && isWindows && (
|
||||
<div className="flex items-center gap-2 px-2 py-1.5 rounded text-xs bg-yellow-500/10 text-yellow-600 border border-yellow-500/20">
|
||||
<span className="material-symbols-outlined text-[14px]">warning</span>
|
||||
<span>Windows: Run 9Router terminal as Administrator</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Password Modal */}
|
||||
{showPasswordModal && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
|
||||
<div className="bg-surface border border-border rounded-xl p-6 w-full max-w-sm flex flex-col gap-4 shadow-xl">
|
||||
<h3 className="font-semibold text-text-main">Sudo Password Required</h3>
|
||||
<div className="flex items-start gap-3 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg">
|
||||
<span className="material-symbols-outlined text-yellow-500 text-[20px]">warning</span>
|
||||
<p className="text-xs text-text-muted">Required for SSL certificate and server startup</p>
|
||||
</div>
|
||||
<Input
|
||||
type="password"
|
||||
placeholder="Enter sudo password"
|
||||
value={sudoPassword}
|
||||
onChange={(e) => setSudoPassword(e.target.value)}
|
||||
onKeyDown={(e) => { if (e.key === "Enter" && !loading) handleConfirmPassword(); }}
|
||||
/>
|
||||
{message && (
|
||||
<div className="flex items-center gap-2 px-2 py-1.5 rounded text-xs bg-red-500/10 text-red-600">
|
||||
<span className="material-symbols-outlined text-[14px]">error</span>
|
||||
<span>{message.text}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<Button variant="ghost" size="sm" onClick={() => { setShowPasswordModal(false); setSudoPassword(""); setMessage(null); }} disabled={loading}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="primary" size="sm" onClick={handleConfirmPassword} loading={loading}>
|
||||
Confirm
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import { Card, Button, Badge, Input, ModelSelectModal } from "@/shared/components";
|
||||
import Image from "next/image";
|
||||
|
||||
/**
|
||||
* Per-tool MITM card — shows DNS status + model mappings.
|
||||
* - Auto-saves model mapping on blur or modal select
|
||||
* - Start/Stop DNS replaces Save Mappings button
|
||||
* - Toggle switch removed; status badge is display-only
|
||||
* - Skips sudo modal if password is already cached
|
||||
*/
|
||||
export default function MitmToolCard({
|
||||
tool,
|
||||
isExpanded,
|
||||
onToggle,
|
||||
serverRunning,
|
||||
dnsActive,
|
||||
certCovered,
|
||||
hasCachedPassword,
|
||||
apiKeys,
|
||||
activeProviders,
|
||||
hasActiveProviders,
|
||||
cloudEnabled,
|
||||
onDnsChange,
|
||||
}) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [message, setMessage] = useState(null);
|
||||
const [showPasswordModal, setShowPasswordModal] = useState(false);
|
||||
const [sudoPassword, setSudoPassword] = useState("");
|
||||
const [pendingDnsAction, setPendingDnsAction] = useState(null);
|
||||
const [modelMappings, setModelMappings] = useState({});
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [currentEditingAlias, setCurrentEditingAlias] = useState(null);
|
||||
|
||||
const isWindows = typeof navigator !== "undefined" && navigator.userAgent?.includes("Windows");
|
||||
|
||||
useEffect(() => {
|
||||
if (isExpanded) loadSavedMappings();
|
||||
}, [isExpanded]);
|
||||
|
||||
const loadSavedMappings = async () => {
|
||||
try {
|
||||
const res = await fetch(`/api/cli-tools/antigravity-mitm/alias?tool=${tool.id}`);
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
if (Object.keys(data.aliases || {}).length > 0) setModelMappings(data.aliases);
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
};
|
||||
|
||||
const saveMappings = useCallback(async (mappings) => {
|
||||
try {
|
||||
await fetch("/api/cli-tools/antigravity-mitm/alias", {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ tool: tool.id, mappings }),
|
||||
});
|
||||
} catch { /* ignore */ }
|
||||
}, [tool.id]);
|
||||
|
||||
const handleMappingBlur = (alias, value) => {
|
||||
saveMappings({ ...modelMappings, [alias]: value });
|
||||
};
|
||||
|
||||
const handleModelMappingChange = (alias, value) => {
|
||||
setModelMappings(prev => ({ ...prev, [alias]: value }));
|
||||
};
|
||||
|
||||
const openModelSelector = (alias) => {
|
||||
setCurrentEditingAlias(alias);
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
const handleModelSelect = (model) => {
|
||||
if (!currentEditingAlias) return;
|
||||
const updated = { ...modelMappings, [currentEditingAlias]: model.value };
|
||||
setModelMappings(updated);
|
||||
saveMappings(updated);
|
||||
};
|
||||
|
||||
// DNS toggle logic
|
||||
const handleDnsToggle = () => {
|
||||
if (!serverRunning) return;
|
||||
const action = dnsActive ? "disable" : "enable";
|
||||
if (isWindows || hasCachedPassword) {
|
||||
doDnsAction(action, "");
|
||||
} else {
|
||||
setPendingDnsAction(action);
|
||||
setShowPasswordModal(true);
|
||||
setMessage(null);
|
||||
}
|
||||
};
|
||||
|
||||
const doDnsAction = async (action, password) => {
|
||||
setLoading(true);
|
||||
setMessage(null);
|
||||
try {
|
||||
const res = await fetch("/api/cli-tools/antigravity-mitm", {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ tool: tool.id, action, sudoPassword: password }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!res.ok) throw new Error(data.error || "Failed to toggle DNS");
|
||||
setMessage({
|
||||
type: "success",
|
||||
text: action === "enable" ? "DNS enabled — traffic intercepted" : "DNS disabled — traffic restored",
|
||||
});
|
||||
setShowPasswordModal(false);
|
||||
setSudoPassword("");
|
||||
onDnsChange?.(data);
|
||||
} catch (error) {
|
||||
setMessage({ type: "error", text: error.message });
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setPendingDnsAction(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleConfirmPassword = () => {
|
||||
if (!sudoPassword.trim()) {
|
||||
setMessage({ type: "error", text: "Sudo password is required" });
|
||||
return;
|
||||
}
|
||||
doDnsAction(pendingDnsAction, sudoPassword);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Card padding="xs" className="overflow-hidden">
|
||||
<div className="flex items-center justify-between hover:cursor-pointer" onClick={onToggle}>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="size-8 flex items-center justify-center shrink-0">
|
||||
<Image
|
||||
src={tool.image}
|
||||
alt={tool.name}
|
||||
width={32}
|
||||
height={32}
|
||||
className="size-8 object-contain rounded-lg"
|
||||
sizes="32px"
|
||||
onError={(e) => { e.target.style.display = "none"; }}
|
||||
/>
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<h3 className="font-medium text-sm">{tool.name}</h3>
|
||||
{!serverRunning ? (
|
||||
<Badge variant="default" size="sm">Server off</Badge>
|
||||
) : dnsActive ? (
|
||||
<Badge variant="success" size="sm">Active</Badge>
|
||||
) : (
|
||||
<Badge variant="warning" size="sm">DNS off</Badge>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-text-muted truncate">{tool.mitmDomain}</p>
|
||||
</div>
|
||||
</div>
|
||||
<span className={`material-symbols-outlined text-text-muted text-[20px] transition-transform ${isExpanded ? "rotate-180" : ""}`}>
|
||||
expand_more
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{isExpanded && (
|
||||
<div className="mt-4 pt-4 border-t border-border flex flex-col gap-4">
|
||||
{/* Info */}
|
||||
<div className="flex flex-col gap-0.5 text-[11px] text-text-muted px-1">
|
||||
<p>
|
||||
<span className="font-medium text-text-main">Domain:</span>{" "}
|
||||
<code className="text-[10px] bg-surface px-1 rounded">{tool.mitmDomain}</code>
|
||||
{certCovered !== undefined && (
|
||||
<span className={`ml-1.5 ${certCovered ? "text-green-600" : "text-red-500"}`}>
|
||||
<span className="material-symbols-outlined text-[11px] align-middle">
|
||||
{certCovered ? "verified" : "warning"}
|
||||
</span>
|
||||
{certCovered ? " cert OK" : " cert missing domain"}
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
<p>Toggle DNS to redirect {tool.name} traffic through 9Router via MITM.</p>
|
||||
</div>
|
||||
|
||||
{message && (
|
||||
<div className={`flex items-center gap-2 px-2 py-1.5 rounded text-xs ${message.type === "success" ? "bg-green-500/10 text-green-600" : "bg-red-500/10 text-red-600"}`}>
|
||||
<span className="material-symbols-outlined text-[14px]">{message.type === "success" ? "check_circle" : "error"}</span>
|
||||
<span>{message.text}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Model Mappings */}
|
||||
{tool.defaultModels?.length > 0 && (
|
||||
<div className="flex flex-col gap-2">
|
||||
{tool.defaultModels.map((model) => (
|
||||
<div key={model.alias} className="flex items-center gap-2">
|
||||
<span className="w-36 shrink-0 text-xs font-semibold text-text-main text-right">{model.name}</span>
|
||||
<span className="material-symbols-outlined text-text-muted text-[14px]">arrow_forward</span>
|
||||
<input
|
||||
type="text"
|
||||
value={modelMappings[model.alias] || ""}
|
||||
onChange={(e) => handleModelMappingChange(model.alias, e.target.value)}
|
||||
onBlur={(e) => handleMappingBlur(model.alias, e.target.value)}
|
||||
placeholder="provider/model-id"
|
||||
className="flex-1 px-2 py-1.5 bg-surface rounded border border-border text-xs focus:outline-none focus:ring-1 focus:ring-primary/50"
|
||||
/>
|
||||
<button
|
||||
onClick={() => openModelSelector(model.alias)}
|
||||
disabled={!hasActiveProviders}
|
||||
className={`px-2 py-1.5 rounded border text-xs transition-colors shrink-0 ${hasActiveProviders ? "bg-surface border-border hover:border-primary cursor-pointer" : "opacity-50 cursor-not-allowed border-border"}`}
|
||||
>
|
||||
Select
|
||||
</button>
|
||||
{modelMappings[model.alias] && (
|
||||
<button
|
||||
onClick={() => {
|
||||
handleModelMappingChange(model.alias, "");
|
||||
saveMappings({ ...modelMappings, [model.alias]: "" });
|
||||
}}
|
||||
className="p-1 text-text-muted hover:text-red-500 rounded transition-colors"
|
||||
title="Clear"
|
||||
>
|
||||
<span className="material-symbols-outlined text-[14px]">close</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{tool.defaultModels?.length === 0 && (
|
||||
<p className="text-xs text-text-muted px-1">Model mappings will be available soon.</p>
|
||||
)}
|
||||
|
||||
{/* Start / Stop DNS button */}
|
||||
<div>
|
||||
{dnsActive ? (
|
||||
<button
|
||||
onClick={handleDnsToggle}
|
||||
disabled={!serverRunning || loading}
|
||||
className="px-4 py-1.5 rounded-lg bg-red-500/10 border border-red-500/30 text-red-500 font-medium text-xs flex items-center gap-1.5 hover:bg-red-500/20 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<span className="material-symbols-outlined text-[16px]">stop_circle</span>
|
||||
Stop DNS
|
||||
</button>
|
||||
) : (
|
||||
<Button
|
||||
variant="primary"
|
||||
size="sm"
|
||||
onClick={handleDnsToggle}
|
||||
loading={loading}
|
||||
disabled={!serverRunning || loading}
|
||||
>
|
||||
<span className="material-symbols-outlined text-[14px] mr-1">play_circle</span>
|
||||
Start DNS
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{/* Password Modal */}
|
||||
{showPasswordModal && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
|
||||
<div className="bg-surface border border-border rounded-xl p-6 w-full max-w-sm flex flex-col gap-4 shadow-xl">
|
||||
<h3 className="font-semibold text-text-main">Sudo Password Required</h3>
|
||||
<div className="flex items-start gap-3 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg">
|
||||
<span className="material-symbols-outlined text-yellow-500 text-[20px]">warning</span>
|
||||
<p className="text-xs text-text-muted">Required to modify /etc/hosts and flush DNS cache</p>
|
||||
</div>
|
||||
<Input
|
||||
type="password"
|
||||
placeholder="Enter sudo password"
|
||||
value={sudoPassword}
|
||||
onChange={(e) => setSudoPassword(e.target.value)}
|
||||
onKeyDown={(e) => { if (e.key === "Enter" && !loading) handleConfirmPassword(); }}
|
||||
/>
|
||||
{message && (
|
||||
<div className="flex items-center gap-2 px-2 py-1.5 rounded text-xs bg-red-500/10 text-red-600">
|
||||
<span className="material-symbols-outlined text-[14px]">error</span>
|
||||
<span>{message.text}</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<Button variant="ghost" size="sm" onClick={() => { setShowPasswordModal(false); setSudoPassword(""); setMessage(null); }} disabled={loading}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="primary" size="sm" onClick={handleConfirmPassword} loading={loading}>
|
||||
Confirm
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Model Select Modal */}
|
||||
<ModelSelectModal
|
||||
isOpen={modalOpen}
|
||||
onClose={() => setModalOpen(false)}
|
||||
onSelect={handleModelSelect}
|
||||
selectedModel={currentEditingAlias ? modelMappings[currentEditingAlias] : null}
|
||||
activeProviders={activeProviders}
|
||||
title={`Select model for ${currentEditingAlias}`}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -6,4 +6,6 @@ export { default as DefaultToolCard } from "./DefaultToolCard";
|
||||
export { default as AntigravityToolCard } from "./AntigravityToolCard";
|
||||
export { default as OpenCodeToolCard } from "./OpenCodeToolCard";
|
||||
export { default as CopilotToolCard } from "./CopilotToolCard";
|
||||
export { default as MitmServerCard } from "./MitmServerCard";
|
||||
export { default as MitmToolCard } from "./MitmToolCard";
|
||||
|
||||
|
||||
93
src/app/(dashboard)/dashboard/mitm/MitmPageClient.js
Normal file
93
src/app/(dashboard)/dashboard/mitm/MitmPageClient.js
Normal file
@@ -0,0 +1,93 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { CLI_TOOLS } from "@/shared/constants/cliTools";
|
||||
import { getModelsByProviderId, PROVIDER_ID_TO_ALIAS } from "@/shared/constants/models";
|
||||
import { MitmServerCard, MitmToolCard } from "@/app/(dashboard)/dashboard/cli-tools/components";
|
||||
|
||||
const MITM_TOOL_IDS = ["antigravity", "copilot"];
|
||||
|
||||
export default function MitmPageClient() {
|
||||
const [connections, setConnections] = useState([]);
|
||||
const [apiKeys, setApiKeys] = useState([]);
|
||||
const [cloudEnabled, setCloudEnabled] = useState(false);
|
||||
const [expandedTool, setExpandedTool] = useState(null);
|
||||
const [mitmStatus, setMitmStatus] = useState({ running: false, certExists: false, dnsStatus: {}, certCoversTools: {}, hasCachedPassword: false });
|
||||
|
||||
useEffect(() => {
|
||||
fetchConnections();
|
||||
fetchApiKeys();
|
||||
fetchCloudSettings();
|
||||
}, []);
|
||||
|
||||
const fetchConnections = async () => {
|
||||
try {
|
||||
const res = await fetch("/api/providers");
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setConnections(data.connections || []);
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
};
|
||||
|
||||
const fetchApiKeys = async () => {
|
||||
try {
|
||||
const res = await fetch("/api/keys");
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setApiKeys(data.keys || []);
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
};
|
||||
|
||||
const fetchCloudSettings = async () => {
|
||||
try {
|
||||
const res = await fetch("/api/settings");
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setCloudEnabled(data.cloudEnabled || false);
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
};
|
||||
|
||||
const getActiveProviders = () => connections.filter(c => c.isActive !== false);
|
||||
|
||||
const hasActiveProviders = () => {
|
||||
const active = getActiveProviders();
|
||||
return active.some(conn => getModelsByProviderId(conn.provider).length > 0);
|
||||
};
|
||||
|
||||
const mitmTools = Object.entries(CLI_TOOLS).filter(([id]) => MITM_TOOL_IDS.includes(id));
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
{/* MITM Server Card */}
|
||||
<MitmServerCard
|
||||
apiKeys={apiKeys}
|
||||
cloudEnabled={cloudEnabled}
|
||||
onStatusChange={setMitmStatus}
|
||||
/>
|
||||
|
||||
{/* Tool Cards */}
|
||||
<div className="flex flex-col gap-2">
|
||||
{mitmTools.map(([toolId, tool]) => (
|
||||
<MitmToolCard
|
||||
key={toolId}
|
||||
tool={tool}
|
||||
isExpanded={expandedTool === toolId}
|
||||
onToggle={() => setExpandedTool(expandedTool === toolId ? null : toolId)}
|
||||
serverRunning={mitmStatus.running}
|
||||
dnsActive={mitmStatus.dnsStatus?.[toolId] || false}
|
||||
certCovered={mitmStatus.certCoversTools?.[toolId] || false}
|
||||
hasCachedPassword={mitmStatus.hasCachedPassword || false}
|
||||
apiKeys={apiKeys}
|
||||
activeProviders={getActiveProviders()}
|
||||
hasActiveProviders={hasActiveProviders()}
|
||||
cloudEnabled={cloudEnabled}
|
||||
onDnsChange={(data) => setMitmStatus(prev => ({ ...prev, dnsStatus: data.dnsStatus ?? prev.dnsStatus }))}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
5
src/app/(dashboard)/dashboard/mitm/page.js
Normal file
5
src/app/(dashboard)/dashboard/mitm/page.js
Normal file
@@ -0,0 +1,5 @@
|
||||
import MitmPageClient from "./MitmPageClient";
|
||||
|
||||
export default function MitmPage() {
|
||||
return <MitmPageClient />;
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import PropTypes from "prop-types";
|
||||
import { useParams, useRouter } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import Image from "next/image";
|
||||
import { Card, Button, Badge, Input, Modal, CardSkeleton, OAuthModal, KiroOAuthWrapper, CursorAuthModal, Toggle, Select } from "@/shared/components";
|
||||
import { Card, Button, Badge, Input, Modal, CardSkeleton, OAuthModal, KiroOAuthWrapper, CursorAuthModal, IFlowCookieModal, Toggle, Select } from "@/shared/components";
|
||||
import { OAUTH_PROVIDERS, APIKEY_PROVIDERS, FREE_PROVIDERS, getProviderAlias, isOpenAICompatibleProvider, isAnthropicCompatibleProvider } from "@/shared/constants/providers";
|
||||
import { getModelsByProviderId } from "@/shared/constants/models";
|
||||
import { useCopyToClipboard } from "@/shared/hooks/useCopyToClipboard";
|
||||
@@ -18,6 +18,7 @@ export default function ProviderDetailPage() {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [providerNode, setProviderNode] = useState(null);
|
||||
const [showOAuthModal, setShowOAuthModal] = useState(false);
|
||||
const [showIFlowCookieModal, setShowIFlowCookieModal] = useState(false);
|
||||
const [showAddApiKeyModal, setShowAddApiKeyModal] = useState(false);
|
||||
const [showEditModal, setShowEditModal] = useState(false);
|
||||
const [showEditNodeModal, setShowEditNodeModal] = useState(false);
|
||||
@@ -25,6 +26,7 @@ export default function ProviderDetailPage() {
|
||||
const [modelAliases, setModelAliases] = useState({});
|
||||
const [headerImgError, setHeaderImgError] = useState(false);
|
||||
const [modelTestResults, setModelTestResults] = useState({});
|
||||
const [modelsTestError, setModelsTestError] = useState("");
|
||||
const [testingModelId, setTestingModelId] = useState(null);
|
||||
const [showAddCustomModel, setShowAddCustomModel] = useState(false);
|
||||
const { copied, copy } = useCopyToClipboard();
|
||||
@@ -175,6 +177,11 @@ export default function ProviderDetailPage() {
|
||||
setShowOAuthModal(false);
|
||||
};
|
||||
|
||||
const handleIFlowCookieSuccess = () => {
|
||||
fetchConnections();
|
||||
setShowIFlowCookieModal(false);
|
||||
};
|
||||
|
||||
const handleSaveApiKey = async (formData) => {
|
||||
try {
|
||||
const res = await fetch("/api/providers", {
|
||||
@@ -270,8 +277,10 @@ export default function ProviderDetailPage() {
|
||||
});
|
||||
const data = await res.json();
|
||||
setModelTestResults((prev) => ({ ...prev, [modelId]: data.ok ? "ok" : "error" }));
|
||||
setModelsTestError(data.ok ? "" : (data.error || "Model not reachable"));
|
||||
} catch {
|
||||
setModelTestResults((prev) => ({ ...prev, [modelId]: "error" }));
|
||||
setModelsTestError("Network error");
|
||||
} finally {
|
||||
setTestingModelId(null);
|
||||
}
|
||||
@@ -356,6 +365,9 @@ export default function ProviderDetailPage() {
|
||||
onCopy={copy}
|
||||
onSetAlias={() => {}}
|
||||
onDeleteAlias={() => handleDeleteAlias(model.alias)}
|
||||
testStatus={modelTestResults[model.id]}
|
||||
onTest={connections.length > 0 ? () => handleTestModel(model.id) : undefined}
|
||||
isTesting={testingModelId === model.id}
|
||||
isCustom
|
||||
/>
|
||||
))}
|
||||
@@ -504,13 +516,26 @@ export default function ProviderDetailPage() {
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="text-lg font-semibold">Connections</h2>
|
||||
{!isCompatible && (
|
||||
<Button
|
||||
size="sm"
|
||||
icon="add"
|
||||
onClick={() => isOAuth ? setShowOAuthModal(true) : setShowAddApiKeyModal(true)}
|
||||
>
|
||||
Add
|
||||
</Button>
|
||||
<div className="flex gap-2">
|
||||
{providerId === "iflow" && (
|
||||
<Button
|
||||
size="sm"
|
||||
icon="cookie"
|
||||
variant="secondary"
|
||||
onClick={() => setShowIFlowCookieModal(true)}
|
||||
title="Add connection using browser cookie"
|
||||
>
|
||||
Cookie
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
icon="add"
|
||||
onClick={() => isOAuth ? setShowOAuthModal(true) : setShowAddApiKeyModal(true)}
|
||||
>
|
||||
Add
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -522,9 +547,16 @@ export default function ProviderDetailPage() {
|
||||
<p className="text-text-main font-medium mb-1">No connections yet</p>
|
||||
<p className="text-sm text-text-muted mb-4">Add your first connection to get started</p>
|
||||
{!isCompatible && (
|
||||
<Button icon="add" onClick={() => isOAuth ? setShowOAuthModal(true) : setShowAddApiKeyModal(true)}>
|
||||
Add Connection
|
||||
</Button>
|
||||
<div className="flex gap-2 justify-center">
|
||||
{providerId === "iflow" && (
|
||||
<Button icon="cookie" variant="secondary" onClick={() => setShowIFlowCookieModal(true)}>
|
||||
Cookie Auth
|
||||
</Button>
|
||||
)}
|
||||
<Button icon="add" onClick={() => isOAuth ? setShowOAuthModal(true) : setShowAddApiKeyModal(true)}>
|
||||
{providerId === "iflow" ? "OAuth" : "Add Connection"}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
@@ -559,6 +591,9 @@ export default function ProviderDetailPage() {
|
||||
{providerInfo.passthroughModels ? "Model Aliases" : "Available Models"}
|
||||
</h2>
|
||||
</div>
|
||||
{!!modelsTestError && (
|
||||
<p className="text-xs text-red-500 mb-3 break-words">{modelsTestError}</p>
|
||||
)}
|
||||
{renderModelsSection()}
|
||||
</Card>
|
||||
|
||||
@@ -585,6 +620,13 @@ export default function ProviderDetailPage() {
|
||||
onClose={() => setShowOAuthModal(false)}
|
||||
/>
|
||||
)}
|
||||
{providerId === "iflow" && (
|
||||
<IFlowCookieModal
|
||||
isOpen={showIFlowCookieModal}
|
||||
onSuccess={handleIFlowCookieSuccess}
|
||||
onClose={() => setShowIFlowCookieModal(false)}
|
||||
/>
|
||||
)}
|
||||
<AddApiKeyModal
|
||||
isOpen={showAddApiKeyModal}
|
||||
provider={providerId}
|
||||
@@ -639,44 +681,46 @@ function ModelRow({ model, fullModel, alias, copied, onCopy, testStatus, isCusto
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
<div className={`group flex items-center gap-2 px-3 py-2 rounded-lg border ${borderColor} hover:bg-sidebar/50`}>
|
||||
<span
|
||||
className="material-symbols-outlined text-base"
|
||||
style={iconColor ? { color: iconColor } : undefined}
|
||||
>
|
||||
{testStatus === "ok" ? "check_circle" : testStatus === "error" ? "cancel" : "smart_toy"}
|
||||
</span>
|
||||
<code className="text-xs text-text-muted font-mono bg-sidebar px-1.5 py-0.5 rounded">{fullModel}</code>
|
||||
{onTest && (
|
||||
<button
|
||||
onClick={onTest}
|
||||
disabled={isTesting}
|
||||
className={`p-0.5 hover:bg-sidebar rounded text-text-muted hover:text-primary transition-opacity ${isTesting ? "opacity-100" : "opacity-0 group-hover:opacity-100"}`}
|
||||
title="Test model"
|
||||
<div className={`group px-3 py-2 rounded-lg border ${borderColor} hover:bg-sidebar/50`}>
|
||||
<div className="flex items-center gap-2">
|
||||
<span
|
||||
className="material-symbols-outlined text-base"
|
||||
style={iconColor ? { color: iconColor } : undefined}
|
||||
>
|
||||
<span className="material-symbols-outlined text-sm" style={isTesting ? { animation: "spin 1s linear infinite" } : undefined}>
|
||||
{isTesting ? "progress_activity" : "science"}
|
||||
{testStatus === "ok" ? "check_circle" : testStatus === "error" ? "cancel" : "smart_toy"}
|
||||
</span>
|
||||
<code className="text-xs text-text-muted font-mono bg-sidebar px-1.5 py-0.5 rounded">{fullModel}</code>
|
||||
{onTest && (
|
||||
<button
|
||||
onClick={onTest}
|
||||
disabled={isTesting}
|
||||
className={`p-0.5 hover:bg-sidebar rounded text-text-muted hover:text-primary transition-opacity ${isTesting ? "opacity-100" : "opacity-0 group-hover:opacity-100"}`}
|
||||
title="Test model"
|
||||
>
|
||||
<span className="material-symbols-outlined text-sm" style={isTesting ? { animation: "spin 1s linear infinite" } : undefined}>
|
||||
{isTesting ? "progress_activity" : "science"}
|
||||
</span>
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={() => onCopy(fullModel, `model-${model.id}`)}
|
||||
className="p-0.5 hover:bg-sidebar rounded text-text-muted hover:text-primary"
|
||||
title="Copy model"
|
||||
>
|
||||
<span className="material-symbols-outlined text-sm">
|
||||
{copied === `model-${model.id}` ? "check" : "content_copy"}
|
||||
</span>
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={() => onCopy(fullModel, `model-${model.id}`)}
|
||||
className="p-0.5 hover:bg-sidebar rounded text-text-muted hover:text-primary"
|
||||
title="Copy model"
|
||||
>
|
||||
<span className="material-symbols-outlined text-sm">
|
||||
{copied === `model-${model.id}` ? "check" : "content_copy"}
|
||||
</span>
|
||||
</button>
|
||||
{isCustom && (
|
||||
<button
|
||||
onClick={onDeleteAlias}
|
||||
className="p-0.5 hover:bg-red-500/10 rounded text-text-muted hover:text-red-500 opacity-0 group-hover:opacity-100 transition-opacity ml-auto"
|
||||
title="Remove custom model"
|
||||
>
|
||||
<span className="material-symbols-outlined text-sm">close</span>
|
||||
</button>
|
||||
)}
|
||||
{isCustom && (
|
||||
<button
|
||||
onClick={onDeleteAlias}
|
||||
className="p-0.5 hover:bg-red-500/10 rounded text-text-muted hover:text-red-500 opacity-0 group-hover:opacity-100 transition-opacity ml-auto"
|
||||
title="Remove custom model"
|
||||
>
|
||||
<span className="material-symbols-outlined text-sm">close</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,21 +1,37 @@
|
||||
"use server";
|
||||
|
||||
import { NextResponse } from "next/server";
|
||||
import { getMitmStatus, startMitm, stopMitm, getCachedPassword, setCachedPassword, loadEncryptedPassword, initDbHooks } from "@/mitm/manager";
|
||||
import {
|
||||
getMitmStatus,
|
||||
startServer,
|
||||
stopServer,
|
||||
enableToolDNS,
|
||||
disableToolDNS,
|
||||
getCachedPassword,
|
||||
setCachedPassword,
|
||||
loadEncryptedPassword,
|
||||
initDbHooks,
|
||||
} from "@/mitm/manager";
|
||||
import { getSettings, updateSettings } from "@/lib/localDb";
|
||||
|
||||
// Inject DB hooks so manager.js (CJS) can persist settings without dynamic import issues
|
||||
initDbHooks(getSettings, updateSettings);
|
||||
|
||||
// GET - Check MITM status
|
||||
const isWin = process.platform === "win32";
|
||||
|
||||
function getPassword(provided) {
|
||||
return provided || getCachedPassword() || null;
|
||||
}
|
||||
|
||||
// GET - Full MITM status (server + per-tool DNS)
|
||||
export async function GET() {
|
||||
try {
|
||||
const status = await getMitmStatus();
|
||||
return NextResponse.json({
|
||||
running: status.running,
|
||||
pid: status.pid || null,
|
||||
dnsConfigured: status.dnsConfigured || false,
|
||||
certExists: status.certExists || false,
|
||||
dnsStatus: status.dnsStatus || {},
|
||||
certCoversTools: status.certCoversTools || {},
|
||||
hasCachedPassword: !!getCachedPassword(),
|
||||
});
|
||||
} catch (error) {
|
||||
@@ -24,13 +40,11 @@ export async function GET() {
|
||||
}
|
||||
}
|
||||
|
||||
// POST - Start MITM proxy
|
||||
// POST - Start MITM server (cert + server, no DNS)
|
||||
export async function POST(request) {
|
||||
try {
|
||||
const { apiKey, sudoPassword } = await request.json();
|
||||
const isWin = process.platform === "win32";
|
||||
// Priority: request password → in-memory cache → encrypted db
|
||||
const pwd = sudoPassword || getCachedPassword() || await loadEncryptedPassword() || "";
|
||||
const pwd = getPassword(sudoPassword) || await loadEncryptedPassword() || "";
|
||||
|
||||
if (!apiKey || (!isWin && !pwd)) {
|
||||
return NextResponse.json(
|
||||
@@ -39,38 +53,64 @@ export async function POST(request) {
|
||||
);
|
||||
}
|
||||
|
||||
const result = await startMitm(apiKey, pwd);
|
||||
const result = await startServer(apiKey, pwd);
|
||||
if (!isWin) setCachedPassword(pwd);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
running: result.running,
|
||||
pid: result.pid,
|
||||
steps: result.steps || { cert: true, server: true, dns: true },
|
||||
});
|
||||
return NextResponse.json({ success: true, running: result.running, pid: result.pid });
|
||||
} catch (error) {
|
||||
console.log("Error starting MITM:", error.message);
|
||||
return NextResponse.json({ error: error.message || "Failed to start MITM proxy" }, { status: 500 });
|
||||
console.log("Error starting MITM server:", error.message);
|
||||
return NextResponse.json({ error: error.message || "Failed to start MITM server" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE - Stop MITM proxy
|
||||
// DELETE - Stop MITM server (removes all DNS first, then kills server)
|
||||
export async function DELETE(request) {
|
||||
try {
|
||||
const { sudoPassword } = await request.json();
|
||||
const isWin = process.platform === "win32";
|
||||
const pwd = sudoPassword || getCachedPassword() || await loadEncryptedPassword() || "";
|
||||
const body = await request.json().catch(() => ({}));
|
||||
const { sudoPassword } = body;
|
||||
const pwd = getPassword(sudoPassword) || await loadEncryptedPassword() || "";
|
||||
|
||||
if (!isWin && !pwd) {
|
||||
return NextResponse.json({ error: "Missing sudoPassword" }, { status: 400 });
|
||||
}
|
||||
|
||||
await stopMitm(pwd);
|
||||
await stopServer(pwd);
|
||||
if (!isWin && sudoPassword) setCachedPassword(sudoPassword);
|
||||
|
||||
return NextResponse.json({ success: true, running: false });
|
||||
} catch (error) {
|
||||
console.log("Error stopping MITM:", error.message);
|
||||
return NextResponse.json({ error: error.message || "Failed to stop MITM proxy" }, { status: 500 });
|
||||
console.log("Error stopping MITM server:", error.message);
|
||||
return NextResponse.json({ error: error.message || "Failed to stop MITM server" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// PATCH - Toggle DNS for a specific tool (enable/disable)
|
||||
export async function PATCH(request) {
|
||||
try {
|
||||
const { tool, action, sudoPassword } = await request.json();
|
||||
const pwd = getPassword(sudoPassword) || await loadEncryptedPassword() || "";
|
||||
|
||||
if (!tool || !action) {
|
||||
return NextResponse.json({ error: "tool and action required" }, { status: 400 });
|
||||
}
|
||||
if (!isWin && !pwd) {
|
||||
return NextResponse.json({ error: "Missing sudoPassword" }, { status: 400 });
|
||||
}
|
||||
|
||||
if (action === "enable") {
|
||||
await enableToolDNS(tool, pwd);
|
||||
} else if (action === "disable") {
|
||||
await disableToolDNS(tool, pwd);
|
||||
} else {
|
||||
return NextResponse.json({ error: "action must be enable or disable" }, { status: 400 });
|
||||
}
|
||||
|
||||
if (!isWin && sudoPassword) setCachedPassword(sudoPassword);
|
||||
|
||||
const status = await getMitmStatus();
|
||||
return NextResponse.json({ success: true, dnsStatus: status.dnsStatus });
|
||||
} catch (error) {
|
||||
console.log("Error toggling DNS:", error.message);
|
||||
return NextResponse.json({ error: error.message || "Failed to toggle DNS" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,15 +34,55 @@ export async function POST(request) {
|
||||
});
|
||||
const latencyMs = Date.now() - start;
|
||||
|
||||
// 200 = ok; 400 = bad request but auth passed (model reachable)
|
||||
const ok = res.status === 200 || res.status === 400;
|
||||
let error = null;
|
||||
if (!ok) {
|
||||
const text = await res.text().catch(() => "");
|
||||
error = `HTTP ${res.status}${text ? `: ${text.slice(0, 120)}` : ""}`;
|
||||
const rawText = await res.text().catch(() => "");
|
||||
let parsed = null;
|
||||
try {
|
||||
parsed = rawText ? JSON.parse(rawText) : null;
|
||||
} catch {}
|
||||
|
||||
if (!res.ok) {
|
||||
const detail = parsed?.error?.message || parsed?.msg || parsed?.message || parsed?.error || rawText;
|
||||
const error = `HTTP ${res.status}${detail ? `: ${String(detail).slice(0, 240)}` : ""}`;
|
||||
return NextResponse.json({ ok: false, latencyMs, error, status: res.status });
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok, latencyMs, error });
|
||||
// Some providers may return HTTP 200 but not a real completion for invalid models.
|
||||
const providerStatus = parsed?.status;
|
||||
const providerMsg = parsed?.msg || parsed?.message;
|
||||
const hasProviderErrorStatus = providerStatus !== undefined
|
||||
&& providerStatus !== null
|
||||
&& String(providerStatus) !== "200"
|
||||
&& String(providerStatus) !== "0";
|
||||
if (hasProviderErrorStatus && providerMsg) {
|
||||
return NextResponse.json({
|
||||
ok: false,
|
||||
latencyMs,
|
||||
status: res.status,
|
||||
error: `Provider status ${providerStatus}: ${String(providerMsg).slice(0, 240)}`,
|
||||
});
|
||||
}
|
||||
|
||||
if (parsed?.error) {
|
||||
const providerError = parsed?.error?.message || parsed?.error || "Provider returned an error";
|
||||
return NextResponse.json({
|
||||
ok: false,
|
||||
latencyMs,
|
||||
status: res.status,
|
||||
error: String(providerError).slice(0, 240),
|
||||
});
|
||||
}
|
||||
|
||||
const hasChoices = Array.isArray(parsed?.choices) && parsed.choices.length > 0;
|
||||
if (!hasChoices) {
|
||||
return NextResponse.json({
|
||||
ok: false,
|
||||
latencyMs,
|
||||
status: res.status,
|
||||
error: "Provider returned no completion choices for this model",
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: true, latencyMs, error: null, status: res.status });
|
||||
} catch (err) {
|
||||
return NextResponse.json({ ok: false, error: err.message }, { status: 500 });
|
||||
}
|
||||
|
||||
137
src/app/api/oauth/iflow/cookie/route.js
Normal file
137
src/app/api/oauth/iflow/cookie/route.js
Normal file
@@ -0,0 +1,137 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { createProviderConnection } from "@/models";
|
||||
|
||||
/**
|
||||
* iFlow Cookie-Based Authentication
|
||||
* POST /api/oauth/iflow/cookie
|
||||
* Body: { cookie: "BXAuth=xxx; ..." }
|
||||
*/
|
||||
export async function POST(request) {
|
||||
try {
|
||||
const { cookie } = await request.json();
|
||||
|
||||
if (!cookie || typeof cookie !== "string") {
|
||||
return NextResponse.json({ error: "Cookie is required" }, { status: 400 });
|
||||
}
|
||||
|
||||
// Normalize cookie
|
||||
const trimmed = cookie.trim();
|
||||
if (!trimmed.includes("BXAuth=")) {
|
||||
return NextResponse.json({ error: "Cookie must contain BXAuth field" }, { status: 400 });
|
||||
}
|
||||
|
||||
let normalizedCookie = trimmed;
|
||||
if (!normalizedCookie.endsWith(";")) {
|
||||
normalizedCookie += ";";
|
||||
}
|
||||
|
||||
// Step 1: GET API key info to get the name
|
||||
const getResponse = await fetch("https://platform.iflow.cn/api/openapi/apikey", {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Cookie": normalizedCookie,
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
|
||||
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
|
||||
"Accept-Encoding": "gzip, deflate, br",
|
||||
"Connection": "keep-alive",
|
||||
"Sec-Fetch-Dest": "empty",
|
||||
"Sec-Fetch-Mode": "cors",
|
||||
"Sec-Fetch-Site": "same-origin",
|
||||
},
|
||||
});
|
||||
|
||||
if (!getResponse.ok) {
|
||||
const errorText = await getResponse.text();
|
||||
return NextResponse.json(
|
||||
{ error: `Failed to fetch API key info: ${errorText}` },
|
||||
{ status: getResponse.status }
|
||||
);
|
||||
}
|
||||
|
||||
const getResult = await getResponse.json();
|
||||
if (!getResult.success) {
|
||||
return NextResponse.json(
|
||||
{ error: `API key fetch failed: ${getResult.message}` },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const keyData = getResult.data;
|
||||
if (!keyData.name) {
|
||||
return NextResponse.json({ error: "Missing name in API key info" }, { status: 400 });
|
||||
}
|
||||
|
||||
// Step 2: POST to refresh API key
|
||||
const postResponse = await fetch("https://platform.iflow.cn/api/openapi/apikey", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Cookie": normalizedCookie,
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
|
||||
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
|
||||
"Accept-Encoding": "gzip, deflate, br",
|
||||
"Connection": "keep-alive",
|
||||
"Origin": "https://platform.iflow.cn",
|
||||
"Referer": "https://platform.iflow.cn/",
|
||||
},
|
||||
body: JSON.stringify({ name: keyData.name }),
|
||||
});
|
||||
|
||||
if (!postResponse.ok) {
|
||||
const errorText = await postResponse.text();
|
||||
return NextResponse.json(
|
||||
{ error: `Failed to refresh API key: ${errorText}` },
|
||||
{ status: postResponse.status }
|
||||
);
|
||||
}
|
||||
|
||||
const postResult = await postResponse.json();
|
||||
if (!postResult.success) {
|
||||
return NextResponse.json(
|
||||
{ error: `API key refresh failed: ${postResult.message}` },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const refreshedKey = postResult.data;
|
||||
if (!refreshedKey.apiKey) {
|
||||
return NextResponse.json({ error: "Missing API key in response" }, { status: 400 });
|
||||
}
|
||||
|
||||
// Extract only BXAuth from cookie
|
||||
const bxAuthMatch = normalizedCookie.match(/BXAuth=([^;]+)/);
|
||||
const bxAuth = bxAuthMatch ? bxAuthMatch[1] : "";
|
||||
const cookieToSave = bxAuth ? `BXAuth=${bxAuth};` : "";
|
||||
|
||||
// Save to database
|
||||
const connection = await createProviderConnection({
|
||||
provider: "iflow",
|
||||
authType: "cookie",
|
||||
name: refreshedKey.name || keyData.name,
|
||||
email: refreshedKey.name || keyData.name,
|
||||
apiKey: refreshedKey.apiKey,
|
||||
providerSpecificData: {
|
||||
cookie: cookieToSave,
|
||||
expireTime: refreshedKey.expireTime,
|
||||
},
|
||||
testStatus: "active",
|
||||
isActive: true,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
connection: {
|
||||
id: connection.id,
|
||||
provider: connection.provider,
|
||||
email: connection.email,
|
||||
apiKey: refreshedKey.apiKey.substring(0, 10) + "...", // masked
|
||||
expireTime: refreshedKey.expireTime,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("iFlow cookie auth error:", error);
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,18 @@ const createOpenAIModelsConfig = (url) => ({
|
||||
parseResponse: parseOpenAIStyleModels
|
||||
});
|
||||
|
||||
const resolveQwenModelsUrl = (connection) => {
|
||||
const fallback = "https://portal.qwen.ai/v1/models";
|
||||
const raw = connection?.providerSpecificData?.resourceUrl;
|
||||
if (!raw || typeof raw !== "string") return fallback;
|
||||
const value = raw.trim();
|
||||
if (!value) return fallback;
|
||||
if (value.startsWith("http://") || value.startsWith("https://")) {
|
||||
return `${value.replace(/\/$/, "")}/models`;
|
||||
}
|
||||
return `https://${value.replace(/\/$/, "")}/v1/models`;
|
||||
};
|
||||
|
||||
// Provider models endpoints configuration
|
||||
const PROVIDER_MODELS_CONFIG = {
|
||||
claude: {
|
||||
@@ -340,6 +352,9 @@ export async function GET(request, { params }) {
|
||||
|
||||
// Build request URL
|
||||
let url = config.url;
|
||||
if (connection.provider === "qwen") {
|
||||
url = resolveQwenModelsUrl(connection);
|
||||
}
|
||||
if (config.authQuery) {
|
||||
url += `?${config.authQuery}=${token}`;
|
||||
}
|
||||
|
||||
@@ -33,7 +33,8 @@ export async function POST(request) {
|
||||
// Build URL and headers using provider service
|
||||
const url = buildProviderUrl(provider, body.model || "test-model", true, {
|
||||
baseUrlIndex: 0,
|
||||
baseUrl: connection.providerSpecificData?.baseUrl
|
||||
baseUrl: connection.providerSpecificData?.baseUrl,
|
||||
qwenResourceUrl: connection.providerSpecificData?.resourceUrl
|
||||
});
|
||||
console.log("🚀 ~ POST ~ url:", url)
|
||||
const headers = buildProviderHeaders(provider, credentials, true, body);
|
||||
|
||||
@@ -93,7 +93,8 @@ export async function POST(request) {
|
||||
// Build URL and headers
|
||||
const url = buildProviderUrl(provider, model, true, {
|
||||
baseUrlIndex: 0,
|
||||
baseUrl: connection.providerSpecificData?.baseUrl
|
||||
baseUrl: connection.providerSpecificData?.baseUrl,
|
||||
qwenResourceUrl: connection.providerSpecificData?.resourceUrl
|
||||
});
|
||||
const headers = buildProviderHeaders(provider, credentials, true, actualBody);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user