"use client"; import { useEffect, useState } from "react"; import { BookOpen, Brain, Loader2 } from "lucide-react"; import { useQuery } from "@tanstack/react-query"; import { Button } from "@/components/ui/button"; import { Checkbox } from "@/components/ui/checkbox"; import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { useI18n, type MessageKey, type TranslateFn, } from "@/i18n/i18n-context"; import { useKnowledgeBases } from "@/hooks/use-knowledge-bases"; import { useMemoryStores } from "@/hooks/use-memory-stores"; import { listMemoryStoreScopesUnfiltered } from "@/services/memory"; import { expandActions, getActionsForGroup, type OperationGroup, type ResourceType, } from "@/lib/arn-utils"; import type { PermissionRule, MemoryStoreScope } from "@/types/api-key"; interface PermissionRuleDialogProps { open: boolean; onOpenChange: (open: boolean) => void; onSave: (rule: PermissionRule) => void; initial?: PermissionRule; } const OPERATION_GROUP_LABEL_KEYS: Record = { read: "apiKeys.operations.read", write: "apiKeys.operations.write", manage: "apiKeys.operations.manage", }; const OPERATION_GROUP_DESCRIPTION_KEYS: Record< string, Record > = { knowledgebase: { read: "apiKeys.operations.knowledgeBaseReadDesc", write: "apiKeys.operations.knowledgeBaseWriteDesc", manage: "apiKeys.operations.knowledgeBaseManageDesc", }, memorystore: { read: "apiKeys.operations.memoryStoreReadDesc", write: "apiKeys.operations.memoryStoreWriteDesc", manage: "apiKeys.operations.memoryStoreManageDesc", }, }; function scopeKey(s: { appId?: string; tenantId?: string; agentId?: string; runId?: string; }): string { return [s.appId ?? "", s.tenantId ?? "", s.agentId ?? "", s.runId ?? ""].join( "|", ); } function formatScope( s: { appId?: string; tenantId?: string; agentId?: string; runId?: string; }, t: TranslateFn, ): string { const parts: string[] = []; if (s.appId) parts.push(`app:${s.appId}`); if (s.tenantId) parts.push(`tenant:${s.tenantId}`); if (s.agentId) parts.push(`agent:${s.agentId}`); if (s.runId) parts.push(`${t("memory.scopeField.run")}:${s.runId}`); return parts.join(", "); } export function PermissionRuleDialog({ open, onOpenChange, onSave, initial, }: PermissionRuleDialogProps) { const { t } = useI18n(); const [resourceType, setResourceType] = useState( initial?.resourceType ?? "knowledgebase", ); const [resourceName, setResourceName] = useState( initial?.resourceName ?? "*", ); const [groups, setGroups] = useState>( new Set(initial?.operationGroups ?? ["read"]), ); const [scope, setScope] = useState(initial?.scope ?? {}); const [sourceIp, setSourceIp] = useState( initial?.condition?.sourceIp?.join(", ") ?? "", ); const [showScope, setShowScope] = useState( Boolean( initial?.scope && (initial.scope.appId || initial.scope.tenantId || initial.scope.agentId || initial.scope.runId), ), ); const [scopeMode, setScopeMode] = useState<"manual" | "select">("manual"); const { data: kbData } = useKnowledgeBases(); const { data: memData } = useMemoryStores(); const shouldFetchScopes = open && resourceType === "memorystore" && resourceName !== "*" && showScope; const { data: scopesData, isLoading: scopesLoading } = useQuery({ queryKey: ["memory-store-scopes-for-rule", resourceName], queryFn: () => listMemoryStoreScopesUnfiltered(resourceName), enabled: shouldFetchScopes, staleTime: 30 * 1000, }); const availableScopes = scopesData?.items ?? []; useEffect(() => { if (!open) return; setResourceType(initial?.resourceType ?? "knowledgebase"); setResourceName(initial?.resourceName ?? "*"); setGroups(new Set(initial?.operationGroups ?? ["read"])); setScope(initial?.scope ?? {}); setSourceIp(initial?.condition?.sourceIp?.join(", ") ?? ""); setShowScope( Boolean( initial?.scope && (initial.scope.appId || initial.scope.tenantId || initial.scope.agentId || initial.scope.runId), ), ); setScopeMode("manual"); }, [open, initial]); function toggleGroup(group: OperationGroup) { setGroups((prev) => { const next = new Set(prev); if (next.has(group)) next.delete(group); else next.add(group); return next; }); } function selectScope(s: { appId?: string; tenantId?: string; agentId?: string; runId?: string; }) { setScope({ appId: s.appId || undefined, tenantId: s.tenantId || undefined, agentId: s.agentId || undefined, runId: s.runId || undefined, }); } function handleSave() { const operationGroups = Array.from(groups); const actions = expandActions(resourceType, operationGroups); const ips = sourceIp .split(/[,,\s]+/) .map((s) => s.trim()) .filter(Boolean); const rule: PermissionRule = { resourceType, resourceName, operationGroups, actions, ...(resourceType === "memorystore" && showScope && hasScopeValues(scope) ? { scope } : {}), ...(ips.length > 0 ? { condition: { sourceIp: ips } } : {}), }; onSave(rule); onOpenChange(false); } const resources = resourceType === "knowledgebase" ? (kbData?.items ?? []).map((kb) => kb.knowledgeBaseName) : (memData?.items ?? []).map((ms) => ms.memoryStoreName); return ( {initial ? t("apiKeys.rule.editTitle") : t("apiKeys.rule.addTitle")}
{/* 资源类型 */}
{/* 资源名称 */}
{/* Scope(仅记忆库且选择了具体库) */} {resourceType === "memorystore" && resourceName !== "*" && (
{ setShowScope(Boolean(c)); if (!c) setScope({}); }} />
{showScope && (
{/* 模式切换 */}
{scopeMode === "select" ? (
{scopesLoading ? (
{t("apiKeys.rule.loadingScopes")}
) : availableScopes.length === 0 ? (

{t("apiKeys.rule.noScopes")}

) : (
{availableScopes.map((s) => { const key = scopeKey(s); const isSelected = scopeKey(scope) === key; return ( ); })}
)}
) : (
setScope((s) => ({ ...s, appId: e.target.value || undefined, })) } placeholder={t("apiKeys.rule.optional")} className="h-8 text-xs" />
setScope((s) => ({ ...s, tenantId: e.target.value || undefined, })) } placeholder={t("apiKeys.rule.optional")} className="h-8 text-xs" />
setScope((s) => ({ ...s, agentId: e.target.value || undefined, })) } placeholder={t("apiKeys.rule.optional")} className="h-8 text-xs" />
setScope((s) => ({ ...s, runId: e.target.value || undefined, })) } placeholder={t("apiKeys.rule.optional")} className="h-8 text-xs" />
)}
)}
)} {/* 操作组 */}
{(["read", "write", "manage"] as const).map((group) => ( ))}
{/* IP 条件 */}
setSourceIp(e.target.value)} placeholder={t("apiKeys.rule.ipPlaceholder")} className="text-xs" />

{t("apiKeys.rule.ipHelp")}

); } function hasScopeValues(scope: MemoryStoreScope): boolean { return Boolean(scope.appId || scope.tenantId || scope.agentId || scope.runId); }