feat(system): consolidate system admin and settings into one Settings panel

Replace the standalone /platform/system/* routes with a single
"系统设置" section inside the canonical Settings modal. The previous
SystemLayout.vue / SystemAdmins.vue surfaces are removed and their
functionality (system admin roster, global settings) is hosted directly
in SystemSettings.vue under the standard `.section-header` /
`.settings-group` skeleton. Legacy URLs redirect to the modal section
so external bookmarks don't 404.

Backend:
- SystemSettingService.Reset + repo.Delete: drop the DB override for a
  key so the 3-tier resolver falls back to ENV / built-in default.
  Idempotent (resetting a never-persisted key returns nil); emits an
  audit row only on real deletions, invalidates the local cache, and
  publishes to peers via the existing pubsub channel.
- TenantService.BulkSetStorageQuota: overwrite every tenant's
  storage_quota in one statement. Powers POST /system/admin/tenants/
  apply-default-storage-quota; bypasses the per-tenant whitelist on
  PUT /tenants/:id which intentionally forbids storage_quota edits.
- AuditAction{SystemAdminPromoted,SystemAdminRevoked} constants and
  emitAdminAudit() in SystemHandler — promote / revoke now leave an
  audit trail with TenantID=0 and {target_email,target_username,
  idempotent|changed} in details.
- SystemSetting.LastModifiedByName: derived per-request display label
  (username, email fallback) so the UI shows "wizardchen" instead of
  a UUID prefix without storing a denormalised column.

Frontend:
- SystemSettings.vue rewritten against the Settings modal skeleton with
  auto-persisting controls (switch/select @change, input/inputnumber
  @blur, tag-input + per-delta popconfirm for SSRF whitelist and admin
  roster). auth.registration_mode change goes through an inline
  popconfirm; cancel rolls back. Reset / bulk-apply also inline
  popconfirms — no dialog modal for these per-row affordances.
- Priority hint panel surfaces the DB > ENV > default resolver order
  so operators can reason about "I set the env but it doesn't show up".
- Router: /platform/system, /platform/system/settings, /platform/system/
  admins are now compatibility redirects to /platform/settings?section=
  system-global.
- Settings modal sized 900x700 → 1080x780 and content-wrapper 600 → 760
  so the wider tables (members, system settings) breathe; <1100px
  viewport still flexes to the screen.
- i18n: system.globalSettings.* keys for title / description / loading /
  empty / badges / priority hint / per-key labels / reset / bulkApply /
  admins (label, placeholder, save messages, popconfirm copy) across
  zh-CN, en-US, ko-KR, ru-RU.

Misc:
- internal/utils/filesize.go doc: clarify MAX_FILE_SIZE_MB is a
  deploy-time-only knob (nginx + docreader + frontend each cache the
  env at startup); a SystemAdmin UI override would mislead operators
  because nginx would still 413. Until all four layers can hot-reload
  the limit in lockstep, this stays env-only.
- internal/utils/security.go: SSRF whitelist parser/runtime now drives
  off SystemSettingService for live updates; ENV remains the fallback
  for never-overridden deployments.
This commit is contained in:
wizardchen
2026-05-26 20:03:35 +08:00
committed by lyingbug
parent 311a033523
commit 9cce0c8e5e
31 changed files with 2207 additions and 753 deletions
+55 -3
View File
@@ -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: boolean
last_modified_by: string
/**
* Display label resolved from last_modified_by (UUID) on the server —
* username when known, email as a fallback. Empty/undefined for
* virtual rows that were never persisted; UI then falls back to the
* UUID prefix.
*/
last_modified_by_name?: string
created_at: string
updated_at: string
/**
@@ -367,3 +387,35 @@ export async function updateSystemSetting(
)
return response as unknown as SystemSettingItem
}
/**
* Reset a system setting back to its ENV / built-in default by deleting
* the DB override row. Idempotent — resetting a key that was never
* persisted resolves successfully.
*/
export async function resetSystemSetting(key: string): Promise<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
}
+5 -3
View File
@@ -353,9 +353,11 @@ const handleSettings = () => {
router.push('/platform/settings')
}
// Open platform-wide settings inside the standard Settings modal.
// Administrator-table workflows still live under /platform/system/admins,
// but global tunables belong with the rest of the configuration surface.
// Open the platform administration area inside the standard Settings
// modal. The admin roster lives at the top of the global-settings
// pane (as a tag-input row) so we route straight there; this is the
// only system-admin section now. Gated by SYSTEM_ADMIN_SECTIONS in
// Settings.vue.
const handleSystemAdmin = () => {
menuVisible.value = false
uiStore.openSettings('system-global')
+104 -1
View File
@@ -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: {
+104 -1
View File
@@ -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: {
+104 -1
View File
@@ -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: {
+104 -1
View File
@@ -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: {
+18 -23
View File
@@ -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 }
},
],
},
],
},
+18 -6
View File
@@ -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 会把操作列挤到贴边;铺满右侧内容列更稳。 */
-259
View File
@@ -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>
-127
View File
@@ -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>
File diff suppressed because it is too large Load Diff