Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat(system): consolidate system admin and settings into one Settings panel
wizardchen9cce0c8e5ec7
diff --git a/.env.example b/.env.exampleindex eef396000..776e1952a 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.tsindex 540c0b366..0c10b9bad 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<SystemAdminUser> {- 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<SystemAdminUser> {+ 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: booleanlast_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?: stringcreated_at: stringupdated_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<void> {+ 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<ApplyDefaultStorageQuotaResult> {+ 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.vueindex 9fd204b5d..3472da77e 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 = falseuiStore.openSettings('system-global')diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex 9684be5a9..b256c2f26 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.tsindex 387dd6c87..5759ef0d0 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.tsindex 1d592eb29..ece7ae10f 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.tsindex ae64386e7..e21237c05 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.tsindex 3e49ff162..141bcc986 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.vueindex 43267e61d..91faa6164 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.vuedeleted file mode 100644index a17b3a926..000000000--- a/frontend/src/views/system/SystemAdmins.vue+++ /dev/null@@ -1,259 +0,0 @@-<template>- <!--- SystemAdmins — list & manage the platform-wide system administrators.- Grants/revokes via the /api/v1/system/admin/{promote,revoke,list}- endpoints (server-side guarded by RequireSystemAdmin middleware).-- P0 milestone scope is deliberately minimal:- - Paginated list of current system admins- - Promote a user by email- - Revoke an existing admin (with last-admin & self-revoke server guards)-- Future milestones can layer richer UX on top — search, audit-log- drawer, bulk operations — but the API surface and gating are stable.- -->- <div class="system-admins">- <div class="page-header">- <div>- <h1 class="page-title">系统管理员</h1>- <p class="page-desc">- 系统管理员独立于租户角色,拥有平台级管理权限(管理其他系统管理员、全局设置、内置模型等)。- </p>- </div>- <t-button theme="primary" @click="openPromoteDialog">- <template #icon><t-icon name="add" /></template>- 提升用户为系统管理员- </t-button>- </div>-- <t-card class="admins-card" :bordered="false">- <t-table- row-key="id"- :data="admins"- :columns="columns"- :loading="loading"- size="medium"- hover- stripe- >- <template #status="{ row }">- <t-tag v-if="row.is_active" theme="success" variant="light">- 活跃- </t-tag>- <t-tag v-else theme="warning" variant="light">已停用</t-tag>- </template>- <template #actions="{ row }">- <t-button- theme="danger"- variant="text"- size="small"- :disabled="row.id === currentUserId"- @click="confirmRevoke(row)"- >- 撤销权限- </t-button>- </template>- </t-table>-- <div class="pagination-bar" v-if="total > 0">- <t-pagination- v-model="page"- v-model:page-size="pageSize"- :total="total"- :page-size-options="[20, 50, 100]"- @change="loadAdmins"- />- </div>- </t-card>-- <!-- Promote dialog -->- <t-dialog- v-model:visible="promoteDialogVisible"- header="提升用户为系统管理员"- :confirm-btn="{ content: '确认提升', loading: promoting }"- @confirm="submitPromote"- @close="resetPromoteDialog"- >- <p class="dialog-hint">- 请输入要提升的用户的 ID。该用户必须已经在系统中注册过;操作幂等,已是管理员的用户不会被重复提升。- </p>- <t-input- v-model="promoteUserId"- placeholder="用户 ID(UUID 形式)"- :disabled="promoting"- clearable- />- </t-dialog>- </div>-</template>--<script setup lang="ts">-import { ref, onMounted, computed } from 'vue'-import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next'-import { useAuthStore } from '@/stores/auth'-import {- listSystemAdmins,- promoteUserToSystemAdmin,- revokeSystemAdmin,- type SystemAdminUser,-} from '@/api/system'--const authStore = useAuthStore()-const currentUserId = computed(() => authStore.currentUserId)--const admins = ref<SystemAdminUser[]>([])-const total = ref(0)-const page = ref(1)-const pageSize = ref(20)-const loading = ref(false)--const promoteDialogVisible = ref(false)-const promoteUserId = ref('')-const promoting = ref(false)--// Columns are defined as a computed (vs a static const) so future-// localization/translation can hook in without component refactor.-const columns = [- { colKey: 'username', title: '用户名', width: 180 },- { colKey: 'email', title: '邮箱', width: 280 },- { colKey: 'status', title: '状态', width: 100 },- { colKey: 'created_at', title: '注册时间', width: 200 },- { colKey: 'actions', title: '操作', width: 120, align: 'right' as const },-]--async function loadAdmins() {- loading.value = true- try {- const offset = (page.value - 1) * pageSize.value- // listSystemAdmins resolves to ListSystemAdminsResponse directly —- // utils/request.ts already unwraps axios's response.data wrapper at- // the interceptor layer (see line 97), so an extra `.data` here- // would explode at runtime as "Cannot read property 'admins' of- // undefined" and surface as the generic load-failed toast.- const res = await listSystemAdmins({ offset, limit: pageSize.value })- admins.value = res.admins ?? []- total.value = res.total ?? 0- } catch (err) {- // Surface a toast and bail — keeping prior list so the user isn't- // left staring at an empty table on a transient failure.- MessagePlugin.error('加载系统管理员列表失败')- console.error('listSystemAdmins failed:', err)- } finally {- loading.value = false- }-}--function openPromoteDialog() {- promoteUserId.value = ''- promoteDialogVisible.value = true-}--function resetPromoteDialog() {- promoteUserId.value = ''- promoting.value = false-}--async function submitPromote() {- const uid = promoteUserId.value.trim()- if (!uid) {- MessagePlugin.warning('请输入用户 ID')- return- }- promoting.value = true- try {- await promoteUserToSystemAdmin(uid)- MessagePlugin.success('已提升为系统管理员')- promoteDialogVisible.value = false- await loadAdmins()- } catch (err: any) {- // utils/request.ts 把后端的 {error: "..."} 提升到了顶层 message- // 字段(line 197-213),同时保留原始 data 字段。我们优先读 message- // —— 它已经是后端的 human-readable 错误文案,覆盖了 user-not-found- // / 自我撤销等业务错误场景。- const msg = err?.message || err?.error || '提升失败,请检查用户 ID 后重试'- MessagePlugin.error(msg)- } finally {- promoting.value = false- }-}--function confirmRevoke(row: SystemAdminUser) {- // Confirmation dialog is mandatory — revoking is destructive and- // the server's last-admin / self-revoke guards return 400 with a- // human-readable message which we re-surface in submitRevoke.- const confirmDialog = DialogPlugin.confirm({- header: '撤销系统管理员权限',- body: `确定要撤销用户 "${row.username}" (${row.email}) 的系统管理员权限吗?`,- confirmBtn: { content: '确认撤销', theme: 'danger' },- cancelBtn: '取消',- onConfirm: async () => {- await submitRevoke(row.id)- confirmDialog.destroy()- },- onClose: () => confirmDialog.destroy(),- })-}--async function submitRevoke(userId: string) {- try {- await revokeSystemAdmin(userId)- MessagePlugin.success('已撤销系统管理员权限')- await loadAdmins()- } catch (err: any) {- // 同 submitPromote 的注释 —— 后端 last-admin / self-revoke 保护- // 走 400 + {error: "..."},被拦截器抬到 err.message。- const msg = err?.message || err?.error || '撤销失败'- MessagePlugin.error(msg)- }-}--onMounted(() => {- loadAdmins()-})-</script>--<style scoped>-.system-admins {- max-width: 1100px;-}--.page-header {- display: flex;- align-items: flex-start;- justify-content: space-between;- gap: 24px;- margin-bottom: 20px;-}--.page-title {- margin: 0 0 6px;- font-size: 22px;- font-weight: 600;- color: var(--td-text-color-primary, #000);-}--.page-desc {- margin: 0;- font-size: 13px;- line-height: 1.6;- color: var(--td-text-color-secondary, #666);- max-width: 720px;-}--.admins-card {- margin-top: 8px;-}--.pagination-bar {- margin-top: 16px;- display: flex;- justify-content: flex-end;-}--.dialog-hint {- margin: 0 0 12px;- font-size: 13px;- color: var(--td-text-color-secondary, #666);- line-height: 1.6;-}-</style>diff --git a/frontend/src/views/system/SystemLayout.vue b/frontend/src/views/system/SystemLayout.vuedeleted file mode 100644index 5b135a9d8..000000000--- a/frontend/src/views/system/SystemLayout.vue+++ /dev/null@@ -1,127 +0,0 @@-<template>- <!--- SystemLayout — top-level shell for the platform-wide administration- area (/platform/system/*). Gated by meta.requiresSystemAdmin in the- router; reaching this component means the caller is an authenticated- SystemAdmin.-- Sidebar is intentionally simple: global system settings live inside- the standard Settings modal, while this routed area keeps workflows- that need a table-oriented management surface.- -->- <div class="system-layout">- <aside class="system-sidebar">- <div class="system-sidebar-header">- <h2 class="system-sidebar-title">系统管理</h2>- <div class="system-sidebar-subtitle">SystemAdmin</div>- </div>- <nav class="system-nav">- <router-link- v-for="item in navItems"- :key="item.name"- :to="{ name: item.name }"- v-slot="{ isActive, navigate }"- custom- >- <div- :class="['system-nav-item', { active: isActive }]"- @click="navigate"- >- <t-icon :name="item.icon" class="system-nav-icon" />- <span class="system-nav-label">{{ item.label }}</span>- </div>- </router-link>- </nav>- </aside>- <main class="system-content">- <router-view />- </main>- </div>-</template>--<script setup lang="ts">-// Nav items are declared here (not in a separate config file) because-// the list is short and tightly coupled to which child routes exist.-// When a new child route is added in router/index.ts under /platform/system,-// add a matching entry here.-const navItems = [- { name: 'systemAdmins', label: '系统管理员', icon: 'user-shield' },-]-</script>--<style scoped>-.system-layout {- display: flex;- height: 100%;- width: 100%;- background: var(--td-bg-color-page, #f5f5f5);-}--.system-sidebar {- width: 240px;- flex-shrink: 0;- background: var(--td-bg-color-container, #fff);- border-right: 1px solid var(--td-border-level-1-color, #e7e7e7);- padding: 20px 12px;- display: flex;- flex-direction: column;- gap: 16px;-}--.system-sidebar-header {- padding: 0 12px 12px;- border-bottom: 1px solid var(--td-border-level-1-color, #e7e7e7);-}--.system-sidebar-title {- margin: 0;- font-size: 16px;- font-weight: 600;- color: var(--td-text-color-primary, #000);-}--.system-sidebar-subtitle {- font-size: 11px;- color: var(--td-text-color-placeholder, #999);- margin-top: 4px;- letter-spacing: 0.5px;-}--.system-nav {- display: flex;- flex-direction: column;- gap: 2px;-}--.system-nav-item {- display: flex;- align-items: center;- gap: 10px;- padding: 8px 12px;- border-radius: 6px;- cursor: pointer;- font-size: 14px;- color: var(--td-text-color-primary, #333);- transition: background-color 0.15s;-}--.system-nav-item:hover {- background: var(--td-bg-color-component-hover, #f3f3f3);-}--.system-nav-item.active {- background: var(--td-brand-color-light, #e0eaff);- color: var(--td-brand-color, #0052d9);- font-weight: 500;-}--.system-nav-icon {- font-size: 16px;-}--.system-content {- flex: 1;- overflow: auto;- padding: 24px 32px;-}-</style>diff --git a/frontend/src/views/system/SystemSettings.vue b/frontend/src/views/system/SystemSettings.vueindex 8b0414a71..e4c0fd562 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 neverreach 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.--><div class="system-settings">- <div class="page-header">- <div>- <h2 class="page-title">全局设置</h2>- <p class="page-desc">- 平台级运行时配置,保存后立即生效。- </p>+ <div class="section-header">+ <h2>{{ t('system.globalSettings.title') }}</h2>+ <p class="section-description">+ {{ t('system.globalSettings.description') }}+ </p>+ </div>++ <!--+ Priority hint. We surface the 3-tier resolver semantics inline so+ operators don't have to dig through code to figure out why a value+ they set in env "doesn't show up" — once a row is overridden in+ the UI, env is shadowed until the row is cleared. The "已覆盖"+ badge per row is the per-key signal; this block is the global key.+ Hand-rolled panel rather than t-alert because the default alert+ slot rendering hid most of the body text in TDesign's layout.+ -->+ <div class="priority-hint">+ <div class="priority-hint-header">+ <t-icon name="info-circle-filled" class="priority-hint-icon" />+ <span class="priority-hint-title">+ {{ t('system.globalSettings.priorityHint.title') }}+ </span></div>- <t-button shape="square" variant="text" @click="loadSettings" :loading="loading">- <template #icon><t-icon name="refresh" /></template>- </t-button>+ <ul class="priority-hint-list">+ <li>{{ t('system.globalSettings.priorityHint.tier1') }}</li>+ <li>{{ t('system.globalSettings.priorityHint.tier2') }}</li>+ <li>{{ t('system.globalSettings.priorityHint.tier3') }}</li>+ </ul></div>- <div v-if="loading && groupedSettings.length === 0" class="loading-state">- <t-loading text="加载中..." />+ <div v-if="loading && settings.length === 0" class="loading-state">+ <t-loading :text="t('system.globalSettings.loading')" /></div>- <div v-else-if="groupedSettings.length === 0" class="empty-state">- <t-icon name="info-circle" size="32px" />- <div>暂无可配置的系统设置</div>+ <div v-else-if="settings.length === 0" class="empty-state">+ <t-icon name="info-circle" size="24px" />+ <span>{{ t('system.globalSettings.empty') }}</span></div>- <section- v-for="group in groupedSettings"- :key="group.category"- class="settings-group"- >- <div class="group-title">- <span class="group-title-text">{{ categoryLabel(group.category) }}</span>- <span class="group-title-count">{{ group.items.length }}</span>+ <div v-else class="settings-group">+ <!--+ System-admins management. Visually identical to SSRF whitelist+ (a tag-input with one entry per email). NOT a system_setting+ row — it's backed by the user table via promote/revoke APIs.+ We sit it at the top because changing who can edit this page+ is structurally more important than tweaking any value below.+ Self-edit safety: the current user is excluded from the visible+ tags (they can't revoke themselves anyway, and showing a tag+ that can't be removed is worse than not showing it).+ -->+ <div class="setting-row">+ <div class="setting-info">+ <label class="setting-label">+ <span>{{ t('system.globalSettings.admins.label') }}</span>+ </label>+ <p class="desc">{{ t('system.globalSettings.admins.description') }}</p>+ </div>+ <div class="setting-control">+ <div class="setting-control-row">+ <t-popconfirm+ v-model:visible="adminPopconfirm.visible"+ :content="adminPopconfirm.content"+ :theme="adminPopconfirm.theme"+ :confirm-btn="adminPopconfirm.confirmBtn"+ :cancel-btn="t('system.globalSettings.confirm.cancelBtn')"+ :popup-props="PROGRAMMATIC_POPCONFIRM_PROPS"+ placement="left"+ @confirm="adminPopconfirm.finish(true)"+ @cancel="adminPopconfirm.finish(false)"+ @visible-change="adminPopconfirm.onVisibleChange"+ >+ <div class="setting-control-anchor">+ <t-tag-input+ v-model="adminEmails"+ :placeholder="t('system.globalSettings.admins.placeholder')"+ :disabled="adminBusy"+ class="setting-input setting-input--wide"+ clearable+ @change="onAdminsChange"+ />+ </div>+ </t-popconfirm>+ <t-loading v-if="adminBusy" size="small" class="setting-saving" />+ </div>+ </div></div>+ <!--+ Flat list — no category grouping. The registry is small enough+ (single digits) that section headers add visual noise without+ helping discovery; if it grows past ~10 keys we'll bring back+ grouping with a real visual treatment instead of a tiny caps+ label.+ --><div- v-for="item in group.items"+ v-for="item in settings":key="item.key"class="setting-row"><div class="setting-info">- <div class="setting-key">- <span class="setting-key-text">{{ item.key }}</span>+ <label class="setting-label">+ <span>{{ keyLabel(item.key) }}</span><t-tagv-if="item.requires_restart"theme="warning"variant="light"size="small"- >需重启</t-tag>+ class="setting-badge"+ >{{ t('system.globalSettings.badgeRequiresRestart') }}</t-tag><t-tagv-if="item.is_secret"theme="primary"variant="light"size="small"- >敏感</t-tag>- </div>- <div v-if="item.description" class="setting-desc">{{ item.description }}</div>- <div class="setting-meta">- <span>类型: {{ item.value_type }}</span>- <span v-if="item.last_modified_by">· 最后修改: {{ item.last_modified_by.slice(0, 8) }}</span>- <span v-if="item.updated_at">· {{ formatDate(item.updated_at) }}</span>+ class="setting-badge"+ >{{ t('system.globalSettings.badgeSecret') }}</t-tag>+ <t-tag+ v-if="hasOverride(item)"+ theme="success"+ variant="light"+ size="small"+ class="setting-badge"+ :title="t('system.globalSettings.badgeOverrideTooltip')"+ >{{ t('system.globalSettings.badgeOverride') }}</t-tag>+ </label>+ <p v-if="item.description" class="desc">{{ item.description }}</p>+ <div v-if="modifiedMeta(item)" class="setting-meta">+ {{ t('system.globalSettings.modifiedAt', { value: modifiedMeta(item) }) }}</div></div><div class="setting-control"><!--- Per-type input. value_type drives which control we render:- int → InputNumber- bool → Switch- string_list → TagInput (each entry as a tag)- string → InputNumber/Input/Select depending on enum- When `enum` is non-empty (regardless of declared type, but- only meaningful for string), we override to a Select.+ Two-row layout: input + spinner on top, secondary actions+ (currently just Reset) on a second row below, right-aligned+ under the input. We tried inlining the reset button on the+ same row as the input but the cluster of input + spinner ++ text-button read as visual noise; pushing reset down keeps+ the primary control visually clean while still placing the+ action close to the value it affects.-->+ <div class="setting-control-row">+ <t-popconfirm+ v-if="hasEnum(item) && isHighRiskKey(item.key)"+ v-model:visible="highRiskPopconfirm.visible"+ :content="highRiskPopconfirm.content"+ :theme="highRiskPopconfirm.theme"+ :confirm-btn="highRiskPopconfirm.confirmBtn"+ :cancel-btn="t('system.globalSettings.confirm.cancelBtn')"+ :popup-props="PROGRAMMATIC_POPCONFIRM_PROPS"+ placement="left"+ @confirm="highRiskPopconfirm.finish(true)"+ @cancel="highRiskPopconfirm.finish(false)"+ @visible-change="highRiskPopconfirm.onVisibleChange"+ >+ <div class="setting-control-anchor">+ <t-select+ v-model="editValues[item.key]"+ :options="enumOptions(item)"+ :disabled="savingKey === item.key"+ class="setting-input"+ @change="onHighRiskSelectChange(item)"+ />+ </div>+ </t-popconfirm><t-select- v-if="hasEnum(item)"+ v-else-if="hasEnum(item)"v-model="editValues[item.key]":options="enumOptions(item)":disabled="savingKey === item.key"class="setting-input"+ @change="onChange(item)"+ />+ <t-switch+ v-else-if="item.value_type === 'bool'"+ v-model="editValues[item.key]"+ :disabled="savingKey === item.key"+ @change="onChange(item)"/><t-input-numberv-else-if="item.value_type === 'int'"v-model="editValues[item.key]"- :placeholder="String(item.value)"+ :placeholder="placeholderFor(item)":disabled="savingKey === item.key"theme="normal":step="1":min="0"class="setting-input"+ @blur="onChange(item)"/>- <t-switch- v-else-if="item.value_type === 'bool'"- v-model="editValues[item.key]"- :disabled="savingKey === item.key"- />- <t-tag-input- v-else-if="item.value_type === 'string_list'"- v-model="editValues[item.key]"- :placeholder="emptyListPlaceholder"- :disabled="savingKey === item.key"- class="setting-input setting-input--wide"- clearable- />+ <t-popconfirm+ v-else-if="item.value_type === 'string_list' && item.key === 'ssrf.whitelist'"+ v-model:visible="ssrfPopconfirm.visible"+ :content="ssrfPopconfirm.content"+ :theme="ssrfPopconfirm.theme"+ :confirm-btn="ssrfPopconfirm.confirmBtn"+ :cancel-btn="t('system.globalSettings.confirm.cancelBtn')"+ :popup-props="PROGRAMMATIC_POPCONFIRM_PROPS"+ placement="left"+ @confirm="ssrfPopconfirm.finish(true)"+ @cancel="ssrfPopconfirm.finish(false)"+ @visible-change="ssrfPopconfirm.onVisibleChange"+ >+ <div class="setting-control-anchor">+ <t-tag-input+ :key="`ssrf-tag-${ssrfTagInputKey()}`"+ :model-value="ssrfWhitelistModelValue()"+ :placeholder="emptyListPlaceholder"+ :disabled="savingKey === item.key"+ class="setting-input setting-input--wide"+ clearable+ @update:model-value="onSsrfWhitelistModelUpdate"+ />+ </div>+ </t-popconfirm><t-inputv-elsev-model="editValues[item.key]"- :placeholder="String(item.value)"+ :placeholder="placeholderFor(item)":disabled="savingKey === item.key"class="setting-input"clearable+ @blur="onChange(item)"/>- <t-button- theme="primary"- variant="outline"- shape="square"- :loading="savingKey === item.key"- :disabled="!isDirty(item)"- @click="saveSetting(item)"- title="保存"+ <!--+ Per-row saving spinner. Appears next to the control while+ a PUT is in flight; the controls stay disabled (see+ :disabled bindings above) so concurrent edits can't race.+ -->+ <t-loading+ v-if="savingKey === item.key"+ size="small"+ class="setting-saving"+ />+ </div>++ <!--+ Reset-to-default lives on the row below the input, right-+ aligned under it. Hidden entirely for virtual (ENV / default)+ rows so the layout collapses to a single row in the common+ case — the "已覆盖" badge is already the cue that an+ override exists, so the button only appears where it can do+ something.+ -->+ <div+ v-if="hasOverride(item) || hasBulkAction(item)"+ class="setting-control-actions">- <template #icon><t-icon name="save" /></template>- </t-button>+ <!--+ Per-key bulk action. Currently only one key+ (tenant.default_storage_quota_gb) carries one — clicking+ writes the current setting value onto every existing+ tenant. We do this as a separate explicit action rather+ than auto-cascade on save so a SystemAdmin who tweaks the+ default while triaging a single new-tenant question+ doesn't accidentally rewrite production quotas. Hidden+ when the row is dirty because applying a not-yet-saved+ value would confuse "what just happened".+ -->+ <t-popconfirm+ v-if="hasBulkAction(item)"+ :content="bulkActionConfirmBody(item)"+ :confirm-btn="{ content: t('system.globalSettings.bulkApply.confirmBtn'), theme: 'primary' }"+ :cancel-btn="{ content: t('system.globalSettings.confirm.cancelBtn') }"+ placement="left"+ @confirm="runBulkAction(item)"+ >+ <t-button+ variant="text"+ size="small"+ :disabled="savingKey === item.key || isDirty(item)"+ :title="t('system.globalSettings.bulkApply.tooltip')"+ class="setting-bulk-btn"+ >+ <template #icon><t-icon name="usergroup" /></template>+ {{ t('system.globalSettings.bulkApply.label') }}+ </t-button>+ </t-popconfirm>++ <t-popconfirm+ v-if="hasOverride(item)"+ :content="t('system.globalSettings.reset.confirmBody', { label: keyLabel(item.key) })"+ :confirm-btn="{ content: t('system.globalSettings.reset.confirmBtn'), theme: 'warning' }"+ :cancel-btn="{ content: t('system.globalSettings.confirm.cancelBtn') }"+ placement="left"+ @confirm="resetSetting(item)"+ >+ <t-button+ variant="text"+ size="small"+ :disabled="savingKey === item.key"+ :title="t('system.globalSettings.reset.tooltip')"+ class="setting-reset-btn"+ >+ <template #icon><t-icon name="refresh" /></template>+ {{ t('system.globalSettings.reset.label') }}+ </t-button>+ </t-popconfirm>+ </div></div></div>- </section>+ </div></div></template><script setup lang="ts">-import { ref, reactive, computed, onMounted } from 'vue'-import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next'+import { ref, reactive, onMounted, computed, nextTick } from 'vue'+import { useI18n } from 'vue-i18n'+import { MessagePlugin } from 'tdesign-vue-next'import {listSystemSettings,updateSystemSetting,+ resetSystemSetting,+ applyDefaultStorageQuotaToAllTenants,+ listSystemAdmins,+ promoteUserToSystemAdmin,+ revokeSystemAdmin,type SystemSettingItem,} from '@/api/system'+import { useAuthStore } from '@/stores/auth'++const authStore = useAuthStore()+const currentUserId = computed(() => authStore.currentUserId)++const { t, te } = useI18n()-// Friendly Chinese labels per category. Falls back to the raw category-// string when a new one shows up that we haven't translated yet, which-// is the right behaviour: a missing translation should be visible, not-// silently empty.-const CATEGORY_LABELS: Record<string, string> = {- limits: '上限',- agent: 'Agent',- auth: '认证',- security: '安全',- storage: '存储',- general: '通用',-}-function categoryLabel(c: string): string {- return CATEGORY_LABELS[c] || c-}--// Keys that change platform-wide trust boundaries. Saving these triggers-// an extra "are you sure?" dialog so a careless click can't, say, flip-// auth.registration_mode=self_serve and let the public spam the system.-// New high-impact keys can be added here when they ship.+// Friendly labels per key live in i18n (system.globalSettings.keyLabels.*).+// Adding a new entry there must accompany every new key registered in+// service/system_setting.go on the backend; locales without an entry+// fall back to the raw key so a misconfigured deploy still renders.+function keyLabel(k: string): string {+ const path = `system.globalSettings.keyLabels.${k}`+ return te(path) ? (t(path) as string) : k+}++// Enum keys whose change triggers a whole-value inline popconfirm before+// PUT. ssrf.whitelist is not here — it uses per-tag confirm instead.const HIGH_RISK_KEYS = new Set<string>([- 'ssrf.whitelist','auth.registration_mode',])-// Friendly labels for enum options (drives the t-select dropdown text).-// We keep them inline rather than fetching from i18n because (a) the-// list is small, (b) the options are tied to backend constants and-// shouldn't drift, (c) translators don't typically need to see them.-const ENUM_LABELS: Record<string, Record<string, string>> = {- 'auth.registration_mode': {- self_serve: '自助注册(任何人可注册)',- invite_only: '仅邀请(关闭公网注册)',- },+function isHighRiskKey(key: string): boolean {+ return HIGH_RISK_KEYS.has(key)+}++type PopconfirmBtn = { content: string; theme?: 'primary' | 'danger' | 'warning' }++// TDesign popconfirm defaults to trigger:click on its inner Popup. Inputs+// wrapped for programmatic confirm must override that, otherwise focus /+// click on the field opens an empty bubble before the user commits a change.+const PROGRAMMATIC_POPCONFIRM_PROPS = { trigger: 'context-menu' as const }++// Shared inline t-popconfirm controller (anchored to the control row,+// same interaction model as Reset / bulk-apply). Replaces modal dialogs.+// State must be reactive (not nested refs) so template bindings unwrap.+function createInlinePopconfirm() {+ const state = reactive({+ visible: false,+ content: '',+ theme: 'warning' as 'default' | 'warning' | 'danger',+ confirmBtn: { content: '', theme: 'primary' } as PopconfirmBtn,+ })+ let resolver: ((ok: boolean) => void) | null = null+ let settled = false++ function ask(opts: {+ content: string+ theme?: 'default' | 'warning' | 'danger'+ confirmBtn: PopconfirmBtn+ }): Promise<boolean> {+ state.content = opts.content+ state.theme = opts.theme ?? 'warning'+ state.confirmBtn = opts.confirmBtn+ settled = false+ return new Promise((resolve) => {+ resolver = resolve+ state.visible = true+ })+ }++ function finish(ok: boolean) {+ if (settled) return+ settled = true+ state.visible = false+ const r = resolver+ resolver = null+ r?.(ok)+ }++ function onVisibleChange(v: boolean) {+ if (!v && resolver) finish(false)+ }++ return Object.assign(state, { ask, finish, onVisibleChange })}-const emptyListPlaceholder = '回车添加条目,例:example.com / *.foo.com / 10.0.0.0/8'+const ssrfPopconfirm = createInlinePopconfirm()+const adminPopconfirm = createInlinePopconfirm()+const highRiskPopconfirm = createInlinePopconfirm()++// Friendly labels for enum options live in i18n+// (system.globalSettings.enumLabels.<key>.<value>). Falls back to the+// raw enum value when no translation exists.+function enumLabel(itemKey: string, optionValue: string): string {+ const path = `system.globalSettings.enumLabels.${itemKey}.${optionValue}`+ return te(path) ? (t(path) as string) : optionValue+}++const emptyListPlaceholder = computed(() => t('system.globalSettings.tagInputPlaceholder'))const settings = ref<SystemSettingItem[]>([])const loading = ref(false)const savingKey = ref<string | null>(null)+// Admin management state. We keep two parallel structures:+// - adminEmails: the v-model bound to the t-tag-input (excludes+// current user; that's the visible source of truth).+// - adminEmailToId: email → user UUID, populated from the list+// endpoint. Needed because revoke takes a UUID, not an email.+// Both reset on every reload to avoid stale entries persisting after+// a peer SystemAdmin makes a change. adminBusy disables the input and+// shows the row spinner only while promote/revoke API calls are in+// flight — not while the inline popconfirm is waiting for a click.+const adminEmails = ref<string[]>([])+const adminEmailToId = ref<Record<string, string>>({})+const adminBusy = ref(false)++// Guards ssrf.whitelist while an async confirm roundtrip is in flight.+const listConfirmBusyKey = ref<string | null>(null)++// Bumped when the SSRF tag-input is snapped back to the saved list so+// Vue remounts the control and clears TDesign's internal tag state.+const ssrfTagInputKeys = reactive<Record<string, number>>({})++// Briefly blocks model updates while the SSRF tag-input remount settles.+const ssrfSnapLocked = ref(false)+// Reactive map of in-progress edits, keyed by setting key. We don't// mutate the canonical `settings` array directly so a failed save// leaves the original value visible until the user retries or refreshes.@@ -196,32 +477,88 @@ const savingKey = ref<string | null>(null)// form (number / boolean / string / string[]).const editValues = reactive<Record<string, unknown>>({})-const groupedSettings = computed(() => {- const buckets: Record<string, SystemSettingItem[]> = {}- for (const item of settings.value) {- const c = item.category || 'general'- if (!buckets[c]) buckets[c] = []- buckets[c].push(item)- }- return Object.keys(buckets)- .sort()- .map((category) => ({ category, items: buckets[category] }))-})-function hasEnum(item: SystemSettingItem): boolean {return Array.isArray(item.enum) && item.enum.length > 0}function enumOptions(item: SystemSettingItem): { label: string; value: string }[] {const opts = item.enum ?? []- const labelMap = ENUM_LABELS[item.key] ?? {}- return opts.map((v) => ({ label: labelMap[v] ?? v, value: v }))+ return opts.map((v) => ({ label: enumLabel(item.key, v), value: v }))+}++// hasOverride reports whether the row carries a real DB override (vs a+// virtual row backed by ENV/default). Distinguishing these is what+// `last_modified_by` was made for: empty string means the value came+// from registry/ENV. Drives the "已覆盖" badge.+function hasOverride(item: SystemSettingItem): boolean {+ return Boolean(item.last_modified_by && item.last_modified_by.trim() !== '')+}++// modifiedMeta returns a humane "上次修改" line for rows that have been+// persisted (last_modified_by non-empty AND updated_at not the Go zero+// value). Returns '' for virtual rows so the meta line collapses+// entirely instead of rendering "1/1/1 08:05:43" garbage.+function modifiedMeta(item: SystemSettingItem): string {+ if (!hasOverride(item)) return ''+ const ts = item.updated_at+ if (!ts || ts.startsWith('0001-')) return ''+ const formatted = formatDate(ts)+ // Prefer the resolved username/email the server enriches via+ // last_modified_by_name. Fall back to the UUID's first 8 chars when+ // the user can't be resolved (deleted account, transient lookup+ // failure) — the full ID is still in the audit log.+ const actor = item.last_modified_by_name && item.last_modified_by_name.trim() !== ''+ ? item.last_modified_by_name+ : (item.last_modified_by || '').slice(0, 8)+ return `${formatted} · ${actor}`+}++const SSRF_WHITELIST_KEY = 'ssrf.whitelist'++function ssrfWhitelistModelValue(): string[] {+ const v = editValues[SSRF_WHITELIST_KEY]+ return Array.isArray(v) ? (v as string[]) : []+}++function ssrfTagInputKey(): number {+ return ssrfTagInputKeys[SSRF_WHITELIST_KEY] ?? 0+}++function resetSsrfTagInput() {+ ssrfTagInputKeys[SSRF_WHITELIST_KEY] = (ssrfTagInputKeys[SSRF_WHITELIST_KEY] ?? 0) + 1+}++function globalSettingsText(path: string, params?: Record<string, string>): string {+ if (!te(path)) return path+ const msg = params ? t(path, params) : t(path)+ return typeof msg === 'string' ? msg : path+}++// Controlled SSRF tag-input: we commit editValues so a declined delta+// can be rolled back without the component re-applying a removal.+function onSsrfWhitelistModelUpdate(next: string[]) {+ if (listConfirmBusyKey.value === SSRF_WHITELIST_KEY || ssrfSnapLocked.value) return+ editValues[SSRF_WHITELIST_KEY] = next+ void onSsrfWhitelistChange()+}++async function onSsrfWhitelistChange() {+ const item = settings.value.find((s) => s.key === SSRF_WHITELIST_KEY)+ if (!item || !isDirty(item)) return+ if (listConfirmBusyKey.value === SSRF_WHITELIST_KEY) return+ await handleSSRFListChange(item)+}++async function snapSsrfWhitelistToSaved(item: SystemSettingItem) {+ const saved = Array.isArray(item.value) ? (item.value as string[]) : []+ editValues[SSRF_WHITELIST_KEY] = [...saved]+ resetSsrfTagInput()+ ssrfSnapLocked.value = true+ await nextTick()+ await nextTick()+ ssrfSnapLocked.value = false}-// isDirty drives the Save button's disabled state. Arrays need-// element-wise comparison; primitives use strict equality. We don't-// import a lodash isEqual to keep the bundle small — the comparison-// surface is intentionally narrow (4 value_types).function isDirty(item: SystemSettingItem): boolean {const cur = editValues[item.key]const orig = item.value@@ -244,6 +581,17 @@ function formatDate(isoString: string): string {}}+// placeholderFor renders the current effective value (DB / ENV / default)+// as a placeholder hint inside the edit control. For string_list it's+// joined with comma; for booleans we show nothing (the switch already+// reflects the value).+function placeholderFor(item: SystemSettingItem): string {+ const v = item.value+ if (v === null || v === undefined) return ''+ if (Array.isArray(v)) return v.join(', ')+ return String(v)+}+async function loadSettings() {loading.value = truetry {@@ -260,59 +608,201 @@ async function loadSettings() {: item.value}} catch (err: any) {- const msg = err?.message || '加载系统设置失败'+ const msg = err?.message || t('system.globalSettings.messages.loadFailed')MessagePlugin.error(msg)} finally {loading.value = false}}-async function saveSetting(item: SystemSettingItem) {- if (!isDirty(item)) return // double-click guard-- // High-risk keys get an extra confirmation. The dialog text is- // intentionally specific: a generic "are you sure?" trains people to- // click through. Mention the actual setting + new value so the user- // re-reads what they're about to do.- if (HIGH_RISK_KEYS.has(item.key)) {- const confirmed = await new Promise<boolean>((resolve) => {- const dlg = DialogPlugin.confirm({- header: '高危操作确认',- body: highRiskConfirmBody(item),- confirmBtn: { content: '确认保存', theme: 'danger' },- cancelBtn: '取消',- onConfirm: () => {- resolve(true)- dlg.destroy()- },- onClose: () => {- resolve(false)- dlg.destroy()- },- })- })- if (!confirmed) return- }+// onChange persists non-SSRF settings. SSRF whitelist and system admins+// have dedicated handlers with inline popconfirm.+async function onChange(item: SystemSettingItem) {+ if (!isDirty(item)) return+ // SSRF whitelist gets the per-entry confirm flow — same shape as the+ // admin tag-input above. Adding or removing each host/CIDR is its+ // own privileged change (a single bad CIDR can punch a hole through+ // the egress firewall), so we ask once per delta instead of once+ // per "save". This matches the operator's mental model: every tag+ // they touch is acknowledged on its own.await persistSetting(item)}-function highRiskConfirmBody(item: SystemSettingItem): string {+async function onHighRiskSelectChange(item: SystemSettingItem) {const newValue = editValues[item.key]- const renderedValue = Array.isArray(newValue)- ? newValue.length === 0- ? '(空)'- : newValue.join(', ')- : String(newValue)- switch (item.key) {- case 'auth.registration_mode':- return `即将把「自助注册模式」改为:${renderedValue}\n\n` +- `如果切到 self_serve,公网任何人都可以注册账号 — 务必确认是预期行为。`- case 'ssrf.whitelist':- return `即将把 SSRF 白名单改为:${renderedValue}\n\n` +- `白名单中的主机/IP/网段会绕过 SSRF 防护。错误配置可能让 Agent 访问内网服务。`- default:- return `即将把「${item.key}」改为:${renderedValue}`+ if (newValue === item.value) return++ // Revert the select immediately so cancel leaves the saved value+ // visible; re-apply only after the inline popconfirm is confirmed.+ editValues[item.key] = item.value++ const ok = await highRiskPopconfirm.ask({+ content: highRiskConfirmBody(item, newValue),+ theme: 'danger',+ confirmBtn: {+ content: t('system.globalSettings.confirm.confirmBtn'),+ theme: 'danger',+ },+ })+ if (!ok) return++ editValues[item.key] = newValue+ await persistSetting(item)+}++function confirmSsrfListEntryChange(+ action: 'add' | 'remove',+ entry: string,+): Promise<boolean> {+ const base = `system.globalSettings.listConfirm.${SSRF_WHITELIST_KEY}.${action}`+ return ssrfPopconfirm.ask({+ content: globalSettingsText(`${base}.body`, { entry }),+ theme: action === 'add' ? 'danger' : 'warning',+ confirmBtn: {+ content: globalSettingsText(`${base}.confirmBtn`),+ theme: action === 'add' ? 'danger' : 'primary',+ },+ })+}++// handleSSRFListChange reconciles the current edit against the saved+// list one entry at a time. The strategy is "confirmed deltas only":+// we start from the saved value, then walk the user's added/removed+// sets and apply each entry the operator individually approves. If+// every prompt is declined we end up identical to the saved value+// and short-circuit before hitting the API. Otherwise we save the+// merged result in a single PUT so the audit log and pubsub get one+// coherent post-image (instead of N noisy events).+async function handleSSRFListChange(item: SystemSettingItem) {+ listConfirmBusyKey.value = item.key+ try {+ const oldArr = Array.isArray(item.value) ? (item.value as string[]) : []+ const nextArr = Array.isArray(editValues[item.key])+ ? (editValues[item.key] as string[])+ : []++ const oldSet = new Set(oldArr)+ const nextSet = new Set(nextArr)++ const added: string[] = []+ for (const v of nextSet) if (!oldSet.has(v)) added.push(v)+ const removed: string[] = []+ for (const v of oldSet) if (!nextSet.has(v)) removed.push(v)++ if (added.length === 0 && removed.length === 0) return++ // Build the candidate value from approved deltas only. We keep+ // insertion order roughly aligned with the operator's intent:+ // start from the saved list (so unchanged entries keep their+ // position), drop approved removals, append approved additions.+ const finalSet = new Set(oldArr)+ for (const entry of added) {+ const ok = await confirmSsrfListEntryChange('add', entry)+ if (ok) {+ finalSet.add(entry)+ } else {+ await snapSsrfWhitelistToSaved(item)+ return+ }+ }+ for (const entry of removed) {+ const ok = await confirmSsrfListEntryChange('remove', entry)+ if (ok) {+ finalSet.delete(entry)+ } else {+ await snapSsrfWhitelistToSaved(item)+ return+ }+ }++ const finalArr = Array.from(finalSet)+ // Compare against saved value, not against `editValues`. If every+ // delta was declined, the saved list still wins; we just need to+ // snap the input back to it.+ const sameAsSaved =+ finalArr.length === oldArr.length &&+ finalArr.every((v, i) => v === oldArr[i])+ if (sameAsSaved) {+ await snapSsrfWhitelistToSaved(item)+ return+ }++ editValues[item.key] = finalArr+ await persistSetting(item)+ } finally {+ await nextTick()+ listConfirmBusyKey.value = null+ }+}++function highRiskConfirmBody(item: SystemSettingItem, value: unknown): string {+ const renderedValue = Array.isArray(value)+ ? value.length === 0+ ? t('system.globalSettings.confirm.emptyValue')+ : value.join(', ')+ : String(value)+ return t('system.globalSettings.confirm.bodyAuthRegistrationMode', {+ label: keyLabel(item.key),+ value: renderedValue,+ })+}++// hasBulkAction tells the template whether the current row carries an+// extra "apply to existing data" action beyond plain save/reset.+// Currently only `tenant.default_storage_quota_gb` does — saving the+// setting only affects future tenants, so the bulk button is the+// escape hatch for "rewrite all current tenants too".+function hasBulkAction(item: SystemSettingItem): boolean {+ return item.key === 'tenant.default_storage_quota_gb'+}++function bulkActionConfirmBody(item: SystemSettingItem): string {+ // Use the canonical (saved) value, not the in-progress edit, so the+ // operator sees exactly what will be written. The button is disabled+ // when the row is dirty (see template), so item.value is the value+ // that's currently in effect for new tenants.+ const v = item.value+ const valueText = v === null || v === undefined ? '' : String(v)+ return t('system.globalSettings.bulkApply.confirmBody', { value: valueText })+}++async function runBulkAction(item: SystemSettingItem) {+ if (!hasBulkAction(item)) return+ savingKey.value = item.key+ try {+ const result = await applyDefaultStorageQuotaToAllTenants()+ MessagePlugin.success(+ t('system.globalSettings.bulkApply.success', {+ count: result.affected,+ gb: result.quota_gb,+ }),+ )+ } catch (err: any) {+ const msg = err?.message || t('system.globalSettings.bulkApply.failed')+ MessagePlugin.error(msg)+ } finally {+ savingKey.value = null+ }+}++// resetSetting drops the DB override and reloads the row so the UI+// reflects the resolved fallback (ENV value if set, otherwise the+// in-code default). We refetch the whole list rather than the single+// row because the list endpoint is what populates the canonical+// settings array and re-running it keeps the modified-by enrichment+// consistent for every row in the table.+async function resetSetting(item: SystemSettingItem) {+ savingKey.value = item.key+ try {+ await resetSystemSetting(item.key)+ await loadSettings()+ MessagePlugin.success(t('system.globalSettings.reset.success'))+ } catch (err: any) {+ const msg = err?.message || t('system.globalSettings.reset.failed')+ MessagePlugin.error(msg)+ } finally {+ savingKey.value = null}}@@ -330,158 +820,364 @@ async function persistSetting(item: SystemSettingItem) {editValues[item.key] = Array.isArray(updated.value)? [...(updated.value as unknown[])]: updated.value- MessagePlugin.success(`已保存 ${item.key}`)+ MessagePlugin.success(t('system.globalSettings.messages.saveSuccess'))} catch (err: any) {- const msg = err?.message || '保存失败'+ const msg = err?.message || t('system.globalSettings.messages.saveFailed')MessagePlugin.error(msg)+ // Roll the input back to the canonical value on failure. Without+ // this an invalid edit (e.g. SSRF whitelist with a malformed CIDR+ // that the backend 400'd) would stay rendered as if accepted, and+ // the user couldn't tell whether the rejection actually stuck.+ const failed = settings.value.find((s) => s.key === item.key)+ if (failed) {+ editValues[item.key] = Array.isArray(failed.value)+ ? [...(failed.value as unknown[])]+ : failed.value+ }} finally {savingKey.value = null}}+// loadAdmins refreshes the admin tag list + the email→id lookup+// table. We exclude the current user from the visible list so the+// "you can't revoke yourself" rule has nothing to enforce in the UI+// (the backend rejects it too, but hiding the tag is friendlier).+async function loadAdmins() {+ try {+ const resp = await listSystemAdmins({ limit: 200 })+ const map: Record<string, string> = {}+ const emails: string[] = []+ for (const u of resp.admins ?? []) {+ // Empty emails would collapse to a single tag "" that can't be+ // round-tripped to a user_id; skip them. Same defensive stance+ // as resolveMaxOwnedTenantsPerUser on the backend.+ if (!u.email) continue+ map[u.email] = u.id+ if (u.id !== currentUserId.value) {+ emails.push(u.email)+ }+ }+ adminEmailToId.value = map+ adminEmails.value = emails+ } catch (err: any) {+ const msg = err?.message || t('system.globalSettings.admins.loadFailed')+ MessagePlugin.error(msg)+ }+}++function confirmAdminChange(action: 'promote' | 'revoke', email: string): Promise<boolean> {+ const base = `system.globalSettings.admins.confirm.${action}`+ return adminPopconfirm.ask({+ content: globalSettingsText(`${base}.body`, { email }),+ theme: action === 'revoke' ? 'danger' : 'warning',+ confirmBtn: {+ content: globalSettingsText(`${base}.confirmBtn`),+ theme: action === 'revoke' ? 'danger' : 'primary',+ },+ })+}++// onAdminsChange diffs the new tag list against the canonical state+// and dispatches one promote / revoke per delta. Failures roll back+// the whole tag list to the server-side truth — this is simpler than+// trying to undo individual ops, and the network/error case for batch+// edits is rare enough that a full reload doesn't surprise anyone.+async function onAdminsChange(next: string[]) {+ if (adminBusy.value) return++ // Snapshot of what's currently authoritative — the email→id map's+ // keys, minus the current user. Anything in `next` that's not here+ // is an addition; anything here that's not in `next` is a removal.+ const authoritative = new Set<string>()+ for (const email of Object.keys(adminEmailToId.value)) {+ if (adminEmailToId.value[email] !== currentUserId.value) {+ authoritative.add(email)+ }+ }+ const nextSet = new Set(next.map((e) => e.trim()).filter(Boolean))++ // Drop the user-typed entry to canonical lowercase/trim before we+ // diff. We don't lowercase server-returned emails because the+ // backend stores the original case; matching against the map's keys+ // happens with the as-typed value, which is what the user sees.+ const added: string[] = []+ for (const email of nextSet) {+ if (!authoritative.has(email)) added.push(email)+ }+ const removed: string[] = []+ for (const email of authoritative) {+ if (!nextSet.has(email)) removed.push(email)+ }++ if (added.length === 0 && removed.length === 0) return++ // Confirm before any privilege change (no loading spinner yet — the+ // popconfirm is the only UI; adminBusy is reserved for API roundtrips).+ for (const email of added) {+ const ok = await confirmAdminChange('promote', email)+ if (!ok) {+ await loadAdmins()+ return+ }+ }+ for (const email of removed) {+ const userId = adminEmailToId.value[email]+ if (!userId) continue+ const ok = await confirmAdminChange('revoke', email)+ if (!ok) {+ await loadAdmins()+ return+ }+ }++ adminBusy.value = true+ let applied = 0+ try {+ for (const email of added) {+ await promoteUserToSystemAdmin({ email })+ applied+++ }+ for (const email of removed) {+ const userId = adminEmailToId.value[email]+ if (!userId) continue+ await revokeSystemAdmin(userId)+ applied+++ }+ await loadAdmins()+ if (applied > 0) {+ MessagePlugin.success(t('system.globalSettings.admins.saveSuccess'))+ }+ } catch (err: any) {+ const msg = err?.message || t('system.globalSettings.admins.saveFailed')+ MessagePlugin.error(msg)+ await loadAdmins()+ } finally {+ adminBusy.value = false+ }+}+onMounted(() => {loadSettings()+ loadAdmins()})</script>-<style scoped>+<style lang="less" scoped>.system-settings {width: 100%;}-.page-header {+.section-header {+ margin-bottom: 24px;++ h2 {+ font-size: 20px;+ font-weight: 600;+ color: var(--td-text-color-primary);+ margin: 0 0 8px 0;+ }++ .section-description {+ font-size: 14px;+ color: var(--td-text-color-secondary);+ margin: 0;+ line-height: 1.5;+ }+}++.priority-hint {+ margin-bottom: 24px;+ padding: 14px 16px;+ border-radius: 6px;+ background: var(--td-bg-color-container-hover);+ border-left: 3px solid var(--td-brand-color);+}++.priority-hint-header {display: flex;- align-items: flex-start;- justify-content: space-between;- gap: 24px;- margin-bottom: 18px;+ align-items: center;+ gap: 8px;+ margin-bottom: 6px;}-.page-title {- margin: 0 0 4px;- font-size: 18px;- font-weight: 600;- color: var(--td-text-color-primary, #000);+.priority-hint-icon {+ color: var(--td-brand-color);+ font-size: 16px;}-.page-desc {- margin: 0;+.priority-hint-title {+ font-size: 14px;+ font-weight: 500;+ color: var(--td-text-color-primary);+}++.priority-hint-list {+ margin: 4px 0 0;+ padding-left: 22px;font-size: 13px;- line-height: 1.5;- color: var(--td-text-color-secondary, #666);- max-width: 720px;+ line-height: 1.65;+ color: var(--td-text-color-primary);+ list-style: disc;++ li + li {+ margin-top: 4px;+ }}-.loading-state,-.empty-state {- display: flex;- flex-direction: column;- align-items: center;- justify-content: center;- gap: 12px;- padding: 60px 0;- color: var(--td-text-color-placeholder, #999);+.setting-reset-btn {+ // Sit flush with the input on the right; size="small" gives it the+ // right footprint to read as secondary action next to the primary+ // edit control.+ flex-shrink: 0;}-.settings-group {- margin-bottom: 22px;+// Anchor wrapper for inline t-popconfirm on inputs (SSRF / admins /+// high-risk select). Popconfirm attaches to this box so the bubble+// appears beside the control, not a full-screen modal.+.setting-control-anchor {+ flex: 1;+ min-width: 0;}-.group-title {+.loading-state,+.empty-state {display: flex;align-items: center;+ justify-content: center;gap: 8px;- padding-bottom: 8px;- border-bottom: 1px solid var(--td-border-level-1-color, #eee);-}--.group-title-text {+ padding: 60px 0;+ color: var(--td-text-color-placeholder);font-size: 13px;- font-weight: 600;- color: var(--td-text-color-secondary, #666);}-.group-title-count {- font-size: 11px;- color: var(--td-text-color-placeholder, #999);+// Skeleton mirrors GeneralSettings.vue 1:1 so the two panes feel like+// they came from the same hand. Values that diverge intentionally:+// - .setting-label is a flex container (vs General's plain <label>)+// because we render badges inline with the title; identical font /+// spacing otherwise.+// - .desc has a max-width so long backend descriptions don't push+// the control off the canvas in narrow viewports.+.settings-group {+ display: flex;+ flex-direction: column;+ gap: 0;}.setting-row {display: flex;align-items: flex-start;justify-content: space-between;- gap: 20px;- padding: 15px 0;- border-bottom: 1px solid var(--td-border-level-1-color, #eee);-}+ padding: 20px 0;+ border-bottom: 1px solid var(--td-component-stroke);-.setting-row:last-child {- border-bottom: none;- padding-bottom: 0;+ &:last-child {+ border-bottom: none;+ }}.setting-info {flex: 1;- min-width: 0;+ max-width: 65%;+ padding-right: 24px;}-.setting-key {+.setting-label {display: flex;align-items: center;- gap: 8px;+ flex-wrap: wrap;+ gap: 6px;+ font-size: 15px;+ font-weight: 500;+ color: var(--td-text-color-primary);margin-bottom: 4px;+ line-height: 1.4;}-.setting-key-text {- font-size: 13px;- font-weight: 500;- color: var(--td-text-color-primary, #000);- font-family: var(--td-font-family-mono, monospace);+.setting-badge {+ vertical-align: middle;}-.setting-desc {- font-size: 12px;+.desc {+ font-size: 13px;+ color: var(--td-text-color-secondary);+ margin: 0;line-height: 1.5;- color: var(--td-text-color-secondary, #666);- margin-bottom: 4px;+ max-width: 480px;}.setting-meta {- font-size: 11px;- color: var(--td-text-color-placeholder, #999);- display: flex;- gap: 4px;- flex-wrap: wrap;+ margin-top: 6px;+ font-size: 12px;+ color: var(--td-text-color-placeholder);}.setting-control {+ flex-shrink: 0;+ min-width: 280px;+ display: flex;+ flex-direction: column;+ align-items: flex-end;+ gap: 6px;+}++.setting-control-row {display: flex;align-items: center;+ justify-content: flex-end;gap: 8px;+}++.setting-control-actions {+ display: flex;+ justify-content: flex-end;+}++.setting-saving {+ // Pin width so the row layout doesn't reflow when the spinner+ // appears / disappears mid-save.+ width: 16px;+ height: 16px;flex-shrink: 0;}.setting-input {- width: 210px;+ width: 240px;}.setting-input--wide {- width: 340px;+ width: 320px;}@media (max-width: 860px) {.setting-row {flex-direction: column;- gap: 10px;+ gap: 12px;}.setting-control {width: 100%;+ align-items: flex-start;+ }++ .setting-control-row {+ width: 100%;+ justify-content: flex-start;+ }++ .setting-control-actions {+ width: 100%;+ justify-content: flex-start;}.setting-input,.setting-input--wide {width: 100%;+ flex: 1;+ }++ .desc {+ max-width: none;}}</style>diff --git a/internal/application/repository/system_setting.go b/internal/application/repository/system_setting.goindex d7a2f7410..bfe05755d 100644--- a/internal/application/repository/system_setting.go+++ b/internal/application/repository/system_setting.go@@ -74,3 +74,17 @@ func (r *systemSettingRepository) Upsert(ctx context.Context, s *types.SystemSet}).Create(s).Error}++// Delete removes the row by key. The boolean return indicates whether+// a row was actually deleted, so the service layer can audit only real+// deletions (vs the idempotent no-op when the key was already absent).+// gorm's RowsAffected is 0 for "no match" — we keep that as (false, nil)+// rather than translating to gorm.ErrRecordNotFound so the caller's+// happy path is a single nil check on err.+func (r *systemSettingRepository) Delete(ctx context.Context, key string) (bool, error) {+ res := r.db.WithContext(ctx).Where("key = ?", key).Delete(&types.SystemSetting{})+ if res.Error != nil {+ return false, res.Error+ }+ return res.RowsAffected > 0, nil+}diff --git a/internal/application/repository/tenant.go b/internal/application/repository/tenant.goindex dfb7a2d51..406c999af 100644--- a/internal/application/repository/tenant.go+++ b/internal/application/repository/tenant.go@@ -162,3 +162,24 @@ func (r *tenantRepository) AdjustStorageUsed(ctx context.Context, tenantID uint6return tx.Save(&tenant).Error})}++// BulkSetStorageQuota writes quotaBytes to storage_quota for every+// tenant in one statement. We don't WHERE-filter (the action is+// "apply globally"), so the affected count equals the row count of+// the tenants table.+//+// No transaction here: the operation is a single statement and we+// don't want to hold a long lock just to update a single column. If+// a concurrent CreateTenant lands in the middle, the new row gets+// the new default via the system-setting resolver in the handler —+// no risk of the new tenant being skipped.+func (r *tenantRepository) BulkSetStorageQuota(ctx context.Context, quotaBytes int64) (int64, error) {+ res := r.db.WithContext(ctx).+ Model(&types.Tenant{}).+ Where("1 = 1"). // GORM refuses unconditional UPDATEs without an explicit WHERE+ Update("storage_quota", quotaBytes)+ if res.Error != nil {+ return 0, res.Error+ }+ return res.RowsAffected, nil+}diff --git a/internal/application/repository/user.go b/internal/application/repository/user.goindex 9e030ca49..a7f27ea27 100644--- a/internal/application/repository/user.go+++ b/internal/application/repository/user.go@@ -167,6 +167,15 @@ func (r *userRepository) ListSystemAdmins(ctx context.Context, offset, limit int// RevokeSystemAdmin revokes system-admin privileges inside a transaction.// It locks the current admin rows before counting so concurrent revokes// cannot both observe "two admins" and leave the platform with zero.+//+// Return contract:+// - (user, nil): revoke actually happened; user.IsSystemAdmin == false+// - (user, ErrUserNotSystemAdmin): target was already not an admin;+// no row was written. Caller should treat as idempotent success but+// MUST distinguish it from a real revoke for audit purposes — the+// surfaced `user` is the unchanged DB row.+// - (nil, ErrCannotRevokeSelf | ErrLastSystemAdmin | ErrUserNotFound | …):+// hard rejection; no row written.func (r *userRepository) RevokeSystemAdmin(ctx context.Context, userID, actorID string) (*types.User, error) {if userID == actorID {return nil, ErrCannotRevokeSelf@@ -213,8 +222,12 @@ func (r *userRepository) RevokeSystemAdmin(ctx context.Context, userID, actorIDrevoked = &userreturn nil})+ // Propagate ErrUserNotSystemAdmin up to the handler alongside the+ // (unchanged) user row. The handler treats it as idempotent success+ // but emits an audit row with changed=false so a probing pattern+ // ("revoke every random user id we know") still leaves a trail.if errors.Is(err, ErrUserNotSystemAdmin) {- return revoked, nil+ return revoked, err}if err != nil {return nil, errdiff --git a/internal/application/service/system_setting.go b/internal/application/service/system_setting.goindex 60eee2481..e0f35e62f 100644--- a/internal/application/service/system_setting.go+++ b/internal/application/service/system_setting.go@@ -95,11 +95,24 @@ type settingSpec struct {// the new value, no in-memory state bound at init time we cannot// re-derive)".var registry = map[string]settingSpec{- "file.max_size_mb": {- Type: "int",- EnvName: "MAX_FILE_SIZE_MB",- Default: int64(50),- },+ // NOTE: file.max_size_mb is intentionally NOT registered. Although+ // the Go upload handlers accept a runtime override via+ // systemSettingSvc.GetInt, the actual upload limit is gated end-to-end+ // by three independent layers:+ // 1. nginx client_max_body_size (templated at container startup+ // from the MAX_FILE_SIZE_MB env var; envsubst writes the+ // computed value into nginx.conf; nginx is never reloaded+ // during the container's lifetime).+ // 2. docreader gRPC max_send/recv_message_length (read from the+ // MAX_FILE_SIZE_MB env at python startup).+ // 3. The frontend client-side check (utils/index.ts) reads+ // window.__RUNTIME_CONFIG__.MAX_FILE_SIZE_MB which is+ // written into /usr/share/nginx/html/config.js by the+ // docker-entrypoint at container start.+ // Surfacing a UI knob whose effect is silently capped by nginx /+ // docreader / the in-page bundle is worse than not having it.+ // Keep MAX_FILE_SIZE_MB as a deploy-time env var until all four+ // layers can be reconfigured in lockstep without restarts."ssrf.whitelist": {Type: "string_list",EnvName: "SSRF_WHITELIST",@@ -117,6 +130,37 @@ var registry = map[string]settingSpec{Description: "自助注册模式。self_serve = 任何人可注册账号;invite_only = 关闭公网注册," +"仅 Owner/Admin 可邀请。修改后立即生效,但谨慎对待 self_serve(公网会接受 spam)。",},+ // tenant.max_owned_per_user caps how many tenants a single non-superuser+ // can create (and Own) via self-service POST /tenants. Read on every+ // request — UI edits take effect immediately, no restart required. The+ // EnvName is the same WEKNORA_TENANT_MAX_OWNED_PER_USER that+ // applyAuthAndTenantDefaults parses at boot, so a deployment that+ // hasn't created a DB row keeps reading from env exactly as before.+ // 0 = use the in-code default (10); negative = disable the cap entirely.+ "tenant.max_owned_per_user": {+ Type: "int",+ EnvName: "WEKNORA_TENANT_MAX_OWNED_PER_USER",+ Default: int64(10),+ Category: "tenant",+ Description: "每个非超管用户通过自助创建可拥有的最大租户数。每次创建租户时实时读取," ++ "修改后立即生效。0 表示使用内置默认值 10;负数表示完全关闭限制(不建议在公开部署使用)。",+ },+ // tenant.default_storage_quota_gb is the default storage quota (in GB)+ // applied to a newly-created tenant when the caller doesn't specify+ // one explicitly. Read at create time only — changing the value does+ // NOT retroactively resize already-existing tenants (they keep the+ // quota stored on their row at creation; superusers can edit+ // individual tenants via the existing tenant-update path).+ // 0 or negative = use the in-code default (10 GB).+ "tenant.default_storage_quota_gb": {+ Type: "int",+ EnvName: "WEKNORA_TENANT_DEFAULT_STORAGE_QUOTA_GB",+ Default: int64(10),+ Category: "tenant",+ Description: "新建租户时默认分配的存储配额(GB),包含向量、原文、文本、索引等。" ++ "仅在创建时读取,修改后只对之后新建的租户生效,不会回写已存在的租户。" ++ "0 或负数表示使用内置默认值 10GB。",+ },}// systemSettingService wires the repository, audit log, and (P2)@@ -721,20 +765,36 @@ func (s *systemSettingService) Update(ctx context.Context, key string, rawValue// Enum check: only meaningful for "string". Compare the decoded// string against the registry-declared whitelist. Done after// encodeForType so we know the raw value passed type validation.+ //+ // Use a local name `str` rather than `s` to avoid shadowing the+ // outer `*systemSettingService` receiver — the previous version+ // relied on the shadow being unused inside the block, which was a+ // trap for future edits.if len(spec.Enum) > 0 && spec.Type == "string" {- s, _ := rawValue.(string)+ str, _ := rawValue.(string)allowed := falsefor _, opt := range spec.Enum {- if s == opt {+ if str == opt {allowed = truebreak}}if !allowed {- return nil, fmt.Errorf("invalid value for %q: %q not in %v", key, s, spec.Enum)+ return nil, fmt.Errorf("invalid value for %q: %q not in %v", key, str, spec.Enum)}}+ // Per-key structural validation. encodeForType already enforces the+ // value_type contract (int / string / bool / string_list); this hook+ // is for keys whose value carries an internal grammar that, if+ // silently malformed, would either fail to take effect at runtime+ // (e.g. SSRF whitelist parser drops bad CIDRs) or actively+ // mis-classify input. Reject with 400 so the UI can show a clear+ // inline error instead of "saved" + nothing happens.+ if err := validateRegistryEntry(key, rawValue); err != nil {+ return nil, fmt.Errorf("invalid value for %q: %w", key, err)+ }+// Capture pre-image for the audit log — pulled fresh, not from// any cache, so concurrent admin edits race-fairly (last writer// wins, audit reflects what was actually replaced).@@ -780,6 +840,15 @@ func (s *systemSettingService) Update(ctx context.Context, key string, rawValue// the upsert already succeeded. Return the optimistic value.persisted = row}+ // Mirror the registry-derived enrichment that List/Get apply.+ // Without this, the persisted row hands back an empty Enum field+ // to the API client, which causes the management UI to swap a+ // t-select for a plain text input on the post-save patch and+ // display the raw enum value (e.g. "self_serve") until the next+ // full reload. Other registry-only fields (Type via ValueType is+ // already on the row; Description/Category are persisted) don't+ // need the same fix-up because they're stored on the row itself.+ persisted.Enum = spec.Enum// Update local cache inline so this replica's next read sees the// new value without waiting for the pubsub roundtrip. Other replicas@@ -796,6 +865,52 @@ func (s *systemSettingService) Update(ctx context.Context, key string, rawValuereturn persisted, nil}+// Reset deletes the DB override for `key` so the resolver falls back+// to ENV / built-in default. Idempotent — deleting a key that was+// never persisted is treated as success (no audit row written, since+// nothing actually changed) so retries from the UI can't pile up+// noise. Mirrors Update's cache+pubsub+audit+side-effect plumbing on+// the success path so other replicas drop the entry too.+//+// Unknown keys still 400 — we don't want a typo on the URL to silently+// pretend it cleared something.+func (s *systemSettingService) Reset(ctx context.Context, key string) error {+ spec, ok := registry[key]+ if !ok {+ return fmt.Errorf("unknown setting key %q", key)+ }++ // Capture pre-image for the audit log before the row vanishes.+ prev, _ := s.repo.Get(ctx, key)++ deleted, err := s.repo.Delete(ctx, key)+ if err != nil {+ return fmt.Errorf("delete system setting %q: %w", key, err)+ }++ // Drop from the local cache regardless of `deleted` so a stale+ // entry from before the row existed (shouldn't happen, but cheap+ // to defend) gets cleared too.+ s.mu.Lock()+ delete(s.cache, key)+ s.mu.Unlock()++ // Side-effect bridges and pubsub fire even for no-op resets so+ // peers that may have a stale cached row converge. publishChange+ // is best-effort; reload() on the peer side handles "row absent"+ // by deleting the cache entry, which is what we want here.+ s.dispatchSideEffects(ctx, key)+ s.publishChange(ctx, key)++ // Only emit an audit row on real deletions. The new_value field+ // is intentionally null to flag this as a reset (vs an Update+ // which always writes a concrete new_value).+ if deleted && prev != nil {+ s.emitChangeAudit(ctx, key, spec.Type, prev.Value, nil)+ }+ return nil+}+// SubscribeRedis starts a single goroutine that subscribes to the// pubsub channel and refreshes the local cache when peers publish// changes. Idempotent (subOnce). When Redis is nil (lite mode) returns@@ -1013,3 +1128,75 @@ func encodeForType(declared string, rawValue any) (types.JSON, error) {return nil, errors.New("unknown declared type: " + declared)}}++// validateRegistryEntry runs key-specific structural validation that+// goes beyond the type contract enforced by encodeForType. It is called+// by Update right after the type/enum checks; nil error means the value+// is acceptable for persistence.+//+// Adding new validators:+// - keep them strict (reject silently-broken input rather than fixing+// it server-side — the user should see what they typed),+// - keep them deterministic (no DNS lookups, no env reads),+// - keep error messages user-facing (the handler surfaces them as the+// 400 body verbatim).+func validateRegistryEntry(key string, rawValue any) error {+ switch key {+ case "ssrf.whitelist":+ // Coerce into the same shape encodeForType produced. We don't+ // look at the encoded JSON because that's already canonicalised+ // — easier to validate the raw input the user typed.+ entries, err := coerceToStringSlice(rawValue)+ if err != nil {+ return err+ }+ return utils.ValidateSSRFWhitelistEntries(entries)+ }+ return nil+}++// coerceToStringSlice mirrors the input shapes accepted by+// encodeForType for "string_list": []any of strings, []string, or a+// comma-separated string. Returns the trimmed, empty-stripped result.+//+// Kept private because the only caller is validateRegistryEntry; the+// main encode path has its own (slightly different) coercion that+// preserves rejection of non-string elements at a specific index for+// clearer error messages.+func coerceToStringSlice(rawValue any) ([]string, error) {+ switch v := rawValue.(type) {+ case []any:+ out := make([]string, 0, len(v))+ for i, item := range v {+ s, ok := item.(string)+ if !ok {+ return nil, fmt.Errorf("expected string at index %d, got %T", i, item)+ }+ s = strings.TrimSpace(s)+ if s != "" {+ out = append(out, s)+ }+ }+ return out, nil+ case []string:+ out := make([]string, 0, len(v))+ for _, s := range v {+ s = strings.TrimSpace(s)+ if s != "" {+ out = append(out, s)+ }+ }+ return out, nil+ case string:+ out := make([]string, 0, 4)+ for _, s := range strings.Split(v, ",") {+ s = strings.TrimSpace(s)+ if s != "" {+ out = append(out, s)+ }+ }+ return out, nil+ default:+ return nil, fmt.Errorf("expected string array, got %T", rawValue)+ }+}diff --git a/internal/application/service/tenant.go b/internal/application/service/tenant.goindex 5e4201b35..02f5ab169 100644--- a/internal/application/service/tenant.go+++ b/internal/application/service/tenant.go@@ -335,6 +335,23 @@ func (s *tenantService) ListAllTenants(ctx context.Context) ([]*types.Tenant, erreturn tenants, nil}+// BulkSetStorageQuota delegates to the repository. Validation is+// minimal — quotaBytes <= 0 is rejected because the storage-quota+// enforcement in knowledge_create.go treats <=0 as "unlimited", which+// is never what a SystemAdmin pressing "apply default" intends.+func (s *tenantService) BulkSetStorageQuota(ctx context.Context, quotaBytes int64) (int64, error) {+ if quotaBytes <= 0 {+ return 0, errors.New("quota must be positive")+ }+ affected, err := s.repo.BulkSetStorageQuota(ctx, quotaBytes)+ if err != nil {+ logger.ErrorWithFields(ctx, err, map[string]interface{}{"quota_bytes": quotaBytes})+ return 0, err+ }+ logger.Infof(ctx, "Bulk set storage_quota=%d on %d tenants", quotaBytes, affected)+ return affected, nil+}+// SearchTenants searches tenants with pagination and filtersfunc (s *tenantService) SearchTenants(ctx context.Context, keyword string, tenantID uint64, page, pageSize int) ([]*types.Tenant, int64, error) {tenants, total, err := s.repo.SearchTenants(ctx, keyword, tenantID, page, pageSize)diff --git a/internal/handler/initialization.go b/internal/handler/initialization.goindex 39d6daa65..0a3a4f3a0 100644--- a/internal/handler/initialization.go+++ b/internal/handler/initialization.go@@ -61,7 +61,6 @@ type InitializationHandler struct {ollamaService *ollama.OllamaServicedocumentReader interfaces.DocumentReaderpooler embedding.EmbedderPooler- systemSettingSvc interfaces.SystemSettingService}// NewInitializationHandler 创建初始化处理器@@ -75,7 +74,6 @@ func NewInitializationHandler(ollamaService *ollama.OllamaService,documentReader interfaces.DocumentReader,pooler embedding.EmbedderPooler,- systemSettingSvc interfaces.SystemSettingService,) *InitializationHandler {return &InitializationHandler{config: config,@@ -87,7 +85,6 @@ func NewInitializationHandler(ollamaService: ollamaService,documentReader: documentReader,pooler: pooler,- systemSettingSvc: systemSettingSvc,}}@@ -2123,8 +2120,9 @@ func (h *InitializationHandler) TestMultimodalFunction(c *gin.Context) {return}- // 验证文件大小 — 走 system_settings 三级 resolver(DB > ENV > 50 默认)- maxSizeMB := h.systemSettingSvc.GetInt(ctx, "file.max_size_mb", "MAX_FILE_SIZE_MB", 50)+ // 验证文件大小 — MAX_FILE_SIZE_MB env (50MB 默认)。+ // 见 utils/filesize.go 注释:故意保留为部署期 env,不做 runtime setting。+ maxSizeMB := utils.GetMaxFileSizeMB()maxSize := maxSizeMB * 1024 * 1024if header.Size > maxSize {logger.Error(ctx, "File size too large")diff --git a/internal/handler/knowledge.go b/internal/handler/knowledge.goindex db3a18911..eefc49b57 100644--- a/internal/handler/knowledge.go+++ b/internal/handler/knowledge.go@@ -34,9 +34,6 @@ type KnowledgeHandler struct {kbShareService interfaces.KBShareServiceagentShareService interfaces.AgentShareServiceasynqClient interfaces.TaskEnqueuer- // systemSettingSvc consults the platform-wide system_settings table- // for runtime tunables (file size limit etc.), with ENV/default fallback.- systemSettingSvc interfaces.SystemSettingService}// NewKnowledgeHandler creates a new knowledge handler instance@@ -46,7 +43,6 @@ func NewKnowledgeHandler(kbShareService interfaces.KBShareService,agentShareService interfaces.AgentShareService,asynqClient interfaces.TaskEnqueuer,- systemSettingSvc interfaces.SystemSettingService,) *KnowledgeHandler {return &KnowledgeHandler{kgService: kgService,@@ -54,7 +50,6 @@ func NewKnowledgeHandler(kbShareService: kbShareService,agentShareService: agentShareService,asynqClient: asynqClient,- systemSettingSvc: systemSettingSvc,}}@@ -271,10 +266,11 @@ func (h *KnowledgeHandler) CreateKnowledgeFromFile(c *gin.Context) {return}- // Validate file size — 3-tier resolver (DB > ENV > 50 MB default).- // SystemAdmin can update this via the global-settings UI and the- // new value applies on the very next upload (no restart needed).- maxSizeMB := h.systemSettingSvc.GetInt(ctx, "file.max_size_mb", "MAX_FILE_SIZE_MB", 50)+ // Validate file size — read MAX_FILE_SIZE_MB env (50MB default).+ // Deliberately not a runtime system_setting; see filesize.go for the+ // rationale (nginx / docreader / browser bundle all cache this at+ // container startup, so a UI knob would silently mismatch).+ maxSizeMB := utils.GetMaxFileSizeMB()maxSize := maxSizeMB * 1024 * 1024if file.Size > maxSize {logger.Error(ctx, "File size too large")diff --git a/internal/handler/session/handler.go b/internal/handler/session/handler.goindex 849ad6a10..3be73cc3e 100644--- a/internal/handler/session/handler.go+++ b/internal/handler/session/handler.go@@ -28,7 +28,6 @@ type Handler struct {fileService interfaces.FileService // Service for file storage (image uploads)modelService interfaces.ModelService // Service for model management (VLM access)userService interfaces.UserService // Service for resolving per-user preferences (e.g. enable_memory default)- systemSettingSvc interfaces.SystemSettingService // 3-tier resolver for runtime tunables (file size limit etc.)attachmentProcessor *AttachmentProcessor // Processor for file attachments}@@ -48,7 +47,6 @@ func NewHandler(userService interfaces.UserService,documentReader interfaces.DocumentReader,imageResolver *docparser.ImageResolver,- systemSettingSvc interfaces.SystemSettingService,) *Handler {return &Handler{sessionService: sessionService,@@ -63,7 +61,6 @@ func NewHandler(fileService: fileService,modelService: modelService,userService: userService,- systemSettingSvc: systemSettingSvc,attachmentProcessor: NewAttachmentProcessor(fileService,documentReader,diff --git a/internal/handler/session/qa.go b/internal/handler/session/qa.goindex 9dd577167..7caf2ff2a 100644--- a/internal/handler/session/qa.go+++ b/internal/handler/session/qa.go@@ -170,9 +170,9 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCoif len(request.AttachmentUploads) > 0 {logger.Infof(ctx, "[%s] processing %d attachment(s)", logPrefix, len(request.AttachmentUploads))- // 3-tier resolver: DB > ENV > 50MB. Edits via the system-admin- // settings UI take effect on the very next request.- maxSizeMB := h.systemSettingSvc.GetInt(ctx, "file.max_size_mb", "MAX_FILE_SIZE_MB", 50)+ // MAX_FILE_SIZE_MB env (50MB default). See utils/filesize.go for+ // why this is deploy-time-only rather than a runtime setting.+ maxSizeMB := secutils.GetMaxFileSizeMB()maxSize := maxSizeMB * 1024 * 1024for i, upload := range request.AttachmentUploads {if upload.FileSize > maxSize {diff --git a/internal/handler/system.go b/internal/handler/system.goindex f8ddea1f5..5ee2ac404 100644--- a/internal/handler/system.go+++ b/internal/handler/system.go@@ -2,6 +2,7 @@ package handlerimport ("context"+ "encoding/json""errors""fmt""net"@@ -35,6 +36,10 @@ type SystemHandler struct {tenantSvc interfaces.TenantServiceuserSvc interfaces.UserServicesystemSettingSvc interfaces.SystemSettingService+ // auditSvc is optional — when nil, emitAdminAudit no-ops so unit+ // tests that wire a partial container still compile. In production+ // the dig graph always provides one.+ auditSvc interfaces.AuditLogService}// NewSystemHandler creates a new system handler@@ -44,6 +49,7 @@ func NewSystemHandler(cfg *config.Config,tenantSvc interfaces.TenantService,userSvc interfaces.UserService,systemSettingSvc interfaces.SystemSettingService,+ auditSvc interfaces.AuditLogService,) *SystemHandler {return &SystemHandler{cfg: cfg,@@ -52,9 +58,52 @@ func NewSystemHandler(cfg *config.Config,tenantSvc: tenantSvc,userSvc: userSvc,systemSettingSvc: systemSettingSvc,+ auditSvc: auditSvc,}}+// emitAdminAudit writes one audit row for a system-admin lifecycle event+// (promote / revoke). Best-effort — a nil audit service or a write+// failure does not bubble up to the caller. Mirrors the failure+// semantics of tenantMemberService.emitAudit and the system settings+// audit hook.+//+// `details` may be nil; the JSON `{}` default applies.+func (h *SystemHandler) emitAdminAudit(+ ctx context.Context,+ action types.AuditAction,+ target *types.User,+ details map[string]any,+) {+ if h.auditSvc == nil {+ return+ }+ actorID, _ := types.UserIDFromContext(ctx)+ var detailsJSON types.JSON+ if details != nil {+ if b, err := json.Marshal(details); err == nil {+ detailsJSON = types.JSON(b)+ }+ }+ entry := &types.AuditLog{+ // tenant_id=0 marks the row as system-scope. The audit_logs+ // table is tenant-scoped; 0 is the convention for platform-wide+ // events (matches AuditActionSystemSettingChanged).+ TenantID: 0,+ ActorUserID: actorID,+ ActorRole: "system_admin",+ Action: action,+ TargetType: "user",+ Outcome: types.AuditOutcomeSuccess,+ Details: detailsJSON,+ }+ if target != nil {+ entry.TargetID = target.ID+ entry.TargetUserID = target.ID+ }+ _ = h.auditSvc.Log(ctx, entry)+}+// GetSystemInfoResponse defines the response structure for system infotype GetSystemInfoResponse struct {Version string `json:"version"`@@ -1017,15 +1066,26 @@ func (h *SystemHandler) ResolveDocumentReader(ctx context.Context, addr string)return reader}-// PromoteUserToSystemAdminRequest defines the request for promoting a user to system admin+// PromoteUserToSystemAdminRequest defines the request for promoting a user to system admin.+//+// Either user_id (UUID) or email must be supplied. When both are present+// user_id wins — explicit IDs are unambiguous, an email collision (extremely+// rare in practice but possible during a tenant merge) would otherwise+// silently target the wrong row.+//+// We don't expose a `binding:"required"` tag on either field because gin's+// validator can't express the OR constraint; the handler does the check+// manually and returns 400 with a specific message for each branch.type PromoteUserToSystemAdminRequest struct {- UserID string `json:"user_id" binding:"required"`+ UserID string `json:"user_id"`+ Email string `json:"email"`}// PromoteUserToSystemAdmin godoc// @Summary Promote a user to system administrator// @Description Grant system administrator privileges to a user (SystemAdmin only).// @Description Idempotent: re-promoting an existing system admin returns 200 with no DB write.+// @Description Identify the user by email (preferred for human operators) or user_id (UUID, for API clients).// @Tags System Admin// @Accept json// @Produce json@@ -1044,9 +1104,30 @@ func (h *SystemHandler) PromoteUserToSystemAdmin(c *gin.Context) {return}- user, err := h.userSvc.GetUserByID(ctx, req.UserID)+ userID := strings.TrimSpace(req.UserID)+ email := strings.TrimSpace(req.Email)+ if userID == "" && email == "" {+ c.JSON(http.StatusBadRequest, gin.H{"error": "Either user_id or email is required"})+ return+ }++ // Resolve user. user_id takes priority when both are sent (see request+ // struct doc); otherwise we look up by email. Both branches funnel+ // into the same {nil-user / error} 404 so we don't leak whether a+ // given email exists in the system to non-admins — though SystemAdmin+ // is already a high-trust role, the parity keeps the surface clean.+ var (+ user *types.User+ err error+ )+ switch {+ case userID != "":+ user, err = h.userSvc.GetUserByID(ctx, userID)+ default:+ user, err = h.userSvc.GetUserByEmail(ctx, email)+ }if err != nil {- logger.Errorf(ctx, "Error fetching user %s: %v", req.UserID, err)+ logger.Errorf(ctx, "Error fetching user (id=%q email=%q): %v", userID, email, err)c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})return}@@ -1056,7 +1137,14 @@ func (h *SystemHandler) PromoteUserToSystemAdmin(c *gin.Context) {}if user.IsSystemAdmin {- // Idempotent: re-promoting an existing system admin is a no-op success.+ // Idempotent: re-promoting an existing system admin is a no-op+ // success. We still emit an audit row so probing the endpoint+ // leaves a forensic trail (idempotent=true marks it as noop).+ h.emitAdminAudit(ctx, types.AuditActionSystemAdminPromoted, user, map[string]any{+ "target_email": user.Email,+ "target_username": user.Username,+ "idempotent": true,+ })c.JSON(http.StatusOK, user.ToUserInfo())return}@@ -1068,6 +1156,11 @@ func (h *SystemHandler) PromoteUserToSystemAdmin(c *gin.Context) {}logger.Infof(ctx, "User %s (ID: %s) promoted to system admin", user.Username, user.ID)+ h.emitAdminAudit(ctx, types.AuditActionSystemAdminPromoted, user, map[string]any{+ "target_email": user.Email,+ "target_username": user.Username,+ "idempotent": false,+ })c.JSON(http.StatusOK, user.ToUserInfo())}@@ -1103,32 +1196,54 @@ func (h *SystemHandler) RevokeSystemAdmin(c *gin.Context) {callerID, _ := types.UserIDFromContext(ctx)user, err := h.userSvc.RevokeSystemAdmin(ctx, req.UserID, callerID)- if err != nil {- switch {- case errors.Is(err, repository.ErrCannotRevokeSelf):- c.JSON(http.StatusBadRequest, gin.H{- "error": "Cannot revoke your own system admin privileges",- })- case errors.Is(err, repository.ErrLastSystemAdmin):- c.JSON(http.StatusBadRequest, gin.H{- "error": "Cannot revoke the last remaining system administrator",- })- case errors.Is(err, repository.ErrUserNotFound):- c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})- default:- logger.Errorf(ctx, "Error revoking system admin from user %s: %v", req.UserID, err)+ switch {+ case err == nil:+ // Real revoke — privileges were actually removed.+ logger.Infof(ctx, "System admin privileges revoked from user %s (ID: %s)", user.Username, user.ID)+ h.emitAdminAudit(ctx, types.AuditActionSystemAdminRevoked, user, map[string]any{+ "target_email": user.Email,+ "target_username": user.Username,+ "changed": true,+ })+ c.JSON(http.StatusOK, user.ToUserInfo())+ return+ case errors.Is(err, repository.ErrUserNotSystemAdmin):+ // Idempotent: target was already not an admin. Return 200 so+ // callers that re-issue the request after a partial failure+ // don't get a confusing 4xx, but mark `changed=false` in the+ // audit row so a forensic reader can tell a real revoke from a+ // noop probe.+ if user == nil {+ logger.Errorf(ctx, "RevokeSystemAdmin returned nil user with ErrUserNotSystemAdmin for %s", req.UserID)c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to revoke system admin privileges"})+ return}+ logger.Infof(ctx, "Revoke noop (user %s was not a system admin)", user.ID)+ h.emitAdminAudit(ctx, types.AuditActionSystemAdminRevoked, user, map[string]any{+ "target_email": user.Email,+ "target_username": user.Username,+ "changed": false,+ })+ c.JSON(http.StatusOK, user.ToUserInfo())return- }- if user == nil {- logger.Errorf(ctx, "RevokeSystemAdmin returned nil user for %s", req.UserID)+ case errors.Is(err, repository.ErrCannotRevokeSelf):+ c.JSON(http.StatusBadRequest, gin.H{+ "error": "Cannot revoke your own system admin privileges",+ })+ return+ case errors.Is(err, repository.ErrLastSystemAdmin):+ c.JSON(http.StatusBadRequest, gin.H{+ "error": "Cannot revoke the last remaining system administrator",+ })+ return+ case errors.Is(err, repository.ErrUserNotFound):+ c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})+ return+ default:+ logger.Errorf(ctx, "Error revoking system admin from user %s: %v", req.UserID, err)c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to revoke system admin privileges"})return}-- logger.Infof(ctx, "System admin privileges revoked from user %s (ID: %s)", user.Username, user.ID)- c.JSON(http.StatusOK, user.ToUserInfo())}// ListSystemAdminsResponse defines the response structure for listing system admins.@@ -1229,9 +1344,57 @@ func (h *SystemHandler) ListSystemSettings(c *gin.Context) {// is safer.rows = []*types.SystemSetting{}}+ h.enrichSettingsModifiedBy(ctx, rows)c.JSON(http.StatusOK, rows)}+// enrichSettingsModifiedBy resolves LastModifiedBy (UUID) → display name+// in a single batch lookup. Failures degrade silently: the UI already+// falls back to the UUID prefix when the name is empty, so a transient+// userSvc error must not break the settings page entirely.+func (h *SystemHandler) enrichSettingsModifiedBy(ctx context.Context, rows []*types.SystemSetting) {+ if len(rows) == 0 || h.userSvc == nil {+ return+ }+ idSet := make(map[string]struct{}, len(rows))+ for _, r := range rows {+ if r != nil && strings.TrimSpace(r.LastModifiedBy) != "" {+ idSet[r.LastModifiedBy] = struct{}{}+ }+ }+ if len(idSet) == 0 {+ return+ }+ ids := make([]string, 0, len(idSet))+ for id := range idSet {+ ids = append(ids, id)+ }+ users, err := h.userSvc.GetUsersByIDs(ctx, ids)+ if err != nil {+ logger.Warnf(ctx, "enrichSettingsModifiedBy: GetUsersByIDs failed: %v", err)+ return+ }+ for _, r := range rows {+ if r == nil {+ continue+ }+ u, ok := users[r.LastModifiedBy]+ if !ok || u == nil {+ continue+ }+ // Username is the canonical display label; fall back to email+ // for older rows where username may be empty (legacy seeded+ // admins). Both empty → leave LastModifiedByName empty so the+ // UI's UUID-prefix fallback kicks in.+ switch {+ case strings.TrimSpace(u.Username) != "":+ r.LastModifiedByName = u.Username+ case strings.TrimSpace(u.Email) != "":+ r.LastModifiedByName = u.Email+ }+ }+}+// GetSystemSetting godoc// @Summary Get a single system setting by key// @Description Returns the row matching :key. 404 when the key is unknown@@ -1309,5 +1472,97 @@ func (h *SystemHandler) UpdateSystemSetting(c *gin.Context) {c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})return}+ h.enrichSettingsModifiedBy(ctx, []*types.SystemSetting{row})c.JSON(http.StatusOK, row)}++// ApplyDefaultStorageQuotaToAllTenants godoc+// @Summary Apply the default storage quota to every existing tenant+// @Description Reads the current value of `tenant.default_storage_quota_gb`+// @Description (3-tier resolver: DB > ENV > default) and writes that many+// @Description GiB into storage_quota for every row in tenants. Bypasses+// @Description the per-tenant PUT whitelist, which forbids storage_quota+// @Description edits by Owners. SystemAdmin only.+// @Description Idempotent — running twice with the same setting is a no-op.+// @Tags System Admin+// @Produce json+// @Success 200 {object} map[string]interface{} "{ affected: int64, quota_bytes: int64 }"+// @Failure 500 {object} map[string]interface{} "DB write failed"+// @Router /system/admin/tenants/apply-default-storage-quota [post]+func (h *SystemHandler) ApplyDefaultStorageQuotaToAllTenants(c *gin.Context) {+ ctx := logger.CloneContext(c.Request.Context())++ // Resolve via the same 3-tier path the CreateTenant handler uses+ // so the action's effect mirrors what new tenants would receive.+ gb := h.systemSettingSvc.GetInt(+ ctx,+ "tenant.default_storage_quota_gb",+ "WEKNORA_TENANT_DEFAULT_STORAGE_QUOTA_GB",+ 10,+ )+ if gb <= 0 {+ gb = 10+ }+ quotaBytes := gb * 1024 * 1024 * 1024++ affected, err := h.tenantSvc.BulkSetStorageQuota(ctx, quotaBytes)+ if err != nil {+ logger.Errorf(ctx, "BulkSetStorageQuota failed: %v", err)+ c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to apply storage quota"})+ return+ }++ // Audit. We capture quota_bytes (the actual value written) rather+ // than the GB literal so the audit row is unambiguous if someone+ // later changes the setting's units.+ if h.auditSvc != nil {+ actorID, _ := types.UserIDFromContext(ctx)+ details, _ := json.Marshal(map[string]any{+ "quota_bytes": quotaBytes,+ "quota_gb": gb,+ "affected": affected,+ })+ _ = h.auditSvc.Log(ctx, &types.AuditLog{+ TenantID: 0,+ ActorUserID: actorID,+ ActorRole: "system_admin",+ Action: types.AuditActionSystemSettingChanged,+ TargetType: "tenant_storage_quota",+ TargetID: "all",+ Outcome: types.AuditOutcomeSuccess,+ Details: types.JSON(details),+ })+ }++ c.JSON(http.StatusOK, gin.H{+ "affected": affected,+ "quota_bytes": quotaBytes,+ "quota_gb": gb,+ })+}++// ResetSystemSetting godoc+// @Summary Reset a system setting to ENV / built-in default+// @Description Removes the DB override for :key so the 3-tier resolver+// @Description falls back to the environment variable (when configured)+// @Description or the in-code default. Idempotent — resetting a key+// @Description that was never persisted returns 200.+// @Tags System Admin+// @Param key path string true "Setting key"+// @Success 200 {object} map[string]interface{} "Reset acknowledged"+// @Failure 400 {object} map[string]interface{} "Unknown key"+// @Failure 500 {object} map[string]interface{} "DB write failed"+// @Router /system/admin/settings/{key} [delete]+func (h *SystemHandler) ResetSystemSetting(c *gin.Context) {+ ctx := logger.CloneContext(c.Request.Context())+ key := c.Param("key")+ if err := h.systemSettingSvc.Reset(ctx, key); err != nil {+ // Service surfaces "unknown key" as a plain error string; treat+ // every error as 400 so the UI captures it as a toast. A real+ // DB failure here is rare and indistinguishable from "bad key"+ // at this layer — operators see the message either way.+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }+ c.JSON(http.StatusOK, gin.H{"success": true})+}diff --git a/internal/handler/tenant.go b/internal/handler/tenant.goindex f5f9de2cd..eed525167 100644--- a/internal/handler/tenant.go+++ b/internal/handler/tenant.go@@ -1,6 +1,7 @@package handlerimport (+ "context""net/http""strconv""strings"@@ -24,6 +25,11 @@ type TenantHandler struct {memberService interfaces.TenantMemberServicekbService interfaces.KnowledgeBaseServiceconfig *config.Config+ // systemSettingSvc resolves runtime tunables for tenant limits+ // (currently `tenant.max_owned_per_user`). Reading goes DB > ENV >+ // in-code default, so a SystemAdmin's UI override applies on the+ // very next CreateTenant call.+ systemSettingSvc interfaces.SystemSettingService}// NewTenantHandler creates a new tenant handler instance with the provided service@@ -49,13 +55,15 @@ func NewTenantHandler(memberService interfaces.TenantMemberService,kbService interfaces.KnowledgeBaseService,config *config.Config,+ systemSettingSvc interfaces.SystemSettingService,) *TenantHandler {return &TenantHandler{- service: service,- userService: userService,- memberService: memberService,- kbService: kbService,- config: config,+ service: service,+ userService: userService,+ memberService: memberService,+ kbService: kbService,+ config: config,+ systemSettingSvc: systemSettingSvc,}}@@ -94,6 +102,25 @@ type updateTenantRequest struct {// blunting drive-by abuse against POST /tenants (see CreateTenant).const defaultMaxOwnedTenantsPerUser = 10+// resolveMaxOwnedTenantsPerUser returns the current cap, walking the+// 3-tier resolver: system_settings DB row > WEKNORA_TENANT_MAX_OWNED_PER_USER+// env > config.Tenant.MaxOwnedPerUser (yaml) > defaultMaxOwnedTenantsPerUser.+// We pre-compute the cfg-derived fallback so the SystemSettingService+// receives a single int64 default — its 3-tier resolver layers DB and+// env on top of that.+func (h *TenantHandler) resolveMaxOwnedTenantsPerUser(ctx context.Context) int {+ fallback := int64(defaultMaxOwnedTenantsPerUser)+ if h.config != nil && h.config.Tenant != nil && h.config.Tenant.MaxOwnedPerUser != 0 {+ fallback = int64(h.config.Tenant.MaxOwnedPerUser)+ }+ return int(h.systemSettingSvc.GetInt(+ ctx,+ "tenant.max_owned_per_user",+ "WEKNORA_TENANT_MAX_OWNED_PER_USER",+ fallback,+ ))+}+// CreateTenant godoc// @Summary 创建租户// @Description 创建新的租户。任意已登录用户均可调用以建立自己的新工作区,@@ -169,10 +196,7 @@ func (h *TenantHandler) CreateTenant(c *gin.Context) {ownedCount++}}- cap := defaultMaxOwnedTenantsPerUser- if h.config != nil && h.config.Tenant != nil && h.config.Tenant.MaxOwnedPerUser != 0 {- cap = h.config.Tenant.MaxOwnedPerUser- }+ cap := h.resolveMaxOwnedTenantsPerUser(ctx)if cap > 0 && ownedCount >= cap {logger.Warnf(ctx,"User %s reached self-service tenant quota (%d/%d)",@@ -191,6 +215,29 @@ func (h *TenantHandler) CreateTenant(c *gin.Context) {}}+ // Apply the system-setting-driven default storage quota when the+ // caller didn't specify one (always true for self-serve; sometimes+ // true for the superuser branch when the JSON omits storage_quota).+ // We resolve at create time on purpose — the on-disk row should+ // carry an explicit value, so changing the setting later doesn't+ // silently shrink/grow established tenants. Negative values are+ // treated as "use default" so a misconfigured setting can't yield+ // a negative quota that the storage-used checks would interpret as+ // "unlimited" (StorageQuota <= 0 disables enforcement in+ // knowledge_create.go).+ if tenantData.StorageQuota <= 0 {+ gb := h.systemSettingSvc.GetInt(+ ctx,+ "tenant.default_storage_quota_gb",+ "WEKNORA_TENANT_DEFAULT_STORAGE_QUOTA_GB",+ 10,+ )+ if gb <= 0 {+ gb = 10+ }+ tenantData.StorageQuota = gb * 1024 * 1024 * 1024+ }+logger.Infof(ctx, "Creating tenant, name: %s", secutils.SanitizeForLog(tenantData.Name))createdTenant, err := h.service.CreateTenant(ctx, &tenantData)@@ -248,10 +295,7 @@ func (h *TenantHandler) CreateTenant(c *gin.Context) {ownedNow++}}- cap := defaultMaxOwnedTenantsPerUser- if h.config != nil && h.config.Tenant != nil && h.config.Tenant.MaxOwnedPerUser != 0 {- cap = h.config.Tenant.MaxOwnedPerUser- }+ cap := h.resolveMaxOwnedTenantsPerUser(ctx)if cap > 0 && ownedNow > cap {logger.Warnf(ctx,"User %s exceeded tenant quota after concurrent create (%d/%d), rolling back tenant %d",diff --git a/internal/middleware/auth.go b/internal/middleware/auth.goindex c2db3e684..cff8b5cfb 100644--- a/internal/middleware/auth.go+++ b/internal/middleware/auth.go@@ -236,14 +236,20 @@ func Auth(}// API-Key 走的是程序化全租户访问,固定授予 Admin 角色:可以做几乎所有事情,// 但保留 Owner-only 操作(删除租户、修改租户级配置)的边界。+ //+ // 显式拒绝 SystemAdmin:API key 通常被存放在 CI / IaC / sidecar 里,+ // 泄露面比 JWT 大得多。即便 key 关联的 user 在 DB 里恰好是 SystemAdmin+ // (例如部署里只有一个用户、自己创建了 tenant 又生成了 API key),+ // 也绝不允许通过这条通道走平台级管理操作(promote/revoke、全局设置)。+ // 平台管理必须走交互式 JWT 登录,留下可追责的人类身份。c.Set(types.UserContextKey.String(), user)c.Set(types.UserIDContextKey.String(), user.ID)c.Set(types.TenantRoleContextKey.String(), types.TenantRoleAdmin)- c.Set(types.SystemAdminContextKey.String(), user.IsSystemAdmin)+ c.Set(types.SystemAdminContextKey.String(), false)ctx = context.WithValue(ctx, types.UserContextKey, user)ctx = context.WithValue(ctx, types.UserIDContextKey, user.ID)ctx = context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleAdmin)- ctx = context.WithValue(ctx, types.SystemAdminContextKey, user.IsSystemAdmin)+ ctx = context.WithValue(ctx, types.SystemAdminContextKey, false)c.Request = c.Request.WithContext(ctx)c.Next()diff --git a/internal/router/router.go b/internal/router/router.goindex e37769b84..69092108b 100644--- a/internal/router/router.go+++ b/internal/router/router.go@@ -752,6 +752,15 @@ func RegisterSystemAdminRoutes(r *gin.RouterGroup, handler *handler.SystemHandleadminRoutes.GET("/settings", handler.ListSystemSettings)adminRoutes.GET("/settings/:key", handler.GetSystemSetting)adminRoutes.PUT("/settings/:key", handler.UpdateSystemSetting)+ adminRoutes.DELETE("/settings/:key", handler.ResetSystemSetting)++ // Bulk action — write the current default-quota setting onto+ // every existing tenant. Lives under /tenants instead of+ // /settings because it changes tenants, not the setting row.+ adminRoutes.POST(+ "/tenants/apply-default-storage-quota",+ handler.ApplyDefaultStorageQuotaToAllTenants,+ )}}diff --git a/internal/types/audit_log.go b/internal/types/audit_log.goindex 3e58605c6..bf0eb0f66 100644--- a/internal/types/audit_log.go+++ b/internal/types/audit_log.go@@ -98,6 +98,24 @@ const (// for now no setting is marked secret). Audit rows always have// tenant_id=0 because the change is system-scope, not tenant-scope.AuditActionSystemSettingChanged AuditAction = "system.setting_changed"++ // AuditActionSystemAdminPromoted fires when a SystemAdmin grants+ // system-administrator privileges to another user via+ // POST /api/v1/system/admin/promote. ActorUserID is the promoter,+ // TargetUserID is the user being promoted. Details payload carries+ // {target_email, target_username, idempotent} — `idempotent=true`+ // means the user was already a system admin and no row was written+ // (we still emit the row so probing the endpoint leaves a trail).+ // TenantID=0 because the change is system-scope.+ AuditActionSystemAdminPromoted AuditAction = "system.admin_promoted"+ // AuditActionSystemAdminRevoked fires when a SystemAdmin removes+ // system-administrator privileges from another user via+ // POST /api/v1/system/admin/revoke. Details payload carries+ // {target_email, target_username, changed} — `changed=false` covers+ // the idempotent path (target was already not an admin) so an audit+ // reader can distinguish a real revoke from a noop attempt.+ // TenantID=0 because the change is system-scope.+ AuditActionSystemAdminRevoked AuditAction = "system.admin_revoked")// AuditOutcome distinguishes successful mutations from middleware-leveldiff --git a/internal/types/interfaces/system_setting.go b/internal/types/interfaces/system_setting.goindex 8f16372d0..3ca3a57fe 100644--- a/internal/types/interfaces/system_setting.go+++ b/internal/types/interfaces/system_setting.go@@ -20,6 +20,11 @@ type SystemSettingRepository interface {// Upsert writes a row keyed by Key. Insert if missing, update if// present. Used by SystemSettingService.Update on every save.Upsert(ctx context.Context, s *types.SystemSetting) error+ // Delete removes the row by key. Returns (true, nil) if a row was+ // deleted, (false, nil) if no row matched (idempotent — service+ // layer treats this as a no-op for audit purposes). Real DB errors+ // surface as (_, err).+ Delete(ctx context.Context, key string) (bool, error)}// SystemSettingService exposes both the 3-tier resolver (used by@@ -70,6 +75,14 @@ type SystemSettingService interface {// written to last_modified_by + the audit log.// Returns the persisted row on success.Update(ctx context.Context, key string, rawValue any) (*types.SystemSetting, error)+ // Reset removes the DB override for `key` so the resolver falls+ // back to ENV / built-in default. Idempotent: deleting a key that+ // was never persisted returns nil. Emits an audit row on actual+ // deletions, invalidates the local cache, and publishes to peers.+ // Returns an error only when the DB write itself fails; callers+ // must NOT translate "no row" into a 404 — that's the success+ // path for an idempotent reset.+ Reset(ctx context.Context, key string) error// SubscribeRedis is a P2 hook: when implemented, it will subscribe// to a "weknora:system_settings:changed" channel and invalidate anydiff --git a/internal/types/interfaces/tenant.go b/internal/types/interfaces/tenant.goindex 0e864122f..6bf8575d9 100644--- a/internal/types/interfaces/tenant.go+++ b/internal/types/interfaces/tenant.go@@ -28,6 +28,13 @@ type TenantService interface {ExtractTenantIDFromAPIKey(apiKey string) (uint64, error)// ListAllTenants lists all tenants (for users with cross-tenant access permission)ListAllTenants(ctx context.Context) ([]*types.Tenant, error)+ // BulkSetStorageQuota overwrites every tenant's storage_quota with+ // quotaBytes. Returns how many rows were affected. Used by the+ // SystemAdmin "apply default to all tenants" action; bypasses the+ // per-tenant whitelist on PUT /tenants/:id (which intentionally+ // forbids storage_quota edits for Owners). quotaBytes must be > 0;+ // callers are responsible for resolving GB→bytes.+ BulkSetStorageQuota(ctx context.Context, quotaBytes int64) (int64, error)// SearchTenants searches tenants with pagination and filtersSearchTenants(ctx context.Context, keyword string, tenantID uint64, page, pageSize int) ([]*types.Tenant, int64, error)// GetTenantByIDForUser gets a tenant by ID with permission check@@ -54,4 +61,6 @@ type TenantRepository interface {DeleteTenant(ctx context.Context, id uint64) error// AdjustStorageUsed adjusts the storage used for a tenantAdjustStorageUsed(ctx context.Context, tenantID uint64, delta int64) error+ // BulkSetStorageQuota — see TenantService.BulkSetStorageQuota.+ BulkSetStorageQuota(ctx context.Context, quotaBytes int64) (int64, error)}diff --git a/internal/types/system_setting.go b/internal/types/system_setting.goindex 03b28725c..2fee8c0e0 100644--- a/internal/types/system_setting.go+++ b/internal/types/system_setting.go@@ -52,6 +52,13 @@ type SystemSetting struct {// means the UI should render a select with these options. Tagged// `gorm:"-"` so GORM never tries to read/write the column.Enum []string `gorm:"-" json:"enum,omitempty"`++ // LastModifiedByName is a display label resolved from LastModifiedBy+ // (the user's UUID) at handler time — username when available,+ // otherwise email. Empty for virtual rows that were never persisted+ // (LastModifiedBy=""). Not stored: derived per request so renaming+ // a user reflects on the next reload without a backfill job.+ LastModifiedByName string `gorm:"-" json:"last_modified_by_name,omitempty"`}// TableName pins the schema to migration 000053 — GORM's defaultdiff --git a/internal/utils/filesize.go b/internal/utils/filesize.goindex 6be8626d1..4c92a60d8 100644--- a/internal/utils/filesize.go+++ b/internal/utils/filesize.go@@ -8,22 +8,19 @@ import (// GetMaxFileSize returns the maximum file upload size in bytes.// Default is 50MB, can be configured via MAX_FILE_SIZE_MB environment variable.//-// This is the legacy ENV-only entry point. Handlers wired with-// interfaces.SystemSettingService should prefer reading the 3-tier-// resolver directly:+// MAX_FILE_SIZE_MB is intentionally a deploy-time-only knob (NOT a+// runtime system_setting). The effective upload limit is gated by+// three other layers that all read this env at startup and cache the+// value:+// - frontend nginx client_max_body_size (envsubst into nginx.conf)+// - docreader gRPC max_send/recv_message_length+// - frontend client-side check via window.__RUNTIME_CONFIG__//-// mb := h.systemSettingSvc.GetInt(ctx, "file.max_size_mb", "MAX_FILE_SIZE_MB", 50)-// maxBytes := mb * 1024 * 1024-//-// That way SystemAdmin's UI override (DB row in system_settings) takes-// precedence over the ENV value. This function is kept for unit tests-// and any non-handler call sites that don't have the service injected;-// it never sees DB values, only ENV.-//-// We deliberately don't expose a "service-aware" wrapper here because-// internal/types depends on internal/utils — wrapping it would create-// an import cycle. Call sites that have a SystemSettingService should-// just use it directly (it's only one extra line).+// Surfacing a SystemAdmin UI knob whose effect is silently capped by+// any of the above would mislead operators ("I raised it to 200MB but+// nginx still returns 413"). Until all four layers can be reconfigured+// in lockstep without container restarts, every call site must read+// the env directly via this helper.func GetMaxFileSize() int64 {if sizeStr := os.Getenv("MAX_FILE_SIZE_MB"); sizeStr != "" {if size, err := strconv.ParseInt(sizeStr, 10, 64); err == nil && size > 0 {diff --git a/internal/utils/security.go b/internal/utils/security.goindex 543cf1b6c..0857444c7 100644--- a/internal/utils/security.go+++ b/internal/utils/security.go@@ -4,6 +4,7 @@ import ("context""fmt""html"+ "log""net""net/http""net/url"@@ -935,6 +936,17 @@ func SetSSRFWhitelistFromRaw(raw string) {// parseSSRFWhitelistRaw parses a comma-separated whitelist string into// a config struct. Pure function; no env reads. Always returns a// non-nil pointer so callers can blindly Load.+//+// Invalid entries (malformed CIDR like "10.0.0.0/333", wildcards+// without a "*." prefix, etc.) are dropped with a `[ssrf-whitelist]`+// log line rather than silently falling through to the exact-host+// branch. Falling through used to turn "10.0.0.0/333" into a literal+// host string that never matches anything — operators would believe+// the entry was active when in reality their SSRF check was unchanged.+//+// Callers that want hard rejection (e.g. ValidateSSRFWhitelistEntries+// for the system_settings Update path) should pre-validate before+// passing the raw string here.func parseSSRFWhitelistRaw(raw string) *ssrfWhitelistConfig {cfg := &ssrfWhitelistConfig{exactHosts: make(map[string]bool),@@ -947,26 +959,80 @@ func parseSSRFWhitelistRaw(raw string) *ssrfWhitelistConfig {if entry == "" {continue}- // CIDR range+ // CIDR range — entries containing '/' are exclusively CIDRs.+ // A parse failure must NOT fall through to the exact-host+ // branch (which would store "10.0.0.0/333" as a literal+ // hostname that can never match anything).if strings.Contains(entry, "/") {_, ipNet, err := net.ParseCIDR(entry)- if err == nil {- cfg.cidrNets = append(cfg.cidrNets, ipNet)+ if err != nil {+ log.Printf("[ssrf-whitelist] dropping invalid CIDR entry %q: %v", entry, err)continue}+ cfg.cidrNets = append(cfg.cidrNets, ipNet)+ continue}// Wildcard domain: *.example.comif strings.HasPrefix(entry, "*.") {suffix := strings.ToLower(entry[1:]) // ".example.com"+ if len(suffix) <= 1 {+ log.Printf("[ssrf-whitelist] dropping bare wildcard entry %q (need *.<domain>)", entry)+ continue+ }cfg.suffixHosts = append(cfg.suffixHosts, suffix)continue}+ // Reject mid-string wildcards like "foo.*.bar" — they look+ // useful but neither parseSSRFWhitelistRaw nor IsSSRFWhitelisted+ // implement glob matching, so the entry would silently never+ // match. Surface it loudly.+ if strings.Contains(entry, "*") {+ log.Printf("[ssrf-whitelist] dropping unsupported wildcard pattern %q (only \"*.\" prefix is supported)", entry)+ continue+ }// Exact host or IPcfg.exactHosts[strings.ToLower(entry)] = true}return cfg}+// ValidateSSRFWhitelistEntries returns nil when every entry in `entries`+// would be accepted by parseSSRFWhitelistRaw, or an error describing+// the first malformed entry. Used by the system_settings Update path+// to give the UI a clear 400 instead of silently dropping bad input+// at parse-time.+//+// Validation rules mirror parseSSRFWhitelistRaw exactly:+// - "<a>/<b>" must be a valid CIDR+// - "*.<domain>" must have a non-empty domain after the prefix+// - mid-string "*" is not supported+// - everything else is treated as an exact host or literal IP+// (we don't pre-resolve DNS here; that's a runtime concern)+func ValidateSSRFWhitelistEntries(entries []string) error {+ for _, entry := range entries {+ entry = strings.TrimSpace(entry)+ if entry == "" {+ continue+ }+ if strings.Contains(entry, "/") {+ if _, _, err := net.ParseCIDR(entry); err != nil {+ return fmt.Errorf("invalid CIDR %q: %w", entry, err)+ }+ continue+ }+ if strings.HasPrefix(entry, "*.") {+ if len(entry) <= 2 {+ return fmt.Errorf("wildcard entry %q is missing a domain (use *.example.com)", entry)+ }+ continue+ }+ if strings.Contains(entry, "*") {+ return fmt.Errorf("wildcard pattern %q is not supported (only the \"*.\" prefix is allowed)", entry)+ }+ }+ return nil+}+// mergeSSRFWhitelistRaws joins two comma-separated raw strings, dropping// the comma when one side is empty. Exposed for the service layer's// "merge SSRF_WHITELIST_EXTRA into the DB-backed list" code path.