import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import type { AxiosError } from "axios"; import { ArrowLeft, Check, ExternalLink, Info, Plus, Save, Search, Shield, Sparkles, Trash2, Upload, X, } from "lucide-react"; import { useEffect, useState } from "react"; import { Link, useNavigate, useParams } from "react-router-dom"; import { Badge } from "../../components/ui/badge"; import { Button } from "../../components/ui/button"; import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from "../../components/ui/card"; import { Input } from "../../components/ui/input"; import { Label } from "../../components/ui/label"; import { Switch } from "../../components/ui/switch"; import { Textarea } from "../../components/ui/textarea"; import { toast } from "../../components/ui/use-toast"; import { createClient, deleteClient, fetchClient, fetchMyTenants, refreshHeadlessJwksCache, revokeHeadlessJwksCache, updateClient, updateClientStatus, } from "../../lib/devApi"; import type { ClientStatus, ClientType, ClientUpsertRequest, MyTenantSummary, TenantSummary, } from "../../lib/devApi"; import { t } from "../../lib/i18n"; import { cn } from "../../lib/utils"; import { ClientDetailTabs } from "./ClientDetailTabs"; interface ScopeItem { id: string; name: string; description: string; mandatory: boolean; locked?: boolean; } type SecurityProfile = "private" | "pkce"; type TokenEndpointAuthMethod = | "none" | "client_secret_basic" | "private_key_jwt"; const HEADLESS_LOGIN_ALLOWED_ALGORITHMS = [ "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512", "EdDSA", ] as const; const HEADLESS_LOGIN_ALLOWED_ALGORITHM_SET = new Set( HEADLESS_LOGIN_ALLOWED_ALGORITHMS, ); function formatHeadlessParsedKeyLabel( kid: string | undefined, index: number, ): string { const trimmedKid = kid?.trim(); if (trimmedKid) { return trimmedKid; } return `key #${index + 1}`; } function isTokenEndpointAuthMethod( value: string, ): value is TokenEndpointAuthMethod { return ( value === "none" || value === "client_secret_basic" || value === "private_key_jwt" ); } function readMetadataString( metadata: Record, key: string, ): string { const value = metadata[key]; return typeof value === "string" ? value : ""; } function isValidUrl(value: string): boolean { try { const url = new URL(value); return url.protocol === "https:" || url.protocol === "http:"; } catch { return false; } } function formatDateTime(value?: string) { if (!value) return "-"; const date = new Date(value); if (Number.isNaN(date.getTime())) return value; return date.toLocaleString(); } function ClientGeneralPage() { const params = useParams(); const navigate = useNavigate(); const queryClient = useQueryClient(); const clientId = params.id; const isCreate = !clientId; const { data, isLoading, error } = useQuery({ queryKey: ["client", clientId], queryFn: () => fetchClient(clientId as string), enabled: !isCreate, }); const { data: tenantData } = useQuery({ queryKey: ["my-tenants"], queryFn: fetchMyTenants, }); const [name, setName] = useState(""); const [description, setDescription] = useState(""); const [logoUrl, setLogoUrl] = useState(""); const [logoPreviewStatus, setLogoPreviewStatus] = useState< "idle" | "loading" | "loaded" | "error" >("idle"); const [clientType, setClientType] = useState("private"); const [status, setStatus] = useState("active"); const [initialStatus, setInitialStatus] = useState("active"); const [redirectUris, setRedirectUris] = useState(""); const [tenantAccessRestricted, setTenantAccessRestricted] = useState(false); const [allowedTenantIds, setAllowedTenantIds] = useState([]); const [tenantSearch, setTenantSearch] = useState(""); const [isTenantSearchOpen, setIsTenantSearchOpen] = useState(false); // Public Key Registration States const [tokenEndpointAuthMethod, setTokenEndpointAuthMethod] = useState("client_secret_basic"); const [jwksUri, setJwksUri] = useState(""); const [headlessLoginEnabled, setHeadlessLoginEnabled] = useState(false); const [scopes, setScopes] = useState(() => [ { id: "1", name: "openid", description: t("msg.dev.clients.scopes.openid", "OIDC 인증 필수 스코프"), mandatory: true, }, { id: "2", name: "tenant", description: t("msg.dev.clients.scopes.tenant", "소속 테넌트 정보 접근"), mandatory: false, }, { id: "3", name: "profile", description: t("msg.dev.clients.scopes.profile", "기본 프로필 정보 접근"), mandatory: false, }, { id: "4", name: "email", description: t("msg.dev.clients.scopes.email", "이메일 주소 접근"), mandatory: false, }, ]); useEffect(() => { if (!data) return; const { client } = data; setName(client.name || client.id); setClientType(client.type); setStatus(client.status); setInitialStatus(client.status); const metadata = client.metadata ?? {}; if (typeof metadata.description === "string") setDescription(metadata.description); if (typeof metadata.logo_url === "string") setLogoUrl(metadata.logo_url); const headlessEnabled = !!metadata.headless_login_enabled; setHeadlessLoginEnabled(headlessEnabled); const restrictedTenants = Array.isArray(metadata.allowed_tenants) ? metadata.allowed_tenants .map((value) => (typeof value === "string" ? value.trim() : "")) .filter(Boolean) : []; setTenantAccessRestricted( restrictedTenants.length > 0 || metadata.tenant_access_restricted === true, ); setAllowedTenantIds(restrictedTenants); const savedAuthMethod = client.tokenEndpointAuthMethod || (client.type === "pkce" ? "none" : "client_secret_basic"); const headlessAuthMethod = readMetadataString( metadata, "headless_token_endpoint_auth_method", ); const selectedAuthMethod = headlessEnabled && isTokenEndpointAuthMethod(headlessAuthMethod) ? headlessAuthMethod : savedAuthMethod; if (isTokenEndpointAuthMethod(selectedAuthMethod)) { setTokenEndpointAuthMethod(selectedAuthMethod); } const headlessJwksUri = readMetadataString(metadata, "headless_jwks_uri"); if (headlessJwksUri) { setJwksUri(headlessJwksUri); } else if (client.jwksUri) { setJwksUri(client.jwksUri); } else { setJwksUri(""); } // Fallbacks from metadata if top-level fields are empty if (!client.tokenEndpointAuthMethod && !headlessEnabled) { const metaAuth = readMetadataString( metadata, "token_endpoint_auth_method", ); if (isTokenEndpointAuthMethod(metaAuth)) { setTokenEndpointAuthMethod(metaAuth); } } if (!client.jwksUri && !headlessEnabled) { const metaJwksUri = readMetadataString(metadata, "jwks_uri"); if (metaJwksUri) { setJwksUri(metaJwksUri); } } const savedScopes = metadata.structured_scopes as ScopeItem[] | undefined; if (savedScopes && Array.isArray(savedScopes)) { setScopes( normalizeScopesForTenantAccess( savedScopes, restrictedTenants.length > 0 || metadata.tenant_access_restricted === true, ), ); } else { setScopes( normalizeScopesForTenantAccess( client.scopes.map((s, idx) => ({ id: String(idx + 1), name: s, description: "", mandatory: s === "openid", })), restrictedTenants.length > 0 || metadata.tenant_access_restricted === true, ), ); } }, [data]); const securityProfile: SecurityProfile = clientType === "pkce" ? "pkce" : "private"; const trimmedLogoUrl = logoUrl.trim(); const hasLogoUrl = trimmedLogoUrl.length > 0; const hasValidLogoUrl = !hasLogoUrl || isValidUrl(trimmedLogoUrl); useEffect(() => { if (!hasLogoUrl) { setLogoPreviewStatus("idle"); return; } if (!hasValidLogoUrl) { setLogoPreviewStatus("error"); return; } setLogoPreviewStatus("loading"); }, [hasLogoUrl, hasValidLogoUrl]); const handleSecurityProfileChange = (profile: SecurityProfile) => { setClientType(profile); if (profile === "pkce") { setTokenEndpointAuthMethod( headlessLoginEnabled ? "private_key_jwt" : "none", ); } else { setTokenEndpointAuthMethod("client_secret_basic"); } }; const handleHeadlessToggle = (enabled: boolean) => { setHeadlessLoginEnabled(enabled); if (clientType === "pkce") { setTokenEndpointAuthMethod(enabled ? "private_key_jwt" : "none"); } }; const tenantScopeDescription = t( "msg.dev.clients.scopes.tenant", "소속 테넌트 정보 접근", ); const buildTenantScope = (id: string): ScopeItem => ({ id, name: "tenant", description: tenantScopeDescription, mandatory: true, locked: true, }); function normalizeScopesForTenantAccess( nextScopes: ScopeItem[], restricted: boolean, ): ScopeItem[] { const normalized = nextScopes.map((scope) => { if (scope.name.trim() !== "tenant") { return scope; } return { ...scope, description: scope.description || tenantScopeDescription, mandatory: restricted, locked: restricted, }; }); if ( restricted && !normalized.some((scope) => scope.name.trim() === "tenant") ) { normalized.push(buildTenantScope(`tenant-${Date.now()}`)); } const openidScopes = normalized.filter( (scope) => scope.name.trim() === "openid", ); const tenantScopes = normalized.filter( (scope) => scope.name.trim() === "tenant", ); const remainingScopes = normalized.filter((scope) => { const name = scope.name.trim(); return name !== "openid" && name !== "tenant"; }); return [...openidScopes, ...tenantScopes, ...remainingScopes]; } const handleTenantAccessToggle = (enabled: boolean) => { setTenantAccessRestricted(enabled); setIsTenantSearchOpen(enabled); if (!enabled) { setTenantSearch(""); } setScopes((current) => normalizeScopesForTenantAccess(current, enabled)); }; const toggleAllowedTenant = (tenantId: string) => { setAllowedTenantIds((current) => current.includes(tenantId) ? current.filter((id) => id !== tenantId) : [...current, tenantId], ); }; const handleSelectAllowedTenant = (tenantId: string) => { setAllowedTenantIds((current) => current.includes(tenantId) ? current : [...current, tenantId], ); setTenantSearch(""); setIsTenantSearchOpen(true); }; const addScope = () => { const newId = String(Date.now()); setScopes([ ...scopes, { id: newId, name: "", description: "", mandatory: false }, ]); }; const updateScope = ( id: string, field: K, value: ScopeItem[K], ) => { setScopes((current) => current.map((scope) => { if (scope.id !== id) { return scope; } if (scope.locked) { return scope; } return { ...scope, [field]: value }; }), ); }; const removeScope = (id: string) => { setScopes((current) => current.filter((scope) => scope.id !== id || scope.locked === true), ); }; const handleStatusChange = (nextStatus: ClientStatus) => { setStatus(nextStatus); const statusLabel = nextStatus === "active" ? t("ui.common.status.active", "Active") : t("ui.common.status.inactive", "Inactive"); toast( t( "msg.dev.clients.general.status_changed", "상태가 {{status}}로 변경되었습니다.", { status: statusLabel }, ), ); }; const validationErrors: string[] = []; const trimmedJwksUri = jwksUri.trim(); const currentHeadlessJwksCache = data?.headlessJwksCache; const parsedKeysForCurrentJwksUri = headlessLoginEnabled && trimmedJwksUri !== "" && currentHeadlessJwksCache?.jwksUri === trimmedJwksUri ? (currentHeadlessJwksCache.parsedKeys ?? []) : []; const unsupportedParsedAlgorithms = parsedKeysForCurrentJwksUri .map((key, index) => ({ alg: key.alg?.trim() ?? "", label: formatHeadlessParsedKeyLabel(key.kid, index), })) .filter( (entry) => entry.alg !== "" && !HEADLESS_LOGIN_ALLOWED_ALGORITHM_SET.has(entry.alg), ); const missingParsedAlgorithms = parsedKeysForCurrentJwksUri .map((key, index) => ({ alg: key.alg?.trim() ?? "", label: formatHeadlessParsedKeyLabel(key.kid, index), })) .filter((entry) => entry.alg === ""); const unsupportedParsedAlgorithmSummary = unsupportedParsedAlgorithms .map((entry) => `${entry.label}: ${entry.alg}`) .join(", "); const missingParsedAlgorithmSummary = missingParsedAlgorithms .map((entry) => entry.label) .join(", "); const allowedHeadlessAlgorithmsTooltip = t( "msg.dev.clients.general.public_key.allowed_algorithms_tooltip", "허용 알고리즘: {{algorithms}}", { algorithms: HEADLESS_LOGIN_ALLOWED_ALGORITHMS.join(", ") }, ); if (headlessLoginEnabled) { if (!trimmedJwksUri) { validationErrors.push( t( "msg.dev.clients.general.public_key.validation.missing_jwks_uri", "JWKS URI를 입력해야 합니다.", ), ); } else if (!isValidUrl(trimmedJwksUri)) { validationErrors.push( t( "msg.dev.clients.general.public_key.validation.invalid_jwks_uri", "JWKS URI 형식이 올바르지 않습니다.", ), ); } if (unsupportedParsedAlgorithms.length > 0) { validationErrors.push( t( "msg.dev.clients.general.public_key.validation.unsupported_parsed_algorithms", "JWKS에 지원하지 않는 알고리즘이 있습니다: {{details}}", { details: unsupportedParsedAlgorithmSummary }, ), ); } if (missingParsedAlgorithms.length > 0) { validationErrors.push( t( "msg.dev.clients.general.public_key.validation.missing_parsed_algorithms", "JWKS에 알고리즘(`alg`)이 선언되지 않은 키가 있습니다: {{details}}", { details: missingParsedAlgorithmSummary }, ), ); } } if (tenantAccessRestricted && allowedTenantIds.length === 0) { validationErrors.push( t( "ui.dev.clients.general.tenant_access.validation_required", "테넌트 접근 제한을 사용할 경우 허용 테넌트를 하나 이상 선택해야 합니다.", ), ); } const hasValidationErrors = validationErrors.length > 0; const normalizedTenantSearch = tenantSearch.trim().toLowerCase(); const tenantOptions: Array = tenantData ?? []; const filteredTenants = tenantOptions.filter((tenant) => { if (!normalizedTenantSearch) { return true; } const searchable = `${tenant.name} ${tenant.slug} ${tenant.description ?? ""} ${tenant.type ?? ""}`.toLowerCase(); return searchable.includes(normalizedTenantSearch); }); const tenantSuggestions = filteredTenants .filter((tenant) => !allowedTenantIds.includes(tenant.id)) .slice(0, 8); const selectedAllowedTenants = allowedTenantIds .map((tenantId) => tenantOptions.find((item) => item.id === tenantId)) .filter( (tenant): tenant is TenantSummary | MyTenantSummary => tenant != null, ); const refreshHeadlessJwksCacheMutation = useMutation({ mutationFn: async () => { if (!clientId) throw new Error("Missing client id"); return refreshHeadlessJwksCache(clientId); }, onSuccess: (result) => { if (clientId) { queryClient.setQueryData(["client", clientId], result); queryClient.invalidateQueries({ queryKey: ["client", clientId] }); } toast( t( "msg.dev.clients.general.public_key.cache_refreshed", "JWKS 캐시를 새로 고쳤습니다.", ), ); }, onError: (err) => { const errorMessage = (err as AxiosError<{ error?: string }>).response?.data?.error ?? (err as Error)?.message ?? t("msg.common.unknown_error", "unknown error"); toast( t( "msg.dev.clients.general.public_key.cache_refresh_failed", "JWKS 캐시 새로고침에 실패했습니다: {{error}}", { error: errorMessage }, ), ); }, }); const revokeHeadlessJwksCacheMutation = useMutation({ mutationFn: async () => { if (!clientId) throw new Error("Missing client id"); return revokeHeadlessJwksCache(clientId); }, onSuccess: () => { if (clientId) { queryClient.invalidateQueries({ queryKey: ["client", clientId] }); } toast( t( "msg.dev.clients.general.public_key.cache_revoked", "JWKS 캐시를 삭제했습니다.", ), ); }, onError: (err) => { const errorMessage = (err as AxiosError<{ error?: string }>).response?.data?.error ?? (err as Error)?.message ?? t("msg.common.unknown_error", "unknown error"); toast( t( "msg.dev.clients.general.public_key.cache_revoke_failed", "JWKS 캐시 삭제에 실패했습니다: {{error}}", { error: errorMessage }, ), ); }, }); const mutation = useMutation({ mutationFn: async () => { if (hasLogoUrl && !hasValidLogoUrl) { throw new Error( t( "msg.dev.clients.general.identity.logo_invalid", "앱 로고 URL 형식이 올바르지 않습니다. http 또는 https 주소를 입력하세요.", ), ); } const normalizedScopes = normalizeScopesForTenantAccess( scopes, tenantAccessRestricted, ); const normalizedAllowedTenantIds = Array.from( new Set(allowedTenantIds.map((id) => id.trim()).filter(Boolean)), ); const scopeNames = normalizedScopes .map((scope) => scope.name.trim()) .filter(Boolean); const effectiveTokenEndpointAuthMethod = clientType === "pkce" && headlessLoginEnabled ? "none" : tokenEndpointAuthMethod; const payload: ClientUpsertRequest = { name, type: clientType, scopes: scopeNames, tokenEndpointAuthMethod: effectiveTokenEndpointAuthMethod, jwksUri: effectiveTokenEndpointAuthMethod === "private_key_jwt" && trimmedJwksUri ? trimmedJwksUri : undefined, metadata: { description, logo_url: trimmedLogoUrl, structured_scopes: normalizedScopes, token_endpoint_auth_method: effectiveTokenEndpointAuthMethod, headless_login_enabled: headlessLoginEnabled, headless_token_endpoint_auth_method: clientType === "pkce" && headlessLoginEnabled ? tokenEndpointAuthMethod : undefined, headless_jwks_uri: clientType === "pkce" && headlessLoginEnabled ? trimmedJwksUri : undefined, tenant_access_restricted: tenantAccessRestricted, allowed_tenants: tenantAccessRestricted ? normalizedAllowedTenantIds : [], }, }; if (isCreate) { payload.status = status; payload.redirectUris = redirectUris .split(",") .map((uri) => uri.trim()) .filter(Boolean); return createClient(payload); } const updated = await updateClient(clientId as string, payload); if (status !== initialStatus) { await updateClientStatus(clientId as string, status); } return updated; }, onSuccess: (result) => { queryClient.invalidateQueries({ queryKey: ["clients"] }); if (status !== initialStatus) { setInitialStatus(status); } if (result?.client?.id) { navigate(`/clients/${result.client.id}/settings`); } toast(t("msg.dev.clients.general.saved", "설정이 저장되었습니다.")); }, onError: (err) => { const axiosError = err as AxiosError<{ error?: string }>; if (axiosError.response?.status === 403) { alert( isCreate ? t( "msg.dev.clients.general.create_forbidden", "이 RP를 생성할 권한이 없습니다.\n관리자에게 개발자 권한 부여를 요청해 주세요.", ) : t( "msg.dev.clients.general.save_forbidden", "이 RP 설정을 수정할 권한이 없습니다.\n관리자에게 RP 일반 설정 또는 RP 관리자 관계 부여를 요청해 주세요.", ), ); return; } const errorMessage = axiosError.response?.data?.error ?? (err as Error)?.message ?? t("msg.common.unknown_error", "unknown error"); toast( t( "msg.dev.clients.general.save_error", "저장에 실패했습니다: {{error}}", { error: errorMessage, }, ), "error", ); }, }); const deleteMutation = useMutation({ mutationFn: (id: string) => deleteClient(id), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ["clients"] }); toast(t("msg.dev.clients.deleted", "앱이 삭제되었습니다.")); navigate("/clients"); }, onError: (err) => { const errorMessage = (err as AxiosError<{ error?: string }>).response?.data?.error ?? (err as Error)?.message; toast( t("msg.dev.clients.delete_error", "삭제 실패: {{error}}", { error: errorMessage, }), "error", ); }, }); const handleDelete = () => { if ( clientId && window.confirm( t( "msg.dev.clients.delete_confirm", "정말로 이 앱을 삭제하시습니까? 이 작업은 되돌릴 수 없습니다.", ), ) ) { deleteMutation.mutate(clientId); } }; if (!isCreate && isLoading) { return (
{t("msg.dev.clients.general.loading", "Loading client...")}
); } if (!isCreate && (error || !data)) { const errMsg = (error as AxiosError<{ error?: string }>).response?.data?.error ?? (error as Error)?.message; return (
{t( "msg.dev.clients.general.load_error", "Error loading client: {{error}}", { error: errMsg || t("msg.common.unknown_error", "unknown error"), }, )}
); } const publicKeyStatusTone = headlessLoginEnabled ? hasValidationErrors ? "border-destructive/40 bg-destructive/5" : "border-primary/30 bg-primary/5" : "border-border bg-muted/20"; const displayName = isCreate ? t("ui.dev.clients.general.display_new", "새 클라이언트") : data?.client?.name || data?.client?.id; return (

{isCreate ? t("ui.dev.clients.general.title_create", "Create Client") : t("ui.dev.clients.general.title_edit", "Client Settings")}

{t( "ui.dev.clients.general.subtitle", "앱 정보, 권한 스코프, 보안 설정을 관리합니다.", )}

{!isCreate && ( {status === "active" ? t("ui.common.status.active", "Active") : t("ui.common.status.inactive", "Inactive")} )}
{!isCreate && ( )}
{/* 1. Application Identity */}
{t( "ui.dev.clients.general.identity.title", "Application Identity", )} {t( "msg.dev.clients.general.identity.subtitle", "앱 이름과 설명, 로고를 설정합니다.", )}
setName(e.target.value)} placeholder={t( "ui.dev.clients.general.identity.name_placeholder", "My Awesome Application", )} />