fix: update the permission for viewing provider pages

This commit is contained in:
2026-07-15 17:56:14 +07:00
parent 4b0acbfc69
commit 5c8d9f80b0
45 changed files with 362 additions and 340 deletions
+3 -2
View File
@@ -138,7 +138,7 @@ Main flow modules:
Primary state DB: Primary state DB:
- `src/lib/localDb.js` - `src/lib/localDb.js`
- file: `${DATA_DIR}/db.json` (or `~/.9router/db.json` when `DATA_DIR` is unset) - file: `${DATA_DIR}/db/data.sqlite` (or `~/.9router/db/data.sqlite` when `DATA_DIR` is unset)
- entities: providerConnections, providerNodes, modelAliases, combos, apiKeys, settings, pricing - entities: providerConnections, providerNodes, modelAliases, combos, apiKeys, settings, pricing
Usage DB: Usage DB:
@@ -151,7 +151,8 @@ Usage DB:
- Dashboard cookie auth: `src/proxy.js`, `src/app/api/auth/login/route.js` - Dashboard cookie auth: `src/proxy.js`, `src/app/api/auth/login/route.js`
- API key generation/verification: `src/shared/utils/apiKey.js` - API key generation/verification: `src/shared/utils/apiKey.js`
- Provider secrets persisted in `providerConnections` entries - Provider secrets persisted in `providerConnections` entries. Provider management is administrator-only: regular users cannot access the Providers dashboard or provider/OAuth management APIs, but their API keys route through the shared active administrator credential pool.
- Schema migration 007 deletes legacy provider connections owned by regular users or missing users, and assigns legacy ownerless connections to the first administrator.
- Optional proxy support for upstream calls via env proxy variables (`open-sse/utils/proxyFetch.js`) - Optional proxy support for upstream calls via env proxy variables (`open-sse/utils/proxyFetch.js`)
## 5) Cloud Sync ## 5) Cloud Sync
@@ -10,7 +10,6 @@ import { getModelsByProviderId, getModelKind } from "@/shared/constants/models";
import { getThinkingLevels } from "open-sse/providers/thinkingLevels.js"; import { getThinkingLevels } from "open-sse/providers/thinkingLevels.js";
import { useCopyToClipboard } from "@/shared/hooks/useCopyToClipboard"; import { useCopyToClipboard } from "@/shared/hooks/useCopyToClipboard";
import { useModelCaps } from "@/shared/hooks/useModelCaps"; import { useModelCaps } from "@/shared/hooks/useModelCaps";
import useUserStore from "@/store/userStore";
import { translate } from "@/i18n/runtime"; import { translate } from "@/i18n/runtime";
import { fetchSuggestedModels } from "@/shared/utils/providerModelsFetcher"; import { fetchSuggestedModels } from "@/shared/utils/providerModelsFetcher";
import { getProviderCustomModelRows } from "@/shared/utils/providerCustomModels"; import { getProviderCustomModelRows } from "@/shared/utils/providerCustomModels";
@@ -39,7 +38,6 @@ export default function ProviderDetailPage() {
const router = useRouter(); const router = useRouter();
const providerId = params.id; const providerId = params.id;
const { getCaps } = useModelCaps(); const { getCaps } = useModelCaps();
const user = useUserStore((state) => state.user);
const [connections, setConnections] = useState([]); const [connections, setConnections] = useState([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [providerNode, setProviderNode] = useState(null); const [providerNode, setProviderNode] = useState(null);
@@ -81,8 +79,6 @@ export default function ProviderDetailPage() {
const [importingQoderModels, setImportingQoderModels] = useState(false); const [importingQoderModels, setImportingQoderModels] = useState(false);
const { copied, copy } = useCopyToClipboard(); const { copied, copy } = useCopyToClipboard();
const canManageModelAvailability = user?.role === "admin";
const AG_RISK_STORAGE_KEY = "ag_risk_confirmed"; const AG_RISK_STORAGE_KEY = "ag_risk_confirmed";
const openOAuthConnection = () => { const openOAuthConnection = () => {
@@ -1121,7 +1117,7 @@ export default function ProviderDetailPage() {
onTest={connections.length > 0 || isFreeNoAuth ? () => handleTestModel(model.id) : undefined} onTest={connections.length > 0 || isFreeNoAuth ? () => handleTestModel(model.id) : undefined}
isTesting={testingModelIds.has(model.id)} isTesting={testingModelIds.has(model.id)}
isFree={model.isFree} isFree={model.isFree}
onDisable={canManageModelAvailability ? () => handleDisableModel(model.id) : undefined} onDisable={() => handleDisableModel(model.id)}
caps={getCaps(`${providerId}/${model.id}`)} caps={getCaps(`${providerId}/${model.id}`)}
thinkingSuffix={resolveThinkingSuffix(model.id)} thinkingSuffix={resolveThinkingSuffix(model.id)}
/> />
@@ -1185,7 +1181,7 @@ export default function ProviderDetailPage() {
})()} })()}
{/* Disabled models — restorable */} {/* Disabled models — restorable */}
{canManageModelAvailability && disabledDisplayModels.length > 0 && ( {disabledDisplayModels.length > 0 && (
<div className="w-full mt-2"> <div className="w-full mt-2">
<p className="text-xs text-text-muted mb-2">Disabled models ({disabledDisplayModels.length}):</p> <p className="text-xs text-text-muted mb-2">Disabled models ({disabledDisplayModels.length}):</p>
<div className="flex flex-wrap gap-2"> <div className="flex flex-wrap gap-2">
@@ -1616,7 +1612,7 @@ export default function ProviderDetailPage() {
</select> </select>
)} )}
</div> </div>
{canManageModelAvailability && !isCompatible && (() => { {!isCompatible && (() => {
const allIds = [ const allIds = [
...models, ...models,
...kiloFreeModels.filter((fm) => !models.some((m) => m.id === fm.id)), ...kiloFreeModels.filter((fm) => !models.some((m) => m.id === fm.id)),
@@ -1,220 +0,0 @@
"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";
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,
}));
export default function NewProviderPage() {
const router = useRouter();
const [loading, setLoading] = useState(false);
const [formData, setFormData] = useState({
provider: "",
authMethod: "api_key",
apiKey: "",
displayName: "",
isActive: true,
});
const [errors, setErrors] = useState({});
const handleChange = (field, value) => {
setFormData((prev) => ({ ...prev, [field]: value }));
if (errors[field]) {
setErrors((prev) => ({ ...prev, [field]: null }));
}
};
const validate = () => {
const newErrors = {};
if (!formData.provider) newErrors.provider = "Please select a provider";
if (formData.authMethod === "api_key" && !formData.apiKey) {
newErrors.apiKey = "API Key is required";
}
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 || "Failed to create provider" });
}
} catch (error) {
setErrors({ submit: "An error occurred. Please try again." });
} finally {
setLoading(false);
}
};
const selectedProvider = AI_PROVIDERS[formData.provider];
return (
<div className="max-w-2xl mx-auto">
{/* 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>
Back to Providers
</Link>
<h1 className="text-3xl font-semibold tracking-tight">Add New Provider</h1>
<p className="text-text-muted mt-2">
Configure a new AI provider to use with your applications.
</p>
</div>
{/* Form */}
<Card>
<form onSubmit={handleSubmit} className="flex flex-col gap-6">
{/* Provider Selection */}
<Select
label="Provider"
options={providerOptions}
value={formData.provider}
onChange={(e) => handleChange("provider", e.target.value)}
placeholder="Select a provider"
error={errors.provider}
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">
Selected provider
</p>
</div>
</Card.Section>
)}
{/* Auth Method */}
<div className="flex flex-col gap-3">
<label className="text-sm font-medium">
Authentication Method <span className="text-red-500">*</span>
</label>
<div className="flex gap-3">
{authMethodOptions.map((method) => (
<button
key={method.value}
type="button"
onClick={() => handleChange("authMethod", method.value)}
className={`flex-1 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">{method.label}</span>
</button>
))}
</div>
</div>
{/* API Key Input */}
{formData.authMethod === "api_key" && (
<Input
label="API Key"
type="password"
placeholder="Enter your API key"
value={formData.apiKey}
onChange={(e) => handleChange("apiKey", e.target.value)}
error={errors.apiKey}
hint="Your API key will be encrypted and stored securely."
required
/>
)}
{/* OAuth2 Button */}
{formData.authMethod === "oauth2" && (
<Card.Section>
<p className="text-sm text-text-muted mb-4">
Connect your account using OAuth2 authentication.
</p>
<Button type="button" variant="secondary" icon="link">
Connect with OAuth2
</Button>
</Card.Section>
)}
{/* Display Name */}
<Input
label="Display Name"
placeholder="e.g., Production API, Dev Environment"
value={formData.displayName}
onChange={(e) => handleChange("displayName", e.target.value)}
hint="Optional. A friendly name to identify this configuration."
/>
{/* Active Toggle */}
<Toggle
checked={formData.isActive}
onChange={(checked) => handleChange("isActive", checked)}
label="Active"
description="Enable this provider for use in your applications"
/>
{/* 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}
</div>
)}
{/* Actions */}
<div className="flex gap-3 pt-4 border-t border-border">
<Link href="/dashboard/providers" className="flex-1">
<Button type="button" variant="ghost" fullWidth>
Cancel
</Button>
</Link>
<Button type="submit" loading={loading} fullWidth className="flex-1">
Create Provider
</Button>
</div>
</form>
</Card>
</div>
);
}
@@ -22,7 +22,6 @@ import Link from "next/link";
import { getErrorCode, getRelativeTime } from "@/shared/utils"; import { getErrorCode, getRelativeTime } from "@/shared/utils";
import { useNotificationStore } from "@/store/notificationStore"; import { useNotificationStore } from "@/store/notificationStore";
import { useHeaderSearchStore } from "@/store/headerSearchStore"; import { useHeaderSearchStore } from "@/store/headerSearchStore";
import useUserStore from "@/store/userStore";
import ModelAvailabilityBadge from "./components/ModelAvailabilityBadge"; import ModelAvailabilityBadge from "./components/ModelAvailabilityBadge";
import AddCompatibleModal from "./components/AddCompatibleModal"; import AddCompatibleModal from "./components/AddCompatibleModal";
@@ -106,12 +105,9 @@ export default function ProvidersPage() {
const [testingMode, setTestingMode] = useState(null); const [testingMode, setTestingMode] = useState(null);
const [testResults, setTestResults] = useState(null); const [testResults, setTestResults] = useState(null);
const notify = useNotificationStore(); const notify = useNotificationStore();
const user = useUserStore((state) => state.user);
const searchQuery = useHeaderSearchStore((s) => s.query); const searchQuery = useHeaderSearchStore((s) => s.query);
const registerSearch = useHeaderSearchStore((s) => s.register); const registerSearch = useHeaderSearchStore((s) => s.register);
const unregisterSearch = useHeaderSearchStore((s) => s.unregister); const unregisterSearch = useHeaderSearchStore((s) => s.unregister);
const isAdmin = user?.role === "admin";
useEffect(() => { useEffect(() => {
registerSearch("Search providers..."); registerSearch("Search providers...");
return () => unregisterSearch(); return () => unregisterSearch();
@@ -287,7 +283,6 @@ export default function ProvidersPage() {
.filter( .filter(
([, info]) => ([, info]) =>
!info.hidden && !info.hidden &&
(user?.role === "admin" || !info.noAuth) &&
matchSearch(info.name), matchSearch(info.name),
) )
.sort(([, a], [, b]) => (b.noAuth ? 1 : 0) - (a.noAuth ? 1 : 0)); .sort(([, a], [, b]) => (b.noAuth ? 1 : 0) - (a.noAuth ? 1 : 0));
@@ -295,7 +290,6 @@ export default function ProvidersPage() {
Object.entries(FREE_TIER_PROVIDERS).filter( Object.entries(FREE_TIER_PROVIDERS).filter(
([, info]) => ([, info]) =>
!info.hidden && !info.hidden &&
(user?.role === "admin" || !info.noAuth) &&
matchSearch(info.name) && matchSearch(info.name) &&
(info.serviceKinds ?? ["llm"]).includes("llm"), (info.serviceKinds ?? ["llm"]).includes("llm"),
), ),
@@ -336,10 +330,10 @@ export default function ProvidersPage() {
freeEntries.length > 0 || freeEntries.length > 0 ||
freeTierEntries.length > 0 || freeTierEntries.length > 0 ||
apikeyEntries.length > 0 || apikeyEntries.length > 0 ||
(isAdmin && ( (
compatibleProviders.length > 0 || compatibleProviders.length > 0 ||
anthropicCompatibleProviders.length > 0 anthropicCompatibleProviders.length > 0
)); );
return ( return (
<div className="flex min-w-0 flex-col gap-6 px-1 sm:px-0"> <div className="flex min-w-0 flex-col gap-6 px-1 sm:px-0">
@@ -353,7 +347,6 @@ export default function ProvidersPage() {
)} )}
{/* Custom provider configuration is administered centrally. */} {/* Custom provider configuration is administered centrally. */}
{isAdmin && (
<div className="flex flex-col gap-4"> <div className="flex flex-col gap-4">
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between"> <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<h2 className="text-lg sm:text-xl font-semibold flex items-center gap-2 leading-tight"> <h2 className="text-lg sm:text-xl font-semibold flex items-center gap-2 leading-tight">
@@ -404,7 +397,6 @@ export default function ProvidersPage() {
</div> </div>
)} )}
</div> </div>
)}
{/* OAuth Providers */} {/* OAuth Providers */}
{oauthEntries.length > 0 && ( {oauthEntries.length > 0 && (
@@ -582,7 +574,7 @@ export default function ProvidersPage() {
</div> </div>
</div> */} </div> */}
{isAdmin && <AddCompatibleModal <AddCompatibleModal
variant="openai" variant="openai"
isOpen={showAddCompatibleModal} isOpen={showAddCompatibleModal}
onClose={() => setShowAddCompatibleModal(false)} onClose={() => setShowAddCompatibleModal(false)}
@@ -590,8 +582,8 @@ export default function ProvidersPage() {
setProviderNodes((prev) => [...prev, node]); setProviderNodes((prev) => [...prev, node]);
setShowAddCompatibleModal(false); setShowAddCompatibleModal(false);
}} }}
/>} />
{isAdmin && <AddCompatibleModal <AddCompatibleModal
variant="anthropic" variant="anthropic"
isOpen={showAddAnthropicCompatibleModal} isOpen={showAddAnthropicCompatibleModal}
onClose={() => setShowAddAnthropicCompatibleModal(false)} onClose={() => setShowAddAnthropicCompatibleModal(false)}
@@ -599,7 +591,7 @@ export default function ProvidersPage() {
setProviderNodes((prev) => [...prev, node]); setProviderNodes((prev) => [...prev, node]);
setShowAddAnthropicCompatibleModal(false); setShowAddAnthropicCompatibleModal(false);
}} }}
/>} />
{/* Test Results Modal */} {/* Test Results Modal */}
{testResults && ( {testResults && (
@@ -17,13 +17,13 @@ async function fetchProviderNames() {
return { providerNameCache, providerNodesCache }; return { providerNameCache, providerNodesCache };
} }
const nodesRes = await fetch("/api/provider-nodes"); const topologyRes = await fetch("/api/usage/topology-providers");
const nodesData = await nodesRes.json(); const topologyData = topologyRes.ok ? await topologyRes.json() : {};
const nodes = nodesData.nodes || []; const nodes = topologyData.providers || [];
providerNodesCache = {}; providerNodesCache = {};
for (const node of nodes) { for (const node of nodes) {
providerNodesCache[node.id] = node.name; providerNodesCache[node.provider] = node.nodeName || node.name || node.provider;
} }
providerNameCache = { providerNameCache = {
@@ -70,7 +70,7 @@ async function completeXaiManualCode(code, state, ownerId) {
// GET /api/oauth/[provider]/device-code - Request device code (for device_code flow) // GET /api/oauth/[provider]/device-code - Request device code (for device_code flow)
export async function GET(request, { params }) { export async function GET(request, { params }) {
try { try {
const { user } = await getProviderConnectionAccess(); const { user } = await getProviderConnectionAccess(request);
const { provider, action } = await params; const { provider, action } = await params;
const { searchParams } = new URL(request.url); const { searchParams } = new URL(request.url);
@@ -184,6 +184,9 @@ export async function GET(request, { params }) {
if (error.message === "Unauthorized") { if (error.message === "Unauthorized") {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
} }
if (error.message === "Forbidden") {
return NextResponse.json({ error: "Administrator access required" }, { status: 403 });
}
console.log("OAuth GET error:", error); console.log("OAuth GET error:", error);
return NextResponse.json({ error: error.message }, { status: 500 }); return NextResponse.json({ error: error.message }, { status: 500 });
} }
@@ -193,7 +196,7 @@ export async function GET(request, { params }) {
// POST /api/oauth/[provider]/poll - Poll for token (device_code flow) // POST /api/oauth/[provider]/poll - Poll for token (device_code flow)
export async function POST(request, { params }) { export async function POST(request, { params }) {
try { try {
const { user } = await getProviderConnectionAccess(); const { user } = await getProviderConnectionAccess(request);
const { provider, action } = await params; const { provider, action } = await params;
let body; let body;
try { try {
@@ -362,6 +365,9 @@ export async function POST(request, { params }) {
if (error.message === "Unauthorized") { if (error.message === "Unauthorized") {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
} }
if (error.message === "Forbidden") {
return NextResponse.json({ error: "Administrator access required" }, { status: 403 });
}
console.log("OAuth POST error:", error); console.log("OAuth POST error:", error);
return NextResponse.json({ error: error.message }, { status: error.status || 500 }); return NextResponse.json({ error: error.message }, { status: error.status || 500 });
} }
+4 -5
View File
@@ -1,7 +1,7 @@
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { createProviderConnection } from "@/models"; import { createProviderConnection } from "@/models";
import { extractCodexAccountInfo } from "@/lib/oauth/providers"; import { extractCodexAccountInfo } from "@/lib/oauth/providers";
import { requireCurrentDashboardUser } from "@/lib/auth/currentUser"; import { requireProviderAdministrator } from "@/lib/providers/connectionAccess";
/** /**
* POST /api/oauth/codex/bulk-import * POST /api/oauth/codex/bulk-import
@@ -20,11 +20,10 @@ import { requireCurrentDashboardUser } from "@/lib/auth/currentUser";
export async function POST(request) { export async function POST(request) {
let user; let user;
try { try {
user = await requireCurrentDashboardUser(); user = await requireProviderAdministrator(request);
} catch (error) { } catch (error) {
if (error.message === "Unauthorized") { if (error.message === "Unauthorized") return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); if (error.message === "Forbidden") return NextResponse.json({ error: "Administrator access required" }, { status: 403 });
}
return NextResponse.json({ error: "Failed to authenticate user" }, { status: 500 }); return NextResponse.json({ error: "Failed to authenticate user" }, { status: 500 });
} }
@@ -12,7 +12,7 @@ import { getProviderConnectionAccess } from "@/lib/providers/connectionAccess";
*/ */
export async function POST(request) { export async function POST(request) {
try { try {
const { user } = await getProviderConnectionAccess(); const { user } = await getProviderConnectionAccess(request);
const { accessToken, name } = await request.json(); const { accessToken, name } = await request.json();
if (!accessToken || typeof accessToken !== "string") { if (!accessToken || typeof accessToken !== "string") {
@@ -1,4 +1,5 @@
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { requireProviderAdministrator } from "@/lib/providers/connectionAccess";
import { access, constants } from "fs/promises"; import { access, constants } from "fs/promises";
import { homedir } from "os"; import { homedir } from "os";
import { join } from "path"; import { join } from "path";
@@ -174,8 +175,9 @@ async function extractTokensViaCLI(dbPath) {
* Auto-detect and extract Cursor tokens from local SQLite database. * Auto-detect and extract Cursor tokens from local SQLite database.
* Strategy: better-sqlite3 → sqlite3 CLI → manual fallback * Strategy: better-sqlite3 → sqlite3 CLI → manual fallback
*/ */
export async function GET() { export async function GET(request) {
try { try {
await requireProviderAdministrator(request);
const platform = process.platform; const platform = process.platform;
const candidates = getCandidatePaths(platform); const candidates = getCandidatePaths(platform);
@@ -249,6 +251,8 @@ export async function GET() {
// Strategy 3: ask user to paste manually // Strategy 3: ask user to paste manually
return NextResponse.json({ found: false, windowsManual: true, dbPath }); return NextResponse.json({ found: false, windowsManual: true, dbPath });
} catch (error) { } catch (error) {
if (error.message === "Unauthorized") return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
if (error.message === "Forbidden") return NextResponse.json({ error: "Administrator access required" }, { status: 403 });
console.log("Cursor auto-import error:", error); console.log("Cursor auto-import error:", error);
return NextResponse.json( return NextResponse.json(
{ found: false, error: error.message }, { found: false, error: error.message },
+1 -1
View File
@@ -13,7 +13,7 @@ import { getProviderConnectionAccess } from "@/lib/providers/connectionAccess";
*/ */
export async function POST(request) { export async function POST(request) {
try { try {
const { user } = await getProviderConnectionAccess(); const { user } = await getProviderConnectionAccess(request);
const { accessToken, machineId } = await request.json(); const { accessToken, machineId } = await request.json();
if (!accessToken || typeof accessToken !== "string") { if (!accessToken || typeof accessToken !== "string") {
+1 -1
View File
@@ -10,7 +10,7 @@ const GITLAB_DEFAULT_BASE = "https://gitlab.com";
*/ */
export async function POST(request) { export async function POST(request) {
try { try {
const { user: dashboardUser } = await getProviderConnectionAccess(); const { user: dashboardUser } = await getProviderConnectionAccess(request);
let body; let body;
try { try {
body = await request.json(); body = await request.json();
+1 -1
View File
@@ -9,7 +9,7 @@ import { getProviderConnectionAccess } from "@/lib/providers/connectionAccess";
*/ */
export async function POST(request) { export async function POST(request) {
try { try {
const { user } = await getProviderConnectionAccess(); const { user } = await getProviderConnectionAccess(request);
const { cookie } = await request.json(); const { cookie } = await request.json();
if (!cookie || typeof cookie !== "string") { if (!cookie || typeof cookie !== "string") {
+1 -1
View File
@@ -11,7 +11,7 @@ import { getProviderConnectionAccess } from "@/lib/providers/connectionAccess";
*/ */
export async function POST(request) { export async function POST(request) {
try { try {
const { user } = await getProviderConnectionAccess(); const { user } = await getProviderConnectionAccess(request);
const { apiKey, region } = await request.json(); const { apiKey, region } = await request.json();
if (!apiKey || typeof apiKey !== "string" || !apiKey.trim()) { if (!apiKey || typeof apiKey !== "string" || !apiKey.trim()) {
+5 -1
View File
@@ -1,4 +1,5 @@
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { requireProviderAdministrator } from "@/lib/providers/connectionAccess";
import { readFile, readdir } from "fs/promises"; import { readFile, readdir } from "fs/promises";
import { homedir } from "os"; import { homedir } from "os";
import { join } from "path"; import { join } from "path";
@@ -9,8 +10,9 @@ import { join } from "path";
* For IDC (organization) tokens, also resolves clientId/clientSecret from the * For IDC (organization) tokens, also resolves clientId/clientSecret from the
* linked client registration file so token refresh works. * linked client registration file so token refresh works.
*/ */
export async function GET() { export async function GET(request) {
try { try {
await requireProviderAdministrator(request);
const cachePath = join(homedir(), ".aws/sso/cache"); const cachePath = join(homedir(), ".aws/sso/cache");
let files; let files;
@@ -123,6 +125,8 @@ export async function GET() {
profileArn, profileArn,
}); });
} catch (error) { } catch (error) {
if (error.message === "Unauthorized") return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
if (error.message === "Forbidden") return NextResponse.json({ error: "Administrator access required" }, { status: 403 });
console.log("Kiro auto-import error:", error); console.log("Kiro auto-import error:", error);
return NextResponse.json( return NextResponse.json(
{ found: false, error: error.message }, { found: false, error: error.message },
@@ -9,7 +9,7 @@ import { getProviderConnectionAccess } from "@/lib/providers/connectionAccess";
*/ */
export async function POST(request) { export async function POST(request) {
try { try {
const { user } = await getProviderConnectionAccess(); const { user } = await getProviderConnectionAccess(request);
const body = await request.json(); const body = await request.json();
const rawAuth = body?.cliProxyAuth ?? body?.auth ?? body?.json ?? body; const rawAuth = body?.cliProxyAuth ?? body?.auth ?? body?.json ?? body;
const tokenData = normalizeKiroExternalIdpAuth(rawAuth); const tokenData = normalizeKiroExternalIdpAuth(rawAuth);
+1 -1
View File
@@ -11,7 +11,7 @@ import { getProviderConnectionAccess } from "@/lib/providers/connectionAccess";
*/ */
export async function POST(request) { export async function POST(request) {
try { try {
const { user } = await getProviderConnectionAccess(); const { user } = await getProviderConnectionAccess(request);
const { refreshToken, clientId, clientSecret, region, authMethod, profileArn } = await request.json(); const { refreshToken, clientId, clientSecret, region, authMethod, profileArn } = await request.json();
if (!refreshToken || typeof refreshToken !== "string") { if (!refreshToken || typeof refreshToken !== "string") {
@@ -1,6 +1,7 @@
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { generatePKCE } from "@/lib/oauth/utils/pkce"; import { generatePKCE } from "@/lib/oauth/utils/pkce";
import { KiroService } from "@/lib/oauth/services/kiro"; import { KiroService } from "@/lib/oauth/services/kiro";
import { requireProviderAdministrator } from "@/lib/providers/connectionAccess";
/** /**
* GET /api/oauth/kiro/social-authorize * GET /api/oauth/kiro/social-authorize
@@ -9,6 +10,7 @@ import { KiroService } from "@/lib/oauth/services/kiro";
*/ */
export async function GET(request) { export async function GET(request) {
try { try {
await requireProviderAdministrator(request);
const { searchParams } = new URL(request.url); const { searchParams } = new URL(request.url);
const provider = searchParams.get("provider"); // "google" or "github" const provider = searchParams.get("provider"); // "google" or "github"
@@ -37,6 +39,8 @@ export async function GET(request) {
provider, provider,
}); });
} catch (error) { } catch (error) {
if (error.message === "Unauthorized") return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
if (error.message === "Forbidden") return NextResponse.json({ error: "Administrator access required" }, { status: 403 });
console.log("Kiro social authorize error:", error); console.log("Kiro social authorize error:", error);
return NextResponse.json({ error: error.message }, { status: 500 }); return NextResponse.json({ error: error.message }, { status: 500 });
} }
@@ -10,7 +10,7 @@ import { getProviderConnectionAccess } from "@/lib/providers/connectionAccess";
*/ */
export async function POST(request) { export async function POST(request) {
try { try {
const { user } = await getProviderConnectionAccess(); const { user } = await getProviderConnectionAccess(request);
const { code, codeVerifier, provider } = await request.json(); const { code, codeVerifier, provider } = await request.json();
if (!code || !codeVerifier) { if (!code || !codeVerifier) {
+3 -3
View File
@@ -1,6 +1,6 @@
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { deleteProviderConnectionsByProvider, deleteProviderNode, getProviderConnections, getProviderNodeById, updateProviderConnection, updateProviderNode } from "@/models"; import { deleteProviderConnectionsByProvider, deleteProviderNode, getProviderConnections, getProviderNodeById, updateProviderConnection, updateProviderNode } from "@/models";
import { requireAdminUser } from "@/lib/auth/currentUser"; import { requireProviderAdministrator } from "@/lib/providers/connectionAccess";
function getAccessErrorResponse(error) { function getAccessErrorResponse(error) {
if (error.message === "Unauthorized") { if (error.message === "Unauthorized") {
@@ -15,7 +15,7 @@ function getAccessErrorResponse(error) {
// PUT /api/provider-nodes/[id] - Update provider node // PUT /api/provider-nodes/[id] - Update provider node
export async function PUT(request, { params }) { export async function PUT(request, { params }) {
try { try {
await requireAdminUser(); await requireProviderAdministrator(request);
const { id } = await params; const { id } = await params;
const body = await request.json(); const body = await request.json();
const { name, prefix, apiType, baseUrl } = body; const { name, prefix, apiType, baseUrl } = body;
@@ -98,7 +98,7 @@ export async function PUT(request, { params }) {
// DELETE /api/provider-nodes/[id] - Delete provider node and its connections // DELETE /api/provider-nodes/[id] - Delete provider node and its connections
export async function DELETE(request, { params }) { export async function DELETE(request, { params }) {
try { try {
await requireAdminUser(); await requireProviderAdministrator(request);
const { id } = await params; const { id } = await params;
const node = await getProviderNodeById(id); const node = await getProviderNodeById(id);
+4 -4
View File
@@ -1,6 +1,6 @@
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { createProviderNode, getProviderNodes } from "@/models"; import { createProviderNode, getProviderNodes } from "@/models";
import { requireAdminUser } from "@/lib/auth/currentUser"; import { requireProviderAdministrator } from "@/lib/providers/connectionAccess";
import { OPENAI_COMPATIBLE_PREFIX, ANTHROPIC_COMPATIBLE_PREFIX, CUSTOM_EMBEDDING_PREFIX } from "@/shared/constants/providers"; import { OPENAI_COMPATIBLE_PREFIX, ANTHROPIC_COMPATIBLE_PREFIX, CUSTOM_EMBEDDING_PREFIX } from "@/shared/constants/providers";
import { generateId } from "@/shared/utils"; import { generateId } from "@/shared/utils";
@@ -29,9 +29,9 @@ function getAccessErrorResponse(error) {
} }
// GET /api/provider-nodes - List all provider nodes // GET /api/provider-nodes - List all provider nodes
export async function GET() { export async function GET(request) {
try { try {
await requireAdminUser(); await requireProviderAdministrator(request);
const nodes = await getProviderNodes(); const nodes = await getProviderNodes();
return NextResponse.json({ nodes }); return NextResponse.json({ nodes });
} catch (error) { } catch (error) {
@@ -46,7 +46,7 @@ export async function GET() {
// POST /api/provider-nodes - Create provider node // POST /api/provider-nodes - Create provider node
export async function POST(request) { export async function POST(request) {
try { try {
await requireAdminUser(); await requireProviderAdministrator(request);
const body = await request.json(); const body = await request.json();
const { name, prefix, apiType, baseUrl, type } = body; const { name, prefix, apiType, baseUrl, type } = body;
@@ -1,6 +1,7 @@
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { assertPublicUrl } from "@/shared/utils/ssrfGuard.js"; import { assertPublicUrl } from "@/shared/utils/ssrfGuard.js";
import { isLocalRequest } from "@/dashboardGuard"; import { isLocalRequest } from "@/dashboardGuard";
import { requireProviderAdministrator } from "@/lib/providers/connectionAccess";
// Fetch with timeout wrapper // Fetch with timeout wrapper
const fetchWithTimeout = (url, options, timeout = 10000) => { const fetchWithTimeout = (url, options, timeout = 10000) => {
@@ -54,6 +55,7 @@ const getChatErrorMessage = (status) => {
// POST /api/provider-nodes/validate - Validate API key against base URL // POST /api/provider-nodes/validate - Validate API key against base URL
export async function POST(request) { export async function POST(request) {
try { try {
await requireProviderAdministrator(request);
const body = await request.json(); const body = await request.json();
const { baseUrl, apiKey, type, modelId } = body; const { baseUrl, apiKey, type, modelId } = body;
@@ -197,6 +199,8 @@ export async function POST(request) {
return NextResponse.json({ valid: false, error: getModelsErrorMessage(res.status) }); return NextResponse.json({ valid: false, error: getModelsErrorMessage(res.status) });
} catch (error) { } catch (error) {
if (error.message === "Unauthorized") return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
if (error.message === "Forbidden") return NextResponse.json({ error: "Administrator access required" }, { status: 403 });
const errorMessage = getErrorMessage(error); const errorMessage = getErrorMessage(error);
console.error("Error validating provider node:", { console.error("Error validating provider node:", {
message: error.message, message: error.message,
+1 -1
View File
@@ -394,7 +394,7 @@ const PROVIDER_MODELS_CONFIG = {
export async function GET(request, { params }) { export async function GET(request, { params }) {
try { try {
const { id } = await params; const { id } = await params;
const { ownerId } = await getProviderConnectionAccess(); const { ownerId } = await getProviderConnectionAccess(request);
const connection = await getProviderConnectionById(id, ownerId); const connection = await getProviderConnectionById(id, ownerId);
if (!connection) { if (!connection) {
+13 -16
View File
@@ -6,20 +6,8 @@ import {
deleteProviderConnection, deleteProviderConnection,
} from "@/models"; } from "@/models";
import { getProviderConnectionAccess } from "@/lib/providers/connectionAccess"; import { getProviderConnectionAccess } from "@/lib/providers/connectionAccess";
import {
isAnthropicCompatibleProvider,
isCustomEmbeddingProvider,
isOpenAICompatibleProvider,
} from "@/shared/constants/providers";
function isAdministratorManagedProvider(provider) {
return isOpenAICompatibleProvider(provider)
|| isAnthropicCompatibleProvider(provider)
|| isCustomEmbeddingProvider(provider);
}
function canMutateConnection(user, connection) { function canMutateConnection(user, connection) {
return !isAdministratorManagedProvider(connection.provider) || user.role === "admin"; return user.role === "admin";
} }
function normalizeProxyConfig(body = {}) { function normalizeProxyConfig(body = {}) {
@@ -79,7 +67,7 @@ function shouldMergeProviderSpecificData(existing, incoming, hasLegacyProxy, has
export async function GET(request, { params }) { export async function GET(request, { params }) {
try { try {
const { id } = await params; const { id } = await params;
const { ownerId } = await getProviderConnectionAccess(); const { ownerId } = await getProviderConnectionAccess(request);
const connection = await getProviderConnectionById(id, ownerId); const connection = await getProviderConnectionById(id, ownerId);
if (!connection) { if (!connection) {
@@ -98,6 +86,9 @@ export async function GET(request, { params }) {
if (error.message === "Unauthorized") { if (error.message === "Unauthorized") {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
} }
if (error.message === "Forbidden") {
return NextResponse.json({ error: "Administrator access required" }, { status: 403 });
}
console.log("Error fetching connection:", error); console.log("Error fetching connection:", error);
return NextResponse.json({ error: "Failed to fetch connection" }, { status: 500 }); return NextResponse.json({ error: "Failed to fetch connection" }, { status: 500 });
} }
@@ -107,7 +98,7 @@ export async function GET(request, { params }) {
export async function PUT(request, { params }) { export async function PUT(request, { params }) {
try { try {
const { id } = await params; const { id } = await params;
const { user, ownerId } = await getProviderConnectionAccess(); const { user, ownerId } = await getProviderConnectionAccess(request);
const body = await request.json(); const body = await request.json();
const { const {
name, name,
@@ -193,6 +184,9 @@ export async function PUT(request, { params }) {
if (error.message === "Unauthorized") { if (error.message === "Unauthorized") {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
} }
if (error.message === "Forbidden") {
return NextResponse.json({ error: "Administrator access required" }, { status: 403 });
}
console.log("Error updating connection:", error); console.log("Error updating connection:", error);
return NextResponse.json({ error: "Failed to update connection" }, { status: 500 }); return NextResponse.json({ error: "Failed to update connection" }, { status: 500 });
} }
@@ -202,7 +196,7 @@ export async function PUT(request, { params }) {
export async function DELETE(request, { params }) { export async function DELETE(request, { params }) {
try { try {
const { id } = await params; const { id } = await params;
const { user, ownerId } = await getProviderConnectionAccess(); const { user, ownerId } = await getProviderConnectionAccess(request);
const existing = await getProviderConnectionById(id, ownerId); const existing = await getProviderConnectionById(id, ownerId);
if (!existing) { if (!existing) {
@@ -222,6 +216,9 @@ export async function DELETE(request, { params }) {
if (error.message === "Unauthorized") { if (error.message === "Unauthorized") {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
} }
if (error.message === "Forbidden") {
return NextResponse.json({ error: "Administrator access required" }, { status: 403 });
}
console.log("Error deleting connection:", error); console.log("Error deleting connection:", error);
return NextResponse.json({ error: "Failed to delete connection" }, { status: 500 }); return NextResponse.json({ error: "Failed to delete connection" }, { status: 500 });
} }
@@ -14,7 +14,7 @@ import { getProviderConnectionAccess } from "@/lib/providers/connectionAccess";
export async function POST(request, { params }) { export async function POST(request, { params }) {
try { try {
const { id } = await params; const { id } = await params;
const { ownerId } = await getProviderConnectionAccess(); const { ownerId } = await getProviderConnectionAccess(request);
const connection = await getProviderConnectionById(id, ownerId); const connection = await getProviderConnectionById(id, ownerId);
if (!connection) { if (!connection) {
return NextResponse.json({ error: "Connection not found" }, { status: 404 }); return NextResponse.json({ error: "Connection not found" }, { status: 404 });
@@ -65,6 +65,9 @@ export async function POST(request, { params }) {
if (error.message === "Unauthorized") { if (error.message === "Unauthorized") {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
} }
if (error.message === "Forbidden") {
return NextResponse.json({ error: "Administrator access required" }, { status: 403 });
}
console.log("Error testing models:", error); console.log("Error testing models:", error);
return NextResponse.json({ error: "Test failed" }, { status: 500 }); return NextResponse.json({ error: "Test failed" }, { status: 500 });
} }
+4 -1
View File
@@ -7,7 +7,7 @@ import { getProviderConnectionAccess } from "@/lib/providers/connectionAccess";
export async function POST(request, { params }) { export async function POST(request, { params }) {
try { try {
const { id } = await params; const { id } = await params;
const { ownerId } = await getProviderConnectionAccess(); const { ownerId } = await getProviderConnectionAccess(request);
const connection = await getProviderConnectionById(id, ownerId); const connection = await getProviderConnectionById(id, ownerId);
if (!connection) { if (!connection) {
return NextResponse.json({ error: "Connection not found" }, { status: 404 }); return NextResponse.json({ error: "Connection not found" }, { status: 404 });
@@ -27,6 +27,9 @@ export async function POST(request, { params }) {
if (error.message === "Unauthorized") { if (error.message === "Unauthorized") {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
} }
if (error.message === "Forbidden") {
return NextResponse.json({ error: "Administrator access required" }, { status: 403 });
}
console.log("Error testing connection:", error); console.log("Error testing connection:", error);
return NextResponse.json({ error: "Test failed" }, { status: 500 }); return NextResponse.json({ error: "Test failed" }, { status: 500 });
} }
+4 -1
View File
@@ -77,7 +77,7 @@ function sortConnections(connections, sort) {
export async function GET(request) { export async function GET(request) {
try { try {
const { ownerId } = await getProviderConnectionAccess(); const { ownerId } = await getProviderConnectionAccess(request);
await backfillCodexEmails(); await backfillCodexEmails();
const { searchParams } = new URL(request.url); const { searchParams } = new URL(request.url);
@@ -126,6 +126,9 @@ export async function GET(request) {
if (error.message === "Unauthorized") { if (error.message === "Unauthorized") {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
} }
if (error.message === "Forbidden") {
return NextResponse.json({ error: "Administrator access required" }, { status: 403 });
}
console.log("Error fetching providers for client:", error); console.log("Error fetching providers for client:", error);
return NextResponse.json({ error: "Failed to fetch providers" }, { status: 500 }); return NextResponse.json({ error: "Failed to fetch providers" }, { status: 500 });
} }
@@ -1,4 +1,5 @@
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { requireProviderAdministrator } from "@/lib/providers/connectionAccess";
const KILO_MODELS_URL = "https://api.kilo.ai/api/gateway/models"; const KILO_MODELS_URL = "https://api.kilo.ai/api/gateway/models";
@@ -8,6 +9,14 @@ let cacheTimestamp = 0;
const CACHE_TTL_MS = 60 * 60 * 1000; // 1 hour const CACHE_TTL_MS = 60 * 60 * 1000; // 1 hour
export async function GET() { export async function GET() {
try {
await requireProviderAdministrator(request);
} catch (error) {
if (error.message === "Unauthorized") return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
if (error.message === "Forbidden") return NextResponse.json({ error: "Administrator access required" }, { status: 403 });
return NextResponse.json({ error: "Failed to authenticate user" }, { status: 500 });
}
const now = Date.now(); const now = Date.now();
// Return cached result if still valid // Return cached result if still valid
+9 -3
View File
@@ -48,9 +48,9 @@ async function normalizeProxyPoolId(proxyPoolId) {
} }
// GET /api/providers - List all connections // GET /api/providers - List all connections
export async function GET() { export async function GET(request) {
try { try {
const { ownerId } = await getProviderConnectionAccess(); const { ownerId } = await getProviderConnectionAccess(request);
const connections = await getProviderConnections(ownerId ? { ownerId } : {}); const connections = await getProviderConnections(ownerId ? { ownerId } : {});
// Build nodeNameMap for compatible providers (id → name) // Build nodeNameMap for compatible providers (id → name)
@@ -83,6 +83,9 @@ export async function GET() {
if (error.message === "Unauthorized") { if (error.message === "Unauthorized") {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
} }
if (error.message === "Forbidden") {
return NextResponse.json({ error: "Administrator access required" }, { status: 403 });
}
console.log("Error fetching providers:", error); console.log("Error fetching providers:", error);
return NextResponse.json({ error: "Failed to fetch providers" }, { status: 500 }); return NextResponse.json({ error: "Failed to fetch providers" }, { status: 500 });
} }
@@ -91,7 +94,7 @@ export async function GET() {
// POST /api/providers - Create new connection (API Key only, OAuth via separate flow) // POST /api/providers - Create new connection (API Key only, OAuth via separate flow)
export async function POST(request) { export async function POST(request) {
try { try {
const { user } = await getProviderConnectionAccess(); const { user } = await getProviderConnectionAccess(request);
const body = await request.json(); const body = await request.json();
const provider = normalizeProviderId(body.provider); const provider = normalizeProviderId(body.provider);
const { apiKey, name, displayName, priority, globalPriority, defaultModel, testStatus } = body; const { apiKey, name, displayName, priority, globalPriority, defaultModel, testStatus } = body;
@@ -205,6 +208,9 @@ export async function POST(request) {
if (error.message === "Unauthorized") { if (error.message === "Unauthorized") {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
} }
if (error.message === "Forbidden") {
return NextResponse.json({ error: "Administrator access required" }, { status: 403 });
}
console.log("Error creating provider:", error); console.log("Error creating provider:", error);
return NextResponse.json( return NextResponse.json(
{ error: error.status === 409 ? error.message : "Failed to create provider" }, { error: error.status === 409 ? error.message : "Failed to create provider" },
@@ -1,9 +1,18 @@
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { FILTERS } from "./filters.js"; import { FILTERS } from "./filters.js";
import { requireProviderAdministrator } from "@/lib/providers/connectionAccess";
export const dynamic = "force-dynamic"; export const dynamic = "force-dynamic";
export async function GET(request) { export async function GET(request) {
try {
await requireProviderAdministrator(request);
} catch (error) {
if (error.message === "Unauthorized") return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
if (error.message === "Forbidden") return NextResponse.json({ error: "Administrator access required" }, { status: 403 });
return NextResponse.json({ error: "Failed to authenticate user" }, { status: 500 });
}
const { searchParams } = new URL(request.url); const { searchParams } = new URL(request.url);
const url = searchParams.get("url"); const url = searchParams.get("url");
const type = searchParams.get("type"); const type = searchParams.get("type");
+4 -1
View File
@@ -43,7 +43,7 @@ function isCompatibleProvider(providerId) {
// POST /api/providers/test-batch - Test multiple connections by group // POST /api/providers/test-batch - Test multiple connections by group
export async function POST(request) { export async function POST(request) {
try { try {
const { ownerId } = await getProviderConnectionAccess(); const { ownerId } = await getProviderConnectionAccess(request);
const body = await request.json(); const body = await request.json();
const { mode, providerId } = body; const { mode, providerId } = body;
@@ -133,6 +133,9 @@ export async function POST(request) {
if (error.message === "Unauthorized") { if (error.message === "Unauthorized") {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
} }
if (error.message === "Forbidden") {
return NextResponse.json({ error: "Administrator access required" }, { status: 403 });
}
console.log("Error in batch test:", error); console.log("Error in batch test:", error);
return NextResponse.json({ error: "Batch test failed" }, { status: 500 }); return NextResponse.json({ error: "Batch test failed" }, { status: 500 });
} }
+4
View File
@@ -5,6 +5,7 @@ import { getDefaultModel } from "open-sse/config/providerModels.js";
import { resolveOllamaLocalHost, resolveXiaomiTokenplanBaseUrl, PROVIDERS } from "open-sse/config/providers.js"; import { resolveOllamaLocalHost, resolveXiaomiTokenplanBaseUrl, PROVIDERS } from "open-sse/config/providers.js";
import { openaiToCommandCodeRequest } from "open-sse/translator/request/openai-to-commandcode.js"; import { openaiToCommandCodeRequest } from "open-sse/translator/request/openai-to-commandcode.js";
import { normalizeProviderId } from "@/lib/providerNormalization"; import { normalizeProviderId } from "@/lib/providerNormalization";
import { requireProviderAdministrator } from "@/lib/providers/connectionAccess";
// Probe a webSearch/webFetch provider using its searchConfig/fetchConfig. // Probe a webSearch/webFetch provider using its searchConfig/fetchConfig.
// Returns true if API key is accepted (status !== 401 && !== 403). // Returns true if API key is accepted (status !== 401 && !== 403).
@@ -83,6 +84,7 @@ async function probeMediaProvider(provider, apiKey) {
// POST /api/providers/validate - Validate API key with provider // POST /api/providers/validate - Validate API key with provider
export async function POST(request) { export async function POST(request) {
try { try {
await requireProviderAdministrator(request);
const body = await request.json(); const body = await request.json();
const provider = normalizeProviderId(body.provider); const provider = normalizeProviderId(body.provider);
const { apiKey, providerSpecificData } = body; const { apiKey, providerSpecificData } = body;
@@ -628,6 +630,8 @@ export async function POST(request) {
error: isValid ? null : (error || "Invalid API key"), error: isValid ? null : (error || "Invalid API key"),
}); });
} catch (error) { } catch (error) {
if (error.message === "Unauthorized") return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
if (error.message === "Forbidden") return NextResponse.json({ error: "Administrator access required" }, { status: 403 });
console.log("Error validating API key:", error); console.log("Error validating API key:", error);
return NextResponse.json({ error: "Validation failed" }, { status: 500 }); return NextResponse.json({ error: "Validation failed" }, { status: 500 });
} }
+13 -1
View File
@@ -1,5 +1,5 @@
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { countActiveAdmins, deleteUser, getUserById, updateUser } from "@/lib/db"; import { countActiveAdmins, countProviderConnectionsByOwnerId, deleteUser, getUserById, updateUser } from "@/lib/db";
import { requireCurrentDashboardUser } from "@/lib/auth/currentUser"; import { requireCurrentDashboardUser } from "@/lib/auth/currentUser";
const NO_STORE_HEADERS = { "Cache-Control": "no-store" }; const NO_STORE_HEADERS = { "Cache-Control": "no-store" };
@@ -25,6 +25,12 @@ function wouldRemoveLastActiveAdmin(target, updates, activeAdminCount) {
return (nextRole !== "admin" || !nextActive) && activeAdminCount <= 1; return (nextRole !== "admin" || !nextActive) && activeAdminCount <= 1;
} }
function wouldDemoteAdmin(target, updates) {
return target.role === "admin"
&& Object.hasOwn(updates, "role")
&& updates.role !== "admin";
}
export async function PATCH(request, { params }) { export async function PATCH(request, { params }) {
try { try {
const actor = await requireCurrentDashboardUser(); const actor = await requireCurrentDashboardUser();
@@ -47,6 +53,9 @@ export async function PATCH(request, { params }) {
if (wouldRemoveLastActiveAdmin(target, updates, await countActiveAdmins())) { if (wouldRemoveLastActiveAdmin(target, updates, await countActiveAdmins())) {
throw new Error("At least one active administrator is required"); throw new Error("At least one active administrator is required");
} }
if (wouldDemoteAdmin(target, updates) && await countProviderConnectionsByOwnerId(target.id) > 0) {
throw new Error("Delete this administrator's provider connections before changing their role");
}
const user = await updateUser(target.id, updates); const user = await updateUser(target.id, updates);
return NextResponse.json({ user }, { headers: NO_STORE_HEADERS }); return NextResponse.json({ user }, { headers: NO_STORE_HEADERS });
@@ -65,6 +74,9 @@ export async function DELETE(request, { params }) {
if (target.role === "admin" && target.isActive && await countActiveAdmins() <= 1) { if (target.role === "admin" && target.isActive && await countActiveAdmins() <= 1) {
throw new Error("At least one active administrator is required"); throw new Error("At least one active administrator is required");
} }
if (target.role === "admin" && await countProviderConnectionsByOwnerId(target.id) > 0) {
throw new Error("Delete this administrator's provider connections before deleting their account");
}
await deleteUser(target.id); await deleteUser(target.id);
return NextResponse.json({ success: true }, { headers: NO_STORE_HEADERS }); return NextResponse.json({ success: true }, { headers: NO_STORE_HEADERS });
+12 -8
View File
@@ -12,7 +12,7 @@ async function getCliToken() {
return cachedCliToken; return cachedCliToken;
} }
async function hasValidCliToken(request) { export async function hasValidCliToken(request) {
const token = request.headers.get(CLI_TOKEN_HEADER); const token = request.headers.get(CLI_TOKEN_HEADER);
if (!token) return false; if (!token) return false;
return token === await getCliToken(); return token === await getCliToken();
@@ -44,6 +44,9 @@ const ALWAYS_PROTECTED = [
// is disabled for local single-user deployments. // is disabled for local single-user deployments.
const ADMIN_ONLY_PATHS = [ const ADMIN_ONLY_PATHS = [
"/api/users", "/api/users",
"/api/providers",
"/api/provider-nodes",
"/api/oauth",
"/api/tunnel", "/api/tunnel",
"/api/headroom", "/api/headroom",
"/api/pxpipe", "/api/pxpipe",
@@ -55,6 +58,7 @@ const ADMIN_ONLY_PATHS = [
// Dashboard paths requiring an administrator. Combo access is handled by its // Dashboard paths requiring an administrator. Combo access is handled by its
// owner-scoped API routes and is available to authenticated users. // owner-scoped API routes and is available to authenticated users.
const ADMIN_ONLY_DASHBOARD_PATHS = [ const ADMIN_ONLY_DASHBOARD_PATHS = [
"/dashboard/providers",
"/dashboard/token-saver", "/dashboard/token-saver",
"/dashboard/pxpipe", "/dashboard/pxpipe",
"/dashboard/media-providers", "/dashboard/media-providers",
@@ -234,13 +238,6 @@ export async function proxy(request) {
} }
} }
// Always protected - require valid JWT or local CLI token (machineId-based)
if (ALWAYS_PROTECTED.some((p) => pathname.startsWith(p))) {
if (await hasValidCliToken(request) || await hasValidToken(request))
return NextResponse.next();
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
if (isPublicLlmApi(pathname)) { if (isPublicLlmApi(pathname)) {
if (await canAccessPublicLlmApi(request)) return NextResponse.next(); if (await canAccessPublicLlmApi(request)) return NextResponse.next();
return NextResponse.json({ error: "API key required for remote API access" }, { status: 401 }); return NextResponse.json({ error: "API key required for remote API access" }, { status: 401 });
@@ -251,6 +248,13 @@ export async function proxy(request) {
return NextResponse.json({ error: "Administrator access required" }, { status: 403 }); return NextResponse.json({ error: "Administrator access required" }, { status: 403 });
} }
// Always protected - require valid JWT or local CLI token (machineId-based)
if (ALWAYS_PROTECTED.some((p) => pathname.startsWith(p))) {
if (await hasValidCliToken(request) || await hasValidToken(request))
return NextResponse.next();
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
// Deny-by-default for /api/* — public allow-list bypasses, everything else requires auth. // Deny-by-default for /api/* — public allow-list bypasses, everything else requires auth.
if (pathname.startsWith("/api/")) { if (pathname.startsWith("/api/")) {
if (isPublicApi(pathname)) return NextResponse.next(); if (isPublicApi(pathname)) return NextResponse.next();
+6 -1
View File
@@ -18,7 +18,7 @@ export {
getProviderConnections, getProviderConnectionById, getProviderConnections, getProviderConnectionById,
createProviderConnection, updateProviderConnection, createProviderConnection, updateProviderConnection,
deleteProviderConnection, deleteProviderConnectionsByProvider, deleteProviderConnection, deleteProviderConnectionsByProvider,
reorderProviderConnections, cleanupProviderConnections, reorderProviderConnections, cleanupProviderConnections, countProviderConnectionsByOwnerId,
} from "./repos/connectionsRepo.js"; } from "./repos/connectionsRepo.js";
// Provider nodes // Provider nodes
@@ -146,9 +146,14 @@ export async function importDb(payload) {
} }
} }
const adminOwnerIds = new Set(
db.all(`SELECT id FROM users WHERE role = 'admin'`).map((user) => user.id),
);
const fallbackOwnerId = db.get(`SELECT id FROM users WHERE role = 'admin' ORDER BY createdAt ASC LIMIT 1`)?.id || null; const fallbackOwnerId = db.get(`SELECT id FROM users WHERE role = 'admin' ORDER BY createdAt ASC LIMIT 1`)?.id || null;
if (!fallbackOwnerId) throw new Error("Database import requires an administrator owner for provider connections");
for (const c of payload.providerConnections || []) { for (const c of payload.providerConnections || []) {
const { id, provider, authType, name, email, ownerId, priority, isActive, createdAt, updatedAt, ...rest } = c; const { id, provider, authType, name, email, ownerId, priority, isActive, createdAt, updatedAt, ...rest } = c;
if (ownerId && !adminOwnerIds.has(ownerId)) continue;
db.run( db.run(
`INSERT OR REPLACE INTO providerConnections(id, provider, authType, name, email, ownerId, priority, isActive, data, createdAt, updatedAt) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, `INSERT OR REPLACE INTO providerConnections(id, provider, authType, name, email, ownerId, priority, isActive, data, createdAt, updatedAt) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[id, provider, authType || "oauth", name || null, email || null, ownerId || fallbackOwnerId, priority || null, isActive === false ? 0 : 1, stringifyJson(rest), createdAt || new Date().toISOString(), updatedAt || new Date().toISOString()] [id, provider, authType || "oauth", name || null, email || null, ownerId || fallbackOwnerId, priority || null, isActive === false ? 0 : 1, stringifyJson(rest), createdAt || new Date().toISOString(), updatedAt || new Date().toISOString()]
@@ -0,0 +1,33 @@
// Provider credentials are shared system infrastructure and may only belong
// to administrators. Remove legacy regular-user/orphaned credentials rather
// than silently preserving credentials a regular user can no longer manage.
const adminProviderConnectionsMigration = {
version: 7,
name: "admin-provider-connections",
up(db) {
const fallbackAdmin = db.get(
`SELECT id FROM users WHERE role = 'admin' ORDER BY createdAt ASC LIMIT 1`,
);
if (fallbackAdmin) {
db.run(
`UPDATE providerConnections
SET ownerId = ?
WHERE ownerId IS NULL OR ownerId = ''`,
[fallbackAdmin.id],
);
}
db.run(
`DELETE FROM providerConnections
WHERE NOT EXISTS (
SELECT 1
FROM users
WHERE users.id = providerConnections.ownerId
AND users.role = 'admin'
)`,
);
},
};
export default adminProviderConnectionsMigration;
+2 -1
View File
@@ -7,8 +7,9 @@ import m003 from "./003-api-key-owners.js";
import m004 from "./004-provider-connection-owners.js"; import m004 from "./004-provider-connection-owners.js";
import m005 from "./005-usage-user-attribution.js"; import m005 from "./005-usage-user-attribution.js";
import m006 from "./006-combo-owners.js"; import m006 from "./006-combo-owners.js";
import m007 from "./007-admin-provider-connections.js";
export const MIGRATIONS = [m001, m002, m003, m004, m005, m006].sort((a, b) => a.version - b.version); export const MIGRATIONS = [m001, m002, m003, m004, m005, m006, m007].sort((a, b) => a.version - b.version);
export function latestVersion() { export function latestVersion() {
return MIGRATIONS.length ? MIGRATIONS[MIGRATIONS.length - 1].version : 0; return MIGRATIONS.length ? MIGRATIONS[MIGRATIONS.length - 1].version : 0;
+13
View File
@@ -157,6 +157,14 @@ function reorderInTx(db, providerId) {
export async function createProviderConnection(data) { export async function createProviderConnection(data) {
const db = await getAdapter(); const db = await getAdapter();
const owner = data.ownerId
? db.get(`SELECT id, role FROM users WHERE id = ?`, [data.ownerId])
: null;
if (!owner || owner.role !== "admin") {
const error = new Error("Provider connections require an administrator owner");
error.status = 403;
throw error;
}
const now = new Date().toISOString(); const now = new Date().toISOString();
let result; let result;
@@ -210,6 +218,11 @@ export async function createProviderConnection(data) {
return result; return result;
} }
export async function countProviderConnectionsByOwnerId(ownerId) {
const db = await getAdapter();
return db.get(`SELECT COUNT(*) AS count FROM providerConnections WHERE ownerId = ?`, [ownerId])?.count || 0;
}
// Critical: OAuth refresh token race — atomic merge inside transaction // Critical: OAuth refresh token race — atomic merge inside transaction
export async function updateProviderConnection(id, data) { export async function updateProviderConnection(id, data) {
const db = await getAdapter(); const db = await getAdapter();
+1 -1
View File
@@ -3,7 +3,7 @@
// pre-change safety backup in migrate.js: when the stored version is lower, // pre-change safety backup in migrate.js: when the stored version is lower,
// one lightweight DB backup is taken before applying schema changes. Forgetting // one lightweight DB backup is taken before applying schema changes. Forgetting
// to bump only skips that backup — it does NOT break the additive auto-sync. // to bump only skips that backup — it does NOT break the additive auto-sync.
export const SCHEMA_VERSION = 6; export const SCHEMA_VERSION = 7;
export const PRAGMA_SQL = ` export const PRAGMA_SQL = `
PRAGMA journal_mode = WAL; PRAGMA journal_mode = WAL;
+21 -4
View File
@@ -1,9 +1,26 @@
import { requireCurrentDashboardUser } from "@/lib/auth/currentUser"; import { requireAdminUser } from "@/lib/auth/currentUser";
import { getUsers } from "@/lib/db";
import { hasValidCliToken } from "@/dashboardGuard";
export async function getProviderConnectionAccess() { /**
const user = await requireCurrentDashboardUser(); * Provider credentials are system-managed. Only administrators may inspect
* or mutate their connections; request API-key ownership remains separate
* and is used solely for authentication and usage attribution.
*/
export async function requireProviderAdministrator(request) {
if (request && await hasValidCliToken(request)) {
const admin = (await getUsers()).find((user) => user.role === "admin" && user.isActive);
if (!admin) throw new Error("No active administrator available for provider management");
return admin;
}
return requireAdminUser();
}
export async function getProviderConnectionAccess(request) {
const user = await requireProviderAdministrator(request);
return { return {
user, user,
ownerId: user.role === "admin" ? null : user.id, ownerId: null,
}; };
} }
+1 -1
View File
@@ -16,7 +16,7 @@ const COMBINED_WEB_ITEM = { id: "web", label: "Web Fetch & Search", icon: "trave
const navItems = [ const navItems = [
{ href: "/dashboard/endpoint", label: "Endpoint & Key", icon: "api" }, { href: "/dashboard/endpoint", label: "Endpoint & Key", icon: "api" },
{ href: "/dashboard/providers", label: "Providers", icon: "dns" }, { href: "/dashboard/providers", label: "Providers", icon: "dns", adminOnly: true },
{ href: "/dashboard/models", label: "Models", icon: "view_list" }, { href: "/dashboard/models", label: "Models", icon: "view_list" },
// { href: "/dashboard/basic-chat", label: "Basic Chat", icon: "chat" }, // Hidden // { href: "/dashboard/basic-chat", label: "Basic Chat", icon: "chat" }, // Hidden
{ href: "/dashboard/combos", label: "Combos", icon: "layers" }, { href: "/dashboard/combos", label: "Combos", icon: "layers" },
@@ -0,0 +1,65 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
let tempDir;
const originalDataDir = process.env.DATA_DIR;
beforeEach(() => {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "9router-admin-providers-"));
process.env.DATA_DIR = tempDir;
delete global._dbAdapter;
vi.resetModules();
});
afterEach(() => {
try { global._dbAdapter?.instance?.close?.(); } catch {}
delete global._dbAdapter;
fs.rmSync(tempDir, { recursive: true, force: true });
if (originalDataDir === undefined) delete process.env.DATA_DIR;
else process.env.DATA_DIR = originalDataDir;
});
describe("administrator provider connections", () => {
it("rejects provider credentials owned by a regular user", async () => {
const db = await import("@/lib/db/index.js");
const user = await db.createUser({ username: "provider-member", password: "password", role: "user" });
await expect(db.createProviderConnection({
provider: "openai",
authType: "apikey",
name: "Member key",
apiKey: "secret",
ownerId: user.id,
})).rejects.toMatchObject({
message: "Provider connections require an administrator owner",
status: 403,
});
});
it("removes user and orphan credentials while retaining legacy credentials for an administrator", async () => {
const db = await import("@/lib/db/index.js");
const { getAdapter } = await import("@/lib/db/driver.js");
const migration = (await import("@/lib/db/migrations/007-admin-provider-connections.js")).default;
const admin = await db.createUser({ username: "migration-admin", password: "password", role: "admin" });
const member = await db.createUser({ username: "migration-member", password: "password", role: "user" });
const adapter = await getAdapter();
const now = new Date().toISOString();
for (const [id, ownerId] of [["legacy", null], ["member", member.id], ["orphan", "missing-user"], ["admin", admin.id]]) {
adapter.run(
`INSERT INTO providerConnections(id, provider, authType, ownerId, isActive, data, createdAt, updatedAt)
VALUES(?, 'openai', 'apikey', ?, 1, '{}', ?, ?)`,
[id, ownerId, now, now],
);
}
adapter.transaction(() => migration.up(adapter));
const remaining = await db.getProviderConnections();
expect(remaining.map((connection) => connection.id).sort()).toEqual(["admin", "legacy"]);
const firstAdmin = (await db.getUsers()).find((user) => user.role === "admin");
expect(remaining.find((connection) => connection.id === "legacy")?.ownerId).toBe(firstAdmin.id);
});
});
+8 -8
View File
@@ -26,8 +26,6 @@ describe("API-key credential access", () => {
const db = await import("@/lib/db/index.js"); const db = await import("@/lib/db/index.js");
const { getProviderCredentials } = await import("@/sse/services/auth.js"); const { getProviderCredentials } = await import("@/sse/services/auth.js");
const admin = await db.createUser({ username: "credential-admin", password: "password", role: "admin" }); const admin = await db.createUser({ username: "credential-admin", password: "password", role: "admin" });
const userA = await db.createUser({ username: "credential-user-a", password: "password", role: "user" });
const userB = await db.createUser({ username: "credential-user-b", password: "password", role: "user" });
const userC = await db.createUser({ username: "credential-user-c", password: "password", role: "user" }); const userC = await db.createUser({ username: "credential-user-c", password: "password", role: "user" });
const adminConnection = await db.createProviderConnection({ const adminConnection = await db.createProviderConnection({
provider: "antigravity", provider: "antigravity",
@@ -36,19 +34,21 @@ describe("API-key credential access", () => {
accessToken: "admin-token", accessToken: "admin-token",
ownerId: admin.id, ownerId: admin.id,
}); });
const secondAdmin = await db.createUser({ username: "credential-admin-two", password: "password", role: "admin" });
const thirdAdmin = await db.createUser({ username: "credential-admin-three", password: "password", role: "admin" });
const userAConnection = await db.createProviderConnection({ const userAConnection = await db.createProviderConnection({
provider: "antigravity", provider: "antigravity",
authType: "oauth", authType: "oauth",
name: "user-a-antigravity", name: "second-admin-antigravity",
accessToken: "user-a-token", accessToken: "second-admin-token",
ownerId: userA.id, ownerId: secondAdmin.id,
}); });
const userBConnection = await db.createProviderConnection({ const userBConnection = await db.createProviderConnection({
provider: "antigravity", provider: "antigravity",
authType: "oauth", authType: "oauth",
name: "user-b-antigravity", name: "third-admin-antigravity",
accessToken: "user-b-token", accessToken: "third-admin-token",
ownerId: userB.id, ownerId: thirdAdmin.id,
}); });
const firstCredentials = await getProviderCredentials("antigravity", new Set(), "gemini-2.5-pro", { const firstCredentials = await getProviderCredentials("antigravity", new Set(), "gemini-2.5-pro", {
@@ -8,6 +8,8 @@ const originalDataDir = process.env.DATA_DIR;
async function setupTestContext(nodeData) { async function setupTestContext(nodeData) {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "9router-compatible-provider-")); const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "9router-compatible-provider-"));
process.env.DATA_DIR = tempDir; process.env.DATA_DIR = tempDir;
try { global._dbAdapter?.instance?.close?.(); } catch {}
delete global._dbAdapter;
vi.resetModules(); vi.resetModules();
vi.doMock("next/server", () => ({ vi.doMock("next/server", () => ({
NextResponse: { NextResponse: {
@@ -19,12 +21,16 @@ async function setupTestContext(nodeData) {
}, },
}, },
})); }));
const { POST } = await import("@/app/api/providers/route.js");
const { const {
createProviderNode, createProviderNode,
getProviderConnections, getProviderConnections,
} = await import("@/models/index.js"); } = await import("@/models/index.js");
const { createUser } = await import("@/lib/db/index.js");
const admin = await createUser({ username: "provider-admin", password: "password", role: "admin" });
vi.doMock("@/lib/providers/connectionAccess", () => ({
getProviderConnectionAccess: vi.fn().mockResolvedValue({ user: admin, ownerId: null }),
}));
const { POST } = await import("@/app/api/providers/route.js");
const node = await createProviderNode(nodeData); const node = await createProviderNode(nodeData);
@@ -38,13 +44,13 @@ async function setupTestContext(nodeData) {
}; };
} }
function makeRequest(provider, name = "Test Connection") { function makeRequest(provider, name = "Test Connection", apiKey = "test-key") {
return new Request("https://9router.local/api/providers", { return new Request("https://9router.local/api/providers", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ body: JSON.stringify({
provider, provider,
apiKey: "test-key", apiKey,
name, name,
defaultModel: "test-model", defaultModel: "test-model",
}), }),
@@ -74,6 +80,8 @@ describe("compatible provider connections API", () => {
}); });
afterEach(() => { afterEach(() => {
try { global._dbAdapter?.instance?.close?.(); } catch {}
delete global._dbAdapter;
vi.doUnmock("next/server"); vi.doUnmock("next/server");
vi.resetModules(); vi.resetModules();
vi.clearAllMocks(); vi.clearAllMocks();
@@ -157,7 +165,7 @@ describe("compatible provider connections API", () => {
cleanup = ctx.cleanup; cleanup = ctx.cleanup;
const firstResponse = await ctx.POST(makeRequest(ctx.node.id, "Key A")); const firstResponse = await ctx.POST(makeRequest(ctx.node.id, "Key A"));
const secondResponse = await ctx.POST(makeRequest(ctx.node.id, "Key B")); const secondResponse = await ctx.POST(makeRequest(ctx.node.id, "Key B", "test-key-b"));
const storedConnections = await ctx.getProviderConnections({ provider: ctx.node.id }); const storedConnections = await ctx.getProviderConnections({ provider: ctx.node.id });
expect(firstResponse.status).toBe(201); expect(firstResponse.status).toBe(201);
+46
View File
@@ -340,6 +340,52 @@ describe("dashboard guard token saver administration access", () => {
}); });
}); });
describe("dashboard guard provider administration access", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.getSettings.mockResolvedValue({});
mocks.getUserById.mockResolvedValue({ id: "user-1", isActive: true, role: "user" });
mocks.getConsistentMachineId.mockResolvedValue("cli-token");
mocks.getDashboardAuthSession.mockResolvedValue({ userId: "user-1" });
mocks.verifyDashboardAuthToken.mockResolvedValue(true);
});
it("rejects normal users from provider pages and management APIs", async () => {
for (const pathname of [
"/api/providers",
"/api/providers/connection-id/test",
"/api/provider-nodes",
"/api/oauth/codex/authorize",
]) {
const response = await proxy(request(pathname, { host: "localhost:20128" }, "user-token"));
expect(response.status).toBe(403);
expect(response.body.error).toBe("Administrator access required");
}
for (const pathname of ["/dashboard/providers", "/dashboard/providers/openai"]) {
const response = await proxy(request(pathname, { host: "localhost:20128" }, "user-token"));
expect(response.status).toBe(307);
expect(response.url.href).toBe("http://localhost/dashboard");
}
});
it("allows administrators to access provider pages and APIs", async () => {
mocks.getUserById.mockResolvedValue({ id: "user-1", isActive: true, role: "admin" });
for (const pathname of [
"/dashboard/providers",
"/dashboard/providers/openai",
"/api/providers",
"/api/provider-nodes",
"/api/oauth/codex/authorize",
]) {
expect(await proxy(request(pathname, { host: "localhost:20128" }, "admin-token"))).toBe(mocks.nextResponse);
}
});
});
describe("dashboard guard helpers", () => { describe("dashboard guard helpers", () => {
it("extracts bearer API keys before x-api-key", () => { it("extracts bearer API keys before x-api-key", () => {
const apiRequest = request("/v1/chat/completions", { const apiRequest = request("/v1/chat/completions", {
@@ -30,7 +30,7 @@ const adminAccess = {
ownerId: null, ownerId: null,
}; };
describe("provider connection administrator-managed access", () => { describe("provider connection administrator-only access", () => {
beforeEach(() => { beforeEach(() => {
getProviderConnectionById.mockReset(); getProviderConnectionById.mockReset();
getProxyPoolById.mockReset(); getProxyPoolById.mockReset();
@@ -39,7 +39,7 @@ describe("provider connection administrator-managed access", () => {
getProviderConnectionAccess.mockReset(); getProviderConnectionAccess.mockReset();
}); });
it("prevents a member from updating their legacy compatible connection", async () => { it("prevents a member from updating a provider connection", async () => {
getProviderConnectionAccess.mockResolvedValue(memberAccess); getProviderConnectionAccess.mockResolvedValue(memberAccess);
getProviderConnectionById.mockResolvedValue({ getProviderConnectionById.mockResolvedValue({
id: "legacy-compatible", id: "legacy-compatible",
@@ -56,7 +56,7 @@ describe("provider connection administrator-managed access", () => {
expect(updateProviderConnection).not.toHaveBeenCalled(); expect(updateProviderConnection).not.toHaveBeenCalled();
}); });
it("prevents a member from deleting their legacy compatible connection", async () => { it("prevents a member from deleting a provider connection", async () => {
getProviderConnectionAccess.mockResolvedValue(memberAccess); getProviderConnectionAccess.mockResolvedValue(memberAccess);
getProviderConnectionById.mockResolvedValue({ getProviderConnectionById.mockResolvedValue({
id: "legacy-compatible", id: "legacy-compatible",
@@ -89,7 +89,7 @@ describe("provider connection administrator-managed access", () => {
expect(deleteProviderConnection).toHaveBeenCalledWith("compatible"); expect(deleteProviderConnection).toHaveBeenCalledWith("compatible");
}); });
it("preserves member control over their non-compatible connection", async () => { it("prevents a member from updating a non-compatible connection", async () => {
getProviderConnectionAccess.mockResolvedValue(memberAccess); getProviderConnectionAccess.mockResolvedValue(memberAccess);
getProviderConnectionById.mockResolvedValue({ getProviderConnectionById.mockResolvedValue({
id: "openai-connection", id: "openai-connection",
@@ -98,21 +98,12 @@ describe("provider connection administrator-managed access", () => {
providerSpecificData: {}, providerSpecificData: {},
authType: "apikey", authType: "apikey",
}); });
updateProviderConnection.mockResolvedValue({
id: "openai-connection",
provider: "openai",
name: "Changed",
});
const response = await PUT(new Request("http://localhost/api/providers/openai-connection", { const response = await PUT(new Request("http://localhost/api/providers/openai-connection", {
method: "PUT", method: "PUT",
body: JSON.stringify({ name: "Changed" }), body: JSON.stringify({ name: "Changed" }),
}), { params: Promise.resolve({ id: "openai-connection" }) }); }), { params: Promise.resolve({ id: "openai-connection" }) });
expect(response.status).toBe(200); expect(response.status).toBe(403);
expect(updateProviderConnection).toHaveBeenCalledWith("openai-connection", { expect(updateProviderConnection).not.toHaveBeenCalled();
name: "Changed",
providerSpecificData: {},
});
}); });
}); });