diff --git a/CHANGELOG.md b/CHANGELOG.md index b1e65a85498394db516bcca5dcbef11c1f160bf7..3d65352a249872d138e56737d21d145a0c9865a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,16 @@ ## [Unreleased] +### 新增 + +- 新增白标(OEM)定制。设置页多出「品牌」标签页,可以改产品名称、简称、浏览器标题、中英文登录副标题、Logo 地址、favicon 和侧栏宽度(180–320px);登录页、侧边栏、浏览器标签、接入教程里的 Codex 示例、监控示例的任务名以及告警消息前缀都跟着变。留空回落到默认值,页面带预览与「恢复默认」。`GET /api/branding` 免鉴权,只返回这些展示字段,供登录页在登录前取用;后台读写需要平台管理员。 +- 登录页品牌区改为居中;侧边栏配置 Logo 后仍显示产品名称(不再只剩一个徽标),空间不足时省略文字;侧栏宽度可在品牌页调整,窄屏回落原有宽度。 +- **兼容边界**: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..d7804163e317927ae0ae9788565b3f8e4064d17f 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 a470cfc1379faa3987f7a799bddecb6a76254682..43aa704c0992c5cd6ccfa1ce64c7eec7b4326f45 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -3,7 +3,8 @@
-{{ t('branding.subtitle') }}
+{{ t('branding.productNameHint') }}
+{{ t('branding.shortNameHint') }}
+{{ t('branding.pageTitleHint') }}
+{{ t('branding.taglineHint') }}
+{{ t('branding.logoHint') }}
+{{ t('branding.faviconHint') }}
+{{ t('branding.sidebarWidthHint') }}
+{{ previewTagline }}
+{{ t('login.subtitle') }}
+{{ branding.taglineFor(locale.current, t('login.subtitle')) }}