Compare commits

...
Author SHA1 Message Date
Wesley Liddick 26d894ef4f Merge pull request #5137 from Wei-Shaw/fix/upstream-url-path-segment-validation
fix(gateway): 收紧上游 URL 路径片段校验
2026-07-31 16:46:00 +08:00
shaw 017f6bbd5e fix(gateway): 收紧上游 URL 路径片段校验
网关有若干位置会把客户端可控的字符串拼进上游请求的 URL path(Responses
子路径、Gemini 模型名)。此前这些字符串未经校验直接参与拼接,可能改变上游
请求的路径结构,使实际发出的请求与客户端意图不一致。

- 新增 internal/service/upstream_path_guard.go:路径片段闭集允许清单
  (\w + `-` + `.`),拒绝空片段、纯点片段、超长片段与过深后缀
- /responses/*subpath 三条路由入口新增守卫,不可转发的子路径直接 404;
  service 层同时保证不产出不合规后缀,拼接函数再兜底一层
- Gemini AI Studio 原先 5 处重复的 URL 拼接收敛为唯一构造点
  buildGeminiAIStudioModelActionURL(校验模型片段 + action 白名单)
- Gemini native / GetModel handler 增加入口校验;ForwardAIStudioGET 逐片段校验
- Grok video 端点的 request_id 增加片段合规校验

合法子路径(/compact、/compact/detail、/{id}/cancel 形态)与既有模型名行为
不变,通配路由保留。
2026-07-31 16:11:45 +08:00
Wesley Liddick f9d2791693 Merge pull request #5032 from Ricardo-binZzz/fix/release-pricing-fallback-resource
fix(release): include pricing fallback resources
2026-07-31 14:00:07 +08:00
Ricardo-binZzz 105e5c5da3 fix(release): include pricing fallback resources 2026-07-31 13:51:22 +08:00
Wesley Liddick bf0fc03ab7 Merge pull request #5018 from hongheshan-svg/fix/glm-5.2-fallback-pricing
fix(billing): 补上 glm-5.2 兜底价,避免被 glm-5 子串匹配抢走
2026-07-31 12:00:45 +08:00
Wesley Liddick 2be08f3f39 Merge pull request #4913 from jeshica/fix/anthropic-count-tokens-max-tokens
fix: strip max_tokens from Anthropic count tokens
2026-07-31 11:58:28 +08:00
hongheshan-svgandClaude Opus 5 493955f7bd fix(billing): add glm-5.2 fallback pricing to stop glm-5 substring match
glm-5.2 has no entry in the fallback table, so getFallbackPricing falls
through to `strings.Contains(modelLower, "glm-5")` and prices it at
GLM-5 rates ($1.00 in / $3.20 out per MTok) instead of the official
z.ai rates ($1.40 / $4.40) — roughly 27% under.

LiteLLM carries no bare `glm-5.2` key either (only provider-prefixed
`cloudflare/@cf/zai-org/glm-5.2` and `fireworks_ai/.../glm-5p2`, which
the lookup candidates never match), so the request always lands on the
fallback path and the discrepancy shows up directly in usage logs.

Add the glm-5.2 entry (same price as glm-5.1 per docs.z.ai) and match it
before the bare `glm-5` branch, with a note that dotted variants must
precede it. The existing regression test asserting the old glm-5 price
is updated accordingly.

Source: https://docs.z.ai/guides/overview/pricing

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-31 11:49:30 +08:00
zhiyu 53aa5cd247 test: align ModelMappingPreservesOtherFields with max_tokens strip
The count_tokens path now strips max_tokens; this sibling test also
exercises ForwardCountTokens but still asserted max_tokens preservation.
Flip its assertion to expect the field is filtered, matching
CountTokensFiltersGenerationFields.
2026-07-31 11:47:21 +08:00
Wesley Liddick 0a45be17d8 Merge pull request #5033 from Ricardo-binZzz/fix/sub2api-no-new-privileges
fix(deploy): prevent application privilege gains
2026-07-31 11:44:28 +08:00
Wesley Liddick 60f6dc91cf Merge pull request #5115 from zvensmoluya/codex/update-gpt56-luna-terra-pricing
[codex] update GPT-5.6 Luna and Terra pricing
2026-07-31 11:44:21 +08:00
Wesley Liddick 1702ee1362 Merge pull request #5078 from wucm667/fix/issue-5072-subscription-expiry-label
fix(frontend): correct subscription expiry labels
2026-07-31 11:44:07 +08:00
Wesley Liddick c4b461c68c Merge pull request #5063 from lucas-ward/codex/issue-4211
fix(payment): keep subscription plan titles readable
2026-07-31 11:44:00 +08:00
Wesley Liddick 3c387a164d Merge pull request #5060 from alexj11324/codex/passkey-deployment-guidance
fix: clarify passkey deployment guidance
2026-07-31 11:43:53 +08:00
Wesley Liddick e854132a57 Merge pull request #4953 from spongehah/brn-qwen3guard-auxiliary-fields
feat(security-audit): allow Qwen3Guard auxiliary fields
2026-07-31 11:43:47 +08:00
Wesley Liddick a8cd33eead Merge pull request #5048 from wucm667/fix/issue-5041-claude-auto-classifier
fix(anthropic): recognize auto mode classifier
2026-07-31 11:43:39 +08:00
Wesley Liddick 276d9cbd9b Merge pull request #4993 from 17Yuns/fix/smtp-message-format
fix(email): generate standards-compliant SMTP messages
2026-07-31 11:43:32 +08:00
Wesley Liddick 1f8b3a9c60 Merge pull request #5037 from heathermhuang/codex/fix-composite-available-models
fix(channels): show Composite models by platform
2026-07-31 11:43:25 +08:00
Wesley Liddick c9156c1e7f Merge pull request #5053 from wucm667/fix/issue-5015-skip-unschedulable-refresh
fix(account): skip unschedulable token refresh candidates
2026-07-31 11:43:18 +08:00
Wesley Liddick 91850d36e6 Merge pull request #5030 from Ricardo-binZzz/fix/ops-cleanup-success-log-level
fix(logging): record cleanup success at info level
2026-07-31 11:43:11 +08:00
Wesley Liddick 6fa784fdd0 Merge pull request #5118 from Wei-Shaw/fix/openai-proxy-stream-circuit-fail-open
fix(openai): 代理断流熔断改为 fail-open 偏好,修复共用代理部署下的调度不可用
2026-07-31 10:42:24 +08:00
Zven 313121f3f7 test(pricing): update requested Terra cost 2026-07-31 10:02:04 +08:00
Zven 488d3b09ec test(pricing): update Terra billing ratios 2026-07-31 09:55:16 +08:00
Zven b2d895fb8d fix(pricing): update GPT-5.6 Luna and Terra rates 2026-07-31 09:42:46 +08:00
wucm667 fb40211305 fix(frontend): correct subscription expiry labels 2026-07-30 12:47:05 +08:00
wucm667 352b21f4e2 fix(claude): relax marker to tolerate category element in classifier output
Real claude-cli/2.1.220 samples insert <category>...</category> between
</block> and <reason>, breaking the previous literal marker.
Also fix an unchecked type assertion in the test suite.
2026-07-29 23:25:02 +08:00
BayinForge 0ee9ea5765 fix(payment): keep subscription plan titles readable 2026-07-29 21:23:16 +08:00
Zhixuan Jiang 711056f5b7 fix: clarify passkey deployment guidance 2026-07-29 08:58:33 -04:00
wucm667 ac90355a87 fix(account): skip unschedulable token refresh candidates 2026-07-29 18:35:56 +08:00
wucm667 54b1f8f6b3 fix(anthropic): recognize auto mode classifier 2026-07-29 16:55:42 +08:00
Ricardo-binZzz 0010894f99 fix(deploy): prevent application privilege gains 2026-07-29 13:25:05 +08:00
Ricardo-binZzz 0353cdadfe fix(logging): record cleanup success at info level 2026-07-29 13:25:03 +08:00
Heatherm Huang 92dc61d401 fix(channels): show composite models by platform
Expand visible Composite groups into each configured concrete model platform while preserving ordinary group isolation and empty-state behavior.\n\nFixes #4985
2026-07-29 12:32:44 +08:00
17Yuns edac19e87a fix(email): generate standards-compliant SMTP messages 2026-07-28 12:28:46 +08:00
spongehah fc495e087d feat(security-audit): allow Qwen3Guard auxiliary fields 2026-07-27 17:40:11 +08:00
jy.liu efa5a2240d fix: strip max_tokens from Anthropic count tokens 2026-07-26 21:20:37 +08:00
61 changed files with 1669 additions and 170 deletions

No files matched your search

+2
View File
@@ -16,6 +16,8 @@ jobs:
run: |
/bin/bash -n deploy/apple-container.sh
/bin/bash deploy/tests/apple-container-test.sh
/bin/sh deploy/tests/docker-compose-security-test.sh
/bin/sh deploy/tests/docker-runtime-resources-test.sh
/bin/sh deploy/test-caddyfile-cache.sh
test:
+1
View File
@@ -49,6 +49,7 @@ dockers:
use: buildx
extra_files:
- deploy/docker-entrypoint.sh
- backend/resources
build_flag_templates:
- "--platform=linux/amd64"
- "--label=org.opencontainers.image.version={{ .Version }}"
+4
View File
@@ -65,6 +65,7 @@ dockers:
use: buildx
extra_files:
- deploy/docker-entrypoint.sh
- backend/resources
build_flag_templates:
- "--platform=linux/amd64"
- "--label=org.opencontainers.image.version={{ .Version }}"
@@ -80,6 +81,7 @@ dockers:
use: buildx
extra_files:
- deploy/docker-entrypoint.sh
- backend/resources
build_flag_templates:
- "--platform=linux/arm64"
- "--label=org.opencontainers.image.version={{ .Version }}"
@@ -95,6 +97,7 @@ dockers:
use: buildx
extra_files:
- deploy/docker-entrypoint.sh
- backend/resources
build_flag_templates:
- "--platform=linux/amd64"
- "--label=org.opencontainers.image.version={{ .Version }}"
@@ -110,6 +113,7 @@ dockers:
use: buildx
extra_files:
- deploy/docker-entrypoint.sh
- backend/resources
build_flag_templates:
- "--platform=linux/arm64"
- "--label=org.opencontainers.image.version={{ .Version }}"
+2 -1
View File
@@ -42,8 +42,9 @@ RUN addgroup -g 1000 sub2api && \
WORKDIR /app
# Copy pre-built binary from GoReleaser
# Copy the pre-built binary and runtime fallback resources from GoReleaser
COPY sub2api /app/sub2api
COPY --chown=sub2api:sub2api backend/resources /app/resources
# Create data directory
RUN mkdir -p /app/data && chown -R sub2api:sub2api /app
@@ -12,12 +12,11 @@ import (
// AvailableChannelHandler 处理用户侧「可用渠道」查询。
//
// 用户侧接口委托 ChannelService.ListAvailable,并在返回前做三层过滤:
// 用户侧接口委托 ChannelService.ListAvailable,并在返回前做四层过滤:
// 1. 行过滤:只保留状态为 Active 且与当前用户可访问分组有交集的渠道;
// 2. 分组过滤:渠道的 Groups 只保留用户可访问的那些;
// 3. 平台过滤:渠道的 SupportedModels 只保留平台在用户可见 Groups 中出现过的模型,
// 防止"渠道同时挂在 antigravity / anthropic 两个平台的分组上,用户只访问
// antigravity,却看到 anthropic 模型"这类跨平台信息泄漏;
// 3. 平台过滤:普通分组只保留自身平台模型;Composite 分组按渠道已配置的具体模型平台
// 展开。这样既防止普通分组跨平台泄漏,也让 Composite 正确展示其多平台能力;
// 4. 字段白名单:仅返回用户需要的字段(省略 BillingModelSource / RestrictModels
// / 内部 ID / Status 等管理字段)。
type AvailableChannelHandler struct {
@@ -172,19 +171,47 @@ func (h *AvailableChannelHandler) List(c *gin.Context) {
}
// buildPlatformSections 把一个渠道按 visibleGroups 的平台集合拆成有序的 section 列表:
// 每个 section 对应一个平台,只包含该平台的 groups 和 supported_models。
// 每个 section 对应一个具体平台,只包含该平台的 groups 和 supported_models。
//
// Composite 分组可访问渠道中所有已配置的具体平台,因此会被展开到每个有支持模型的
// 平台 section。普通分组仍严格留在自身平台,避免跨平台模型信息泄漏。Composite 渠道
// 尚未配置任何模型时保留 composite section,以便前端继续展示该分组和“未配置模型”状态。
// 输出按 platform 字母序稳定排序,便于前端等效比较与回归测试。
func buildPlatformSections(
ch service.AvailableChannel,
visibleGroups []userAvailableGroup,
) []userChannelPlatformSection {
groupsByPlatform := make(map[string][]userAvailableGroup, 4)
compositeGroups := make([]userAvailableGroup, 0, 1)
for _, g := range visibleGroups {
if g.Platform == "" {
continue
}
if g.Platform == service.PlatformComposite {
compositeGroups = append(compositeGroups, g)
continue
}
groupsByPlatform[g.Platform] = append(groupsByPlatform[g.Platform], g)
}
if len(compositeGroups) > 0 {
modelPlatforms := make(map[string]struct{}, len(ch.SupportedModels))
for i := range ch.SupportedModels {
if platform := ch.SupportedModels[i].Platform; platform != "" {
modelPlatforms[platform] = struct{}{}
}
}
if len(modelPlatforms) == 0 {
groupsByPlatform[service.PlatformComposite] = append(
groupsByPlatform[service.PlatformComposite],
compositeGroups...,
)
} else {
for platform := range modelPlatforms {
groupsByPlatform[platform] = append(groupsByPlatform[platform], compositeGroups...)
}
}
}
if len(groupsByPlatform) == 0 {
return nil
}
@@ -155,3 +155,101 @@ func TestBuildPlatformSections_GroupsByPlatform(t *testing.T) {
require.Len(t, sections[0].SupportedModels, 1)
require.Equal(t, "claude-sonnet-4-6", sections[0].SupportedModels[0].Name)
}
func TestBuildPlatformSections_CompositeGroupExpandsAcrossConfiguredModelPlatforms(t *testing.T) {
anthropicPrice := 3e-6
openAIPrice := 2.5e-6
ch := service.AvailableChannel{
Name: "composite-channel",
SupportedModels: []service.SupportedModel{
{
Name: "claude-sonnet-4-6",
Platform: service.PlatformAnthropic,
Pricing: &service.ChannelModelPricing{InputPrice: &anthropicPrice},
},
{
Name: "gpt-5",
Platform: service.PlatformOpenAI,
Pricing: &service.ChannelModelPricing{InputPrice: &openAIPrice},
},
},
}
visible := []userAvailableGroup{
{ID: 9, Name: "composite", Platform: service.PlatformComposite},
}
sections := buildPlatformSections(ch, visible)
require.Len(t, sections, 2)
require.Equal(t, service.PlatformAnthropic, sections[0].Platform)
require.Equal(t, service.PlatformOpenAI, sections[1].Platform)
for _, section := range sections {
require.Len(t, section.Groups, 1)
require.Equal(t, int64(9), section.Groups[0].ID)
require.Equal(t, service.PlatformComposite, section.Groups[0].Platform)
require.Len(t, section.SupportedModels, 1)
require.Equal(t, section.Platform, section.SupportedModels[0].Platform)
require.NotNil(t, section.SupportedModels[0].Pricing)
}
require.Equal(t, "claude-sonnet-4-6", sections[0].SupportedModels[0].Name)
require.Equal(t, "gpt-5", sections[1].SupportedModels[0].Name)
}
func TestBuildPlatformSections_OrdinaryGroupRemainsPlatformIsolated(t *testing.T) {
ch := service.AvailableChannel{
SupportedModels: []service.SupportedModel{
{Name: "claude-sonnet-4-6", Platform: service.PlatformAnthropic},
{Name: "gpt-5", Platform: service.PlatformOpenAI},
},
}
visible := []userAvailableGroup{
{ID: 1, Name: "anthropic-only", Platform: service.PlatformAnthropic},
}
sections := buildPlatformSections(ch, visible)
require.Len(t, sections, 1)
require.Equal(t, service.PlatformAnthropic, sections[0].Platform)
require.Len(t, sections[0].SupportedModels, 1)
require.Equal(t, "claude-sonnet-4-6", sections[0].SupportedModels[0].Name)
}
func TestBuildPlatformSections_CompositeAndOrdinaryGroupsShareConcreteSection(t *testing.T) {
ch := service.AvailableChannel{
SupportedModels: []service.SupportedModel{
{Name: "claude-sonnet-4-6", Platform: service.PlatformAnthropic},
{Name: "gpt-5", Platform: service.PlatformOpenAI},
},
}
visible := []userAvailableGroup{
{ID: 1, Name: "anthropic-only", Platform: service.PlatformAnthropic},
{ID: 9, Name: "composite", Platform: service.PlatformComposite},
}
sections := buildPlatformSections(ch, visible)
require.Len(t, sections, 2)
require.Equal(t, service.PlatformAnthropic, sections[0].Platform)
require.Equal(t, []int64{1, 9}, []int64{
sections[0].Groups[0].ID,
sections[0].Groups[1].ID,
})
require.Equal(t, service.PlatformOpenAI, sections[1].Platform)
require.Len(t, sections[1].Groups, 1)
require.Equal(t, int64(9), sections[1].Groups[0].ID)
}
func TestBuildPlatformSections_CompositeWithoutModelsKeepsEmptyCompositeSection(t *testing.T) {
visible := []userAvailableGroup{
{ID: 9, Name: "composite", Platform: service.PlatformComposite},
}
sections := buildPlatformSections(service.AvailableChannel{
SupportedModels: []service.SupportedModel{{Name: "invalid-without-platform"}},
}, visible)
require.Len(t, sections, 1)
require.Equal(t, service.PlatformComposite, sections[0].Platform)
require.Len(t, sections[0].Groups, 1)
require.Empty(t, sections[0].SupportedModels)
}
@@ -98,6 +98,12 @@ func (h *GatewayHandler) GeminiV1BetaGetModel(c *gin.Context) {
googleError(c, http.StatusBadRequest, "Missing model in URL")
return
}
// 模型名会被拼进上游 URL 的 path,先在入口校验片段合规性,
// 见 service/upstream_path_guard.go。
if !service.IsSafeGeminiModelPathSegment(modelName) {
googleError(c, http.StatusBadRequest, "Invalid model in URL")
return
}
if resolvedModel, ok := service.ResolvedUpstreamModelFromContext(c.Request.Context()); ok && strings.TrimSpace(resolvedModel) != "" {
modelName = strings.TrimSpace(resolvedModel)
}
@@ -169,6 +175,12 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
googleError(c, http.StatusNotFound, err.Error())
return
}
// URL 里的模型名最终会被拼进上游 /v1beta/models/{model}:{action},
// 先在入口校验片段合规性,见 service/upstream_path_guard.go。
if !service.IsSafeGeminiModelPathSegment(modelName) {
googleError(c, http.StatusBadRequest, "Invalid model in URL")
return
}
if resolvedModel, ok := service.ResolvedUpstreamModelFromContext(c.Request.Context()); ok && strings.TrimSpace(resolvedModel) != "" {
modelName = strings.TrimSpace(resolvedModel)
}
@@ -1407,7 +1407,7 @@ func TestOpenAIResponsesWebSocket_PassthroughTracksModelPerTurn(t *testing.T) {
require.Equal(t, "gpt-5.6-terra", *got.logs[1].UpstreamModel)
require.NotNil(t, got.logs[1].ModelMappingChain)
require.Equal(t, "terra→terra-channel→gpt-5.6-terra", *got.logs[1].ModelMappingChain)
require.InDelta(t, got.logs[1].TotalCost*2, got.logs[0].TotalCost, 1e-12,
require.InDelta(t, got.logs[1].TotalCost*2.5, got.logs[0].TotalCost, 1e-12,
"each turn must be billed with its own channel-mapped model")
}
@@ -1477,7 +1477,7 @@ func TestOpenAIResponsesWebSocket_PassthroughKeepsTurnMappingSnapshot(t *testing
require.Equal(t, "gpt-5.6-terra", *got.logs[1].UpstreamModel)
require.NotNil(t, got.logs[1].ModelMappingChain)
require.Equal(t, "sol→gpt-5.6-terra", *got.logs[1].ModelMappingChain)
require.InDelta(t, got.logs[1].TotalCost*2, got.logs[0].TotalCost, 1e-12,
require.InDelta(t, got.logs[1].TotalCost*2.5, got.logs[0].TotalCost, 1e-12,
"the next turn must use the updated channel mapping")
}
@@ -1506,7 +1506,7 @@ func TestOpenAIResponsesWebSocket_CtxPoolAppliesPerTurnMappingAndPreservesReques
require.Equal(t, "gpt-5.6-terra", got.logs[1].RequestedModel)
require.NotNil(t, got.logs[1].ModelMappingChain)
require.Equal(t, "gpt-5.6-terra→gpt-5.6-sol", *got.logs[1].ModelMappingChain)
require.InDelta(t, 20e-6, got.logs[1].TotalCost, 1e-12,
require.InDelta(t, 16e-6, got.logs[1].TotalCost, 1e-12,
"BillingModelSourceRequested must use the client model before channel mapping")
}
+5
View File
@@ -611,6 +611,11 @@ func BuildVideoURLWithValidator(baseURL, requestID string, validator BaseURLVali
if requestID == "" {
return "", fmt.Errorf("request id is required")
}
// requestID 由客户端提供并拼进上游 URL 的 path。PathEscape 之外再要求它不是
// 纯点片段、不含控制字符,保证它只能是一个普通的路径片段。
if requestID == "." || requestID == ".." || strings.ContainsAny(requestID, "\x00\r\n") {
return "", fmt.Errorf("invalid request id")
}
return validatedBaseURL + "/videos/" + url.PathEscape(requestID), nil
}
@@ -1107,6 +1107,7 @@ func (r *accountRepository) ListOAuthRefreshCandidatePage(ctx context.Context, o
SELECT id
FROM accounts
WHERE deleted_at IS NULL
AND schedulable = TRUE
AND platform = ANY($1)
AND id > $2`
if options.ActiveOnly {
@@ -327,6 +327,14 @@ func (s *AccountRepoSuite) TestListOAuthRefreshCandidatePage_GrokCursorAndExclus
"expires_at": now.Add(30 * time.Minute).Format(time.RFC3339),
},
})
unschedulable := mustCreateAccount(s.T(), s.client, &service.Account{
Name: "grok-oauth-unschedulable-excluded",
Platform: service.PlatformGrok,
Type: service.AccountTypeOAuth,
Status: service.StatusActive,
Credentials: map[string]any{"refresh_token": "refresh-unschedulable"},
})
s.Require().NoError(s.client.Account.UpdateOneID(unschedulable.ID).SetSchedulable(false).Exec(s.ctx))
mustCreateAccount(s.T(), s.client, &service.Account{
Name: "grok-api-key-excluded",
Platform: service.PlatformGrok,
@@ -386,6 +394,7 @@ func (s *AccountRepoSuite) TestListOAuthRefreshCandidatePage_GrokCursorAndExclus
first := firstPage.Accounts
s.Require().Len(first, 2)
s.Require().Equal([]int64{valid1.ID, valid2.ID}, []int64{first[0].ID, first[1].ID})
s.Require().NotContains([]int64{first[0].ID, first[1].ID}, unschedulable.ID)
options.AfterID = first[len(first)-1].ID
secondPage, err := s.repo.ListOAuthRefreshCandidatePage(s.ctx, options)
@@ -276,6 +276,8 @@ func TestAccountRepository_ListOAuthRefreshCandidatePage_SQLFilter(t *testing.T)
normalized := normalizeSQLWhitespace(capturedSQL)
require.Contains(t, normalized, "deleted_at IS NULL")
require.Contains(t, normalized, "schedulable = TRUE",
"permanently unschedulable accounts must not remain OAuth refresh candidates")
require.Contains(t, normalized, "status = 'active'")
// setup-token 的 access_token 同为 8h 短期令牌,必须与 oauth 一起纳入后台刷新候选
require.Contains(t, normalized, "type IN ('oauth', 'setup-token')")
@@ -86,19 +86,13 @@ func NormalizeCategory(value string) string {
}
func ParseQwen3Guard(content string, enabledScanners []string) (*NormalizedResult, error) {
lines := make([]string, 0, 2)
for _, line := range strings.Split(strings.ReplaceAll(content, "\r\n", "\n"), "\n") {
line = strings.TrimSpace(line)
if line != "" {
lines = append(lines, line)
}
}
if len(lines) != 2 {
return nil, &GuardError{Code: ErrorCodeInvalidResponse, Retryable: false}
}
var safety string
var categoryLine string
for _, line := range lines {
for _, line := range strings.Split(strings.ReplaceAll(content, "\r\n", "\n"), "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
}
lower := strings.ToLower(line)
switch {
case strings.HasPrefix(lower, "safety:"):
@@ -112,7 +106,7 @@ func ParseQwen3Guard(content string, enabledScanners []string) (*NormalizedResul
}
categoryLine = strings.TrimSpace(line[len("categories:"):])
default:
return nil, &GuardError{Code: ErrorCodeInvalidResponse}
// Auxiliary Guard fields, such as Refusal, do not affect audit decisions.
}
}
switch strings.ToLower(safety) {
@@ -22,7 +22,7 @@ func TestParseQwen3GuardStrictAndPolicy(t *testing.T) {
{"unsafe", "Safety: Unsafe\nCategories: Jailbreak", AllScannerIDs, EventCritical, ActionBlock, false},
{"unknown unsafe", "Safety: Unsafe\nCategories: Future Risk", AllScannerIDs, EventCritical, ActionBlock, false},
{"disabled unsafe warns", "Safety: Unsafe\nCategories: Violent", []string{"PII"}, EventFlag, ActionWarn, false},
{"extra explanation", "Safety: Safe\nCategories: None\nThis is safe", AllScannerIDs, "", "", true},
{"extra explanation", "Safety: Safe\nCategories: None\nThis is safe", AllScannerIDs, EventPass, ActionAllow, false},
{"duplicate", "Safety: Safe\nSafety: Safe", AllScannerIDs, "", "", true},
{"duplicate categories", "Safety: Safe\nCategories: None\nCategories: PII", AllScannerIDs, "", "", true},
{"missing categories", "Safety: Safe\n", AllScannerIDs, "", "", true},
@@ -42,6 +42,18 @@ func TestParseQwen3GuardStrictAndPolicy(t *testing.T) {
}
}
func TestParseQwen3GuardIgnoresAuxiliaryResponseFields(t *testing.T) {
result, err := ParseQwen3Guard("Safety: Unsafe\nCategories: Jailbreak\nRefusal: No", AllScannerIDs)
require.NoError(t, err)
require.Equal(t, "Unsafe", result.Safety)
require.Equal(t, []string{"jailbreak"}, result.Categories)
serialized, err := json.Marshal(result)
require.NoError(t, err)
require.NotContains(t, string(serialized), "Refusal")
require.NotContains(t, string(serialized), "No")
}
func TestQwen3GuardOfficialCategoriesAliasesAndUnknownAreStable(t *testing.T) {
official := "Violent, Non-violent Illegal Acts, Sexual Content or Sexual Acts, PII, Suicide & Self-Harm, Unethical Acts, Politically Sensitive Topics, Copyright Violation, Jailbreak"
result, err := ParseQwen3Guard("Safety: Unsafe\nCategories: "+official, AllScannerIDs)
+23 -4
View File
@@ -153,6 +153,25 @@ func RegisterGatewayRoutes(
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate)
c.JSON(http.StatusNotFound, gin.H{"error": gin.H{"type": "not_found_error", "message": "Videos API is not supported for this platform"}})
}
// /responses/*subpath 的子路径会被转发到上游同名端点之后,因此在入口就拒掉
// 不可转发的子路径,不让它进入调度与转发流程。可转发的判定见
// service.IsForwardableOpenAIResponsesRequestPath 及 upstream_path_guard.go。
guardResponsesSubpath := func(next gin.HandlerFunc) gin.HandlerFunc {
return func(c *gin.Context) {
if !service.IsForwardableOpenAIResponsesRequestPath(c) {
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalPolicyDenied)
c.AbortWithStatusJSON(http.StatusNotFound, gin.H{
"error": gin.H{
"type": "not_found_error",
"message": "Unsupported responses subpath",
},
})
return
}
next(c)
}
}
// API网关(Claude API兼容)
gateway := r.Group("/v1")
gateway.Use(bodyLimit)
@@ -190,13 +209,13 @@ func RegisterGatewayRoutes(
}
h.Gateway.Responses(c)
})
gateway.POST("/responses/*subpath", func(c *gin.Context) {
gateway.POST("/responses/*subpath", guardResponsesSubpath(func(c *gin.Context) {
if isOpenAIResponsesCompatibleGatewayPlatform(c) {
h.OpenAIGateway.Responses(c)
return
}
h.Gateway.Responses(c)
})
}))
gateway.POST("/alpha/search", textBodyLimit, h.OpenAIGateway.AlphaSearch)
gateway.GET("/responses", func(c *gin.Context) {
h.OpenAIGateway.ResponsesWebSocket(c)
@@ -269,7 +288,7 @@ func RegisterGatewayRoutes(
h.Gateway.Responses(c)
}
r.POST("/responses", bodyLimit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), compositeTarget, requireGroupAnthropic, responsesHandler)
r.POST("/responses/*subpath", bodyLimit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), compositeTarget, requireGroupAnthropic, responsesHandler)
r.POST("/responses/*subpath", bodyLimit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), compositeTarget, requireGroupAnthropic, guardResponsesSubpath(responsesHandler))
r.POST("/alpha/search", textBodyLimit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), compositeTarget, requireGroupAnthropic, h.OpenAIGateway.AlphaSearch)
r.GET("/responses", bodyLimit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), compositeTarget, requireGroupAnthropic, func(c *gin.Context) {
h.OpenAIGateway.ResponsesWebSocket(c)
@@ -282,7 +301,7 @@ func RegisterGatewayRoutes(
codexDirect.POST("/realtime/calls", h.OpenAIGateway.Live)
codexDirect.GET("/:call_id", h.OpenAIGateway.LiveSideband)
codexDirect.POST("/responses", responsesHandler)
codexDirect.POST("/responses/*subpath", responsesHandler)
codexDirect.POST("/responses/*subpath", guardResponsesSubpath(responsesHandler))
codexDirect.POST("/alpha/search", textBodyLimit, h.OpenAIGateway.AlphaSearch)
codexDirect.GET("/responses", func(c *gin.Context) {
h.OpenAIGateway.ResponsesWebSocket(c)
@@ -333,6 +333,33 @@ func TestGatewayRoutesGrokAllowsCLICompatibilityEntrypoints(t *testing.T) {
}
}
// TestGatewayRoutesResponsesSubpathRejectsNonConformingSubpaths 端到端锁定不变式:
// /responses/*subpath 的子路径会被转发到上游同名端点之后,因此不合规的子路径必须
// 在入口就被拒绝,不得进入调度与转发流程。
func TestGatewayRoutesResponsesSubpathRejectsNonConformingSubpaths(t *testing.T) {
router := newGatewayRoutesTestRouter()
for _, path := range []string{
"/v1/responses/../../x/y",
"/v1/responses/..%2f..%2fx/y",
"/v1/responses/%2e%2e/%2e%2e/x",
"/responses/%2e%2e%2fx",
"/backend-api/codex/responses/..%2f..%2fx",
`/v1/responses/..\..\x`,
"/v1/responses/%3fa=b",
"/v1/responses/x%23frag",
"/v1/responses/compact%2f..",
} {
req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(`{"model":"gpt-5"}`))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
require.Equal(t, http.StatusNotFound, w.Code, "path=%s must be rejected at the edge", path)
require.Contains(t, w.Body.String(), "Unsupported responses subpath", "path=%s", path)
}
}
func TestGatewayRoutesOpenAICountTokensPathIsRegistered(t *testing.T) {
router := newGatewayRoutesTestRouter(service.PlatformOpenAI)
@@ -1209,8 +1209,10 @@ func (s *AccountTestService) buildGeminiAPIKeyRequest(ctx context.Context, accou
}
// Use streamGenerateContent for real-time feedback
fullURL := fmt.Sprintf("%s/v1beta/models/%s:streamGenerateContent?alt=sse",
strings.TrimRight(normalizedBaseURL, "/"), modelID)
fullURL, err := buildGeminiAIStudioModelActionURL(normalizedBaseURL, modelID, "streamGenerateContent", true)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, "POST", fullURL, bytes.NewReader(payload))
if err != nil {
@@ -1246,7 +1248,10 @@ func (s *AccountTestService) buildGeminiOAuthRequest(ctx context.Context, accoun
if err != nil {
return nil, err
}
fullURL := fmt.Sprintf("%s/v1beta/models/%s:streamGenerateContent?alt=sse", strings.TrimRight(normalizedBaseURL, "/"), modelID)
fullURL, err := buildGeminiAIStudioModelActionURL(normalizedBaseURL, modelID, "streamGenerateContent", true)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, fullURL, bytes.NewReader(payload))
if err != nil {
+28 -17
View File
@@ -316,27 +316,27 @@ func (s *BillingService) initFallbackPricing() {
LongContextOutputMultiplier: openAIGPT54LongContextOutputMultiplier,
}
s.fallbackPrices["gpt-5.6-terra"] = &ModelPricing{
InputPricePerToken: 2.5e-6,
InputPricePerTokenPriority: 5e-6,
OutputPricePerToken: 15e-6,
OutputPricePerTokenPriority: 30e-6,
CacheCreationPricePerToken: 3.125e-6,
CacheCreationPricePerTokenPriority: 6.25e-6,
CacheReadPricePerToken: 0.25e-6,
CacheReadPricePerTokenPriority: 0.5e-6,
InputPricePerToken: 2e-6,
InputPricePerTokenPriority: 4e-6,
OutputPricePerToken: 12e-6,
OutputPricePerTokenPriority: 24e-6,
CacheCreationPricePerToken: 2.5e-6,
CacheCreationPricePerTokenPriority: 5e-6,
CacheReadPricePerToken: 0.2e-6,
CacheReadPricePerTokenPriority: 0.4e-6,
LongContextInputThreshold: openAIGPT54LongContextInputThreshold,
LongContextInputMultiplier: openAIGPT54LongContextInputMultiplier,
LongContextOutputMultiplier: openAIGPT54LongContextOutputMultiplier,
}
s.fallbackPrices["gpt-5.6-luna"] = &ModelPricing{
InputPricePerToken: 1e-6,
InputPricePerTokenPriority: 2e-6,
OutputPricePerToken: 6e-6,
OutputPricePerTokenPriority: 12e-6,
CacheCreationPricePerToken: 1.25e-6,
CacheCreationPricePerTokenPriority: 2.5e-6,
CacheReadPricePerToken: 0.1e-6,
CacheReadPricePerTokenPriority: 0.2e-6,
InputPricePerToken: 0.2e-6,
InputPricePerTokenPriority: 0.4e-6,
OutputPricePerToken: 1.2e-6,
OutputPricePerTokenPriority: 2.4e-6,
CacheCreationPricePerToken: 0.25e-6,
CacheCreationPricePerTokenPriority: 0.5e-6,
CacheReadPricePerToken: 0.02e-6,
CacheReadPricePerTokenPriority: 0.04e-6,
LongContextInputThreshold: openAIGPT54LongContextInputThreshold,
LongContextInputMultiplier: openAIGPT54LongContextInputMultiplier,
LongContextOutputMultiplier: openAIGPT54LongContextOutputMultiplier,
@@ -403,6 +403,13 @@ func (s *BillingService) initFallbackPricing() {
// Source: https://docs.z.ai/guides/overview/pricing (USD per 1M tokens)
// 注意:CacheReadPricePerToken 即"缓存命中"价格,CacheCreationPricePerToken 留空(智谱未公开写入价,按 0 处理)。
// GLM-4.6 与 GLM-4.5 在 z.ai 国际版上定价一致;GLM-4.5 国内按 ¥0.8/¥2,汇率换算后约 $0.112/$0.28,与国际版 $0.6/$2.2 不同,本分支采用国际版 USD 口径与现有 Claude/GPT 一致。
// GLM-5.2 与 GLM-5.1 在 z.ai 上同价。
s.fallbackPrices["glm-5.2"] = &ModelPricing{
InputPricePerToken: 1.4e-6, // $1.40 per MTok
OutputPricePerToken: 4.4e-6, // $4.40 per MTok
CacheReadPricePerToken: 0.26e-6,
SupportsCacheBreakdown: false,
}
s.fallbackPrices["glm-5.1"] = &ModelPricing{
InputPricePerToken: 1.4e-6, // $1.40 per MTok
OutputPricePerToken: 4.4e-6, // $4.40 per MTok
@@ -670,8 +677,12 @@ func (s *BillingService) getFallbackPricing(model string) *ModelPricing {
// 匹配策略:长 key 优先(具体模型 → 系列 / 厂商),未知型号不回退以避免误计价。
// 与 DeepSeek 一样采用"白名单"语义:未在本表命中的国产模型 alias 一律不返回兜底价。
// 智谱 GLM(z.ai 公开 SKU:glm-5.1 / glm-5 / glm-5-turbo / glm-4.7 / glm-4.6 / glm-4.5 等)
// 智谱 GLM(z.ai 公开 SKU:glm-5.2 / glm-5.1 / glm-5 / glm-5-turbo / glm-4.7 / glm-4.6 / glm-4.5 等)
// 匹配顺序:先判别最高 tier,再依次降级。
// 注意:带小数点的型号必须排在裸 "glm-5" 之前,否则会被 strings.Contains 抢走。
if strings.Contains(modelLower, "glm-5.2") {
return s.fallbackPrices["glm-5.2"]
}
if strings.Contains(modelLower, "glm-5.1") {
return s.fallbackPrices["glm-5.1"]
}
@@ -158,17 +158,19 @@ func TestGetModelPricing_FallbackWarnPerModelNotGlobal(t *testing.T) {
require.Equal(t, 0, strings.Count(out, "model: GLM-5.2"), out) // 大写经 ToLower 归一,不应单独成行
}
// 回归:glm-5.2 仍解析到 glm-5 兜底价(计费金额不变,防止日志改动掩盖未来计费回归)。
func TestGetModelPricing_GLM52FallsBackToGLM5Price(t *testing.T) {
// 回归:glm-5.2 必须命中自己的兜底价,不能被 strings.Contains("glm-5") 抢成 glm-5 价。
// 历史 bug:兜底表缺 glm-5.2 条目,使用记录按 $1.00/$3.20 计费,比官方 $1.40/$4.40 少收约 27%。
func TestGetModelPricing_GLM52UsesOwnPrice(t *testing.T) {
svc := newTestBillingService()
got, err := svc.GetModelPricing("glm-5.2")
require.NoError(t, err)
require.NotNil(t, got)
// glm-5 base:Input 1e-6 / Output 3.2e-6(见 TestGetFallbackPricing_FamilyMatching)。
require.InDelta(t, 1e-6, got.InputPricePerToken, 1e-12)
require.InDelta(t, 3.2e-6, got.OutputPricePerToken, 1e-12)
// 官方 z.ai 口径:与 glm-5.1 同价(见 TestGetFallbackPricing_FamilyMatching)。
require.InDelta(t, 1.4e-6, got.InputPricePerToken, 1e-12)
require.InDelta(t, 4.4e-6, got.OutputPricePerToken, 1e-12)
require.InDelta(t, 0.26e-6, got.CacheReadPricePerToken, 1e-12)
}
func TestGetModelPricing_UnknownClaudeModelFallsBackToSonnet(t *testing.T) {
@@ -489,6 +491,13 @@ func TestGetFallbackPricing_FamilyMatching(t *testing.T) {
},
// ---- 智谱 GLM(z.ai USD 口径)----
{
name: "glm 5.2 flagship",
model: "glm-5.2",
expectedInput: 1.4e-6,
expectedOutput: floatPtr(4.4e-6),
expectedCacheRead: floatPtr(0.26e-6),
},
{
name: "glm 5.1 flagship",
model: "glm-5.1",
@@ -572,7 +581,7 @@ func TestGetFallbackPricing_FamilyMatching(t *testing.T) {
expectedInput: 0.1e-6,
expectedOutput: floatPtr(0.1e-6),
},
// 关键:5.1 必须先于 5 匹配(避免被 glm-5 抢走)
// 关键:5.1 / 5.2 必须先于 5 匹配(避免被 glm-5 抢走)
{
name: "glm 5.1 vs glm 5 ordering (verbatim 5.1)",
model: "glm-5.1",
@@ -580,6 +589,13 @@ func TestGetFallbackPricing_FamilyMatching(t *testing.T) {
expectedOutput: floatPtr(4.4e-6),
expectedCacheRead: floatPtr(0.26e-6),
},
{
name: "glm 5.2 vs glm 5 ordering (verbatim 5.2)",
model: "glm-5.2",
expectedInput: 1.4e-6, // = glm-5.2 价格(不是 glm-5 的 1e-6)
expectedOutput: floatPtr(4.4e-6),
expectedCacheRead: floatPtr(0.26e-6),
},
{
name: "glm 4.5-air vs glm 4.5 ordering",
model: "glm-4.5-air",
@@ -48,9 +48,14 @@ var claudeCodeSystemPrompts = []string{
}
const (
// These markers identify Claude Code's official security-monitor classifier
// request without coupling validation to every wording change in the prompt.
claudeCodeSecurityMonitorPromptPrefix = "You are a security monitor for autonomous AI coding agents."
claudeCodeSecurityMonitorPromptMinLen = 10_000
// claudeCodeBillingHeaderPrefix 是 Claude Code 在 system 数组首块注入的计费归因块前缀。
// 该块存在于所有真实 Claude Code CLI 请求中(含安全监视器等无身份 prose 的子请求),
// 格式固定、不随提示词改版漂移,是比身份 prose 更稳定的客户端标识。
// 大多数真实 CLI 请求(含部分无身份 prose 的子请求)会携带该块;不携带该块的
// 固定官方辅助请求由独立规则识别。该格式比身份 prose 更稳定。
// 生成见 gateway_billing_block.go;同类识别见 pkg/apicompat/anthropic_to_responses.go。
claudeCodeBillingHeaderPrefix = "x-anthropic-billing-header"
// claudeCodeEntrypointMarker 标识计费块携带入口归因字段。不绑定具体入口值
@@ -167,6 +172,10 @@ func (v *ClaudeCodeValidator) hasClaudeCodeSystemPrompt(body map[string]any) boo
return false
}
if isClaudeCodeSecurityMonitorPrompt(systemEntries) {
return true
}
// 检查每个 system entry
for _, entry := range systemEntries {
entryMap, ok := entry.(map[string]any)
@@ -196,6 +205,46 @@ func (v *ClaudeCodeValidator) hasClaudeCodeSystemPrompt(body map[string]any) boo
return false
}
func isClaudeCodeSecurityMonitorPrompt(systemEntries []any) bool {
if len(systemEntries) != 1 {
return false
}
entry, ok := systemEntries[0].(map[string]any)
if !ok {
return false
}
entryType, ok := entry["type"].(string)
if !ok || entryType != "text" {
return false
}
text, ok := entry["text"].(string)
if !ok || len(text) < claudeCodeSecurityMonitorPromptMinLen ||
!strings.HasPrefix(text, claudeCodeSecurityMonitorPromptPrefix) {
return false
}
markers := []string{
"## Threat Model",
"- `<transcript>`:",
"## HARD BLOCK",
"## SOFT BLOCK",
"## Classification Process",
"## Output Format",
"<block>yes</block>",
"<block>no</block>",
}
for _, marker := range markers {
if !strings.Contains(text, marker) {
return false
}
}
return true
}
// bestSimilarityScore 计算文本与所有 Claude Code 模板的最佳相似度
func (v *ClaudeCodeValidator) bestSimilarityScore(text string) float64 {
normalizedText := normalizePrompt(text)
@@ -5,6 +5,7 @@ import (
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
@@ -135,6 +136,152 @@ func TestClaudeCodeValidator_BillingBlockRecognizedWithoutIdentityPrompt(t *test
require.True(t, ok)
}
func TestClaudeCodeValidator_SecurityMonitorWithoutBillingBlock(t *testing.T) {
monitorPrompt, err := os.ReadFile("testdata/security_monitor_system_prompt.txt")
require.NoError(t, err)
validHeaders := map[string]string{
"User-Agent": "claude-cli/2.1.220 (external, cli)",
"X-App": "cli",
"anthropic-beta": "claude-code-20250219",
"anthropic-version": "2023-06-01",
}
validBody := func(prompt string) map[string]any {
return map[string]any{
"model": "claude-haiku-4-5-20251001",
"system": []any{
map[string]any{"type": "text", "text": prompt},
},
"metadata": map[string]any{"user_id": claudeCodeMetadataUserIDJSON},
}
}
tests := []struct {
name string
headers map[string]string
body map[string]any
wantAccept bool
}{
{
name: "official classifier request",
headers: validHeaders,
body: validBody(string(monitorPrompt)),
wantAccept: true,
},
{
name: "classifier output with category element",
headers: validHeaders,
body: validBody(strings.Replace(
string(monitorPrompt),
"<block>yes</block><reason>",
"<block>yes</block><category>Exact BLOCK Rule Name</category><reason>",
1,
)),
wantAccept: true,
},
{
name: "non-Claude user agent",
headers: map[string]string{
"User-Agent": "curl/8.0.0",
"X-App": "cli",
"anthropic-beta": "claude-code-20250219",
"anthropic-version": "2023-06-01",
},
body: validBody(string(monitorPrompt)),
},
{
name: "missing X-App",
headers: map[string]string{
"User-Agent": validHeaders["User-Agent"],
"anthropic-beta": validHeaders["anthropic-beta"],
"anthropic-version": validHeaders["anthropic-version"],
},
body: validBody(string(monitorPrompt)),
},
{
name: "missing anthropic-beta",
headers: map[string]string{
"User-Agent": validHeaders["User-Agent"],
"X-App": validHeaders["X-App"],
"anthropic-version": validHeaders["anthropic-version"],
},
body: validBody(string(monitorPrompt)),
},
{
name: "missing anthropic-version",
headers: map[string]string{
"User-Agent": validHeaders["User-Agent"],
"X-App": validHeaders["X-App"],
"anthropic-beta": validHeaders["anthropic-beta"],
},
body: validBody(string(monitorPrompt)),
},
{
name: "missing metadata",
headers: validHeaders,
body: map[string]any{
"model": "claude-haiku-4-5-20251001",
"system": []any{map[string]any{"type": "text", "text": string(monitorPrompt)}},
},
},
{
name: "invalid metadata user ID",
headers: validHeaders,
body: func() map[string]any {
body := validBody(string(monitorPrompt))
body["metadata"] = map[string]any{"user_id": "invalid"}
return body
}(),
},
{
name: "unrelated prompt",
headers: validHeaders,
body: validBody("You are a different security classifier for coding agents."),
wantAccept: false,
},
{
name: "opening sentence alone",
headers: validHeaders,
body: validBody(claudeCodeSecurityMonitorPromptPrefix),
wantAccept: false,
},
{
name: "opening sentence plus arbitrary altered suffix",
headers: validHeaders,
body: validBody(claudeCodeSecurityMonitorPromptPrefix + "\n\n" +
strings.Repeat("This is arbitrary altered classifier content. ", 300)),
wantAccept: false,
},
{
name: "multiple system entries without billing block",
headers: validHeaders,
body: func() map[string]any {
body := validBody(string(monitorPrompt))
system, ok := body["system"].([]any)
require.True(t, ok)
body["system"] = append(system, map[string]any{
"type": "text",
"text": "Additional unrelated system content.",
})
return body
}(),
wantAccept: false,
},
}
validator := NewClaudeCodeValidator()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "http://example.com/v1/messages", nil)
for name, value := range tt.headers {
req.Header.Set(name, value)
}
require.Equal(t, tt.wantAccept, validator.Validate(req, tt.body))
})
}
}
func TestClaudeCodeValidator_BillingBlockVSCodeEntrypointRecognized(t *testing.T) {
// 回归:Claude Code 在 VSCode 扩展内运行时,计费块入口为 cc_entrypoint=claude-vscode
// 而非 cli。其安全监视器子请求同样不携带身份 prose,此前写死 cc_entrypoint=cli 的
+111
View File
@@ -0,0 +1,111 @@
package service
import (
"bytes"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"mime"
"mime/quotedprintable"
"net/mail"
"strings"
"time"
)
type smtpMessage struct {
envelopeFrom string
envelopeTo string
data []byte
}
func buildSMTPMessage(config *SMTPConfig, to, subject, body string) (smtpMessage, error) {
if config == nil {
return smtpMessage{}, errors.New("missing SMTP configuration")
}
fromAddress, err := parseSMTPAddress(config.From, "from")
if err != nil {
return smtpMessage{}, err
}
recipientAddress, err := parseSMTPAddress(to, "recipient")
if err != nil {
return smtpMessage{}, err
}
messageID, err := generateEmailMessageID(fromAddress.Address, config.Host)
if err != nil {
return smtpMessage{}, fmt.Errorf("generate message ID: %w", err)
}
fromName := sanitizeEmailHeader(config.FromName)
if strings.TrimSpace(fromName) == "" {
fromName = fromAddress.Name
}
fromHeader := (&mail.Address{
Name: fromName,
Address: fromAddress.Address,
}).String()
toHeader := (&mail.Address{
Name: recipientAddress.Name,
Address: recipientAddress.Address,
}).String()
subjectHeader := mime.QEncoding.Encode("UTF-8", sanitizeEmailHeader(subject))
var message bytes.Buffer
fmt.Fprintf(&message, "From: %s\r\n", fromHeader)
fmt.Fprintf(&message, "To: %s\r\n", toHeader)
fmt.Fprintf(&message, "Date: %s\r\n", time.Now().UTC().Format(time.RFC1123Z))
fmt.Fprintf(&message, "Message-ID: %s\r\n", messageID)
fmt.Fprintf(&message, "Subject: %s\r\n", subjectHeader)
fmt.Fprint(&message, "MIME-Version: 1.0\r\n"+
"Content-Type: text/html; charset=UTF-8\r\n"+
"Content-Transfer-Encoding: quoted-printable\r\n\r\n")
bodyWriter := quotedprintable.NewWriter(&message)
if _, err := bodyWriter.Write([]byte(body)); err != nil {
return smtpMessage{}, fmt.Errorf("encode email body: %w", err)
}
if err := bodyWriter.Close(); err != nil {
return smtpMessage{}, fmt.Errorf("close email body encoder: %w", err)
}
return smtpMessage{
envelopeFrom: fromAddress.Address,
envelopeTo: recipientAddress.Address,
data: message.Bytes(),
}, nil
}
func parseSMTPAddress(value, field string) (*mail.Address, error) {
if strings.ContainsAny(value, "\r\n") {
return nil, fmt.Errorf("invalid SMTP %s address: contains a line break", field)
}
cleaned := strings.TrimSpace(value)
address, err := mail.ParseAddress(cleaned)
if err != nil || strings.TrimSpace(address.Address) == "" {
if err == nil {
err = fmt.Errorf("address is empty")
}
return nil, fmt.Errorf("invalid SMTP %s address: %w", field, err)
}
return address, nil
}
func generateEmailMessageID(fromAddress, smtpHost string) (string, error) {
randomID := make([]byte, 16)
if _, err := rand.Read(randomID); err != nil {
return "", err
}
domain := strings.TrimSpace(sanitizeEmailHeader(smtpHost))
if at := strings.LastIndexByte(fromAddress, '@'); at >= 0 && at < len(fromAddress)-1 {
domain = fromAddress[at+1:]
}
domain = strings.Trim(domain, "[]<>")
if domain == "" {
domain = "localhost"
}
return fmt.Sprintf("<%s@%s>", hex.EncodeToString(randomID), domain), nil
}
@@ -0,0 +1,117 @@
//go:build unit
package service
import (
"bytes"
"io"
"mime"
"mime/quotedprintable"
"net/mail"
"regexp"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
func TestBuildSMTPMessageProducesStandardsCompliantMIME(t *testing.T) {
config := &SMTPConfig{
Host: "smtp.example.com",
From: "reply@example.com",
FromName: "Sub2API 通知",
}
body := "<html>\n<body>验证码:123456 &amp; ready</body>\n</html>"
message, err := buildSMTPMessage(config, "User <user@example.net>", "邮箱验证码", body)
require.NoError(t, err)
require.Equal(t, "reply@example.com", message.envelopeFrom)
require.Equal(t, "user@example.net", message.envelopeTo)
parsed, err := mail.ReadMessage(bytes.NewReader(message.data))
require.NoError(t, err)
from, err := mail.ParseAddress(parsed.Header.Get("From"))
require.NoError(t, err)
require.Equal(t, "Sub2API 通知", from.Name)
require.Equal(t, "reply@example.com", from.Address)
recipient, err := mail.ParseAddress(parsed.Header.Get("To"))
require.NoError(t, err)
require.Equal(t, "User", recipient.Name)
require.Equal(t, "user@example.net", recipient.Address)
decodedSubject, err := new(mime.WordDecoder).DecodeHeader(parsed.Header.Get("Subject"))
require.NoError(t, err)
require.Equal(t, "邮箱验证码", decodedSubject)
require.NotEmpty(t, parsed.Header.Get("Date"))
_, err = mail.ParseDate(parsed.Header.Get("Date"))
require.NoError(t, err)
require.Regexp(t, regexp.MustCompile(`^<[0-9a-f]{32}@example\.com>$`), parsed.Header.Get("Message-ID"))
require.Equal(t, "1.0", parsed.Header.Get("MIME-Version"))
require.Equal(t, "quoted-printable", parsed.Header.Get("Content-Transfer-Encoding"))
mediaType, params, err := mime.ParseMediaType(parsed.Header.Get("Content-Type"))
require.NoError(t, err)
require.Equal(t, "text/html", mediaType)
require.Equal(t, "UTF-8", params["charset"])
decodedBody, err := io.ReadAll(quotedprintable.NewReader(parsed.Body))
require.NoError(t, err)
require.Equal(t, strings.ReplaceAll(body, "\n", "\r\n"), string(decodedBody))
}
func TestBuildSMTPMessagePreventsHeaderInjection(t *testing.T) {
config := &SMTPConfig{
Host: "smtp.example.com",
From: "reply@example.com",
FromName: "Sender\r\nBcc: hidden@example.com",
}
message, err := buildSMTPMessage(config, "user@example.net", "Subject\r\nCc: hidden@example.com", "body")
require.NoError(t, err)
parsed, err := mail.ReadMessage(bytes.NewReader(message.data))
require.NoError(t, err)
require.Empty(t, parsed.Header.Get("Bcc"))
require.Empty(t, parsed.Header.Get("Cc"))
decodedSubject, err := new(mime.WordDecoder).DecodeHeader(parsed.Header.Get("Subject"))
require.NoError(t, err)
require.Equal(t, "SubjectCc: hidden@example.com", decodedSubject)
}
func TestBuildSMTPMessageRejectsInvalidConfiguration(t *testing.T) {
_, err := buildSMTPMessage(nil, "user@example.net", "subject", "body")
require.ErrorContains(t, err, "missing SMTP configuration")
_, err = buildSMTPMessage(&SMTPConfig{Host: "smtp.example.com"}, "user@example.net", "subject", "body")
require.ErrorContains(t, err, "invalid SMTP from address")
_, err = buildSMTPMessage(&SMTPConfig{
Host: "smtp.example.com",
From: "reply@example.com",
}, "invalid recipient <>", "subject", "body")
require.ErrorContains(t, err, "invalid SMTP recipient address")
_, err = buildSMTPMessage(&SMTPConfig{
Host: "smtp.example.com",
From: "reply@example.com",
}, "user@example.net\r\nBcc: hidden@example.net", "subject", "body")
require.ErrorContains(t, err, "invalid SMTP recipient address")
}
func TestBuildSMTPMessageUsesUniqueMessageIDs(t *testing.T) {
config := &SMTPConfig{Host: "smtp.example.com", From: "reply@example.com"}
first, err := buildSMTPMessage(config, "user@example.net", "subject", "body")
require.NoError(t, err)
second, err := buildSMTPMessage(config, "user@example.net", "subject", "body")
require.NoError(t, err)
firstParsed, err := mail.ReadMessage(bytes.NewReader(first.data))
require.NoError(t, err)
secondParsed, err := mail.ReadMessage(bytes.NewReader(second.data))
require.NoError(t, err)
require.NotEqual(t, firstParsed.Header.Get("Message-ID"), secondParsed.Header.Get("Message-ID"))
}
+5 -12
View File
@@ -186,26 +186,19 @@ const smtpIOTimeout = 20 * time.Second
// SendEmailWithConfig 使用指定配置发送邮件
func (s *EmailService) SendEmailWithConfig(config *SMTPConfig, to, subject, body string) error {
// Sanitize all SMTP header fields to prevent header injection (CR/LF removal).
to = sanitizeEmailHeader(to)
subject = sanitizeEmailHeader(subject)
from := sanitizeEmailHeader(config.From)
if config.FromName != "" {
from = fmt.Sprintf("%s <%s>", sanitizeEmailHeader(config.FromName), sanitizeEmailHeader(config.From))
message, err := buildSMTPMessage(config, to, subject, body)
if err != nil {
return err
}
msg := fmt.Sprintf("From: %s\r\nTo: %s\r\nSubject: %s\r\nMIME-Version: 1.0\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n%s",
from, to, subject, body)
addr := fmt.Sprintf("%s:%d", config.Host, config.Port)
auth := smtp.PlainAuth("", config.Username, config.Password, config.Host)
if config.UseTLS {
return s.sendMailTLS(addr, auth, config.From, to, []byte(msg), config.Host)
return s.sendMailTLS(addr, auth, message.envelopeFrom, message.envelopeTo, message.data, config.Host)
}
return s.sendMailPlain(addr, auth, config.From, to, []byte(msg), config.Host)
return s.sendMailPlain(addr, auth, message.envelopeFrom, message.envelopeTo, message.data, config.Host)
}
// sendMailPlain sends mail without TLS using a dialer with timeout.
@@ -523,7 +523,8 @@ func TestGatewayService_AnthropicAPIKeyPassthrough_ModelMappingPreservesOtherFie
require.Equal(t, "hello world", gjson.GetBytes(sentBody, "messages.0.content.0.text").String(), "messages 字段不应被修改")
require.Equal(t, "enabled", gjson.GetBytes(sentBody, "thinking.type").String(), "thinking 字段不应被修改")
require.Equal(t, int64(5000), gjson.GetBytes(sentBody, "thinking.budget_tokens").Int(), "thinking.budget_tokens 不应被修改")
require.Equal(t, int64(1024), gjson.GetBytes(sentBody, "max_tokens").Int(), "max_tokens 不应被修改")
require.False(t, gjson.GetBytes(sentBody, "max_tokens").Exists(),
"max_tokens 作为生成参数应被 count_tokens 过滤剥离")
}
func TestGatewayService_AnthropicAPIKeyPassthrough_CountTokensFiltersGenerationFields(t *testing.T) {
@@ -582,7 +583,8 @@ func TestGatewayService_AnthropicAPIKeyPassthrough_CountTokensFiltersGenerationF
require.Equal(t, "sys", gjson.GetBytes(sentBody, "system.0.text").String())
require.Equal(t, "hello", gjson.GetBytes(sentBody, "messages.0.content").String())
require.Equal(t, "tool", gjson.GetBytes(sentBody, "tools.0.name").String())
require.Equal(t, int64(1024), gjson.GetBytes(sentBody, "max_tokens").Int())
require.False(t, gjson.GetBytes(sentBody, "max_tokens").Exists(),
"count_tokens 请求不得携带生成参数 max_tokens")
require.Equal(t, "enabled", gjson.GetBytes(sentBody, "thinking.type").String())
}
@@ -596,6 +596,35 @@ func TestBuildCountTokensRequest_OAuthMimicHaiku_PreservesContextManagementEndTo
"count_tokens 路径必须含 token-counting beta")
}
func TestBuildCountTokensRequest_OAuthMimic_DropsInjectedMaxTokens(t *testing.T) {
// OAuth mimicry injects max_tokens=128000 for normal messages requests. It is
// invalid for Anthropic's count_tokens endpoint and must be stripped on wire.
gin.SetMode(gin.TestMode)
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages/count_tokens", nil)
account := &Account{ID: 413, Platform: PlatformAnthropic, Type: AccountTypeOAuth,
Credentials: map[string]any{"access_token": "oauth-tok"},
Status: StatusActive, Schedulable: true,
}
normalized, _ := normalizeClaudeOAuthRequestBody(
[]byte(`{"model":"claude-sonnet-4-5","messages":[]}`),
"claude-sonnet-4-5", claudeOAuthNormalizeOptions{},
)
require.Equal(t, int64(128000), gjson.GetBytes(normalized, "max_tokens").Int(),
"precondition: OAuth mimicry injects the Claude Code default")
svc := &GatewayService{cfg: &config.Config{}}
req, _, err := svc.buildCountTokensRequest(
context.Background(), c, account, normalized,
"oauth-tok", "oauth", "claude-sonnet-4-5", true,
)
require.NoError(t, err)
require.False(t, gjson.GetBytes(readUpstreamBodyForTest(t, req), "max_tokens").Exists(),
"count_tokens wire body must not contain max_tokens")
}
func TestBuildCountTokensRequest_APIKeyHaiku_StripsContextManagementEndToEnd(t *testing.T) {
// API-key + haiku + 客户端 header 不带 context-management beta → final beta 不含 → strip
gin.SetMode(gin.TestMode)
@@ -584,6 +584,10 @@ func sanitizeCountTokensRequestBody(body []byte) []byte {
"stream",
"stop_sequences",
"stop",
// Anthropic's /v1/messages/count_tokens accepts request-input fields only.
// max_tokens is a generation parameter; OAuth mimicry may inject it to
// resemble Claude Code messages requests, so it must never reach this endpoint.
"max_tokens",
} {
if gjson.GetBytes(out, path).Exists() {
if next, ok := deleteJSONPathBytes(out, path); ok {
@@ -322,9 +322,9 @@ func (s *GeminiMessagesCompatService) buildGeminiChatCompletionsUpstreamRequestF
if clientStream {
action = "streamGenerateContent"
}
fullURL := fmt.Sprintf("%s/v1beta/models/%s:%s", strings.TrimRight(normalizedBaseURL, "/"), mappedModel, action)
if clientStream {
fullURL += "?alt=sse"
fullURL, err := buildGeminiAIStudioModelActionURL(normalizedBaseURL, mappedModel, action, clientStream)
if err != nil {
return nil, "", err
}
restGeminiReq := normalizeGeminiRequestForAIStudio(geminiReq)
@@ -389,9 +389,9 @@ func (s *GeminiMessagesCompatService) buildGeminiChatCompletionsUpstreamRequestF
return nil, "", err
}
fullURL := fmt.Sprintf("%s/v1beta/models/%s:%s", strings.TrimRight(normalizedBaseURL, "/"), mappedModel, action)
if useUpstreamStream {
fullURL += "?alt=sse"
fullURL, err := buildGeminiAIStudioModelActionURL(normalizedBaseURL, mappedModel, action, useUpstreamStream)
if err != nil {
return nil, "", err
}
restGeminiReq := normalizeGeminiRequestForAIStudio(geminiReq)
@@ -638,9 +638,9 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex
if req.Stream {
action = "streamGenerateContent"
}
fullURL := fmt.Sprintf("%s/v1beta/models/%s:%s", strings.TrimRight(normalizedBaseURL, "/"), mappedModel, action)
if req.Stream {
fullURL += "?alt=sse"
fullURL, err := buildGeminiAIStudioModelActionURL(normalizedBaseURL, mappedModel, action, req.Stream)
if err != nil {
return nil, "", err
}
restGeminiReq := normalizeGeminiRequestForAIStudio(geminiReq)
@@ -712,9 +712,9 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex
return nil, "", err
}
fullURL := fmt.Sprintf("%s/v1beta/models/%s:%s", strings.TrimRight(normalizedBaseURL, "/"), mappedModel, action)
if useUpstreamStream {
fullURL += "?alt=sse"
fullURL, err := buildGeminiAIStudioModelActionURL(normalizedBaseURL, mappedModel, action, useUpstreamStream)
if err != nil {
return nil, "", err
}
restGeminiReq := normalizeGeminiRequestForAIStudio(geminiReq)
@@ -1181,9 +1181,9 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin.
return nil, "", err
}
fullURL := fmt.Sprintf("%s/v1beta/models/%s:%s", strings.TrimRight(normalizedBaseURL, "/"), mappedModel, upstreamAction)
if useUpstreamStream {
fullURL += "?alt=sse"
fullURL, err := buildGeminiAIStudioModelActionURL(normalizedBaseURL, mappedModel, upstreamAction, useUpstreamStream)
if err != nil {
return nil, "", err
}
upstreamReq, err := http.NewRequestWithContext(ctx, http.MethodPost, fullURL, bytes.NewReader(body))
@@ -1249,9 +1249,9 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin.
return nil, "", err
}
fullURL := fmt.Sprintf("%s/v1beta/models/%s:%s", strings.TrimRight(normalizedBaseURL, "/"), mappedModel, upstreamAction)
if useUpstreamStream {
fullURL += "?alt=sse"
fullURL, err := buildGeminiAIStudioModelActionURL(normalizedBaseURL, mappedModel, upstreamAction, useUpstreamStream)
if err != nil {
return nil, "", err
}
upstreamReq, err := http.NewRequestWithContext(ctx, http.MethodPost, fullURL, bytes.NewReader(body))
@@ -2701,10 +2701,13 @@ func (s *GeminiMessagesCompatService) ForwardAIStudioGET(ctx context.Context, ac
if account == nil {
return nil, errors.New("account is nil")
}
path = strings.TrimSpace(path)
if path == "" || !strings.HasPrefix(path, "/") {
// path 会被直接拼到上游 base URL 后面,因此按路径护栏逐片段校验,
// 见 upstream_path_guard.go。
sanitizedPath, ok := sanitizedUpstreamPathSuffix(path)
if !ok || sanitizedPath == "" {
return nil, errors.New("invalid path")
}
path = sanitizedPath
baseURL := account.GetGeminiBaseURL(geminicli.AIStudioBaseURL)
normalizedBaseURL, err := s.validateUpstreamBaseURL(baseURL)
@@ -0,0 +1,51 @@
package service
import (
"errors"
"fmt"
"strings"
)
// geminiAIStudioActions 是允许出现在上游 URL 里的 action 集合,与 ForwardNative
// 的入站校验保持一致,同时避免 compat 侧把可变字符串直接拼进 path。
var geminiAIStudioActions = map[string]struct{}{
"generateContent": {},
"streamGenerateContent": {},
"countTokens": {},
}
// buildGeminiAIStudioModelActionURL 组装 AI Studio 的
// /v1beta/models/{model}:{action} 上游 URL。
//
// model 是客户端可控的(native 路由取自 URL 片段,compat 路由取自请求体的 model
// 字段,之后可能再经渠道映射),因此必须先过路径片段护栏才能拼进 path,
// 见 upstream_path_guard.go。新增 AI Studio 端点请一律走本函数。
func buildGeminiAIStudioModelActionURL(baseURL, model, action string, stream bool) (string, error) {
trimmedBase := strings.TrimRight(strings.TrimSpace(baseURL), "/")
if trimmedBase == "" {
return "", errors.New("gemini base url is required")
}
trimmedModel := strings.TrimSpace(model)
if trimmedModel == "" {
return "", errors.New("gemini model is required")
}
if err := validateUpstreamPathSegment("gemini model", trimmedModel); err != nil {
return "", err
}
trimmedAction := strings.TrimSpace(action)
if _, ok := geminiAIStudioActions[trimmedAction]; !ok {
return "", fmt.Errorf("unsupported gemini action: %s", trimmedAction)
}
fullURL := fmt.Sprintf("%s/v1beta/models/%s:%s", trimmedBase, trimmedModel, trimmedAction)
if stream {
fullURL += "?alt=sse"
}
return fullURL, nil
}
// IsSafeGeminiModelPathSegment 供 handler 层在解析出 URL 里的模型名后立刻校验,
// 让客户端拿到明确的 400,而不是等到构造上游请求时才报错。
func IsSafeGeminiModelPathSegment(model string) bool {
return isSafeUpstreamPathSegment(strings.TrimSpace(model))
}
@@ -0,0 +1,62 @@
package service
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestBuildGeminiAIStudioModelActionURL(t *testing.T) {
const base = "https://generativelanguage.googleapis.com"
got, err := buildGeminiAIStudioModelActionURL(base, "gemini-2.5-pro", "generateContent", false)
require.NoError(t, err)
require.Equal(t, base+"/v1beta/models/gemini-2.5-pro:generateContent", got)
got, err = buildGeminiAIStudioModelActionURL(base+"/", " gemini-2.5-flash ", "streamGenerateContent", true)
require.NoError(t, err)
require.Equal(t, base+"/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse", got)
got, err = buildGeminiAIStudioModelActionURL(base, "gemini-2.5-pro", "countTokens", false)
require.NoError(t, err)
require.Equal(t, base+"/v1beta/models/gemini-2.5-pro:countTokens", got)
}
// TestBuildGeminiAIStudioModelActionURLRejectsNonConformingModel 锁定不变式:
// 模型名来自客户端(native 路由的 URL 片段 / compat 路由的请求体),
// 只有合规的路径片段才允许拼进上游 URL。
func TestBuildGeminiAIStudioModelActionURLRejectsNonConformingModel(t *testing.T) {
const base = "https://generativelanguage.googleapis.com"
for _, model := range []string{
"../../x/y",
"..",
".",
"gemini-2.5-pro/../../x",
`..\..\x`,
"gemini-2.5-pro?a=b",
"gemini-2.5-pro#frag",
"gemini-2.5-pro%2f..",
"gemini 2.5 pro",
"gemini\x00pro",
"gemini-2.5-pro@001",
"gemini~pro",
"models/gemini-2.5-pro",
"...",
"",
" ",
} {
t.Run("model_"+model, func(t *testing.T) {
_, err := buildGeminiAIStudioModelActionURL(base, model, "generateContent", false)
require.Error(t, err, "model %q must be rejected", model)
require.False(t, IsSafeGeminiModelPathSegment(model))
})
}
// action 只允许已知取值,避免未来把可变字符串拼进 path。
_, err := buildGeminiAIStudioModelActionURL(base, "gemini-2.5-pro", "deleteModel", false)
require.Error(t, err)
_, err = buildGeminiAIStudioModelActionURL("", "gemini-2.5-pro", "generateContent", false)
require.Error(t, err)
}
@@ -4,7 +4,10 @@ import (
"bufio"
"context"
"errors"
"io"
"mime/quotedprintable"
"net"
"net/mail"
"strings"
"sync"
"sync/atomic"
@@ -598,6 +601,21 @@ func (s *notificationEmailTestSMTPServer) lastMessage() string {
return s.messageBodies[len(s.messageBodies)-1]
}
func (s *notificationEmailTestSMTPServer) lastMessageBody(t *testing.T) string {
t.Helper()
message, err := mail.ReadMessage(strings.NewReader(s.lastMessage()))
require.NoError(t, err)
bodyReader := io.Reader(message.Body)
if strings.EqualFold(message.Header.Get("Content-Transfer-Encoding"), "quoted-printable") {
bodyReader = quotedprintable.NewReader(message.Body)
}
body, err := io.ReadAll(bodyReader)
require.NoError(t, err)
return string(body)
}
func (s *notificationEmailTestSMTPServer) close() {
_ = s.listener.Close()
s.wg.Wait()
@@ -364,7 +364,27 @@ func resolveOpenAICompactSessionID(c *gin.Context) string {
return uuid.NewString()
}
// openAIResponsesRequestPathSuffix 返回可拼接到上游 /responses URL 后面的子路径。
// 不可转发的子路径返回空串(退化为裸 /responses);真正的拒绝由入口守卫
// IsForwardableOpenAIResponsesRequestPath 负责。这样即便将来新增路由漏挂守卫,
// 拼进上游 URL 的也只会是合规片段。
func openAIResponsesRequestPathSuffix(c *gin.Context) string {
suffix, ok := sanitizedUpstreamPathSuffix(rawOpenAIResponsesRequestPathSuffix(c))
if !ok {
return ""
}
return suffix
}
// IsForwardableOpenAIResponsesRequestPath 判断入站请求携带的 /responses 子路径
// 是否可以安全转发。路由层用它在鉴权后、调度前直接拒绝畸形子路径。
func IsForwardableOpenAIResponsesRequestPath(c *gin.Context) bool {
_, ok := sanitizedUpstreamPathSuffix(rawOpenAIResponsesRequestPathSuffix(c))
return ok
}
// rawOpenAIResponsesRequestPathSuffix 仅做提取,不做任何安全判断。
func rawOpenAIResponsesRequestPathSuffix(c *gin.Context) string {
if c == nil || c.Request == nil || c.Request.URL == nil {
return ""
}
@@ -388,8 +408,9 @@ func openAIResponsesRequestPathSuffix(c *gin.Context) string {
func appendOpenAIResponsesRequestPathSuffix(baseURL, suffix string) string {
trimmedBase := strings.TrimRight(strings.TrimSpace(baseURL), "/")
trimmedSuffix := strings.TrimSpace(suffix)
if trimmedBase == "" || trimmedSuffix == "" {
// 兜底:调用方漏了校验时,这里也不会把不合规的片段拼进上游 URL。
trimmedSuffix, ok := sanitizedUpstreamPathSuffix(suffix)
if !ok || trimmedBase == "" || trimmedSuffix == "" {
return trimmedBase
}
return trimmedBase + trimmedSuffix
@@ -15,6 +15,7 @@ import (
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
"github.com/robfig/cron/v3"
"go.uber.org/zap"
)
const (
@@ -285,7 +286,10 @@ func (s *OpsCleanupService) runScheduled() {
return
}
s.recordHeartbeatSuccess(runAt, time.Since(startedAt), counts)
logger.LegacyPrintf("service.ops_cleanup", "[OpsCleanup] cleanup complete: %s", counts)
logger.L().Info("[OpsCleanup] cleanup complete",
zap.String("component", "service.ops_cleanup"),
zap.String("deleted_counts", counts.String()),
)
}
func (s *OpsCleanupService) runCleanupOnce(ctx context.Context) (opsCleanupDeletedCounts, error) {
@@ -131,9 +131,9 @@ func TestOpsScheduledReportLegacyTemplateReceivesSummaryHTML(t *testing.T) {
require.NoError(t, err)
require.Equal(t, 1, attempts)
require.Equal(t, int64(1), smtpServer.messageCount())
message := smtpServer.lastMessage()
require.Contains(t, message, `<section data-template="legacy">`)
require.Contains(t, message, `<h2>日报</h2>`)
messageBody := smtpServer.lastMessageBody(t)
require.Contains(t, messageBody, `<section data-template="legacy">`)
require.Contains(t, messageBody, `<h2>日报</h2>`)
}
func TestFormatOpsReportIntegerGroupsDigits(t *testing.T) {
+16 -16
View File
@@ -53,14 +53,14 @@ var (
SupportsPromptCaching: true,
}
openAIGPT56TerraFallbackPricing = &LiteLLMModelPricing{
InputCostPerToken: 2.5e-06,
InputCostPerTokenPriority: 5e-06,
OutputCostPerToken: 1.5e-05,
OutputCostPerTokenPriority: 3e-05,
CacheCreationInputTokenCost: 3.125e-06,
CacheCreationInputTokenCostPriority: 6.25e-06,
CacheReadInputTokenCost: 2.5e-07,
CacheReadInputTokenCostPriority: 5e-07,
InputCostPerToken: 2e-06,
InputCostPerTokenPriority: 4e-06,
OutputCostPerToken: 1.2e-05,
OutputCostPerTokenPriority: 2.4e-05,
CacheCreationInputTokenCost: 2.5e-06,
CacheCreationInputTokenCostPriority: 5e-06,
CacheReadInputTokenCost: 2e-07,
CacheReadInputTokenCostPriority: 4e-07,
LongContextInputTokenThreshold: openAIGPT54LongContextInputThreshold,
LongContextInputCostMultiplier: openAIGPT54LongContextInputMultiplier,
LongContextOutputCostMultiplier: openAIGPT54LongContextOutputMultiplier,
@@ -70,14 +70,14 @@ var (
SupportsPromptCaching: true,
}
openAIGPT56LunaFallbackPricing = &LiteLLMModelPricing{
InputCostPerToken: 1e-06,
InputCostPerTokenPriority: 2e-06,
OutputCostPerToken: 6e-06,
OutputCostPerTokenPriority: 1.2e-05,
CacheCreationInputTokenCost: 1.25e-06,
CacheCreationInputTokenCostPriority: 2.5e-06,
CacheReadInputTokenCost: 1e-07,
CacheReadInputTokenCostPriority: 2e-07,
InputCostPerToken: 2e-07,
InputCostPerTokenPriority: 4e-07,
OutputCostPerToken: 1.2e-06,
OutputCostPerTokenPriority: 2.4e-06,
CacheCreationInputTokenCost: 2.5e-07,
CacheCreationInputTokenCostPriority: 5e-07,
CacheReadInputTokenCost: 2e-08,
CacheReadInputTokenCostPriority: 4e-08,
LongContextInputTokenThreshold: openAIGPT54LongContextInputThreshold,
LongContextInputCostMultiplier: openAIGPT54LongContextInputMultiplier,
LongContextOutputCostMultiplier: openAIGPT54LongContextOutputMultiplier,
@@ -88,8 +88,8 @@ func TestBillingService_GPT56CacheWritePricingUsesOfficialMultiplier(t *testing.
cacheReadPriority float64
}{
{model: "gpt-5.6-sol", input: 5e-6, inputPriority: 10e-6, output: 30e-6, outputPriority: 60e-6, cacheRead: 0.5e-6, cacheReadPriority: 1e-6},
{model: "gpt-5.6-terra", input: 2.5e-6, inputPriority: 5e-6, output: 15e-6, outputPriority: 30e-6, cacheRead: 0.25e-6, cacheReadPriority: 0.5e-6},
{model: "gpt-5.6-luna", input: 1e-6, inputPriority: 2e-6, output: 6e-6, outputPriority: 12e-6, cacheRead: 0.1e-6, cacheReadPriority: 0.2e-6},
{model: "gpt-5.6-terra", input: 2e-6, inputPriority: 4e-6, output: 12e-6, outputPriority: 24e-6, cacheRead: 0.2e-6, cacheReadPriority: 0.4e-6},
{model: "gpt-5.6-luna", input: 0.2e-6, inputPriority: 0.4e-6, output: 1.2e-6, outputPriority: 2.4e-6, cacheRead: 0.02e-6, cacheReadPriority: 0.04e-6},
}
for _, tt := range tests {
t.Run(tt.model, func(t *testing.T) {
@@ -136,8 +136,8 @@ func TestBillingService_GPT56UsesLongContextPricingAcrossModelsAndTiers(t *testi
cacheWrite, output float64
}{
{name: "gpt-5.6-sol", input: 5e-6, cached: 0.5e-6, cacheWrite: 6.25e-6, output: 30e-6},
{name: "gpt-5.6-terra", input: 2.5e-6, cached: 0.25e-6, cacheWrite: 3.125e-6, output: 15e-6},
{name: "gpt-5.6-luna", input: 1e-6, cached: 0.1e-6, cacheWrite: 1.25e-6, output: 6e-6},
{name: "gpt-5.6-terra", input: 2e-6, cached: 0.2e-6, cacheWrite: 2.5e-6, output: 12e-6},
{name: "gpt-5.6-luna", input: 0.2e-6, cached: 0.02e-6, cacheWrite: 0.25e-6, output: 1.2e-6},
}
tiers := []struct {
name string
@@ -188,8 +188,8 @@ func TestBillingService_GPT56LongContextBoundaryIsExclusive(t *testing.T) {
func TestPricingService_BareGPT56AliasDeterministicallyUsesSol(t *testing.T) {
pricingSvc := &PricingService{pricingData: map[string]*LiteLLMModelPricing{
"gpt-5.6-sol": {InputCostPerToken: 5e-6},
"gpt-5.6-terra": {InputCostPerToken: 2.5e-6},
"gpt-5.6-luna": {InputCostPerToken: 1e-6},
"gpt-5.6-terra": {InputCostPerToken: 2e-6},
"gpt-5.6-luna": {InputCostPerToken: 0.2e-6},
"gpt-5.4": {InputCostPerToken: 2.5e-6},
}}
@@ -226,8 +226,8 @@ func TestDefaultPricingIncludesOfficialGPT56Rates(t *testing.T) {
inputPriority, cachedPriority, cacheWritePriority, outputPriority float64
}{
{model: "gpt-5.6-sol", input: 5e-6, cached: 0.5e-6, cacheWrite: 6.25e-6, output: 30e-6, inputPriority: 10e-6, cachedPriority: 1e-6, cacheWritePriority: 12.5e-6, outputPriority: 60e-6},
{model: "gpt-5.6-terra", input: 2.5e-6, cached: 0.25e-6, cacheWrite: 3.125e-6, output: 15e-6, inputPriority: 5e-6, cachedPriority: 0.5e-6, cacheWritePriority: 6.25e-6, outputPriority: 30e-6},
{model: "gpt-5.6-luna", input: 1e-6, cached: 0.1e-6, cacheWrite: 1.25e-6, output: 6e-6, inputPriority: 2e-6, cachedPriority: 0.2e-6, cacheWritePriority: 2.5e-6, outputPriority: 12e-6},
{model: "gpt-5.6-terra", input: 2e-6, cached: 0.2e-6, cacheWrite: 2.5e-6, output: 12e-6, inputPriority: 4e-6, cachedPriority: 0.4e-6, cacheWritePriority: 5e-6, outputPriority: 24e-6},
{model: "gpt-5.6-luna", input: 0.2e-6, cached: 0.02e-6, cacheWrite: 0.25e-6, output: 1.2e-6, inputPriority: 0.4e-6, cachedPriority: 0.04e-6, cacheWritePriority: 0.5e-6, outputPriority: 2.4e-6},
}
for _, tt := range tests {
t.Run(tt.model, func(t *testing.T) {
@@ -254,8 +254,8 @@ func TestGPT56DedicatedFallbacksUseOfficialRates(t *testing.T) {
input, cached, cacheWrite, output float64
}{
{model: "gpt-5.6-sol", input: 5e-6, cached: 0.5e-6, cacheWrite: 6.25e-6, output: 30e-6},
{model: "gpt-5.6-terra", input: 2.5e-6, cached: 0.25e-6, cacheWrite: 3.125e-6, output: 15e-6},
{model: "gpt-5.6-luna", input: 1e-6, cached: 0.1e-6, cacheWrite: 1.25e-6, output: 6e-6},
{model: "gpt-5.6-terra", input: 2e-6, cached: 0.2e-6, cacheWrite: 2.5e-6, output: 12e-6},
{model: "gpt-5.6-luna", input: 0.2e-6, cached: 0.02e-6, cacheWrite: 0.25e-6, output: 1.2e-6},
}
for _, tt := range tests {
@@ -51,6 +51,7 @@ func (r *tokenRefreshCandidateRepo) ListOAuthRefreshCandidatePage(_ context.Cont
}
}
if options.ActiveOnly && account.Status != StatusActive ||
!account.Schedulable ||
account.Type != AccountTypeOAuth ||
!platformAllowed ||
options.RequireRefreshToken && strings.TrimSpace(refreshToken) == "" ||
@@ -122,6 +123,7 @@ func TestTokenRefreshService_ProcessRefreshUsesOAuthRefreshCandidates(t *testing
Platform: PlatformOpenAI,
Type: AccountTypeOAuth,
Status: StatusActive,
Schedulable: true,
Credentials: map[string]any{"refresh_token": "refresh-token"},
},
{
@@ -129,6 +131,7 @@ func TestTokenRefreshService_ProcessRefreshUsesOAuthRefreshCandidates(t *testing
Platform: PlatformOpenAI,
Type: AccountTypeOAuth,
Status: StatusActive,
Schedulable: true,
Credentials: map[string]any{},
},
{
@@ -143,6 +146,7 @@ func TestTokenRefreshService_ProcessRefreshUsesOAuthRefreshCandidates(t *testing
Platform: PlatformAntigravity,
Type: AccountTypeOAuth,
Status: StatusActive,
Schedulable: true,
Credentials: map[string]any{"refresh_token": "refresh-token"},
TempUnschedulableUntil: &future,
TempUnschedulableReason: "token refresh retry exhausted: network timeout",
@@ -152,6 +156,7 @@ func TestTokenRefreshService_ProcessRefreshUsesOAuthRefreshCandidates(t *testing
Platform: "other",
Type: AccountTypeOAuth,
Status: StatusActive,
Schedulable: true,
Credentials: map[string]any{"refresh_token": "refresh-token"},
},
{
@@ -159,11 +164,20 @@ func TestTokenRefreshService_ProcessRefreshUsesOAuthRefreshCandidates(t *testing
Platform: PlatformAntigravity,
Type: AccountTypeOAuth,
Status: StatusActive,
Schedulable: true,
Credentials: map[string]any{"refresh_token": "refresh-token"},
Extra: map[string]any{"privacy_mode": AntigravityPrivacySet},
TempUnschedulableUntil: &future,
TempUnschedulableReason: "OAuth 401: unauthorized",
},
{
ID: 7,
Platform: PlatformOpenAI,
Type: AccountTypeOAuth,
Status: StatusActive,
Schedulable: false,
Credentials: map[string]any{"refresh_token": "permanently-rejected-token"},
},
},
}
svc := &TokenRefreshService{
@@ -0,0 +1,95 @@
package service
import (
"fmt"
"strings"
)
// 上游 URL 路径片段护栏。
//
// 网关会把若干客户端可控的字符串(Responses 子路径、Gemini 模型名)拼进上游请求
// 的 URL path。约定:这些字符串只允许"结构惰性"的字符,即拼进去之后不可能改变
// 上游请求的路径结构;不符合的一律拒绝。
//
// 实现上是**闭集允许清单(默认拒绝)**,请勿改成"逐个拒绝已知的坏字符":后者要求
// 穷举,漏一项就失效;默认拒绝则相反,清单外的写法天然被挡住,无需跟着改代码。
//
// 另外注意:到达业务代码的 c.Request.URL.Path 已经是百分号解码后的结果,因此校验
// 必须放在这一层,不能假设上游看到的路径与客户端书写形式一致。
//
// 这里只校验、不改写:把不合规输入自动修正成合规路径,会让上游收到与客户端意图
// 不同的请求,也会掩盖调用方的错误。
const (
// maxUpstreamPathSegmentLen 单个路径片段长度上限。真实的 response id、模型名
// 都远短于此,留足余量只为拒绝异常输入。
maxUpstreamPathSegmentLen = 128
// maxUpstreamPathSegments 后缀允许的片段数上限(如 /{id}/cancel 为 2)。
maxUpstreamPathSegments = 8
)
// isSafeUpstreamPathSegmentByte 是闭集允许清单:只放行 `\w`(即 [A-Za-z0-9_])
// 以及真实取值必需的 `-` 与 `.`。其余字符(含控制字符与非 ASCII)一律拒绝。
func isSafeUpstreamPathSegmentByte(b byte) bool {
switch {
case b >= 'a' && b <= 'z', b >= 'A' && b <= 'Z', b >= '0' && b <= '9':
return true
case b == '_', b == '-', b == '.':
return true
default:
return false
}
}
// isSafeUpstreamPathSegment 判断 segment 能否原样拼进上游 URL 的一个 path 片段。
//
// 允许清单里唯一在路径语义中有特殊含义的字符是 `.`,因此额外要求片段不能只由点
// 组成——各类实现对这种片段的解释并不一致,直接拒绝最省心。
func isSafeUpstreamPathSegment(segment string) bool {
if segment == "" || len(segment) > maxUpstreamPathSegmentLen {
return false
}
dotsOnly := true
for i := 0; i < len(segment); i++ {
if !isSafeUpstreamPathSegmentByte(segment[i]) {
return false
}
if segment[i] != '.' {
dotsOnly = false
}
}
return !dotsOnly
}
// sanitizedUpstreamPathSuffix 校验 "/a/b" 形态的路径后缀。
// ok=false 表示后缀不可转发,调用方必须拒绝请求,而不是降级成空后缀——否则
// /responses/compact 之类的请求语义会被静默改写。空后缀合法,表示"没有子路径"。
func sanitizedUpstreamPathSuffix(raw string) (string, bool) {
suffix := strings.TrimSpace(raw)
if suffix == "" {
return "", true
}
if !strings.HasPrefix(suffix, "/") {
return "", false
}
segments := strings.Split(strings.TrimPrefix(suffix, "/"), "/")
if len(segments) > maxUpstreamPathSegments {
return "", false
}
for _, segment := range segments {
if !isSafeUpstreamPathSegment(segment) {
return "", false
}
}
return suffix, true
}
// validateUpstreamPathSegment 供 URL 构造点使用:不合规的片段直接变成显式错误,
// 不再继续构造与发出上游请求。
func validateUpstreamPathSegment(kind, segment string) error {
if isSafeUpstreamPathSegment(strings.TrimSpace(segment)) {
return nil
}
// 不回显原始输入,避免把它写进日志与错误响应。
return fmt.Errorf("invalid %s for upstream url path", kind)
}
@@ -0,0 +1,160 @@
package service
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
func TestSanitizedUpstreamPathSuffixRejectsNonConformingSegments(t *testing.T) {
// 到达业务代码的 URL.Path 已是百分号解码后的结果,因此用例按解码后的形态书写。
rejected := []string{
"/..",
"/../..",
"/../../x/y",
"/./compact",
"/compact/..",
`/..\..\x`,
`/compact\..`,
"/?a=b",
"/compact?a=b",
"/compact#frag",
"/compact%2f..",
"/100%",
"//double",
"/compact//detail",
"/compact/",
"/ compact",
"/compact\x00",
"/compact\nX-Injected: 1",
"/模型",
"compact",
"/a:b",
"/a;b",
"/a,b",
"/a=b",
"/a&b",
// 允许清单是闭集:`\w` + `-` + `.` 以外的字符一律拒绝,
// 不依赖任何"已知坏字符"清单。
"/a~b",
"/a@b",
"/a+b",
"/a|b",
"/a*b",
"/a$b",
"/a(b)",
"/a'b",
"/a\"b",
"/a<b",
"/a\tb",
"/a b",
"/a∕b", // DIVISION SLASH
"/a/b", // FULLWIDTH SOLIDUS
// 只由点组成的片段一律拒绝(各实现对其解释不一致)。
"/...",
"/....",
"/compact/...",
}
for _, suffix := range rejected {
t.Run("reject_"+suffix, func(t *testing.T) {
got, ok := sanitizedUpstreamPathSuffix(suffix)
require.False(t, ok, "suffix %q must be rejected", suffix)
require.Empty(t, got)
})
}
accepted := map[string]string{
"": "",
"/compact": "/compact",
"/compact/detail": "/compact/detail",
"/resp_68f0a1b2c3d4/cancel": "/resp_68f0a1b2c3d4/cancel",
"/gemini-2.5-pro_v1.2": "/gemini-2.5-pro_v1.2",
"/a.b.c": "/a.b.c",
}
for suffix, want := range accepted {
t.Run("accept_"+suffix, func(t *testing.T) {
got, ok := sanitizedUpstreamPathSuffix(suffix)
require.True(t, ok, "suffix %q must be accepted", suffix)
require.Equal(t, want, got)
})
}
}
func TestSanitizedUpstreamPathSuffixEnforcesBounds(t *testing.T) {
longSegment := "/"
for i := 0; i < maxUpstreamPathSegmentLen+1; i++ {
longSegment += "a"
}
_, ok := sanitizedUpstreamPathSuffix(longSegment)
require.False(t, ok, "over-long segment must be rejected")
deep := ""
for i := 0; i <= maxUpstreamPathSegments; i++ {
deep += "/a"
}
_, ok = sanitizedUpstreamPathSuffix(deep)
require.False(t, ok, "over-deep suffix must be rejected")
}
// TestOpenAIResponsesRequestPathSuffixRejectsNonConformingSubpaths 锁定不变式:
// /responses/*subpath 的子路径不得改变上游请求的路径结构;不合规时既不参与拼接,
// 也不会被误判成 compact 请求。
func TestOpenAIResponsesRequestPathSuffixRejectsNonConformingSubpaths(t *testing.T) {
gin.SetMode(gin.TestMode)
nonConformingPaths := []string{
"/v1/responses/../../x/y",
"/v1/responses/..%2f..%2fx/y",
"/v1/responses/%2e%2e/%2e%2e/x",
"/responses/%2e%2e%2fx",
"/backend-api/codex/responses/../../../x",
`/v1/responses/..\..\x`,
"/v1/responses/%3fa=b",
"/v1/responses/x%23frag",
"/v1/responses//double",
}
for _, path := range nonConformingPaths {
t.Run(path, func(t *testing.T) {
c := newResponsesSuffixTestContext(t, path)
require.False(t, IsForwardableOpenAIResponsesRequestPath(c),
"path %q must be rejected at the gateway edge", path)
require.Empty(t, openAIResponsesRequestPathSuffix(c),
"path %q must never contribute an upstream path suffix", path)
require.Equal(t, chatgptCodexURL,
appendOpenAIResponsesRequestPathSuffix(chatgptCodexURL, openAIResponsesRequestPathSuffix(c)))
require.False(t, isOpenAIResponsesCompactPath(c))
})
}
// 合法子路径必须保持原样转发。
for path, want := range map[string]string{
"/v1/responses": "",
"/v1/responses/compact": "/compact",
"/responses/compact/": "/compact",
"/backend-api/codex/responses/compact": "/compact",
} {
t.Run("forwardable_"+path, func(t *testing.T) {
c := newResponsesSuffixTestContext(t, path)
require.True(t, IsForwardableOpenAIResponsesRequestPath(c))
require.Equal(t, want, openAIResponsesRequestPathSuffix(c))
})
}
}
func TestAppendOpenAIResponsesRequestPathSuffixRefusesUnsafeSuffix(t *testing.T) {
// 调用方漏了校验时,拼接函数本身也不得把不合规片段带进上游 URL。
require.Equal(t, chatgptCodexURL, appendOpenAIResponsesRequestPathSuffix(chatgptCodexURL, "/../../x"))
require.Equal(t, chatgptCodexURL, appendOpenAIResponsesRequestPathSuffix(chatgptCodexURL, "/?a=b"))
require.Equal(t, chatgptCodexURL+"/compact", appendOpenAIResponsesRequestPathSuffix(chatgptCodexURL, "/compact"))
}
func newResponsesSuffixTestContext(t *testing.T, path string) *gin.Context {
t.Helper()
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(http.MethodPost, path, nil)
return c
}
@@ -5066,17 +5066,17 @@
"supports_xhigh_reasoning_effort": true
},
"gpt-5.6-terra": {
"cache_creation_input_token_cost": 3.125e-06,
"cache_creation_input_token_cost_batches": 1.5625e-06,
"cache_creation_input_token_cost_flex": 1.5625e-06,
"cache_creation_input_token_cost_priority": 6.25e-06,
"cache_read_input_token_cost": 2.5e-07,
"cache_read_input_token_cost_flex": 1.25e-07,
"cache_read_input_token_cost_priority": 5e-07,
"input_cost_per_token": 2.5e-06,
"input_cost_per_token_batches": 1.25e-06,
"input_cost_per_token_flex": 1.25e-06,
"input_cost_per_token_priority": 5e-06,
"cache_creation_input_token_cost": 2.5e-06,
"cache_creation_input_token_cost_batches": 1.25e-06,
"cache_creation_input_token_cost_flex": 1.25e-06,
"cache_creation_input_token_cost_priority": 5e-06,
"cache_read_input_token_cost": 2e-07,
"cache_read_input_token_cost_flex": 1e-07,
"cache_read_input_token_cost_priority": 4e-07,
"input_cost_per_token": 2e-06,
"input_cost_per_token_batches": 1e-06,
"input_cost_per_token_flex": 1e-06,
"input_cost_per_token_priority": 4e-06,
"long_context_input_token_threshold": 272000,
"long_context_input_cost_multiplier": 2.0,
"long_context_output_cost_multiplier": 1.5,
@@ -5085,10 +5085,10 @@
"max_output_tokens": 128000,
"max_tokens": 128000,
"mode": "chat",
"output_cost_per_token": 1.5e-05,
"output_cost_per_token_batches": 7.5e-06,
"output_cost_per_token_flex": 7.5e-06,
"output_cost_per_token_priority": 3e-05,
"output_cost_per_token": 1.2e-05,
"output_cost_per_token_batches": 6e-06,
"output_cost_per_token_flex": 6e-06,
"output_cost_per_token_priority": 2.4e-05,
"supported_endpoints": [
"/v1/chat/completions",
"/v1/batch",
@@ -5118,17 +5118,17 @@
"supports_xhigh_reasoning_effort": true
},
"gpt-5.6-luna": {
"cache_creation_input_token_cost": 1.25e-06,
"cache_creation_input_token_cost_batches": 6.25e-07,
"cache_creation_input_token_cost_flex": 6.25e-07,
"cache_creation_input_token_cost_priority": 2.5e-06,
"cache_read_input_token_cost": 1e-07,
"cache_read_input_token_cost_flex": 5e-08,
"cache_read_input_token_cost_priority": 2e-07,
"input_cost_per_token": 1e-06,
"input_cost_per_token_batches": 5e-07,
"input_cost_per_token_flex": 5e-07,
"input_cost_per_token_priority": 2e-06,
"cache_creation_input_token_cost": 2.5e-07,
"cache_creation_input_token_cost_batches": 1.25e-07,
"cache_creation_input_token_cost_flex": 1.25e-07,
"cache_creation_input_token_cost_priority": 5e-07,
"cache_read_input_token_cost": 2e-08,
"cache_read_input_token_cost_flex": 1e-08,
"cache_read_input_token_cost_priority": 4e-08,
"input_cost_per_token": 2e-07,
"input_cost_per_token_batches": 1e-07,
"input_cost_per_token_flex": 1e-07,
"input_cost_per_token_priority": 4e-07,
"long_context_input_token_threshold": 272000,
"long_context_input_cost_multiplier": 2.0,
"long_context_output_cost_multiplier": 1.5,
@@ -5137,10 +5137,10 @@
"max_output_tokens": 128000,
"max_tokens": 128000,
"mode": "chat",
"output_cost_per_token": 6e-06,
"output_cost_per_token_batches": 3e-06,
"output_cost_per_token_flex": 3e-06,
"output_cost_per_token_priority": 1.2e-05,
"output_cost_per_token": 1.2e-06,
"output_cost_per_token_batches": 6e-07,
"output_cost_per_token_flex": 6e-07,
"output_cost_per_token_priority": 2.4e-06,
"supported_endpoints": [
"/v1/chat/completions",
"/v1/batch",
+2 -1
View File
@@ -103,8 +103,9 @@ RUN addgroup -g 1000 sub2api && \
# Set working directory
WORKDIR /app
# Copy binary from builder
# Copy binary and runtime fallback resources from builder
COPY --from=backend-builder /app/sub2api /app/sub2api
COPY --from=backend-builder --chown=sub2api:sub2api /app/backend/resources /app/resources
# Create data directory
RUN mkdir -p /app/data && chown -R sub2api:sub2api /app
+2
View File
@@ -17,6 +17,8 @@ services:
NPM_CONFIG_REGISTRY: ${NPM_CONFIG_REGISTRY:-https://registry.npmmirror.com}
container_name: sub2api-dev
restart: unless-stopped
security_opt:
- no-new-privileges:true
ports:
- "${BIND_HOST:-127.0.0.1}:${SERVER_PORT:-8080}:8080"
volumes:
+2
View File
@@ -27,6 +27,8 @@ services:
image: weishaw/sub2api:latest
container_name: sub2api
restart: unless-stopped
security_opt:
- no-new-privileges:true
ulimits:
nofile:
soft: 100000
+2
View File
@@ -15,6 +15,8 @@ services:
image: weishaw/sub2api:latest
container_name: sub2api
restart: unless-stopped
security_opt:
- no-new-privileges:true
ulimits:
nofile:
soft: 100000
+2
View File
@@ -19,6 +19,8 @@ services:
image: weishaw/sub2api:latest
container_name: sub2api
restart: unless-stopped
security_opt:
- no-new-privileges:true
ulimits:
nofile:
soft: 100000
+44
View File
@@ -0,0 +1,44 @@
#!/bin/sh
set -eu
repo_root=$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)
cd "$repo_root"
check_application_security_opt() {
file=$1
count=$(
awk '
$0 == " sub2api:" {
in_application = 1
next
}
in_application && $0 ~ /^ [A-Za-z0-9_-]+:$/ {
in_application = 0
}
in_application && $0 == " security_opt:" {
in_security_opt = 1
next
}
in_application && in_security_opt && $0 == " - no-new-privileges:true" {
count++
}
END { print count + 0 }
' "$file"
)
if [ "$count" -ne 1 ]; then
printf '%s must enable no-new-privileges exactly once for the sub2api service\n' "$file" >&2
exit 1
fi
}
for compose_file in \
deploy/docker-compose.yml \
deploy/docker-compose.local.yml \
deploy/docker-compose.standalone.yml \
deploy/docker-compose.dev.yml
do
check_application_security_opt "$compose_file"
done
printf 'docker compose security test passed\n'
+34
View File
@@ -0,0 +1,34 @@
#!/bin/sh
set -eu
repo_root=$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)
cd "$repo_root"
fail() {
printf 'docker runtime resources test failed: %s\n' "$1" >&2
exit 1
}
assert_line() {
file=$1
line=$2
grep -Fqx "$line" "$file" || fail "$file is missing: $line"
}
assert_count() {
file=$1
line=$2
expected=$3
actual=$(grep -Fxc "$line" "$file" || true)
[ "$actual" -eq "$expected" ] || fail "$file has $actual occurrences of '$line', expected $expected"
}
test -s backend/resources/model-pricing/model_prices_and_context_window.json || \
fail 'fallback pricing data is missing or empty'
assert_line Dockerfile.goreleaser 'COPY --chown=sub2api:sub2api backend/resources /app/resources'
assert_line deploy/Dockerfile 'COPY --from=backend-builder --chown=sub2api:sub2api /app/backend/resources /app/resources'
assert_count .goreleaser.yaml ' - backend/resources' 4
assert_count .goreleaser.simple.yaml ' - backend/resources' 1
printf 'docker runtime resources test passed\n'
@@ -14,12 +14,12 @@
<!-- Header: name + badge + price -->
<div class="mb-3 flex items-start justify-between gap-2">
<div class="min-w-0 flex-1">
<div class="flex items-center gap-2">
<h3 class="truncate text-base font-bold text-gray-900 dark:text-white">{{ plan.name }}</h3>
<span :class="['shrink-0 rounded-full px-2 py-0.5 text-[11px] font-medium', badgeLightClass]">
{{ pLabel }}
</span>
</div>
<h3
:title="plan.name"
class="h-12 min-w-0 break-words [overflow-wrap:anywhere] text-base font-bold leading-6 text-gray-900 dark:text-white line-clamp-2"
>
{{ plan.name }}
</h3>
<p v-if="plan.description" class="mt-0.5 text-xs leading-relaxed text-gray-500 dark:text-dark-400 line-clamp-2">
{{ plan.description }}
</p>
@@ -30,7 +30,12 @@
<span :class="['text-2xl font-extrabold tracking-tight', textClass]">{{ plan.price }}</span>
<span v-if="plan.currency" class="text-xs font-medium text-gray-400 dark:text-dark-500">{{ plan.currency }}</span>
</div>
<span class="text-[11px] text-gray-400 dark:text-dark-500">/ {{ validitySuffix }}</span>
<div class="flex items-center justify-end gap-1">
<span :class="['inline-flex shrink-0 rounded-full px-2 py-0.5 text-[11px] font-medium', badgeLightClass]">
{{ pLabel }}
</span>
<span class="text-[11px] text-gray-400 dark:text-dark-500">/ {{ validitySuffix }}</span>
</div>
<div v-if="plan.original_price" class="mt-0.5 flex items-center justify-end gap-1.5">
<span class="text-xs text-gray-400 line-through dark:text-dark-500">{{ planCurrencySymbol }}{{ plan.original_price }}<template v-if="plan.currency"> {{ plan.currency }}</template></span>
<span :class="['rounded px-1 py-0.5 text-[10px] font-semibold', discountClass]">{{ discountText }}</span>
@@ -86,4 +86,66 @@ describe("SubscriptionPlanCard", () => {
expect(mountPlanCard("openai", { currency: "USD" }).text()).toContain("$10USD");
expect(mountPlanCard("openai", { currency: "" }).text()).toContain("$10");
});
it.each([
["long Chinese", "企业全球加速专业订阅套餐(含高级模型与优先支持)"],
["long English", "Enterprise Global Acceleration Subscription with Priority Support"],
["unbroken token", "EnterpriseGlobalAccelerationSubscriptionWithPrioritySupport1234567890"],
])("keeps the full %s plan title accessible in a bounded two-line area", (_label, name) => {
const wrapper = mountPlanCard("openai", { name });
const title = wrapper.get("h3");
expect(title.text()).toBe(name);
expect(title.attributes("title")).toBe(name);
expect(title.classes()).toEqual(expect.arrayContaining([
"min-w-0",
"h-12",
"break-words",
"line-clamp-2",
"[overflow-wrap:anywhere]",
]));
expect(title.classes()).not.toContain("truncate");
});
it("keeps title, badge, price, description, and purchase action in separate bounded regions", () => {
const wrapper = mountPlanCard("openai", {
name: "Enterprise Global Acceleration Subscription with Priority Support",
price: 123.45,
currency: "USD",
description: "Includes advanced models and priority support.",
});
const title = wrapper.get("h3");
const badge = wrapper.findAll("span").find((node) => node.text() === "OpenAI");
const price = wrapper.findAll("span").find((node) => node.text() === "123.45");
expect(title.element.parentElement?.classList).toContain("min-w-0");
expect(title.element.parentElement?.classList).toContain("flex-1");
expect(badge?.classes()).toContain("shrink-0");
expect([...(badge?.element.parentElement?.classList ?? [])]).toEqual(expect.arrayContaining([
"flex",
"items-center",
"justify-end",
]));
expect(badge?.element.parentElement?.textContent).toContain("/ 30payment.days");
expect(badge?.element.parentElement?.parentElement?.classList).toContain("shrink-0");
expect(price?.element.parentElement?.parentElement?.classList).toContain("shrink-0");
expect(wrapper.get("p").text()).toBe("Includes advanced models and priority support.");
expect(wrapper.get("button").text()).toBe("payment.subscribeNow");
});
it("keeps short plan titles compact and aligned", () => {
const wrapper = mountPlanCard("openai", { name: "Pro", description: "" });
const title = wrapper.get("h3");
const badge = wrapper.findAll("span").find((node) => node.text() === "OpenAI");
expect(title.text()).toBe("Pro");
expect(title.attributes("title")).toBe("Pro");
expect(title.classes()).toEqual(expect.arrayContaining(["text-base", "font-bold", "h-12"]));
expect([...(badge?.element.parentElement?.classList ?? [])]).toEqual(expect.arrayContaining([
"flex",
"items-center",
"justify-end",
]));
expect(badge?.element.parentElement?.textContent).toContain("/ 30payment.days");
});
});
@@ -623,7 +623,9 @@ export default {
quotaEndsInMinutes: 'Quota ends in {minutes}m',
quotaEndsInHoursMinutes: 'Quota ends in {hours}h {minutes}m',
quotaEndsInDaysHours: 'Quota ends in {days}d {hours}h',
daysRemaining: 'days remaining',
daysRemaining: '{days} days remaining',
hoursMinutesRemaining: '{hours}h {minutes}m remaining',
minutesRemaining: '{minutes}m remaining',
remainingDays: 'Remaining days',
noExpiration: 'No expiration',
status: {
@@ -144,6 +144,7 @@ export default {
passkeyRPID: 'RP ID',
passkeyOrigins: 'Allowed HTTPS origins',
passkeyValueNotConfigured: 'Not configured',
passkeyDeploymentHint: 'Ask the server operator to set webauthn.enabled to true, configure webauthn.rp_id (domain only) and webauthn.rp_origins (full HTTPS origins), then restart the service.',
stepUp: 'Step-up 2FA for Sensitive Operations',
stepUpHint: 'When enabled, sensitive operations (account/proxy export, backup creation and download, S3 config changes, promoting admins) require a recent TOTP verification (valid for 15 minutes). Your own account must have 2FA enabled before turning this on; turning it off also requires step-up verification.',
stepUpEnableRequiresTotp: 'Enable 2FA (TOTP) for your own account in Profile before turning on step-up verification.',
@@ -623,7 +623,9 @@ export default {
quotaEndsInMinutes: '额度将在 {minutes} 分钟后结束',
quotaEndsInHoursMinutes: '额度将在 {hours} 小时 {minutes} 分钟后结束',
quotaEndsInDaysHours: '额度将在 {days} 天 {hours} 小时后结束',
daysRemaining: '天剩余',
daysRemaining: '剩余 {days} 天',
hoursMinutesRemaining: '剩余 {hours} 小时 {minutes} 分钟',
minutesRemaining: '剩余 {minutes} 分钟',
remainingDays: '剩余天数',
noExpiration: '无过期时间',
status: {
@@ -144,6 +144,7 @@ export default {
passkeyRPID: 'RP ID',
passkeyOrigins: '允许的 HTTPS 来源',
passkeyValueNotConfigured: '未配置',
passkeyDeploymentHint: '请由服务器运维在部署配置中将 webauthn.enabled 设为 true,填写 webauthn.rp_id(仅域名)与 webauthn.rp_origins(完整 HTTPS 来源),然后重启服务。',
stepUp: '敏感操作二次验证 (step-up 2FA)',
stepUpHint: '开启后,账号/代理导出、备份创建与下载、S3 配置修改、提升管理员等敏感操作需要先完成 TOTP 二次验证(15 分钟内有效)。开启前需本人已启用 2FA;关闭该开关本身也需要二次验证。',
stepUpEnableRequiresTotp: '开启敏感操作二次验证前,请先在个人资料中为当前账号启用 2FA (TOTP)。',
@@ -0,0 +1,64 @@
import { describe, expect, it } from 'vitest'
import { getExpirationDateRelation, getRemainingExpiryDuration } from '../subscriptionQuota'
describe('subscription expiry timing', () => {
it('uses local calendar dates for today and tomorrow', () => {
const now = new Date(2026, 2, 7, 23, 30)
expect(getExpirationDateRelation(new Date(2026, 2, 7, 23, 45), now)).toBe('today')
expect(getExpirationDateRelation(new Date(2026, 2, 8, 3, 30), now)).toBe('tomorrow')
})
it('treats the exact expiry instant and elapsed expiries as expired', () => {
const now = new Date(2026, 6, 30, 9, 0)
expect(getExpirationDateRelation(now, now)).toBe('expired')
expect(getRemainingExpiryDuration(now, now)).toBeNull()
expect(getExpirationDateRelation(new Date(2026, 6, 30, 8, 59), now)).toBe('expired')
expect(getRemainingExpiryDuration(new Date(2026, 6, 30, 8, 59), now)).toBeNull()
})
it('rejects invalid target and current dates', () => {
const invalid = new Date('invalid')
const valid = new Date(2026, 6, 30, 9, 0)
expect(getExpirationDateRelation(invalid, valid)).toBeNull()
expect(getExpirationDateRelation(valid, invalid)).toBeNull()
expect(getRemainingExpiryDuration(invalid, valid)).toBeNull()
expect(getRemainingExpiryDuration(valid, invalid)).toBeNull()
})
it('returns rounded-up hours and minutes for an expiry under 24 hours away', () => {
const now = new Date(2026, 6, 30, 9, 0)
expect(getRemainingExpiryDuration(new Date(2026, 6, 31, 8, 30), now)).toEqual({
unit: 'hoursMinutes',
hours: 23,
minutes: 30
})
expect(getRemainingExpiryDuration(new Date(now.getTime() + 1), now)).toEqual({
unit: 'hoursMinutes',
hours: 0,
minutes: 1
})
expect(getRemainingExpiryDuration(new Date(now.getTime() + 23 * 60 * 60 * 1000 + 1), now)).toEqual({
unit: 'hoursMinutes',
hours: 23,
minutes: 1
})
})
it('preserves rounded-up day display from 24 hours onward', () => {
const now = new Date(2026, 6, 30, 9, 0)
expect(getRemainingExpiryDuration(new Date(now.getTime() + 24 * 60 * 60 * 1000), now)).toEqual({
unit: 'days',
days: 1
})
expect(getRemainingExpiryDuration(new Date(now.getTime() + 24 * 60 * 60 * 1000 + 1), now)).toEqual({
unit: 'days',
days: 2
})
})
})
+49
View File
@@ -2,6 +2,12 @@ import type { UserSubscription } from '@/types'
const ONE_DAY_MS = 24 * 60 * 60 * 1000
export type ExpirationDateRelation = 'expired' | 'today' | 'tomorrow' | 'later'
export type RemainingExpiryDuration =
| { unit: 'days'; days: number }
| { unit: 'hoursMinutes'; hours: number; minutes: number }
export interface RemainingDurationParts {
days: number
hours: number
@@ -40,3 +46,46 @@ export function getRemainingDurationParts(
return { days, hours, minutes }
}
export function getExpirationDateRelation(
targetAt: Date | string,
now: Date = new Date()
): ExpirationDateRelation | null {
const target = targetAt instanceof Date ? targetAt : new Date(targetAt)
const targetTime = target.getTime()
const nowTime = now.getTime()
if (!Number.isFinite(targetTime) || !Number.isFinite(nowTime)) return null
if (targetTime <= nowTime) return 'expired'
const targetDay = Date.UTC(target.getFullYear(), target.getMonth(), target.getDate())
const currentDay = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate())
const calendarDays = Math.round((targetDay - currentDay) / ONE_DAY_MS)
if (calendarDays === 0) return 'today'
if (calendarDays === 1) return 'tomorrow'
return 'later'
}
export function getRemainingExpiryDuration(
targetAt: Date | string,
now: Date = new Date()
): RemainingExpiryDuration | null {
const targetTime = targetAt instanceof Date ? targetAt.getTime() : new Date(targetAt).getTime()
const nowTime = now.getTime()
if (!Number.isFinite(targetTime) || !Number.isFinite(nowTime)) return null
const diffMs = targetTime - nowTime
if (diffMs <= 0) return null
if (diffMs >= ONE_DAY_MS) {
return { unit: 'days', days: Math.ceil(diffMs / ONE_DAY_MS) }
}
const totalMinutes = Math.ceil(diffMs / (60 * 1000))
return {
unit: 'hoursMinutes',
hours: Math.floor(totalMinutes / 60),
minutes: totalMinutes % 60
}
}
@@ -1631,6 +1631,9 @@
)
}}
</p>
<p v-if="!form.passkey_configured" class="mt-2">
{{ t("admin.settings.security.passkeyDeploymentHint") }}
</p>
</div>
</div>
+29 -4
View File
@@ -353,9 +353,14 @@
>
{{ formatDateTimeToMinute(value) }}
</span>
<div v-if="getDaysRemaining(value) !== null" class="text-xs text-gray-500">
{{ getDaysRemaining(value) }} {{ t('admin.subscriptions.daysRemaining') }}
</div>
<template
v-for="remainingExpiry in [formatRemainingExpiry(value)]"
:key="remainingExpiry ?? 'expired'"
>
<div v-if="remainingExpiry" class="text-xs text-gray-500">
{{ remainingExpiry }}
</div>
</template>
</div>
<span v-else class="text-sm text-gray-500">{{
t('admin.subscriptions.noExpiration')
@@ -777,7 +782,12 @@ import Select from '@/components/common/Select.vue'
import GroupBadge from '@/components/common/GroupBadge.vue'
import GroupOptionItem from '@/components/common/GroupOptionItem.vue'
import Icon from '@/components/icons/Icon.vue'
import { getRemainingDurationParts, isOneTimeDailyQuota, type RemainingDurationParts } from '@/utils/subscriptionQuota'
import {
getRemainingDurationParts,
getRemainingExpiryDuration,
isOneTimeDailyQuota,
type RemainingDurationParts
} from '@/utils/subscriptionQuota'
const { t } = useI18n()
const appStore = useAppStore()
@@ -1334,6 +1344,21 @@ const getDaysRemaining = (expiresAt: string): number | null => {
return Math.ceil(diff / (1000 * 60 * 60 * 24))
}
const formatRemainingExpiry = (expiresAt: string): string | null => {
const duration = getRemainingExpiryDuration(expiresAt)
if (!duration) return null
if (duration.unit === 'days') {
return t('admin.subscriptions.daysRemaining', { days: duration.days })
}
if (duration.hours) {
return t('admin.subscriptions.hoursMinutesRemaining', {
hours: duration.hours,
minutes: duration.minutes
})
}
return t('admin.subscriptions.minutesRemaining', { minutes: duration.minutes })
}
const isExpiringSoon = (expiresAt: string): boolean => {
const days = getDaysRemaining(expiresAt)
return days !== null && days <= 7
@@ -225,6 +225,8 @@ vi.mock("vue-i18n", async () => {
"admin.settings.upstreamBillingProbe.intervalHint": "范围 5–1440 分钟。",
"admin.settings.upstreamBillingProbe.saved": "上游倍率自动探测设置已保存",
"admin.settings.upstreamBillingProbe.saveFailed": "保存上游倍率自动探测设置失败",
"admin.settings.security.passkeyDeploymentHint":
"请由服务器运维在部署配置中将 webauthn.enabled 设为 true,填写 webauthn.rp_id(仅域名)与 webauthn.rp_origins(完整 HTTPS 来源),然后重启服务。",
"admin.settings.site.uploadImage": "上传图片",
"admin.settings.site.remove": "移除",
"admin.settings.platformQuota.platform": "平台",
@@ -737,6 +739,7 @@ describe("admin SettingsView payment visible method controls", () => {
expect(toggle.attributes("disabled")).toBeUndefined();
expect(settings.text()).toContain("sub3.nebula-spaces.com");
expect(settings.text()).toContain("https://sub3.nebula-spaces.com");
expect(settings.text()).not.toContain("webauthn.enabled");
await toggle.setValue(false);
await wrapper.find("form").trigger("submit.prevent");
@@ -762,9 +765,14 @@ describe("admin SettingsView payment visible method controls", () => {
const settings = wrapper.get('[data-testid="passkey-settings"]');
expect(settings.get('[data-testid="passkey-toggle"]').attributes("disabled")).toBeDefined();
expect(settings.get('[data-testid="passkey-config-status"]').text()).toContain(
const status = settings.get('[data-testid="passkey-config-status"]');
expect(status.text()).toContain(
"admin.settings.security.passkeyNotConfigured",
);
expect(status.text()).toContain("webauthn.enabled");
expect(status.text()).toContain("webauthn.rp_id");
expect(status.text()).toContain("webauthn.rp_origins");
expect(status.text()).toContain("然后重启服务");
});
it("loads, edits, validates, and saves forwarded client-IP headers", async () => {
+13 -5
View File
@@ -259,7 +259,12 @@ import Icon from '@/components/icons/Icon.vue'
import { formatDateTimeToMinute } from '@/utils/format'
import { hasPeakRate, formatPeakRateWindow, serverTimezoneLabel } from '@/utils/peak-rate'
import { platformBorderClass, platformBadgeClass, platformButtonClass, platformLabel } from '@/utils/platformColors'
import { getRemainingDurationParts, isOneTimeDailyQuota, type RemainingDurationParts } from '@/utils/subscriptionQuota'
import {
getExpirationDateRelation,
getRemainingDurationParts,
isOneTimeDailyQuota,
type RemainingDurationParts
} from '@/utils/subscriptionQuota'
function platformAccentDotClass(p: string): string {
switch (p) {
@@ -317,17 +322,20 @@ function formatExpirationDate(expiresAt: string): string {
const expires = new Date(expiresAt)
const diff = expires.getTime() - now.getTime()
const days = Math.ceil(diff / (1000 * 60 * 60 * 24))
const relation = getExpirationDateRelation(expires, now)
if (days < 0) {
if (relation === null) return ''
if (relation === 'expired') {
return t('userSubscriptions.status.expired')
}
const dateStr = formatDateTimeToMinute(expires)
if (days === 0) {
if (relation === 'today') {
return `${dateStr} (${t('common.today')})`
}
if (days === 1) {
if (relation === 'tomorrow') {
return `${dateStr} (${t('common.tomorrow')})`
}
@@ -340,7 +348,7 @@ function getExpirationClass(expiresAt: string): string {
const diff = expires.getTime() - now.getTime()
const days = Math.ceil(diff / (1000 * 60 * 60 * 24))
if (days <= 0) return 'text-red-600 dark:text-red-400 font-medium'
if (diff <= 0) return 'text-red-600 dark:text-red-400 font-medium'
if (days <= 3) return 'text-red-600 dark:text-red-400'
if (days <= 7) return 'text-orange-600 dark:text-orange-400'
return 'text-gray-700 dark:text-gray-300'
@@ -3,6 +3,7 @@ import { flushPromises, shallowMount } from '@vue/test-utils'
import PaymentView from '../PaymentView.vue'
import { PAYMENT_RECOVERY_STORAGE_KEY } from '@/components/payment/paymentFlow'
import { formatPaymentAmount } from '@/components/payment/currency'
import SubscriptionPlanCard from '@/components/payment/SubscriptionPlanCard.vue'
import type { CheckoutInfoResponse, MethodLimit, SubscriptionPlan } from '@/types/payment'
const routeState = vi.hoisted(() => ({
@@ -236,6 +237,61 @@ async function mountSubscriptionConfirm(options: Parameters<typeof checkoutInfoW
return wrapper
}
async function mountSubscriptionPlanList(planCount: number) {
vi.useRealTimers()
routeState.path = '/purchase'
routeState.query = { tab: 'subscription' }
routerReplace.mockReset().mockResolvedValue(undefined)
routerPush.mockReset().mockResolvedValue(undefined)
routerResolve.mockClear()
createOrder.mockReset()
refreshUser.mockReset()
fetchActiveSubscriptions.mockReset().mockResolvedValue(undefined)
showError.mockReset()
showInfo.mockReset()
showWarning.mockReset()
const basePlan = checkoutInfoWithPlansFixture().data.plans[0]
const plans = Array.from({ length: planCount }, (_, index) => ({
...basePlan,
id: index + 1,
name: `Plan ${index + 1}`,
}))
getCheckoutInfo.mockReset().mockResolvedValue(checkoutInfoFixture({ plans }))
bridgeInvoke.mockReset()
window.localStorage.clear()
;(window as Window & { WeixinJSBridge?: { invoke: typeof bridgeInvoke } }).WeixinJSBridge = undefined
const wrapper = shallowMount(PaymentView, {
global: {
stubs: {
AppLayout: {
template: '<div><slot /></div>',
},
Teleport: true,
Transition: false,
},
},
})
await flushPromises()
await flushPromises()
return wrapper
}
describe('PaymentView subscription plan grid', () => {
it.each([3, 4, 6])('keeps %i plans on the existing mobile/tablet/desktop grid', async (planCount) => {
const wrapper = await mountSubscriptionPlanList(planCount)
const cards = wrapper.findAllComponents(SubscriptionPlanCard)
expect(cards).toHaveLength(planCount)
expect([...(cards[0].element.parentElement?.classList ?? [])]).toEqual(expect.arrayContaining([
'grid',
'grid-cols-1',
'sm:grid-cols-2',
'lg:grid-cols-3',
]))
})
})
describe('PaymentView subscription confirmation amounts', () => {
it('shows converted CNY pay amount using the subscription rate, not the balance multiplier', async () => {
const wrapper = await mountSubscriptionConfirm({