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
@@ -10,7 +10,6 @@ import { getModelsByProviderId, getModelKind } from "@/shared/constants/models";
import { getThinkingLevels } from "open-sse/providers/thinkingLevels.js";
import { useCopyToClipboard } from "@/shared/hooks/useCopyToClipboard";
import { useModelCaps } from "@/shared/hooks/useModelCaps";
import useUserStore from "@/store/userStore";
import { translate } from "@/i18n/runtime";
import { fetchSuggestedModels } from "@/shared/utils/providerModelsFetcher";
import { getProviderCustomModelRows } from "@/shared/utils/providerCustomModels";
@@ -39,7 +38,6 @@ export default function ProviderDetailPage() {
const router = useRouter();
const providerId = params.id;
const { getCaps } = useModelCaps();
const user = useUserStore((state) => state.user);
const [connections, setConnections] = useState([]);
const [loading, setLoading] = useState(true);
const [providerNode, setProviderNode] = useState(null);
@@ -81,8 +79,6 @@ export default function ProviderDetailPage() {
const [importingQoderModels, setImportingQoderModels] = useState(false);
const { copied, copy } = useCopyToClipboard();
const canManageModelAvailability = user?.role === "admin";
const AG_RISK_STORAGE_KEY = "ag_risk_confirmed";
const openOAuthConnection = () => {
@@ -1121,7 +1117,7 @@ export default function ProviderDetailPage() {
onTest={connections.length > 0 || isFreeNoAuth ? () => handleTestModel(model.id) : undefined}
isTesting={testingModelIds.has(model.id)}
isFree={model.isFree}
onDisable={canManageModelAvailability ? () => handleDisableModel(model.id) : undefined}
onDisable={() => handleDisableModel(model.id)}
caps={getCaps(`${providerId}/${model.id}`)}
thinkingSuffix={resolveThinkingSuffix(model.id)}
/>
@@ -1185,7 +1181,7 @@ export default function ProviderDetailPage() {
})()}
{/* Disabled models — restorable */}
{canManageModelAvailability && disabledDisplayModels.length > 0 && (
{disabledDisplayModels.length > 0 && (
<div className="w-full mt-2">
<p className="text-xs text-text-muted mb-2">Disabled models ({disabledDisplayModels.length}):</p>
<div className="flex flex-wrap gap-2">
@@ -1616,7 +1612,7 @@ export default function ProviderDetailPage() {
</select>
)}
</div>
{canManageModelAvailability && !isCompatible && (() => {
{!isCompatible && (() => {
const allIds = [
...models,
...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 { useNotificationStore } from "@/store/notificationStore";
import { useHeaderSearchStore } from "@/store/headerSearchStore";
import useUserStore from "@/store/userStore";
import ModelAvailabilityBadge from "./components/ModelAvailabilityBadge";
import AddCompatibleModal from "./components/AddCompatibleModal";
@@ -106,12 +105,9 @@ export default function ProvidersPage() {
const [testingMode, setTestingMode] = useState(null);
const [testResults, setTestResults] = useState(null);
const notify = useNotificationStore();
const user = useUserStore((state) => state.user);
const searchQuery = useHeaderSearchStore((s) => s.query);
const registerSearch = useHeaderSearchStore((s) => s.register);
const unregisterSearch = useHeaderSearchStore((s) => s.unregister);
const isAdmin = user?.role === "admin";
useEffect(() => {
registerSearch("Search providers...");
return () => unregisterSearch();
@@ -287,7 +283,6 @@ export default function ProvidersPage() {
.filter(
([, info]) =>
!info.hidden &&
(user?.role === "admin" || !info.noAuth) &&
matchSearch(info.name),
)
.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(
([, info]) =>
!info.hidden &&
(user?.role === "admin" || !info.noAuth) &&
matchSearch(info.name) &&
(info.serviceKinds ?? ["llm"]).includes("llm"),
),
@@ -336,10 +330,10 @@ export default function ProvidersPage() {
freeEntries.length > 0 ||
freeTierEntries.length > 0 ||
apikeyEntries.length > 0 ||
(isAdmin && (
(
compatibleProviders.length > 0 ||
anthropicCompatibleProviders.length > 0
));
);
return (
<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. */}
{isAdmin && (
<div className="flex flex-col gap-4">
<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">
@@ -404,7 +397,6 @@ export default function ProvidersPage() {
</div>
)}
</div>
)}
{/* OAuth Providers */}
{oauthEntries.length > 0 && (
@@ -582,7 +574,7 @@ export default function ProvidersPage() {
</div>
</div> */}
{isAdmin && <AddCompatibleModal
<AddCompatibleModal
variant="openai"
isOpen={showAddCompatibleModal}
onClose={() => setShowAddCompatibleModal(false)}
@@ -590,8 +582,8 @@ export default function ProvidersPage() {
setProviderNodes((prev) => [...prev, node]);
setShowAddCompatibleModal(false);
}}
/>}
{isAdmin && <AddCompatibleModal
/>
<AddCompatibleModal
variant="anthropic"
isOpen={showAddAnthropicCompatibleModal}
onClose={() => setShowAddAnthropicCompatibleModal(false)}
@@ -599,7 +591,7 @@ export default function ProvidersPage() {
setProviderNodes((prev) => [...prev, node]);
setShowAddAnthropicCompatibleModal(false);
}}
/>}
/>
{/* Test Results Modal */}
{testResults && (
@@ -17,13 +17,13 @@ async function fetchProviderNames() {
return { providerNameCache, providerNodesCache };
}
const nodesRes = await fetch("/api/provider-nodes");
const nodesData = await nodesRes.json();
const nodes = nodesData.nodes || [];
const topologyRes = await fetch("/api/usage/topology-providers");
const topologyData = topologyRes.ok ? await topologyRes.json() : {};
const nodes = topologyData.providers || [];
providerNodesCache = {};
for (const node of nodes) {
providerNodesCache[node.id] = node.name;
providerNodesCache[node.provider] = node.nodeName || node.name || node.provider;
}
providerNameCache = {
@@ -70,7 +70,7 @@ async function completeXaiManualCode(code, state, ownerId) {
// GET /api/oauth/[provider]/device-code - Request device code (for device_code flow)
export async function GET(request, { params }) {
try {
const { user } = await getProviderConnectionAccess();
const { user } = await getProviderConnectionAccess(request);
const { provider, action } = await params;
const { searchParams } = new URL(request.url);
@@ -184,6 +184,9 @@ export async function GET(request, { params }) {
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("OAuth GET error:", error);
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)
export async function POST(request, { params }) {
try {
const { user } = await getProviderConnectionAccess();
const { user } = await getProviderConnectionAccess(request);
const { provider, action } = await params;
let body;
try {
@@ -362,6 +365,9 @@ export async function POST(request, { params }) {
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("OAuth POST error:", error);
return NextResponse.json({ error: error.message }, { status: error.status || 500 });
}
+4 -5
View File
@@ -1,7 +1,7 @@
import { NextResponse } from "next/server";
import { createProviderConnection } from "@/models";
import { extractCodexAccountInfo } from "@/lib/oauth/providers";
import { requireCurrentDashboardUser } from "@/lib/auth/currentUser";
import { requireProviderAdministrator } from "@/lib/providers/connectionAccess";
/**
* POST /api/oauth/codex/bulk-import
@@ -20,11 +20,10 @@ import { requireCurrentDashboardUser } from "@/lib/auth/currentUser";
export async function POST(request) {
let user;
try {
user = await requireCurrentDashboardUser();
user = await requireProviderAdministrator(request);
} catch (error) {
if (error.message === "Unauthorized") {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
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 });
}
@@ -12,7 +12,7 @@ import { getProviderConnectionAccess } from "@/lib/providers/connectionAccess";
*/
export async function POST(request) {
try {
const { user } = await getProviderConnectionAccess();
const { user } = await getProviderConnectionAccess(request);
const { accessToken, name } = await request.json();
if (!accessToken || typeof accessToken !== "string") {
@@ -1,4 +1,5 @@
import { NextResponse } from "next/server";
import { requireProviderAdministrator } from "@/lib/providers/connectionAccess";
import { access, constants } from "fs/promises";
import { homedir } from "os";
import { join } from "path";
@@ -174,8 +175,9 @@ async function extractTokensViaCLI(dbPath) {
* Auto-detect and extract Cursor tokens from local SQLite database.
* Strategy: better-sqlite3 → sqlite3 CLI → manual fallback
*/
export async function GET() {
export async function GET(request) {
try {
await requireProviderAdministrator(request);
const platform = process.platform;
const candidates = getCandidatePaths(platform);
@@ -249,6 +251,8 @@ export async function GET() {
// Strategy 3: ask user to paste manually
return NextResponse.json({ found: false, windowsManual: true, dbPath });
} 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);
return NextResponse.json(
{ found: false, error: error.message },
+1 -1
View File
@@ -13,7 +13,7 @@ import { getProviderConnectionAccess } from "@/lib/providers/connectionAccess";
*/
export async function POST(request) {
try {
const { user } = await getProviderConnectionAccess();
const { user } = await getProviderConnectionAccess(request);
const { accessToken, machineId } = await request.json();
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) {
try {
const { user: dashboardUser } = await getProviderConnectionAccess();
const { user: dashboardUser } = await getProviderConnectionAccess(request);
let body;
try {
body = await request.json();
+1 -1
View File
@@ -9,7 +9,7 @@ import { getProviderConnectionAccess } from "@/lib/providers/connectionAccess";
*/
export async function POST(request) {
try {
const { user } = await getProviderConnectionAccess();
const { user } = await getProviderConnectionAccess(request);
const { cookie } = await request.json();
if (!cookie || typeof cookie !== "string") {
+1 -1
View File
@@ -11,7 +11,7 @@ import { getProviderConnectionAccess } from "@/lib/providers/connectionAccess";
*/
export async function POST(request) {
try {
const { user } = await getProviderConnectionAccess();
const { user } = await getProviderConnectionAccess(request);
const { apiKey, region } = await request.json();
if (!apiKey || typeof apiKey !== "string" || !apiKey.trim()) {
+5 -1
View File
@@ -1,4 +1,5 @@
import { NextResponse } from "next/server";
import { requireProviderAdministrator } from "@/lib/providers/connectionAccess";
import { readFile, readdir } from "fs/promises";
import { homedir } from "os";
import { join } from "path";
@@ -9,8 +10,9 @@ import { join } from "path";
* For IDC (organization) tokens, also resolves clientId/clientSecret from the
* linked client registration file so token refresh works.
*/
export async function GET() {
export async function GET(request) {
try {
await requireProviderAdministrator(request);
const cachePath = join(homedir(), ".aws/sso/cache");
let files;
@@ -123,6 +125,8 @@ export async function GET() {
profileArn,
});
} 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);
return NextResponse.json(
{ found: false, error: error.message },
@@ -9,7 +9,7 @@ import { getProviderConnectionAccess } from "@/lib/providers/connectionAccess";
*/
export async function POST(request) {
try {
const { user } = await getProviderConnectionAccess();
const { user } = await getProviderConnectionAccess(request);
const body = await request.json();
const rawAuth = body?.cliProxyAuth ?? body?.auth ?? body?.json ?? body;
const tokenData = normalizeKiroExternalIdpAuth(rawAuth);
+1 -1
View File
@@ -11,7 +11,7 @@ import { getProviderConnectionAccess } from "@/lib/providers/connectionAccess";
*/
export async function POST(request) {
try {
const { user } = await getProviderConnectionAccess();
const { user } = await getProviderConnectionAccess(request);
const { refreshToken, clientId, clientSecret, region, authMethod, profileArn } = await request.json();
if (!refreshToken || typeof refreshToken !== "string") {
@@ -1,6 +1,7 @@
import { NextResponse } from "next/server";
import { generatePKCE } from "@/lib/oauth/utils/pkce";
import { KiroService } from "@/lib/oauth/services/kiro";
import { requireProviderAdministrator } from "@/lib/providers/connectionAccess";
/**
* GET /api/oauth/kiro/social-authorize
@@ -9,6 +10,7 @@ import { KiroService } from "@/lib/oauth/services/kiro";
*/
export async function GET(request) {
try {
await requireProviderAdministrator(request);
const { searchParams } = new URL(request.url);
const provider = searchParams.get("provider"); // "google" or "github"
@@ -37,6 +39,8 @@ export async function GET(request) {
provider,
});
} 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);
return NextResponse.json({ error: error.message }, { status: 500 });
}
@@ -10,7 +10,7 @@ import { getProviderConnectionAccess } from "@/lib/providers/connectionAccess";
*/
export async function POST(request) {
try {
const { user } = await getProviderConnectionAccess();
const { user } = await getProviderConnectionAccess(request);
const { code, codeVerifier, provider } = await request.json();
if (!code || !codeVerifier) {
+3 -3
View File
@@ -1,6 +1,6 @@
import { NextResponse } from "next/server";
import { deleteProviderConnectionsByProvider, deleteProviderNode, getProviderConnections, getProviderNodeById, updateProviderConnection, updateProviderNode } from "@/models";
import { requireAdminUser } from "@/lib/auth/currentUser";
import { requireProviderAdministrator } from "@/lib/providers/connectionAccess";
function getAccessErrorResponse(error) {
if (error.message === "Unauthorized") {
@@ -15,7 +15,7 @@ function getAccessErrorResponse(error) {
// PUT /api/provider-nodes/[id] - Update provider node
export async function PUT(request, { params }) {
try {
await requireAdminUser();
await requireProviderAdministrator(request);
const { id } = await params;
const body = await request.json();
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
export async function DELETE(request, { params }) {
try {
await requireAdminUser();
await requireProviderAdministrator(request);
const { id } = await params;
const node = await getProviderNodeById(id);
+4 -4
View File
@@ -1,6 +1,6 @@
import { NextResponse } from "next/server";
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 { generateId } from "@/shared/utils";
@@ -29,9 +29,9 @@ function getAccessErrorResponse(error) {
}
// GET /api/provider-nodes - List all provider nodes
export async function GET() {
export async function GET(request) {
try {
await requireAdminUser();
await requireProviderAdministrator(request);
const nodes = await getProviderNodes();
return NextResponse.json({ nodes });
} catch (error) {
@@ -46,7 +46,7 @@ export async function GET() {
// POST /api/provider-nodes - Create provider node
export async function POST(request) {
try {
await requireAdminUser();
await requireProviderAdministrator(request);
const body = await request.json();
const { name, prefix, apiType, baseUrl, type } = body;
@@ -1,6 +1,7 @@
import { NextResponse } from "next/server";
import { assertPublicUrl } from "@/shared/utils/ssrfGuard.js";
import { isLocalRequest } from "@/dashboardGuard";
import { requireProviderAdministrator } from "@/lib/providers/connectionAccess";
// Fetch with timeout wrapper
const fetchWithTimeout = (url, options, timeout = 10000) => {
@@ -54,6 +55,7 @@ const getChatErrorMessage = (status) => {
// POST /api/provider-nodes/validate - Validate API key against base URL
export async function POST(request) {
try {
await requireProviderAdministrator(request);
const body = await request.json();
const { baseUrl, apiKey, type, modelId } = body;
@@ -197,6 +199,8 @@ export async function POST(request) {
return NextResponse.json({ valid: false, error: getModelsErrorMessage(res.status) });
} 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);
console.error("Error validating provider node:", {
message: error.message,
+1 -1
View File
@@ -394,7 +394,7 @@ const PROVIDER_MODELS_CONFIG = {
export async function GET(request, { params }) {
try {
const { id } = await params;
const { ownerId } = await getProviderConnectionAccess();
const { ownerId } = await getProviderConnectionAccess(request);
const connection = await getProviderConnectionById(id, ownerId);
if (!connection) {
+13 -16
View File
@@ -6,20 +6,8 @@ import {
deleteProviderConnection,
} from "@/models";
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) {
return !isAdministratorManagedProvider(connection.provider) || user.role === "admin";
return user.role === "admin";
}
function normalizeProxyConfig(body = {}) {
@@ -79,7 +67,7 @@ function shouldMergeProviderSpecificData(existing, incoming, hasLegacyProxy, has
export async function GET(request, { params }) {
try {
const { id } = await params;
const { ownerId } = await getProviderConnectionAccess();
const { ownerId } = await getProviderConnectionAccess(request);
const connection = await getProviderConnectionById(id, ownerId);
if (!connection) {
@@ -98,6 +86,9 @@ export async function GET(request, { params }) {
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 fetching connection:", error);
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 }) {
try {
const { id } = await params;
const { user, ownerId } = await getProviderConnectionAccess();
const { user, ownerId } = await getProviderConnectionAccess(request);
const body = await request.json();
const {
name,
@@ -193,6 +184,9 @@ export async function PUT(request, { params }) {
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 updating connection:", error);
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 }) {
try {
const { id } = await params;
const { user, ownerId } = await getProviderConnectionAccess();
const { user, ownerId } = await getProviderConnectionAccess(request);
const existing = await getProviderConnectionById(id, ownerId);
if (!existing) {
@@ -222,6 +216,9 @@ export async function DELETE(request, { params }) {
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 deleting connection:", error);
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 }) {
try {
const { id } = await params;
const { ownerId } = await getProviderConnectionAccess();
const { ownerId } = await getProviderConnectionAccess(request);
const connection = await getProviderConnectionById(id, ownerId);
if (!connection) {
return NextResponse.json({ error: "Connection not found" }, { status: 404 });
@@ -65,6 +65,9 @@ export async function POST(request, { params }) {
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 testing models:", error);
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 }) {
try {
const { id } = await params;
const { ownerId } = await getProviderConnectionAccess();
const { ownerId } = await getProviderConnectionAccess(request);
const connection = await getProviderConnectionById(id, ownerId);
if (!connection) {
return NextResponse.json({ error: "Connection not found" }, { status: 404 });
@@ -27,6 +27,9 @@ export async function POST(request, { params }) {
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 testing connection:", error);
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) {
try {
const { ownerId } = await getProviderConnectionAccess();
const { ownerId } = await getProviderConnectionAccess(request);
await backfillCodexEmails();
const { searchParams } = new URL(request.url);
@@ -126,6 +126,9 @@ export async function GET(request) {
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 fetching providers for client:", error);
return NextResponse.json({ error: "Failed to fetch providers" }, { status: 500 });
}
@@ -1,4 +1,5 @@
import { NextResponse } from "next/server";
import { requireProviderAdministrator } from "@/lib/providers/connectionAccess";
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
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();
// Return cached result if still valid
+9 -3
View File
@@ -48,9 +48,9 @@ async function normalizeProxyPoolId(proxyPoolId) {
}
// GET /api/providers - List all connections
export async function GET() {
export async function GET(request) {
try {
const { ownerId } = await getProviderConnectionAccess();
const { ownerId } = await getProviderConnectionAccess(request);
const connections = await getProviderConnections(ownerId ? { ownerId } : {});
// Build nodeNameMap for compatible providers (id → name)
@@ -83,6 +83,9 @@ export async function GET() {
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 fetching providers:", error);
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)
export async function POST(request) {
try {
const { user } = await getProviderConnectionAccess();
const { user } = await getProviderConnectionAccess(request);
const body = await request.json();
const provider = normalizeProviderId(body.provider);
const { apiKey, name, displayName, priority, globalPriority, defaultModel, testStatus } = body;
@@ -205,6 +208,9 @@ export async function POST(request) {
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 creating provider:", error);
return NextResponse.json(
{ error: error.status === 409 ? error.message : "Failed to create provider" },
@@ -1,9 +1,18 @@
import { NextResponse } from "next/server";
import { FILTERS } from "./filters.js";
import { requireProviderAdministrator } from "@/lib/providers/connectionAccess";
export const dynamic = "force-dynamic";
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 url = searchParams.get("url");
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
export async function POST(request) {
try {
const { ownerId } = await getProviderConnectionAccess();
const { ownerId } = await getProviderConnectionAccess(request);
const body = await request.json();
const { mode, providerId } = body;
@@ -133,6 +133,9 @@ export async function POST(request) {
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 in batch test:", error);
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 { openaiToCommandCodeRequest } from "open-sse/translator/request/openai-to-commandcode.js";
import { normalizeProviderId } from "@/lib/providerNormalization";
import { requireProviderAdministrator } from "@/lib/providers/connectionAccess";
// Probe a webSearch/webFetch provider using its searchConfig/fetchConfig.
// 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
export async function POST(request) {
try {
await requireProviderAdministrator(request);
const body = await request.json();
const provider = normalizeProviderId(body.provider);
const { apiKey, providerSpecificData } = body;
@@ -628,6 +630,8 @@ export async function POST(request) {
error: isValid ? null : (error || "Invalid API key"),
});
} 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);
return NextResponse.json({ error: "Validation failed" }, { status: 500 });
}
+13 -1
View File
@@ -1,5 +1,5 @@
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";
const NO_STORE_HEADERS = { "Cache-Control": "no-store" };
@@ -25,6 +25,12 @@ function wouldRemoveLastActiveAdmin(target, updates, activeAdminCount) {
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 }) {
try {
const actor = await requireCurrentDashboardUser();
@@ -47,6 +53,9 @@ export async function PATCH(request, { params }) {
if (wouldRemoveLastActiveAdmin(target, updates, await countActiveAdmins())) {
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);
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) {
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);
return NextResponse.json({ success: true }, { headers: NO_STORE_HEADERS });