From f02c6f2b4ce0c0e6564b01c28dafa916a2857730 Mon Sep 17 00:00:00 2001 From: oc Date: Mon, 16 Nov 2026 21:12:45 +0800 Subject: [PATCH 1/3] fix(ui): expand and remove every model on the channel form The models picker collapsed the ninth tag and later behind a +N label that cannot be clicked, and it had no options at all, so those models could neither be seen nor removed. Every tag now keeps its remove button, and the dropdown lists fetched and configured models. --- CHANGELOG.md | 4 ++++ frontend/src/i18n/messages.ts | 4 ++-- frontend/src/views/Channels.vue | 12 +++++++++--- 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b1e65a8..81c5d40 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ ## [Unreleased] +### 修复 + +- 渠道编辑的“可用模型”把第 9 个及之后的模型折叠成 `+2`,这个标签点不开也删不掉;下拉里又没有任何选项,只显示“无数据”,这些模型既看不到也改不了。现在已选模型全部显示为带删除按钮的标签,下拉列出拉取过的和渠道已配置的模型,可直接勾选取消,也仍可输入新模型名回车添加。 + ## [0.6.2] - 2026-11-14 ### 修复 diff --git a/frontend/src/i18n/messages.ts b/frontend/src/i18n/messages.ts index 8cf6137..3d9b0eb 100644 --- a/frontend/src/i18n/messages.ts +++ b/frontend/src/i18n/messages.ts @@ -380,7 +380,7 @@ export const en = { 'channels.apiKeyOptional': 'Optional for self-hosted services', 'channels.apiKeyHint': 'One key per line. Multiple keys rotate; a rate-limited key pauses automatically. Stored encrypted.', 'channels.keyPool': 'Keys {ready}/{total} ready', - 'channels.modelsHint': 'Fetch from /models, or type a model name and press Enter', + 'channels.modelsHint': 'Fetch from /models, or type a model name and press Enter. Remove a model by unchecking it in the list or clicking × on its tag.', 'channels.modelsPlaceholder': 'Enter a model name and press Enter', 'channels.fetch': 'Fetch', 'channels.mapping': 'Model Mapping', @@ -1192,7 +1192,7 @@ export const zh: Record = { 'channels.apiKeyOptional': '自建服务可以留空', 'channels.apiKeyHint': '每行一个 Key,多个 Key 轮流使用,被限流的自动暂停。加密保存。', 'channels.keyPool': 'Key 可用 {ready}/{total}', - 'channels.modelsHint': '从 /models 拉取,或输入模型名后回车', + 'channels.modelsHint': '从 /models 拉取,或输入模型名后回车;下拉里取消勾选,或点标签上的 × 即可移除模型', 'channels.modelsPlaceholder': '输入模型名后回车', 'channels.fetch': '拉取', 'channels.mapping': '模型映射', diff --git a/frontend/src/views/Channels.vue b/frontend/src/views/Channels.vue index ee539e3..3f12137 100644 --- a/frontend/src/views/Channels.vue +++ b/frontend/src/views/Channels.vue @@ -145,11 +145,11 @@ filterable allow-create default-first-option - collapse-tags - :max-collapse-tags="8" :placeholder="t('channels.modelsPlaceholder')" class="grow" - /> + > + + {{ t('channels.fetch') }}
{{ t('channels.modelsHint') }}
@@ -293,6 +293,9 @@ const emptyForm = () => ({ }) const form = ref(emptyForm()) const enabledCount = computed(() => channels.value.filter(channel => channel.is_enabled).length) +/** Candidate models for the picker: fetched from upstream plus the ones already configured on this channel. */ +const fetchedModels = ref([]) +const modelOptions = computed(() => [...new Set([...fetchedModels.value, ...form.value.models])]) const pricingModelOptions = computed(() => [ ...new Set([...form.value.models, ...mappingRows.value.map(row => row.to.trim()).filter(Boolean)]), ]) @@ -417,6 +420,7 @@ async function fetchModels() { added++ } } + fetchedModels.value = [...new Set([...fetchedModels.value, ...res.models])] ElMessage.success(t('channels.fetched', { count: res.models.length, added })) } catch (error) { ElMessage.error(apiError(error, t('channels.fetchFailed'))) @@ -428,6 +432,7 @@ async function fetchModels() { function openCreate() { editingId.value = null form.value = emptyForm() + fetchedModels.value = [] loadRows({}, {}) dialogVisible.value = true } @@ -441,6 +446,7 @@ function openEdit(row: any) { model_mapping: { ...row.model_mapping }, price_overrides: { ...row.price_overrides }, } + fetchedModels.value = [...row.models] loadRows(form.value.model_mapping, form.value.price_overrides) dialogVisible.value = true } -- Gitee From a551414e8a080c9435dd74fc48837efa358040cf Mon Sep 17 00:00:00 2001 From: oc Date: Wed, 18 Nov 2026 10:47:50 +0800 Subject: [PATCH 2/3] feat: add white-label branding for the console - Public GET /api/branding for the sign-in page; admin GET/PUT /api/settings/branding with branding.update audit - Product name, short name, browser title, taglines, logo, favicon and sidebar width (180-320px) - Login page, sidebar, tab title, Codex snippet, metrics example and alert prefix follow the config; no migration needed --- CHANGELOG.md | 6 + backend/app/main.py | 3 + backend/app/routers/branding.py | 16 ++ backend/app/routers/settings.py | 28 ++- backend/app/services/alerts.py | 4 +- backend/app/services/settings_service.py | 94 ++++++- backend/tests/test_branding.py | 114 +++++++++ backend/tests/test_route_guards.py | 8 +- docs/DESIGN.md | 2 + docs/OPERATIONS.md | 17 ++ frontend/components.d.ts | 2 + frontend/index.html | 3 +- frontend/src/api/branding.ts | 23 ++ frontend/src/components/BrandingSettings.vue | 244 +++++++++++++++++++ frontend/src/components/MetricsToken.vue | 4 +- frontend/src/i18n/messages.ts | 46 ++++ frontend/src/layouts/AdminLayout.vue | 23 +- frontend/src/main.ts | 11 +- frontend/src/stores/branding.ts | 98 ++++++++ frontend/src/views/Login.vue | 20 +- frontend/src/views/Onboarding.vue | 12 +- frontend/src/views/Settings.vue | 2 + 22 files changed, 759 insertions(+), 21 deletions(-) create mode 100644 backend/app/routers/branding.py create mode 100644 backend/tests/test_branding.py create mode 100644 frontend/src/api/branding.ts create mode 100644 frontend/src/components/BrandingSettings.vue create mode 100644 frontend/src/stores/branding.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 81c5d40..3d65352 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ ## [Unreleased] +### 新增 + +- 新增白标(OEM)定制。设置页多出「品牌」标签页,可以改产品名称、简称、浏览器标题、中英文登录副标题、Logo 地址、favicon 和侧栏宽度(180–320px);登录页、侧边栏、浏览器标签、接入教程里的 Codex 示例、监控示例的任务名以及告警消息前缀都跟着变。留空回落到默认值,页面带预览与「恢复默认」。`GET /api/branding` 免鉴权,只返回这些展示字段,供登录页在登录前取用;后台读写需要平台管理员。 +- 登录页品牌区改为居中;侧边栏配置 Logo 后仍显示产品名称(不再只剩一个徽标),空间不足时省略文字;侧栏宽度可在品牌页调整,窄屏回落原有宽度。 +- **兼容边界**:API Key 前缀 `five-`、JWT 受众、Redis 键前缀、Prometheus 指标名和 `x-five-downgraded-to` 响应头保持 `five` 不变,白标只影响界面文案。无需数据库迁移;旧库没有品牌记录时全部走默认。 + ### 修复 - 渠道编辑的“可用模型”把第 9 个及之后的模型折叠成 `+2`,这个标签点不开也删不掉;下拉里又没有任何选项,只显示“无数据”,这些模型既看不到也改不了。现在已选模型全部显示为带删除按钮的标签,下拉列出拉取过的和渠道已配置的模型,可直接勾选取消,也仍可输入新模型名回车添加。 diff --git a/backend/app/main.py b/backend/app/main.py index 7485d43..9ea0bd7 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -163,9 +163,12 @@ def create_app() -> FastAPI: openai_proxy, anthropic_proxy, metrics, ) + from app.routers import branding as branding_router + app.include_router(openai_proxy.router) app.include_router(anthropic_proxy.router) app.include_router(auth.router) + app.include_router(branding_router.router) app.include_router(channels.router) app.include_router(keys.router) app.include_router(logs.router) diff --git a/backend/app/routers/branding.py b/backend/app/routers/branding.py new file mode 100644 index 0000000..c1327b0 --- /dev/null +++ b/backend/app/routers/branding.py @@ -0,0 +1,16 @@ +"""Public branding for the sign-in page and the SPA shell. + +Only display fields leave this route. Everything else stays behind +require_platform_admin. +""" + +from fastapi import APIRouter + +from app.services.settings_service import branding_config + +router = APIRouter(prefix="/api", tags=["branding"]) + + +@router.get("/branding") +async def get_branding(): + return await branding_config() diff --git a/backend/app/routers/settings.py b/backend/app/routers/settings.py index 6874953..cc466d1 100644 --- a/backend/app/routers/settings.py +++ b/backend/app/routers/settings.py @@ -8,9 +8,11 @@ from app.models import User from app.services import alerts from app.services.auth import require_platform_admin from app.services.settings_service import ( + branding_config, gateway_config, metrics_token, reset_metrics_token, + set_branding, set_gateway_config, patch_gateway_config, ) @@ -44,6 +46,29 @@ async def update_settings( return await patch_gateway_config(body.model_dump(exclude_none=True)) +class BrandingSettingsBody(BaseModel): + # Real limits live in settings_service: over-long input is trimmed, not rejected. + product_name: str = Field(default="", max_length=200) + short_name: str = Field(default="", max_length=200) + page_title: str = Field(default="", max_length=2000) + tagline: dict[str, str] = Field(default_factory=dict) + logo_url: str = Field(default="", max_length=2000) + favicon_url: str = Field(default="", max_length=2000) + # Clamped to 180-320 in settings_service; 0 means "use the default". + sidebar_width: int = Field(default=0) + + +@router.get("/branding") +async def get_branding_settings(_: User = Depends(require_platform_admin)): + return await branding_config() + + +@router.put("/branding") +@audit_mutation("branding.update") +async def update_branding_settings(body: BrandingSettingsBody, _: User = Depends(require_platform_admin)): + return await set_branding(body.model_dump()) + + @router.get("/metrics-token") async def get_metrics_token(_: User = Depends(require_platform_admin)): return {"token": await metrics_token()} @@ -96,7 +121,8 @@ async def test_alerts(body: AlertTestBody, _: User = Depends(require_platform_ad ] if not hooks: raise HTTPException(status_code=404, detail="No saved webhook") + product = (await branding_config())["product_name"] results = await alerts.deliver( - hooks, "test", "[Five API] 告警测试", "这是一条测试消息,收到说明 Webhook 配置正确。", {"test": True}, + hooks, "test", f"[{product}] 告警测试", "这是一条测试消息,收到说明 Webhook 配置正确。", {"test": True}, ) return {"items": results} diff --git a/backend/app/services/alerts.py b/backend/app/services/alerts.py index e5aaf98..3ecab6d 100644 --- a/backend/app/services/alerts.py +++ b/backend/app/services/alerts.py @@ -20,6 +20,7 @@ import httpx from app import dependencies from app.models import APIKey, Channel, SystemSetting from app.services.budget_usage import budget_usages +from app.services.settings_service import branding_config from app.utils.secrets import decrypt_secret, encrypt_secret logger = logging.getLogger(__name__) @@ -219,7 +220,8 @@ async def notify(event: str, subject: str, title: str, text: str, data: dict, de redis = await dependencies.get_redis() if not await redis.set(f"five:alert:{event}:{subject}", "1", ex=dedupe_seconds, nx=True): return False - task = asyncio.create_task(deliver(config["webhooks"], event, f"[Five API] {title}", text, data)) + product = (await branding_config())["product_name"] + task = asyncio.create_task(deliver(config["webhooks"], event, f"[{product}] {title}", text, data)) _tasks.add(task) task.add_done_callback(_tasks.discard) return True diff --git a/backend/app/services/settings_service.py b/backend/app/services/settings_service.py index 08236ca..18fbc5b 100644 --- a/backend/app/services/settings_service.py +++ b/backend/app/services/settings_service.py @@ -3,6 +3,7 @@ 网关运行参数存在 system_settings。没有记录时用环境变量里的默认值。 """ +import re import secrets import time @@ -16,12 +17,14 @@ KEYWORD_FILTER_KEY = "keyword_filter_enabled" SECRET_SCAN_KEY = "secret_scan_enabled" AI_AUDIT_KEY = "ai_audit" GATEWAY_KEY = "gateway" +BRANDING_KEY = "branding" METRICS_TOKEN_KEY = "metrics_token" _CACHE_TTL = 2.0 _cache: tuple[float, bool] | None = None _secret_cache: tuple[float, bool] | None = None _ai_cache: tuple[float, dict] | None = None _gateway_cache: tuple[float, dict] | None = None +_branding_cache: tuple[float, dict] | None = None async def metrics_token() -> str: """Bearer token for scraping /metrics remotely, created on first use.""" @@ -277,9 +280,98 @@ async def patch_gateway_config(delta: dict) -> dict: return stored +BRAND_TEXT_LIMITS = {"product_name": 40, "page_title": 80, "tagline": 80} +_SHORT_NAME_PATTERN = re.compile(r"[^a-z0-9-]+") + + +def default_branding() -> dict: + return { + "product_name": "Five API", + "short_name": "five", + "page_title": "", + "tagline": {"zh": "", "en": ""}, + "logo_url": "", + "favicon_url": "", + "sidebar_width": 200, + } + + +def _brand_sidebar_width(value) -> int: + """180-320px; 0, empty or garbage keeps the default instead of collapsing the sidebar.""" + try: + number = int(str(value).strip()) + except (TypeError, ValueError): + return default_branding()["sidebar_width"] + if number <= 0: + return default_branding()["sidebar_width"] + return max(180, min(320, number)) + + +def _brand_text(value, limit: int) -> str: + return " ".join(str(value or "").split())[:limit] + + +def _brand_short_name(value) -> str: + name = _SHORT_NAME_PATTERN.sub("-", str(value or "").strip().lower()).strip("-")[:20] + return name.strip("-") or default_branding()["short_name"] + + +def _brand_url(value, limit: int = 512) -> str: + """Only absolute http(s) URLs and site-relative paths; never javascript: or data:.""" + text = str(value or "").strip() + if not text or len(text) > limit: + return "" + if any(ord(char) < 33 for char in text) or any(char in text for char in "\"'<>`"): + return "" + if text.lower().startswith(("http://", "https://")): + return text + if text.startswith("/") and not text.startswith("//"): + return text + return "" + + +def _normalize_branding(value) -> dict: + defaults = default_branding() + raw = value if isinstance(value, dict) else {} + tagline = raw.get("tagline") if isinstance(raw.get("tagline"), dict) else {} + return { + "product_name": _brand_text(raw.get("product_name"), BRAND_TEXT_LIMITS["product_name"]) + or defaults["product_name"], + "short_name": _brand_short_name(raw.get("short_name")), + "page_title": _brand_text(raw.get("page_title"), BRAND_TEXT_LIMITS["page_title"]), + "tagline": { + "zh": _brand_text(tagline.get("zh"), BRAND_TEXT_LIMITS["tagline"]), + "en": _brand_text(tagline.get("en"), BRAND_TEXT_LIMITS["tagline"]), + }, + "logo_url": _brand_url(raw.get("logo_url")), + "favicon_url": _brand_url(raw.get("favicon_url")), + "sidebar_width": _brand_sidebar_width(raw.get("sidebar_width")), + } + + +async def branding_config() -> dict: + global _branding_cache + now = time.monotonic() + if _branding_cache is not None and now - _branding_cache[0] < _CACHE_TTL: + return _branding_cache[1] + row = await SystemSetting.get_or_none(key=BRANDING_KEY) + config = _normalize_branding(row.value if row is not None else None) + _branding_cache = (now, config) + return config + + +async def set_branding(value: dict) -> dict: + global _branding_cache + stored = _normalize_branding(value) + await SystemSetting.update_or_create(key=BRANDING_KEY, defaults={"value": stored}) + _branding_cache = (time.monotonic(), stored) + return stored + + def clear_settings_cache() -> None: - global _cache, _secret_cache, _ai_cache, _gateway_cache + global _cache, _secret_cache, _ai_cache, _gateway_cache, _branding_cache _cache = None _secret_cache = None _ai_cache = None _gateway_cache = None + _branding_cache = None diff --git a/backend/tests/test_branding.py b/backend/tests/test_branding.py new file mode 100644 index 0000000..2bbeb3a --- /dev/null +++ b/backend/tests/test_branding.py @@ -0,0 +1,114 @@ +import pytest + +from app.models import ManagementEvent +from app.services.auth import create_access_token +from tests.conftest import auth_header, create_admin, create_tenant_account + +pytestmark = [pytest.mark.asyncio, pytest.mark.regression] + + +DEFAULTS = { + "product_name": "Five API", + "short_name": "five", + "page_title": "", + "tagline": {"zh": "", "en": ""}, + "logo_url": "", + "favicon_url": "", + "sidebar_width": 200, +} + + +async def _admin_headers() -> dict: + admin = await create_admin("brandadmin", "pw") + return auth_header(create_access_token({"sub": str(admin.id)})) + + +async def test_public_branding_defaults_to_five_api(client): + resp = await client.get("/api/branding") + assert resp.status_code == 200 + assert resp.json() == DEFAULTS + + +async def test_branding_round_trip_shared_by_public_and_admin_routes(client): + headers = await _admin_headers() + body = { + "product_name": "Acme Gateway", + "short_name": "acme", + "page_title": "Acme Console", + "tagline": {"zh": "自建模型网关", "en": "Your own model gateway"}, + "logo_url": "https://cdn.example.com/logo.png", + "favicon_url": "/favicon-acme.ico", + "sidebar_width": 260, + } + saved = await client.put("/api/settings/branding", json=body, headers=headers) + assert saved.status_code == 200 + assert saved.json() == body + + assert (await client.get("/api/settings/branding", headers=headers)).json() == body + assert (await client.get("/api/branding")).json() == body + + event = await ManagementEvent.get(action="branding.update") + assert "product_name" in event.detail["fields"] + + +async def test_branding_normalizes_text_and_rejects_unsafe_values(client): + headers = await _admin_headers() + saved = await client.put( + "/api/settings/branding", + json={ + "product_name": " Acme\n AI ", + "short_name": "ACME AI!", + "page_title": "x" * 120, + "tagline": {"zh": " 多 空格 ", "en": "", "fr": "ignore"}, + "logo_url": "javascript:alert(1)", + "favicon_url": "//evil.example.com/f.ico", + "sidebar_width": 999, + }, + headers=headers, + ) + assert saved.status_code == 200 + data = saved.json() + assert data["product_name"] == "Acme AI" + assert data["short_name"] == "acme-ai" + assert len(data["page_title"]) == 80 + assert data["tagline"] == {"zh": "多 空格", "en": ""} + assert data["logo_url"] == "" + assert data["favicon_url"] == "" + assert data["sidebar_width"] == 320 + + cleared = await client.put("/api/settings/branding", json={"product_name": "", "short_name": ""}, headers=headers) + assert cleared.json()["product_name"] == "Five API" + assert cleared.json()["short_name"] == "five" + assert cleared.json()["sidebar_width"] == 200 + + narrow = await client.put("/api/settings/branding", json={"sidebar_width": 12}, headers=headers) + assert narrow.json()["sidebar_width"] == 180 + + +async def test_branding_settings_require_platform_admin(client): + _, _, headers = await create_tenant_account() + assert (await client.get("/api/settings/branding", headers=headers)).status_code == 403 + assert (await client.put( + "/api/settings/branding", json={"product_name": "Leak"}, headers=headers + )).status_code == 403 + + +async def test_alert_titles_follow_the_configured_name(): + from unittest.mock import AsyncMock, patch + + from app.services import alerts + from app.services.settings_service import set_branding + + await set_branding({"product_name": "Acme Gateway"}) + await alerts.save_config({ + "enabled": True, + "webhooks": [{ + "type": "feishu", + "name": "ops", + "url": "https://open.feishu.cn/open-apis/bot/v2/hook/abcdef123456", + }], + }) + with patch.object(alerts, "deliver", AsyncMock(return_value=[])) as deliver: + assert await alerts.notify("channel", "acme-1", "渠道熔断", "text", {}, 60) + await alerts.drain_alerts() + assert deliver.await_args.args[2] == "[Acme Gateway] 渠道熔断" diff --git a/backend/tests/test_route_guards.py b/backend/tests/test_route_guards.py index 02b9d0e..f168323 100644 --- a/backend/tests/test_route_guards.py +++ b/backend/tests/test_route_guards.py @@ -13,7 +13,13 @@ from app.models import APIKey from app.services.auth import hash_api_key from tests.conftest import auth_header, create_tenant_account -PUBLIC = {("POST", "/api/login"), ("GET", "/healthz"), ("GET", "/metrics"), ("GET", "/{full_path:path}")} +PUBLIC = { + ("POST", "/api/login"), + ("GET", "/api/branding"), + ("GET", "/healthz"), + ("GET", "/metrics"), + ("GET", "/{full_path:path}"), +} # Any signed-in account, including one that still has to change its temporary password. SELF_SERVICE = {("GET", "/api/me"), ("PUT", "/api/password")} TENANT_PREFIX = "/api/keys" diff --git a/docs/DESIGN.md b/docs/DESIGN.md index cce7d91..cb0961a 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -53,6 +53,8 @@ | `POST /api/login` | username、password,返回 access_token、expires_in、must_change_password | | `GET /api/me` | 当前账号、角色、tenant_id 和是否需要改密 | | `PUT /api/password` | old_password、new_password,返回新 JWT,旧 JWT 失效 | +| `GET /api/branding` | 免鉴权;只返回白标展示字段(产品名称、简称、浏览器标题、中英文副标题、Logo 与 favicon),登录页在登录前取用 | +| `GET /api/settings/branding`、`PUT /api/settings/branding` | 仅平台;读写白标配置,留空回落默认值,写入记录 `branding.update` 审计。只改界面文案,不动 Key 前缀、JWT 受众、Redis 键、指标名与响应头 | | `POST /api/tenants` | 仅平台;创建租户及其账号,初始额度 0。只需 `username`,`name` 省略时与用户名相同,控制台不再单独填写名称。不传 `password` 时服务端生成一次性临时密码,只在本次响应的 `temporary_password` 中返回(no-store) | | `POST /api/users`、`PUT /api/users/{id}/password` | 仅平台;创建平台管理员、重置其密码。密码规则和 `temporary_password` 返回方式与租户相同 | | `PUT /api/tenants/{id}` | 仅平台;说明、启停、模型范围、Key 数量上限、共享限流(接口仍接受 `name`,控制台不再提供) | diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md index 509f0b9..655555c 100644 --- a/docs/OPERATIONS.md +++ b/docs/OPERATIONS.md @@ -110,6 +110,23 @@ cp .env five-api.env 迁移 24 把模型售价的倍率乘进单价后删除倍率列,客户价不变;删除渠道上游成本表、成本倍率、分时规则和日志、日汇总的 upstream_cost。所有渠道倍率为 1、所有 Key 不绑定渠道,行为与升级前一致。降级只恢复列结构,渠道倍率、固定价和 Key 渠道绑定会丢失,上游成本不可恢复。 +## 白标(OEM)定制 + +设置 → 品牌(仅平台管理员)。保存后立即生效;多 worker 部署时其它进程最多 2 秒同步。 + +| 字段 | 说明 | +| --- | --- | +| 产品名称 | 登录页标题、侧边栏、告警消息前缀。留空回落 `Five API` | +| 简称 | 小写字母、数字、连字符。派生接入教程里的 Codex 提供方标识、`FIVE_API_KEY` 这类环境变量名、监控示例的任务名和占位 Key 前缀 | +| 浏览器标题 | 标签页标题;留空用产品名称 | +| 登录页副标题 | 中文、英文各一套;留空用内置文案 | +| Logo / favicon | `https://` 地址或本站路径;Logo 留空时显示产品名称文字,favicon 留空时用浏览器默认图标。配了 Logo 时侧边栏仍会在徽标右侧显示产品名称,空间不足自动省略 | +| 侧栏宽度 | 180–320 像素,默认 200;只影响后台左侧导航(≤900px 视口回落 180,手机抽屉固定 200) | + +登录页在登录前通过 `GET /api/branding` 取配置,该接口免鉴权且只返回上面这些展示字段;后台读写走 `/api/settings/branding`。 + +不在白标范围内(改了会破坏兼容):API Key 前缀 `five-`、JWT 受众 `five-api-management`、Redis 键前缀 `five:`、Prometheus 指标名 `five_*`、`x-five-downgraded-to` 响应头、镜像与数据库名、`/docs` 标题。 + ## 泄露和故障排查 推理 Key 泄露:立即撤销,创建新 Key,更新受控应用配置;新建不恢复已用额度。账号凭据泄露:在租户账号或平台管理员页点“重置密码”,系统生成新的临时密码并撤销旧 JWT,对方下次登录必须改密;临时密码只显示一次,请用私密渠道转交。上游 Key 泄露:在厂商侧撤销并更新渠道;外置秘密泄露需要人工安排重新加密与会话失效,没有自动轮换服务。 diff --git a/frontend/components.d.ts b/frontend/components.d.ts index b3e97d5..d780416 100644 --- a/frontend/components.d.ts +++ b/frontend/components.d.ts @@ -13,6 +13,7 @@ declare module 'vue' { export interface GlobalComponents { AlertSettings: typeof import('./src/components/AlertSettings.vue')['default'] AuditRequestRow: typeof import('./src/components/AuditRequestRow.vue')['default'] + BrandingSettings: typeof import('./src/components/BrandingSettings.vue')['default'] ChannelTestDialog: typeof import('./src/components/ChannelTestDialog.vue')['default'] ElAlert: typeof import('element-plus/es')['ElAlert'] ElAside: typeof import('element-plus/es')['ElAside'] @@ -54,6 +55,7 @@ declare module 'vue' { ElRow: typeof import('element-plus/es')['ElRow'] ElSelect: typeof import('element-plus/es')['ElSelect'] ElSkeleton: typeof import('element-plus/es')['ElSkeleton'] + ElSlider: typeof import('element-plus/es')['ElSlider'] ElSwitch: typeof import('element-plus/es')['ElSwitch'] ElTable: typeof import('element-plus/es')['ElTable'] ElTableColumn: typeof import('element-plus/es')['ElTableColumn'] diff --git a/frontend/index.html b/frontend/index.html index a470cfc..43aa704 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -3,7 +3,8 @@ - Five API Gateway + + API Gateway
diff --git a/frontend/src/api/branding.ts b/frontend/src/api/branding.ts new file mode 100644 index 0000000..8c5021b --- /dev/null +++ b/frontend/src/api/branding.ts @@ -0,0 +1,23 @@ +import client from './client' + +export interface BrandingTagline { + zh: string + en: string +} + +export interface Branding { + product_name: string + short_name: string + page_title: string + tagline: BrandingTagline + logo_url: string + favicon_url: string + sidebar_width: number +} + +export const brandingApi = { + // Public: the sign-in page needs it before anyone is authenticated. + get: async (): Promise => (await client.get('/branding', { timeout: 5000 })).data, + read: async (): Promise => (await client.get('/settings/branding')).data, + save: async (body: Branding): Promise => (await client.put('/settings/branding', body)).data, +} diff --git a/frontend/src/components/BrandingSettings.vue b/frontend/src/components/BrandingSettings.vue new file mode 100644 index 0000000..a6fc21d --- /dev/null +++ b/frontend/src/components/BrandingSettings.vue @@ -0,0 +1,244 @@ + + + + + diff --git a/frontend/src/components/MetricsToken.vue b/frontend/src/components/MetricsToken.vue index 356605f..10f0832 100644 --- a/frontend/src/components/MetricsToken.vue +++ b/frontend/src/components/MetricsToken.vue @@ -16,10 +16,12 @@ import { computed, onMounted, ref } from 'vue' import { ElMessage, ElMessageBox } from 'element-plus' import { metricsTokenApi } from '@/api/settings' import { useAuthStore } from '@/stores/auth' +import { useBrandingStore } from '@/stores/branding' import { useI18n } from '@/i18n' const { t } = useI18n() const auth = useAuthStore() +const branding = useBrandingStore() const canWrite = computed(() => auth.isPlatformAdmin) const token = ref('') const loading = ref(false) @@ -27,7 +29,7 @@ const resetting = ref(false) const example = computed(() => [ 'scrape_configs:', - ' - job_name: five-api', + ` - job_name: ${branding.shortName}-api`, ' authorization: { credentials: "" }', ' static_configs:', ` - targets: ["${location.host}"]`, diff --git a/frontend/src/i18n/messages.ts b/frontend/src/i18n/messages.ts index 3d9b0eb..3c5c311 100644 --- a/frontend/src/i18n/messages.ts +++ b/frontend/src/i18n/messages.ts @@ -53,6 +53,7 @@ export const en = { 'settings.tabRouting': 'Routing', 'settings.tabAlerts': 'Notifications', 'settings.tabMetrics': 'Metrics', + 'settings.tabBranding': 'Branding', 'settings.tabSettlements': 'Settlement recovery', 'settings.cache': 'Request caching', 'settings.advanced': 'Advanced rules', @@ -806,6 +807,28 @@ export const en = { 'settings.healthInterval': 'Probe interval (seconds)', 'settings.healthHint': 'Only isolated channels are probed. A saved interval applies on the next probe cycle.', 'settings.loadFailed': 'Failed to load settings', + 'branding.title': 'Branding', + 'branding.subtitle': 'White-label the console: the sign-in page, sidebar, browser tab, onboarding snippets, metrics example and alert titles follow these fields. Empty values fall back to the defaults.', + 'branding.naming': 'Naming', + 'branding.productName': 'Product name', + 'branding.productNameHint': 'Shown on the sign-in page, in the sidebar and in alert titles. At most 40 characters.', + 'branding.shortName': 'Short name', + 'branding.shortNameHint': 'Lowercase letters, digits and hyphens. Used for the Codex provider id, the FIVE_API_KEY style variable and the metrics job name.', + 'branding.pageTitle': 'Browser title', + 'branding.pageTitleHint': 'Leave empty to use the product name.', + 'branding.taglineZh': 'Sign-in subtitle (Chinese)', + 'branding.taglineEn': 'Sign-in subtitle (English)', + 'branding.taglineHint': 'Empty values keep the built-in subtitle.', + 'branding.assets': 'Images', + 'branding.logoUrl': 'Logo URL', + 'branding.logoHint': 'An https:// URL or a path on this site. Leave empty to show the product name as text.', + 'branding.faviconUrl': 'Favicon URL', + 'branding.faviconHint': 'An https:// URL or a path on this site. Leave empty to keep the browser default icon.', + 'branding.layout': 'Layout', + 'branding.sidebarWidth': 'Sidebar width', + 'branding.sidebarWidthHint': 'Applies to the admin sidebar only, 180-320 px. Default 200.', + 'branding.preview': 'Preview', + 'branding.restore': 'Restore defaults', } as const export type MessageKey = keyof typeof en @@ -865,6 +888,7 @@ export const zh: Record = { 'settings.tabRouting': '路由策略', 'settings.tabAlerts': '告警通知', 'settings.tabMetrics': '监控接入', + 'settings.tabBranding': '品牌', 'settings.tabSettlements': '结算恢复', 'settings.cache': '请求缓存', 'settings.advanced': '高级规则', @@ -1618,4 +1642,26 @@ export const zh: Record = { 'settings.healthInterval': '探测间隔(秒)', 'settings.healthHint': '只探测已经隔离的渠道。改过的间隔从下一次探测开始生效。', 'settings.loadFailed': '设置加载失败', + 'branding.title': '品牌', + 'branding.subtitle': '白标定制:登录页、侧边栏、浏览器标签、接入教程示例、监控示例和告警标题都跟着这些字段变。留空则回落默认值。', + 'branding.naming': '名称', + 'branding.productName': '产品名称', + 'branding.productNameHint': '显示在登录页、侧边栏和告警标题里,最多 40 个字符。', + 'branding.shortName': '简称', + 'branding.shortNameHint': '小写字母、数字和连字符。用于 Codex 提供方标识、FIVE_API_KEY 这类环境变量名和监控任务名。', + 'branding.pageTitle': '浏览器标题', + 'branding.pageTitleHint': '留空则使用产品名称。', + 'branding.taglineZh': '登录页副标题(中文)', + 'branding.taglineEn': '登录页副标题(英文)', + 'branding.taglineHint': '留空则使用内置文案。', + 'branding.assets': '图片', + 'branding.logoUrl': 'Logo 地址', + 'branding.logoHint': 'https:// 开头,或本站路径。留空则显示产品名称文字。', + 'branding.faviconUrl': 'favicon 地址', + 'branding.faviconHint': 'https:// 开头,或本站路径。留空则使用浏览器默认图标。', + 'branding.layout': '布局', + 'branding.sidebarWidth': '侧栏宽度', + 'branding.sidebarWidthHint': '仅影响后台左侧导航,180-320 像素,默认 200。', + 'branding.preview': '预览', + 'branding.restore': '恢复默认', } diff --git a/frontend/src/layouts/AdminLayout.vue b/frontend/src/layouts/AdminLayout.vue index 8d3aa41..ab86ff8 100644 --- a/frontend/src/layouts/AdminLayout.vue +++ b/frontend/src/layouts/AdminLayout.vue @@ -1,9 +1,10 @@