diff --git a/CHANGELOG.md b/CHANGELOG.md index b1e65a85498394db516bcca5dcbef11c1f160bf7..696a8f09a9a13773b1b7aac111302a7ce000c2cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,17 @@ ## [Unreleased] +### 新增 + +- 新增白标(OEM)定制。设置页多出「品牌」标签页,可以改产品名称、简称、浏览器标题、中英文登录副标题、Logo 地址、favicon 和侧栏宽度(180–320px);登录页、侧边栏、浏览器标签、接入教程里的 Codex 示例、监控示例的任务名以及告警消息前缀都跟着变。留空回落到默认值,页面带预览与「恢复默认」。`GET /api/branding` 免鉴权,只返回这些展示字段,供登录页在登录前取用;后台读写需要平台管理员。 +- 登录页品牌区改为居中;侧边栏配置 Logo 后仍显示产品名称(不再只剩一个徽标),空间不足时省略文字;侧栏宽度可在品牌页调整,窄屏回落原有宽度。 +- 新增明暗主题,顶栏和登录页右上角可切「浅色 / 深色 / 跟随系统」,选择存在浏览器本地,刷新和重新登录都保持;首屏在挂载前就落主题,暗色用户不会先看到一帧白底。配色全部走 Element Plus 官方暗色变量,侧边栏、卡片、表格、弹窗、下拉与看板图表的坐标轴/系列色一起适配。 +- **兼容边界**:API Key 前缀 `five-`、JWT 受众、Redis 键前缀、Prometheus 指标名和 `x-five-downgraded-to` 响应头保持 `five` 不变,白标只影响界面文案。无需数据库迁移;旧库没有品牌记录时全部走默认。 + +### 修复 + +- 渠道编辑的“可用模型”把第 9 个及之后的模型折叠成 `+2`,这个标签点不开也删不掉;下拉里又没有任何选项,只显示“无数据”,这些模型既看不到也改不了。现在已选模型全部显示为带删除按钮的标签,下拉列出拉取过的和渠道已配置的模型,可直接勾选取消,也仍可输入新模型名回车添加。 + ## [0.6.2] - 2026-11-14 ### 修复 diff --git a/backend/app/main.py b/backend/app/main.py index 7485d43ded62d214e7f16fc04be0b24fb8b5ca08..9ea0bd70c5ae5babdabaf4f2065e2b3746e18391 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 0000000000000000000000000000000000000000..c1327b03e05451ca9ddb95ccbc5da20ba43b2f00 --- /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 68749533ef943552b09af957f54a57bc9d797dc2..cc466d1aa1d79581b8f2b8fe8eb3f06717eb817a 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 e5aaf98f43e9111e65b5c0124da616220798e139..3ecab6dc33a2602bf13f29672546f141ece0b09d 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 08236ca9da1dc22fc5c1c152e88474bf66fa1ba9..18fbc5b030a9a891d86ebdcefe054360c40b65c8 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 0000000000000000000000000000000000000000..2bbeb3ab4bd8dde5703f81c42f4a1bfef5c39b33 --- /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 02b9d0ea340b59f1648af007e45a7b7479bbb2c8..f168323d85d68fe535ef6bfcd3356a430793093c 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 cce7d91cdaf348a5b38d81b6aeb24567727ebca7..cb0961a391f54994548077e310d165b640e8c0b8 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 509f0b96c229f744bed22d68ed9352b7f6bac2ea..655555c503f476b04b987f59ee0423f59330da0c 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 b3e97d5421673a8d680d341bb178bef39f6676cc..2fc9e3c761702ccbbea187a03d6962992b1f509b 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'] @@ -70,6 +72,7 @@ declare module 'vue' { SettlementNotice: typeof import('./src/components/SettlementNotice.vue')['default'] SettlementStatus: typeof import('./src/components/SettlementStatus.vue')['default'] TemporaryPasswordDialog: typeof import('./src/components/TemporaryPasswordDialog.vue')['default'] + ThemeSwitch: typeof import('./src/components/ThemeSwitch.vue')['default'] WindowLimitsInput: typeof import('./src/components/WindowLimitsInput.vue')['default'] WindowUsage: typeof import('./src/components/WindowUsage.vue')['default'] } diff --git a/frontend/index.html b/frontend/index.html index a470cfc1379faa3987f7a799bddecb6a76254682..2b6f58df4dcaef7ea40ac555987d6a33164b6d06 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -3,7 +3,25 @@ - Five API Gateway + + API Gateway + +
diff --git a/frontend/src/api/branding.ts b/frontend/src/api/branding.ts new file mode 100644 index 0000000000000000000000000000000000000000..8c5021b2006d0307f7889773ceed2f3c56bf418a --- /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/AlertSettings.vue b/frontend/src/components/AlertSettings.vue index 61665f90c5dc3c81ba434d3dc1e47868de05e25e..0016db2d63278ece6c4266feab1fe73014658536 100644 --- a/frontend/src/components/AlertSettings.vue +++ b/frontend/src/components/AlertSettings.vue @@ -152,7 +152,7 @@ h4 { margin: 0; font-size: 14px; font-weight: 650; - color: #1c1f23; + color: var(--el-text-color-primary); } .hint { @@ -160,7 +160,7 @@ h4 { width: 100%; font-size: 13px; line-height: 1.5; - color: #646a73; + color: var(--el-text-color-secondary); } .hook-list, @@ -185,7 +185,7 @@ h4 { width: 110px; } -.hook-row { padding: 14px; border: 1px solid #e5e9ef; border-radius: 8px; background: #fafbfc; box-sizing: border-box; } +.hook-row { padding: 14px; border: 1px solid var(--el-border-color-lighter); border-radius: 8px; background: var(--el-fill-color-lighter); box-sizing: border-box; } .event-row { padding: 4px 0; } @media (max-width: 720px) { .hook-name, .hook-url, .hook-secret { width: 100% !important; min-width: 0 !important; flex-basis: 100%; } @@ -211,6 +211,6 @@ h4 { .muted { font-size: 13px; - color: #8f959e; + color: var(--el-text-color-secondary); } diff --git a/frontend/src/components/AuditRequestRow.vue b/frontend/src/components/AuditRequestRow.vue index 6b03b6190d2e741269b8967eff66bb9be862178b..80eb88cd30af6724fda04db5b0e7cfd673139510 100644 --- a/frontend/src/components/AuditRequestRow.vue +++ b/frontend/src/components/AuditRequestRow.vue @@ -44,11 +44,11 @@ const { t } = useI18n() diff --git a/frontend/src/components/ChannelTestDialog.vue b/frontend/src/components/ChannelTestDialog.vue index 60097da153b0b3518683e763aaac4e5425fc07e9..9dcf80b1a2b1237685dc42ac59de34a0f1b973b7 100644 --- a/frontend/src/components/ChannelTestDialog.vue +++ b/frontend/src/components/ChannelTestDialog.vue @@ -180,15 +180,15 @@ async function runChecks() { diff --git a/frontend/src/components/MetricsToken.vue b/frontend/src/components/MetricsToken.vue index 356605f3c607df1a5b50a62553e7fd8b49996291..670c9d48efe24185bdcc393c88a144360a9d8c28 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}"]`, @@ -86,14 +88,14 @@ h4 { margin: 0; font-size: 14px; font-weight: 650; - color: #1c1f23; + color: var(--el-text-color-primary); } .hint { margin: 6px 0 12px; font-size: 13px; line-height: 1.5; - color: #646a73; + color: var(--el-text-color-secondary); } .token-row { @@ -113,9 +115,9 @@ h4 { max-width: 640px; font-size: 12px; line-height: 1.6; - background: #f5f6f7; + background: var(--el-fill-color-light); border-radius: 6px; - color: #1c1f23; + color: var(--el-text-color-primary); overflow-x: auto; } diff --git a/frontend/src/components/ModelCheckPanel.vue b/frontend/src/components/ModelCheckPanel.vue index 0cf9514a99940edd251820c6de5be4dd14f64d89..954c618b664178b106923eae5b61bb226f57ed34 100644 --- a/frontend/src/components/ModelCheckPanel.vue +++ b/frontend/src/components/ModelCheckPanel.vue @@ -122,17 +122,17 @@ watch(() => [visible.value, props.model.model], () => { diff --git a/frontend/src/components/SettlementStatus.vue b/frontend/src/components/SettlementStatus.vue index e59e67e61d3fc7e8090043a98be111462ebf20c4..414754994da31c060956d0efabfe9d23299106e2 100644 --- a/frontend/src/components/SettlementStatus.vue +++ b/frontend/src/components/SettlementStatus.vue @@ -69,14 +69,14 @@ onMounted(load) diff --git a/frontend/src/components/TemporaryPasswordDialog.vue b/frontend/src/components/TemporaryPasswordDialog.vue index 043c1b1dc1240ad2308caa67f14a545d334937a8..795dca9cc587e82bef0b383f79a1669f39400d5b 100644 --- a/frontend/src/components/TemporaryPasswordDialog.vue +++ b/frontend/src/components/TemporaryPasswordDialog.vue @@ -66,12 +66,12 @@ async function copy(): Promise { gap: 12px; align-items: baseline; margin: 0 0 8px; - color: #646a73; + color: var(--el-text-color-secondary); font-size: 13px; } .account-line strong { - color: #1c1f23; + color: var(--el-text-color-primary); font-size: 14px; } @@ -83,7 +83,7 @@ async function copy(): Promise { .hint { margin: 12px 0 0; - color: #646a73; + color: var(--el-text-color-secondary); font-size: 13px; line-height: 1.6; } diff --git a/frontend/src/components/ThemeSwitch.vue b/frontend/src/components/ThemeSwitch.vue new file mode 100644 index 0000000000000000000000000000000000000000..da571d6cf9ab56eeb9f3618adffc9b9bd92f06c6 --- /dev/null +++ b/frontend/src/components/ThemeSwitch.vue @@ -0,0 +1,77 @@ + + + + + diff --git a/frontend/src/components/WindowLimitsInput.vue b/frontend/src/components/WindowLimitsInput.vue index a92e280666a0005f01f6210a94040c11e9dd75f7..ec4b39f66942b8808fa9a742cb2b33d099b5306e 100644 --- a/frontend/src/components/WindowLimitsInput.vue +++ b/frontend/src/components/WindowLimitsInput.vue @@ -55,6 +55,6 @@ function update(window: string, value: number | null | undefined) { .window-label { font-size: 12px; line-height: 18px; - color: #646a73; + color: var(--el-text-color-secondary); } diff --git a/frontend/src/components/WindowUsage.vue b/frontend/src/components/WindowUsage.vue index 8a35b5e9df3f3cb2ce22deb98252d8d831e205e9..706254bc8807f5441dc7df6ccec169175e7ad1d6 100644 --- a/frontend/src/components/WindowUsage.vue +++ b/frontend/src/components/WindowUsage.vue @@ -27,11 +27,11 @@ const rows = computed(() => gap: 2px 8px; margin-top: 2px; font-size: 12px; - color: #64748b; + color: var(--el-text-color-secondary); } .over { - color: #f56c6c; + color: var(--el-color-danger); font-weight: 600; } diff --git a/frontend/src/i18n/messages.ts b/frontend/src/i18n/messages.ts index 8cf613706eddad4a4ce2b08f8e5dc63ca206c997..5c3087984615a648325df7cebde65bc92a9389e6 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', @@ -127,6 +128,10 @@ export const en = { 'tenants.quotaAfter': "Total after change", 'tenants.quotaFloor': "The total cannot be below used plus occupied ({min}).", 'lang.label': 'Language', + 'theme.label': 'Theme', + 'theme.light': 'Light', + 'theme.dark': 'Dark', + 'theme.auto': 'Follow system', 'common.save': 'Save', 'common.cancel': 'Cancel', 'common.delete': 'Delete', @@ -380,7 +385,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', @@ -806,6 +811,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 +892,7 @@ export const zh: Record = { 'settings.tabRouting': '路由策略', 'settings.tabAlerts': '告警通知', 'settings.tabMetrics': '监控接入', + 'settings.tabBranding': '品牌', 'settings.tabSettlements': '结算恢复', 'settings.cache': '请求缓存', 'settings.advanced': '高级规则', @@ -939,6 +967,10 @@ export const zh: Record = { 'tenants.quotaAfter': "调整后总额度", 'tenants.quotaFloor': "总额度不能低于已用加占用({min})。", 'lang.label': '语言', + 'theme.label': '主题', + 'theme.light': '浅色', + 'theme.dark': '深色', + 'theme.auto': '跟随系统', 'common.save': '保存', 'common.cancel': '取消', 'common.delete': '删除', @@ -1192,7 +1224,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': '模型映射', @@ -1618,4 +1650,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 8d3aa4139fea94168101942f019aebef2c676724..19e88ea0f02df37d2ae64491483264bdd0c7979a 100644 --- a/frontend/src/layouts/AdminLayout.vue +++ b/frontend/src/layouts/AdminLayout.vue @@ -1,9 +1,10 @@ @@ -372,42 +372,42 @@ onMounted(load) diff --git a/frontend/src/views/Onboarding.vue b/frontend/src/views/Onboarding.vue index 35f7a88bef6d33dfe625fed10ff9114df7b8b1f4..e2ae0dd02dc25675c1cdce143c833dba8c3ab6c0 100644 --- a/frontend/src/views/Onboarding.vue +++ b/frontend/src/views/Onboarding.vue @@ -14,7 +14,7 @@ - +
{{ t('onboard.keyHint') }}
@@ -49,11 +49,12 @@ import { useRouter } from 'vue-router' import { ElMessage } from 'element-plus' import { modelsApi } from '@/api/models' import { useAuthStore } from '@/stores/auth' +import { useBrandingStore } from '@/stores/branding' import { useI18n } from '@/i18n' -const KEY_PLACEHOLDER = 'sk-your-five-api-key' const { t } = useI18n() const auth = useAuthStore() +const branding = useBrandingStore() const router = useRouter() const baseUrl = ref(window.location.origin) const apiKey = ref('') @@ -61,7 +62,8 @@ const model = ref('') const models = ref([]) const tab = ref('claude') -const key = computed(() => apiKey.value.trim() || KEY_PLACEHOLDER) +const keyPlaceholder = computed(() => `sk-your-${branding.shortName}-key`) +const key = computed(() => apiKey.value.trim() || keyPlaceholder.value) const base = computed(() => baseUrl.value.trim().replace(/\/+$/, '')) const modelName = computed(() => model.value || 'claude-sonnet-4-6') @@ -96,9 +98,9 @@ const snippets = computed(() => [ blocks: [ { title: '~/.codex/config.toml', - code: `model = "${modelName.value}"\nmodel_provider = "five"\n\n[model_providers.five]\nname = "Five API"\nbase_url = "${base.value}/v1"\nenv_key = "FIVE_API_KEY"\nwire_api = "responses"`, + code: `model = "${modelName.value}"\nmodel_provider = "${branding.shortName}"\n\n[model_providers.${branding.shortName}]\nname = "${branding.name}"\nbase_url = "${base.value}/v1"\nenv_key = "${branding.apiKeyEnv}"\nwire_api = "responses"`, }, - { title: 'shell', code: `export FIVE_API_KEY=${key.value}\ncodex` }, + { title: 'shell', code: `export ${branding.apiKeyEnv}=${key.value}\ncodex` }, ], note: t('onboard.codexNote'), }, @@ -202,12 +204,12 @@ onMounted(async () => { .intro { margin: 0 0 12px; font-size: 13px; - color: #474d57; + color: var(--el-text-color-regular); } .snippet { margin-bottom: 12px; - border: 1px solid #e5e7eb; + border: 1px solid var(--el-border-color); border-radius: 8px; overflow: hidden; } @@ -218,9 +220,9 @@ onMounted(async () => { justify-content: space-between; padding: 4px 8px 4px 12px; font-size: 12px; - color: #646a73; - background: #f7f8fa; - border-bottom: 1px solid #e5e7eb; + color: var(--el-text-color-secondary); + background: var(--el-fill-color-lighter); + border-bottom: 1px solid var(--el-border-color); } pre { @@ -229,12 +231,12 @@ pre { overflow-x: auto; font-size: 12.5px; line-height: 1.6; - background: #fbfbfc; + background: var(--el-fill-color-lighter); } .hint { margin: 4px 0 0; font-size: 12px; - color: #8f959e; + color: var(--el-text-color-secondary); } diff --git a/frontend/src/views/Security.vue b/frontend/src/views/Security.vue index 1ada8e5811ef8e49054d40bfec1cc17d8029417f..e5930848b31f18993dc477e8c9b98a78a52d3c5a 100644 --- a/frontend/src/views/Security.vue +++ b/frontend/src/views/Security.vue @@ -294,7 +294,7 @@ onMounted(load) .setting-title { font-size: 16px; font-weight: 650; - color: #1d2129; + color: var(--el-text-color-primary); } .setting-desc { @@ -302,6 +302,6 @@ onMounted(load) max-width: 720px; font-size: 14px; line-height: 1.6; - color: #4e5969; + color: var(--el-text-color-regular); } diff --git a/frontend/src/views/Settings.vue b/frontend/src/views/Settings.vue index 5ada11291463086003c0a9ffba9f9b0798f4ed47..96926e3b75dd76dd17e91c98d39d7e6d5a4f51a5 100644 --- a/frontend/src/views/Settings.vue +++ b/frontend/src/views/Settings.vue @@ -102,6 +102,7 @@ + @@ -113,6 +114,7 @@ import { computed, onMounted, reactive, ref } from 'vue' import { ElMessage } from 'element-plus' import { settingsApi, type GatewaySettings } from '@/api/settings' import AlertSettings from '@/components/AlertSettings.vue' +import BrandingSettings from '@/components/BrandingSettings.vue' import MetricsToken from '@/components/MetricsToken.vue' import SettlementNotice from '@/components/SettlementNotice.vue' import { modelsApi } from '@/api/models' @@ -232,7 +234,7 @@ onMounted(load) .settings-tabs :deep(.el-tabs__header) { margin-bottom: 18px; } .settings-tabs :deep(.el-tabs__item) { font-weight: 500; } .settings-tabs :deep(.el-card) { margin-top: 0 !important; border-radius: 10px; } -.settings-section { padding-bottom: 20px; margin-bottom: 20px; border-bottom: 1px solid #edf0f3; } +.settings-section { padding-bottom: 20px; margin-bottom: 20px; border-bottom: 1px solid var(--el-border-color-lighter); } .settings-section:last-of-type { border-bottom: 0; padding-bottom: 0; margin-bottom: 0; } .settings-section :deep(.el-form-item) { margin-bottom: 18px; } .settings-section :deep(.el-form-item:last-child) { margin-bottom: 0; } @@ -240,9 +242,10 @@ onMounted(load) .advanced-heading h4 { margin-bottom: 4px; } .advanced-rules :deep(.el-collapse-item__header) { font-size: 14px; } .advanced-rules :deep(.el-collapse-item__content) { padding: 14px 0 18px; } -.settings-footer { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin: 24px -20px -20px; padding: 16px 20px; border-top: 1px solid #edf0f3; background: #fafbfc; } -.settings-footer span { font-size: 13px; color: #86909c; } -.settings-footer .changed { color: #b7791f; } +/* 负边距要和 .el-card__body 的 16px 内边距对齐,否则内容区被撑大 4px,悬停时露出滚动条 */ +.settings-footer { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin: 24px -16px -16px; padding: 16px; border-top: 1px solid var(--el-border-color-lighter); background: var(--el-fill-color-lighter); } +.settings-footer span { font-size: 13px; color: var(--el-text-color-secondary); } +.settings-footer .changed { color: var(--el-color-warning-dark-2); } .load-error { margin-bottom: 16px; } @media (max-width: 720px) { .fallback-row { flex-wrap: wrap; } @@ -254,7 +257,7 @@ h4 { margin: 8px 0 12px; font-size: 14px; font-weight: 650; - color: #1c1f23; + color: var(--el-text-color-primary); } h4:not(:first-child) { @@ -287,11 +290,11 @@ h4:not(:first-child) { .threshold-label { font-size: 13px; - color: #474d57; + color: var(--el-text-color-regular); } .fallback-arrow { - color: #8f959e; + color: var(--el-text-color-secondary); } .hint { @@ -299,6 +302,6 @@ h4:not(:first-child) { width: 100%; font-size: 13px; line-height: 1.5; - color: #646a73; + color: var(--el-text-color-secondary); }