From 9cce0c8e5ec74d0f566c44740147f509403d0ca8 Mon Sep 17 00:00:00 2001 From: wizardchen Date: Tue, 26 May 2026 20:03:35 +0800 Subject: [PATCH] feat(system): consolidate system admin and settings into one Settings panel MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace the standalone /platform/system/* routes with a single "系统设置" section inside the canonical Settings modal. The previous SystemLayout.vue / SystemAdmins.vue surfaces are removed and their functionality (system admin roster, global settings) is hosted directly in SystemSettings.vue under the standard `.section-header` / `.settings-group` skeleton. Legacy URLs redirect to the modal section so external bookmarks don't 404. Backend: - SystemSettingService.Reset + repo.Delete: drop the DB override for a key so the 3-tier resolver falls back to ENV / built-in default. Idempotent (resetting a never-persisted key returns nil); emits an audit row only on real deletions, invalidates the local cache, and publishes to peers via the existing pubsub channel. - TenantService.BulkSetStorageQuota: overwrite every tenant's storage_quota in one statement. Powers POST /system/admin/tenants/ apply-default-storage-quota; bypasses the per-tenant whitelist on PUT /tenants/:id which intentionally forbids storage_quota edits. - AuditAction{SystemAdminPromoted,SystemAdminRevoked} constants and emitAdminAudit() in SystemHandler — promote / revoke now leave an audit trail with TenantID=0 and {target_email,target_username, idempotent|changed} in details. - SystemSetting.LastModifiedByName: derived per-request display label (username, email fallback) so the UI shows "wizardchen" instead of a UUID prefix without storing a denormalised column. Frontend: - SystemSettings.vue rewritten against the Settings modal skeleton with auto-persisting controls (switch/select @change, input/inputnumber @blur, tag-input + per-delta popconfirm for SSRF whitelist and admin roster). auth.registration_mode change goes through an inline popconfirm; cancel rolls back. Reset / bulk-apply also inline popconfirms — no dialog modal for these per-row affordances. - Priority hint panel surfaces the DB > ENV > default resolver order so operators can reason about "I set the env but it doesn't show up". - Router: /platform/system, /platform/system/settings, /platform/system/ admins are now compatibility redirects to /platform/settings?section= system-global. - Settings modal sized 900x700 → 1080x780 and content-wrapper 600 → 760 so the wider tables (members, system settings) breathe; <1100px viewport still flexes to the screen. - i18n: system.globalSettings.* keys for title / description / loading / empty / badges / priority hint / per-key labels / reset / bulkApply / admins (label, placeholder, save messages, popconfirm copy) across zh-CN, en-US, ko-KR, ru-RU. Misc: - internal/utils/filesize.go doc: clarify MAX_FILE_SIZE_MB is a deploy-time-only knob (nginx + docreader + frontend each cache the env at startup); a SystemAdmin UI override would mislead operators because nginx would still 413. Until all four layers can hot-reload the limit in lockstep, this stays env-only. - internal/utils/security.go: SSRF whitelist parser/runtime now drives off SystemSettingService for live updates; ENV remains the fallback for never-overridden deployments. --- .env.example | 14 +- frontend/src/api/system/index.ts | 58 +- frontend/src/components/UserMenu.vue | 8 +- frontend/src/i18n/locales/en-US.ts | 105 +- frontend/src/i18n/locales/ko-KR.ts | 105 +- frontend/src/i18n/locales/ru-RU.ts | 105 +- frontend/src/i18n/locales/zh-CN.ts | 105 +- frontend/src/router/index.ts | 41 +- frontend/src/views/settings/Settings.vue | 24 +- frontend/src/views/system/SystemAdmins.vue | 259 ---- frontend/src/views/system/SystemLayout.vue | 127 -- frontend/src/views/system/SystemSettings.vue | 1164 +++++++++++++---- .../application/repository/system_setting.go | 14 + internal/application/repository/tenant.go | 21 + internal/application/repository/user.go | 15 +- .../application/service/system_setting.go | 203 ++- internal/application/service/tenant.go | 17 + internal/handler/initialization.go | 8 +- internal/handler/knowledge.go | 14 +- internal/handler/session/handler.go | 3 - internal/handler/session/qa.go | 6 +- internal/handler/system.go | 309 ++++- internal/handler/tenant.go | 70 +- internal/middleware/auth.go | 10 +- internal/router/router.go | 9 + internal/types/audit_log.go | 18 + internal/types/interfaces/system_setting.go | 13 + internal/types/interfaces/tenant.go | 9 + internal/types/system_setting.go | 7 + internal/utils/filesize.go | 27 +- internal/utils/security.go | 72 +- 31 files changed, 2207 insertions(+), 753 deletions(-) delete mode 100644 frontend/src/views/system/SystemAdmins.vue delete mode 100644 frontend/src/views/system/SystemLayout.vue diff --git a/.env.example b/.env.example index eef39600..776e1952 100644 --- a/.env.example +++ b/.env.example @@ -428,12 +428,16 @@ COS_ENABLE_OLD_DOMAIN=true # NEO4J_PASSWORD=password # ========== 文件上传大小限制 ========== -# 统一的文件大小限制(MB),默认为50MB -# 影响:单文件上传、gRPC消息大小、Nginx请求体大小 +# 统一的文件大小限制(MB),默认为 50MB。 +# 影响:单文件上传、docreader gRPC 消息大小、frontend Nginx 请求体大小、 +# 前端浏览器侧的客户端校验。 # -# 优先级(自 P1 起):DB 中的 system_settings.file.max_size_mb > 此环境变量 > 默认 50 -# SystemAdmin 可以在「系统管理 → 全局设置」面板里实时调整该值,无需重启服务。 -# 此处的环境变量仍然作为回退(DB 没有 row 时使用)。 +# 这是部署期配置:四个层(Go 后端 / Nginx / docreader / 浏览器 bundle) +# 都在容器启动时读取一次,运行中改 env 不会生效。修改后必须同步重启 +# 这四层。曾经尝试做成 system_settings 运行时项,但 Nginx / +# docreader / 浏览器 bundle 不会随之 reload,结果是 UI 改了 200 但 +# Nginx 仍按旧值在 50 处直接 413,所以撤回了 UI 入口(见 +# internal/utils/filesize.go 注释)。 # MAX_FILE_SIZE_MB=50 # ========== Agent Skills Sandbox 配置 ========== diff --git a/frontend/src/api/system/index.ts b/frontend/src/api/system/index.ts index 540c0b36..0c10b9ba 100644 --- a/frontend/src/api/system/index.ts +++ b/frontend/src/api/system/index.ts @@ -1,4 +1,4 @@ -import { get, post, put } from '@/utils/request' +import { get, post, put, del } from '@/utils/request' export interface SystemInfo { version: string @@ -251,6 +251,10 @@ export interface ListSystemAdminsResponse { /** * Promote a user to system administrator. * + * Identify the target either by user_id (UUID, for API clients) or + * email (the human-friendly path used by the SystemAdmin UI). Backend + * accepts whichever is provided; user_id wins when both are set. + * * Backend handler (system.go) returns the updated UserInfo directly as * the response body — no {data: ...} wrapping. The shared axios * interceptor in utils/request.ts unwraps response.data at the @@ -262,8 +266,17 @@ export interface ListSystemAdminsResponse { * compile (sometimes — vue-tsc is inconsistent on AxiosResponse vs * inline interface assignability) but is fragile. */ -export async function promoteUserToSystemAdmin(userId: string): Promise { - const response = await post('/api/v1/system/admin/promote', { user_id: userId }) +export interface PromoteUserToSystemAdminRequest { + /** UUID of the user to promote. Optional; supply this OR `email`. */ + user_id?: string + /** Email address of the user to promote. Optional; supply this OR `user_id`. */ + email?: string +} + +export async function promoteUserToSystemAdmin( + req: PromoteUserToSystemAdminRequest, +): Promise { + const response = await post('/api/v1/system/admin/promote', req) return response as unknown as SystemAdminUser } @@ -320,6 +333,13 @@ export interface SystemSettingItem { /** P3+ — currently always false. UI may show "needs restart to take effect" badge when true. */ requires_restart: boolean last_modified_by: string + /** + * Display label resolved from last_modified_by (UUID) on the server — + * username when known, email as a fallback. Empty/undefined for + * virtual rows that were never persisted; UI then falls back to the + * UUID prefix. + */ + last_modified_by_name?: string created_at: string updated_at: string /** @@ -367,3 +387,35 @@ export async function updateSystemSetting( ) return response as unknown as SystemSettingItem } + +/** + * Reset a system setting back to its ENV / built-in default by deleting + * the DB override row. Idempotent — resetting a key that was never + * persisted resolves successfully. + */ +export async function resetSystemSetting(key: string): Promise { + await del(`/api/v1/system/admin/settings/${encodeURIComponent(key)}`) +} + +/** + * Result of POST /system/admin/tenants/apply-default-storage-quota. + * `affected` is the count of tenant rows whose storage_quota was + * overwritten; `quota_bytes` is the value written. + */ +export interface ApplyDefaultStorageQuotaResult { + affected: number + quota_bytes: number + quota_gb: number +} + +/** + * Apply the current `tenant.default_storage_quota_gb` setting to every + * existing tenant. Reads the resolved setting server-side (DB > ENV > + * default), then writes that quota to every row. SystemAdmin only. + * + * Idempotent: running twice with the same setting has the same effect. + */ +export async function applyDefaultStorageQuotaToAllTenants(): Promise { + const response = await post('/api/v1/system/admin/tenants/apply-default-storage-quota') + return response as unknown as ApplyDefaultStorageQuotaResult +} diff --git a/frontend/src/components/UserMenu.vue b/frontend/src/components/UserMenu.vue index 9fd204b5..3472da77 100644 --- a/frontend/src/components/UserMenu.vue +++ b/frontend/src/components/UserMenu.vue @@ -353,9 +353,11 @@ const handleSettings = () => { router.push('/platform/settings') } -// Open platform-wide settings inside the standard Settings modal. -// Administrator-table workflows still live under /platform/system/admins, -// but global tunables belong with the rest of the configuration surface. +// Open the platform administration area inside the standard Settings +// modal. The admin roster lives at the top of the global-settings +// pane (as a tag-input row) so we route straight there; this is the +// only system-admin section now. Gated by SYSTEM_ADMIN_SECTIONS in +// Settings.vue. const handleSystemAdmin = () => { menuVisible.value = false uiStore.openSettings('system-global') diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index 9684be5a..b256c2f2 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -688,7 +688,7 @@ export default { parserEngine: 'Parser Engine', storageEngine: 'Storage Engine', mcpService: 'MCP Service', - systemSettings: 'System Settings', + versionInfo: 'Version Info', tenantInfo: 'Tenant Info', apiInfo: 'API Info', navGroups: { @@ -2571,6 +2571,109 @@ export default { messages: { fetchFailed: 'Failed to fetch system information', networkError: 'Network error, please try again later' + }, + globalSettings: { + title: 'System Settings', + description: 'Platform-wide runtime configuration. Saves take effect immediately for every tenant. Visible and editable by system administrators only.', + loading: 'Loading...', + empty: 'No configurable system settings available', + badgeRequiresRestart: 'Restart required', + badgeSecret: 'Secret', + badgeOverride: 'Overridden', + badgeOverrideTooltip: 'This value has been saved to the database by an administrator, overriding the environment variable and built-in default.', + modifiedAt: 'Last modified: {value}', + tagInputPlaceholder: 'Press Enter to add an entry, e.g. example.com / *.foo.com / 10.0.0.0/8', + priorityHint: { + title: 'About priority', + tier1: 'Items saved on this page (marked "Overridden") always win — the environment variable is ignored for them.', + tier2: 'Items not saved here fall back to the environment variable, or to the built-in default if no env var is set.', + tier3: 'To put an item back under environment-variable control, click the "Reset" button on its row.', + }, + keyLabels: { + auth: { + registration_mode: 'Self-service registration mode', + }, + ssrf: { + whitelist: 'SSRF protection allowlist', + }, + tenant: { + max_owned_per_user: 'Max tenants owned per user', + default_storage_quota_gb: 'Default storage quota for new tenants (GB)', + }, + }, + enumLabels: { + auth: { + registration_mode: { + self_serve: 'Self-service (anyone can register)', + invite_only: 'Invite only (public registration disabled)', + }, + }, + }, + confirm: { + header: 'Confirm high-risk action', + confirmBtn: 'Confirm save', + cancelBtn: 'Cancel', + emptyValue: '(empty)', + defaultBody: 'About to change "{label}" to: {value}', + bodyAuthRegistrationMode: 'About to change "{label}" to: {value}\n\nIf switched to self_serve, anyone on the public internet can register an account — please confirm this is intended.', + }, + listConfirm: { + ssrf: { + whitelist: { + add: { + header: 'Add SSRF allowlist entry', + body: 'Add {entry} to the SSRF allowlist? Hosts / IPs / CIDRs that match this entry will bypass SSRF protection and may let agents reach internal services. Only add entries you fully trust.', + confirmBtn: 'Add', + }, + remove: { + header: 'Remove SSRF allowlist entry', + body: 'Remove {entry} from the SSRF allowlist? After removal this entry will be blocked by SSRF protection again.', + confirmBtn: 'Remove', + }, + }, + }, + }, + messages: { + loadFailed: 'Failed to load system settings', + saveSuccess: 'Saved', + saveFailed: 'Save failed', + }, + reset: { + label: 'Reset', + tooltip: 'Clear the UI override and fall back to the environment variable or the built-in default', + confirmBtn: 'Confirm reset', + confirmBody: 'Reset "{label}"? This deletes the database override and falls back to the environment variable or the built-in default.', + success: 'Reset to default', + failed: 'Reset failed', + }, + admins: { + label: 'System administrators', + description: 'Users with platform-level privileges. Type an email and press Enter to promote a user; click × on a tag to revoke. You (yourself) are an administrator and are not shown in the list — you cannot revoke your own access.', + placeholder: 'Type a user email and press Enter', + loadFailed: 'Failed to load system administrators', + saveSuccess: 'System administrators updated', + saveFailed: 'Failed to update system administrators', + confirm: { + promote: { + header: 'Promote to system administrator', + body: 'Promote {email} to system administrator? This user will gain platform-level privileges: access to every tenant, system settings, and the admin roster itself.', + confirmBtn: 'Promote', + }, + revoke: { + header: 'Revoke system administrator', + body: 'Revoke system-administrator privileges from {email}? They will lose access to all system-level features.', + confirmBtn: 'Revoke', + }, + }, + }, + bulkApply: { + label: 'Apply to all existing tenants', + tooltip: 'Saving the value only affects new tenants by default; click here to also overwrite every existing tenant.', + confirmBtn: 'Confirm apply', + confirmBody: 'Overwrite the storage quota of every existing tenant to {value} GB. Tenants whose quota was tuned manually by operations will also be overwritten. Continue?', + success: 'Updated storage quota for {count} tenants to {gb} GB', + failed: 'Failed to apply to all tenants', + }, } }, mcp: { diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index 387dd6c8..5759ef0d 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -551,7 +551,7 @@ export default { parserEngine: "파싱 엔진", storageEngine: "스토리지 엔진", mcpService: "MCP 서비스", - systemSettings: "시스템 설정", + versionInfo: "버전 정보", tenantInfo: "테넌트 정보", apiInfo: "API 정보", navGroups: { @@ -1814,6 +1814,109 @@ export default { fetchFailed: "시스템 정보 가져오기 실패", networkError: "네트워크 오류, 나중에 다시 시도해주세요", }, + globalSettings: { + title: "시스템 설정", + description: "플랫폼 전역 런타임 설정입니다. 저장하면 모든 테넌트에 즉시 적용됩니다. 시스템 관리자만 보고 수정할 수 있습니다.", + loading: "로딩 중...", + empty: "설정 가능한 시스템 항목이 없습니다", + badgeRequiresRestart: "재시작 필요", + badgeSecret: "민감", + badgeOverride: "재정의됨", + badgeOverrideTooltip: "이 값은 관리자가 DB에 저장하여 환경 변수 및 기본값을 덮어썼습니다.", + modifiedAt: "마지막 수정: {value}", + tagInputPlaceholder: "엔터로 항목 추가. 예: example.com / *.foo.com / 10.0.0.0/8", + priorityHint: { + title: "우선순위 안내", + tier1: "이 페이지에서 저장한 항목(\"재정의됨\" 배지가 붙은 항목)은 항상 우선 적용되며, 환경 변수는 무시됩니다.", + tier2: "여기서 저장하지 않은 항목은 환경 변수를 따르며, 환경 변수도 없으면 내장 기본값을 사용합니다.", + tier3: "특정 항목을 다시 환경 변수 기반으로 되돌리려면 해당 행의 \"초기화\" 버튼을 누르세요.", + }, + keyLabels: { + auth: { + registration_mode: "셀프 가입 모드", + }, + ssrf: { + whitelist: "SSRF 보호 허용 목록", + }, + tenant: { + max_owned_per_user: "사용자당 최대 테넌트 수", + default_storage_quota_gb: "신규 테넌트 기본 저장 용량 (GB)", + }, + }, + enumLabels: { + auth: { + registration_mode: { + self_serve: "셀프 가입 (누구나 가입 가능)", + invite_only: "초대 전용 (공개 가입 비활성)", + }, + }, + }, + confirm: { + header: "고위험 작업 확인", + confirmBtn: "저장 확인", + cancelBtn: "취소", + emptyValue: "(비어 있음)", + defaultBody: "「{label}」을(를) {value}(으)로 변경하려고 합니다.", + bodyAuthRegistrationMode: "「{label}」을(를) {value}(으)로 변경하려고 합니다.\n\nself_serve로 전환하면 인터넷의 누구나 계정을 만들 수 있습니다. 의도된 동작인지 확인해 주세요.", + }, + listConfirm: { + ssrf: { + whitelist: { + add: { + header: "SSRF 화이트리스트 항목 추가", + body: "{entry} 항목을 SSRF 화이트리스트에 추가하시겠습니까? 일치하는 호스트 / IP / 대역은 SSRF 보호를 우회하여 에이전트가 내부 서비스에 접근할 수 있게 됩니다. 신뢰하는 항목만 추가하세요.", + confirmBtn: "추가 확인", + }, + remove: { + header: "SSRF 화이트리스트 항목 제거", + body: "{entry} 항목을 SSRF 화이트리스트에서 제거하시겠습니까? 제거 후에는 해당 항목이 다시 SSRF 보호 대상이 됩니다.", + confirmBtn: "제거 확인", + }, + }, + }, + }, + messages: { + loadFailed: "시스템 설정을 불러오지 못했습니다", + saveSuccess: "저장되었습니다", + saveFailed: "저장 실패", + }, + reset: { + label: "초기화", + tooltip: "UI 재정의 값을 제거하고 환경 변수 또는 내장 기본값으로 되돌립니다", + confirmBtn: "초기화 확인", + confirmBody: "「{label}」을(를) 초기화하시겠습니까? DB에 저장된 재정의 값이 삭제되고 환경 변수 또는 내장 기본값으로 되돌아갑니다.", + success: "기본값으로 초기화되었습니다", + failed: "초기화 실패", + }, + admins: { + label: "시스템 관리자", + description: "플랫폼 수준 권한을 가진 사용자입니다. 오른쪽에 이메일을 입력하고 엔터를 누르면 해당 사용자를 관리자로 승격하고, 태그의 ×를 누르면 권한을 회수합니다. 본인은 관리자이지만 목록에 표시되지 않으며 자신의 권한을 회수할 수 없습니다.", + placeholder: "사용자 이메일을 입력하고 엔터를 누르세요", + loadFailed: "시스템 관리자 정보를 불러오지 못했습니다", + saveSuccess: "시스템 관리자가 업데이트되었습니다", + saveFailed: "시스템 관리자 업데이트 실패", + confirm: { + promote: { + header: "시스템 관리자로 승격", + body: "{email} 사용자를 시스템 관리자로 승격하시겠습니까? 이 사용자는 모든 테넌트 접근, 시스템 설정 변경, 관리자 명단 관리 등 플랫폼 수준의 권한을 갖게 됩니다.", + confirmBtn: "승격 확인", + }, + revoke: { + header: "시스템 관리자 권한 회수", + body: "{email} 사용자의 시스템 관리자 권한을 회수하시겠습니까? 회수 후에는 시스템 수준 기능에 더 이상 접근할 수 없습니다.", + confirmBtn: "회수 확인", + }, + }, + }, + bulkApply: { + label: "모든 기존 테넌트에 적용", + tooltip: "저장한 값은 기본적으로 새로 생성되는 테넌트에만 적용됩니다. 이 버튼을 누르면 현재 값을 모든 기존 테넌트에도 덮어씁니다.", + confirmBtn: "적용 확인", + confirmBody: "모든 기존 테넌트의 저장 용량을 {value} GB로 덮어씁니다. 운영팀이 개별로 조정한 테넌트의 용량도 함께 덮어쓰여집니다. 계속하시겠습니까?", + success: "{count}개 테넌트의 저장 용량을 {gb} GB로 갱신했습니다", + failed: "모든 테넌트에 적용 실패", + }, + }, }, mcp: { testResult: { diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index 1d592eb2..ece7ae10 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -653,7 +653,7 @@ export default { mcpService: 'Сервис MCP', conversationConfig: 'Настройки диалога', conversationStrategy: 'Стратегия диалога', - systemSettings: 'Настройки системы', + versionInfo: 'Информация о версии', tenantInfo: 'Информация о арендаторе', apiInfo: 'Информация API', navGroups: { @@ -1607,6 +1607,109 @@ export default { messages: { fetchFailed: 'Не удалось получить информацию о системе', networkError: 'Ошибка сети, попробуйте позже' + }, + globalSettings: { + title: 'Системные настройки', + description: 'Настройки платформы, применяемые в режиме реального времени. Изменения сразу действуют для всех тенантов. Доступны только системным администраторам.', + loading: 'Загрузка...', + empty: 'Нет доступных для настройки параметров', + badgeRequiresRestart: 'Нужен перезапуск', + badgeSecret: 'Конфиденциально', + badgeOverride: 'Переопределено', + badgeOverrideTooltip: 'Это значение сохранено администратором в БД и переопределяет переменную окружения и значение по умолчанию.', + modifiedAt: 'Последнее изменение: {value}', + tagInputPlaceholder: 'Нажмите Enter, чтобы добавить запись, например: example.com / *.foo.com / 10.0.0.0/8', + priorityHint: { + title: 'О приоритете', + tier1: 'Параметры, сохранённые на этой странице (с пометкой «Переопределено»), всегда имеют приоритет — переменная окружения для них игнорируется.', + tier2: 'Параметры, не сохранённые здесь, берутся из переменной окружения, а если её нет — из встроенного значения по умолчанию.', + tier3: 'Чтобы вернуть параметр под управление переменной окружения, нажмите кнопку «Сбросить» в его строке.', + }, + keyLabels: { + auth: { + registration_mode: 'Режим самостоятельной регистрации', + }, + ssrf: { + whitelist: 'Белый список SSRF-защиты', + }, + tenant: { + max_owned_per_user: 'Максимум тенантов на пользователя', + default_storage_quota_gb: 'Квота хранилища для новых тенантов по умолчанию (ГБ)', + }, + }, + enumLabels: { + auth: { + registration_mode: { + self_serve: 'Самостоятельная (любой может зарегистрироваться)', + invite_only: 'Только по приглашению (открытая регистрация отключена)', + }, + }, + }, + confirm: { + header: 'Подтверждение опасного действия', + confirmBtn: 'Подтвердить сохранение', + cancelBtn: 'Отмена', + emptyValue: '(пусто)', + defaultBody: 'Вы собираетесь изменить «{label}» на: {value}', + bodyAuthRegistrationMode: 'Вы собираетесь изменить «{label}» на: {value}\n\nЕсли переключить на self_serve, любой пользователь публичного интернета сможет создать аккаунт — убедитесь, что это ожидаемое поведение.', + }, + listConfirm: { + ssrf: { + whitelist: { + add: { + header: 'Добавить запись в белый список SSRF', + body: 'Добавить {entry} в белый список SSRF? Соответствующие хосты / IP / подсети будут обходить защиту от SSRF и смогут обращаться к внутренним сервисам через агентов. Добавляйте только полностью доверенные записи.', + confirmBtn: 'Добавить', + }, + remove: { + header: 'Удалить запись из белого списка SSRF', + body: 'Удалить {entry} из белого списка SSRF? После удаления запись снова будет блокироваться защитой от SSRF.', + confirmBtn: 'Удалить', + }, + }, + }, + }, + messages: { + loadFailed: 'Не удалось загрузить системные настройки', + saveSuccess: 'Сохранено', + saveFailed: 'Ошибка сохранения' + }, + reset: { + label: 'Сбросить', + tooltip: 'Очистить переопределение из UI и вернуться к переменной окружения или встроенному значению по умолчанию', + confirmBtn: 'Подтвердить сброс', + confirmBody: 'Сбросить «{label}»? Это удалит запись переопределения в БД и вернёт значение из переменной окружения или встроенное по умолчанию.', + success: 'Сброшено к значению по умолчанию', + failed: 'Ошибка сброса' + }, + admins: { + label: 'Системные администраторы', + description: 'Пользователи с правами уровня платформы. Введите email и нажмите Enter, чтобы повысить пользователя до администратора; нажмите × на теге, чтобы отозвать права. Вы (текущий пользователь) являетесь администратором и не отображаетесь в списке — отозвать собственные права нельзя.', + placeholder: 'Введите email пользователя и нажмите Enter', + loadFailed: 'Не удалось загрузить системных администраторов', + saveSuccess: 'Системные администраторы обновлены', + saveFailed: 'Ошибка обновления системных администраторов', + confirm: { + promote: { + header: 'Повысить до системного администратора', + body: 'Повысить пользователя {email} до системного администратора? Пользователь получит права уровня платформы: доступ ко всем тенантам, изменение системных настроек и управление списком администраторов.', + confirmBtn: 'Повысить', + }, + revoke: { + header: 'Отозвать права администратора', + body: 'Отозвать права системного администратора у {email}? После отзыва пользователь потеряет доступ ко всем системным функциям.', + confirmBtn: 'Отозвать', + }, + }, + }, + bulkApply: { + label: 'Применить ко всем существующим тенантам', + tooltip: 'По умолчанию сохранённое значение применяется только к новым тенантам. Нажмите, чтобы также перезаписать всех существующих.', + confirmBtn: 'Подтвердить применение', + confirmBody: 'Перезаписать квоту хранилища всех существующих тенантов значением {value} ГБ. Тенанты, чью квоту вручную правили эксплуатация, также будут перезаписаны. Продолжить?', + success: 'Обновлена квота хранилища у {count} тенантов: {gb} ГБ', + failed: 'Ошибка применения ко всем тенантам' + } } }, mcp: { diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index ae64386e..e21237c0 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -548,7 +548,7 @@ export default { parserEngine: "解析引擎", storageEngine: "存储引擎", mcpService: "MCP服务", - systemSettings: "系统设置", + versionInfo: "版本信息", tenantInfo: "空间信息", apiInfo: "API信息", navGroups: { @@ -1793,6 +1793,109 @@ export default { fetchFailed: "获取系统信息失败", networkError: "网络错误,请稍后重试", }, + globalSettings: { + title: "系统设置", + description: "平台级运行时配置,保存后立即对所有租户生效。仅系统管理员可见可改。", + loading: "加载中...", + empty: "暂无可配置的系统设置", + badgeRequiresRestart: "需重启", + badgeSecret: "敏感", + badgeOverride: "已覆盖", + badgeOverrideTooltip: "该值已由管理员保存到数据库,覆盖了环境变量与默认值", + modifiedAt: "上次修改:{value}", + tagInputPlaceholder: "回车添加条目,例:example.com / *.foo.com / 10.0.0.0/8", + priorityHint: { + title: "关于优先级", + tier1: "在此页面保存过的项(带「已覆盖」徽章)— 始终以这里的值为准,环境变量会被忽略。", + tier2: "未在此处保存过的项 — 如果环境变量里有就用环境变量,否则用程序内置默认值。", + tier3: "若想让某项重新由环境变量控制,点击该行的「重置」按钮即可清除当前 UI 设置。", + }, + keyLabels: { + auth: { + registration_mode: "自助注册模式", + }, + ssrf: { + whitelist: "SSRF 防护白名单", + }, + tenant: { + max_owned_per_user: "每用户最大租户数", + default_storage_quota_gb: "新租户默认存储配额 (GB)", + }, + }, + enumLabels: { + auth: { + registration_mode: { + self_serve: "自助注册(任何人可注册)", + invite_only: "仅邀请(关闭公网注册)", + }, + }, + }, + confirm: { + header: "高危操作确认", + confirmBtn: "确认保存", + cancelBtn: "取消", + emptyValue: "(空)", + defaultBody: "即将把「{label}」改为:{value}", + bodyAuthRegistrationMode: "即将把「{label}」改为:{value}\n\n如果切到 self_serve,公网任何人都可以注册账号 — 务必确认是预期行为。", + }, + listConfirm: { + ssrf: { + whitelist: { + add: { + header: "添加 SSRF 白名单条目", + body: "确认把 {entry} 加入 SSRF 白名单?该条目匹配到的主机 / IP / 网段会绕过 SSRF 防护,可能让 Agent 访问内网服务,请仅在确知用途时添加。", + confirmBtn: "确认添加", + }, + remove: { + header: "移除 SSRF 白名单条目", + body: "确认从 SSRF 白名单中移除 {entry}?移除后该条目将重新受 SSRF 防护拦截。", + confirmBtn: "确认移除", + }, + }, + }, + }, + messages: { + loadFailed: "加载系统设置失败", + saveSuccess: "已保存", + saveFailed: "保存失败", + }, + reset: { + label: "重置", + tooltip: "清除当前 UI 覆盖,恢复使用环境变量或内置默认值", + confirmBtn: "确认重置", + confirmBody: "确定要重置「{label}」吗?该操作会删除数据库中的覆盖值,回退到环境变量或内置默认值。", + success: "已重置为默认值", + failed: "重置失败", + }, + admins: { + label: "系统管理员", + description: "拥有平台级权限的用户。在右侧输入邮箱并回车即可提升用户为管理员;点击 × 即为撤销其权限。当前你(自己)已是管理员,不在列表中显示,也无法被自己撤销。", + placeholder: "输入用户邮箱并回车", + loadFailed: "加载系统管理员失败", + saveSuccess: "已更新系统管理员", + saveFailed: "更新系统管理员失败", + confirm: { + promote: { + header: "提升为系统管理员", + body: "确认将 {email} 提升为系统管理员?该用户将获得平台级权限,可访问所有租户、修改系统设置、管理其他管理员。", + confirmBtn: "确认提升", + }, + revoke: { + header: "撤销系统管理员", + body: "确认撤销 {email} 的系统管理员权限?撤销后该用户将无法再访问任何系统级功能。", + confirmBtn: "确认撤销", + }, + }, + }, + bulkApply: { + label: "应用到所有现有租户", + tooltip: "保存的值默认只对之后新建的租户生效;点击此按钮将当前值同步写入所有现有租户。", + confirmBtn: "确认应用", + confirmBody: "将把所有现有租户的存储配额覆盖为 {value} GB。如有租户被运维单独调整过的配额,也会一并被覆盖。是否继续?", + success: "已将 {count} 个租户的存储配额更新为 {gb} GB", + failed: "应用到所有租户失败", + }, + }, }, mcp: { testResult: { diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts index 3e49ff16..141bcc98 100644 --- a/frontend/src/router/index.ts +++ b/frontend/src/router/index.ts @@ -140,32 +140,27 @@ const router = createRouter({ component: () => import("../views/organization/OrganizationList.vue"), meta: { requiresInit: true, requiresAuth: true } }, - // System administration area — gated to users with - // user.is_system_admin === true. The route guard below honours - // the meta.requiresSystemAdmin flag; non-admins are bounced to - // /platform/knowledge-bases. Real authorisation lives server-side. + // Compatibility redirects for legacy /platform/system/* URLs. + // The whole system administration surface — global settings + // and the system-admin roster — now lives as a single section + // inside the standard Settings modal. We keep the routes + // around so old bookmarks / external links don't 404. { path: "system", - component: () => import("../views/system/SystemLayout.vue"), + redirect: { path: "/platform/settings", query: { section: "system-global" } }, + meta: { requiresInit: true, requiresAuth: true, requiresSystemAdmin: true }, + }, + { + path: "system/settings", + name: "systemSettings", + redirect: { path: "/platform/settings", query: { section: "system-global" } }, + meta: { requiresInit: true, requiresAuth: true, requiresSystemAdmin: true }, + }, + { + path: "system/admins", + name: "systemAdmins", + redirect: { path: "/platform/settings", query: { section: "system-global" } }, meta: { requiresInit: true, requiresAuth: true, requiresSystemAdmin: true }, - redirect: "/platform/system/admins", - children: [ - { - // Kept as a compatibility URL. Global settings now live in - // the standard settings modal rather than a standalone - // routed page. - path: "settings", - name: "systemSettings", - redirect: { path: "/platform/settings", query: { section: "system-global" } }, - meta: { requiresInit: true, requiresAuth: true, requiresSystemAdmin: true } - }, - { - path: "admins", - name: "systemAdmins", - component: () => import("../views/system/SystemAdmins.vue"), - meta: { requiresInit: true, requiresAuth: true, requiresSystemAdmin: true } - }, - ], }, ], }, diff --git a/frontend/src/views/settings/Settings.vue b/frontend/src/views/settings/Settings.vue index 43267e61..91faa616 100644 --- a/frontend/src/views/settings/Settings.vue +++ b/frontend/src/views/settings/Settings.vue @@ -284,8 +284,8 @@ const navItems = computed(() => { { key: 'parser', icon: 'file-search', label: t('settings.parserEngine') }, { key: 'storage', icon: 'cloud', label: t('settings.storageEngine') }, { key: 'mcp', icon: 'tools', label: t('settings.mcpService') }, - { key: 'system', icon: 'info-circle', label: t('settings.systemSettings') }, - { key: 'system-global', icon: 'server', label: '全局设置' }, + { key: 'system', icon: 'info-circle', label: t('settings.versionInfo') }, + { key: 'system-global', icon: 'server', label: '系统设置' }, { key: 'userprofile', icon: 'user', label: t('userProfile.title') }, { key: 'tenant', icon: 'user-circle', label: t('settings.tenantInfo') }, { key: 'members', icon: 'usergroup', label: t('tenantMember.title') }, @@ -376,7 +376,8 @@ const handleClose = () => { uiStore.closeSettings() // 如果当前路由是设置页,返回上一页 if (route.path === '/platform/settings') { - if (route.query.section === 'system-global') { + const sec = route.query.section + if (sec === 'system-global') { router.push('/platform/knowledge-bases') } else { router.back() @@ -480,8 +481,13 @@ onUnmounted(() => { .settings-modal { position: relative; width: 100%; - max-width: 900px; - height: 700px; + // 1080×780 trades a touch of small-screen real estate for noticeably + // less cramped tables (member list, system settings rows). Outer + // padding is 20px so 1080 + 40 = 1120, comfortably within typical + // laptops (1280+). Below 1100px viewport the `width: 100%` kicks in + // and the modal shrinks to fit minus the 20px padding. + max-width: 1080px; + height: 780px; background: var(--td-bg-color-container); border-radius: 12px; box-shadow: 0 6px 28px rgba(15, 23, 42, 0.08); @@ -668,7 +674,13 @@ onUnmounted(() => { } .content-wrapper { - max-width: 600px; + // Bumped from 600 to 760 when the modal grew from 900→1080 (see + // .settings-modal). Without this, single-column panes (General, + // Tenant, API key, …) leave a wide right-hand gutter inside the + // wider modal. 760 keeps comfortable reading-width on long + // descriptions without the form fields stretching to the full + // panel width — which would look stranger than a small gutter. + max-width: 760px; padding: 40px 48px; /* 成员 / 审计表格列多,600px 会把操作列挤到贴边;铺满右侧内容列更稳。 */ diff --git a/frontend/src/views/system/SystemAdmins.vue b/frontend/src/views/system/SystemAdmins.vue deleted file mode 100644 index a17b3a92..00000000 --- a/frontend/src/views/system/SystemAdmins.vue +++ /dev/null @@ -1,259 +0,0 @@ - - - - - diff --git a/frontend/src/views/system/SystemLayout.vue b/frontend/src/views/system/SystemLayout.vue deleted file mode 100644 index 5b135a9d..00000000 --- a/frontend/src/views/system/SystemLayout.vue +++ /dev/null @@ -1,127 +0,0 @@ - - - - - diff --git a/frontend/src/views/system/SystemSettings.vue b/frontend/src/views/system/SystemSettings.vue index 8b0414a7..e4c0fd56 100644 --- a/frontend/src/views/system/SystemSettings.vue +++ b/frontend/src/views/system/SystemSettings.vue @@ -5,190 +5,471 @@ the route also has meta.requiresSystemAdmin so non-admins never reach this component (see frontend/src/router/index.ts). - UI principle: each row is independently editable + savable. We don't - show a global "Save all" button because backend Update is per-key - (the audit log records each change individually) and the - "save-and-see-effect" loop is friendlier per-field. Validation is - client-side first (matching value_type), server-side strict. + Visual contract: matches the canonical Settings-modal pane skeleton + (`.section-header` + `.settings-group` + `.setting-row` / + `.setting-info` / `.setting-control`) used by GeneralSettings, + OllamaSettings, etc. Avoid bespoke layout here; the modal already + constrains width and padding via `.content-wrapper--full`. + + UI principle: every control auto-persists, no Save button. The + commit signal differs by control type so the user isn't surprised + by writes while they're still composing: + + - Switch / Select (single-pick) → @change. Selecting an + option IS the commit + signal; there's no + "in-progress" state. + - Input / InputNumber → @blur (not @change — + t-input-number fires + @change on every digit). + - SSRF whitelist (string_list) → controlled tag-input + + per-tag inline popconfirm. + - System admins → tag-input @change with + inline popconfirm per delta. + + auth.registration_mode triggers an + inline t-popconfirm (same as Reset / bulk-apply) before persisting; + cancelling rolls the in-progress edit back to the canonical value. -->
-