Repository navigation
Conversation
- Add PassThroughHeaders field to ChannelOtherSettings - Implement selective header forwarding in SetupApiRequestHeader - Add UI switch in channel edit modal for Claude (type 14) - Add debug logging to compare client vs upstream headers This feature allows forwarding all client headers to upstream providers to resolve 403 errors caused by client restrictions. By default, only Content-Type and Accept headers are forwarded. When enabled, all headers except sensitive ones (Authorization, Host, X-Forwarded-*, etc.) are passed through.
Move the pass_through_headers UI switch from Claude-specific section to the general Channel Extra Settings section, making it available for all channel types. This change aligns with the backend implementation which already supports header pass-through for all channels. Now users can enable this feature for any upstream provider that has client restrictions. Location: Placed next to pass_through_body_enabled for better UX.
修复编辑渠道时未正确加载 pass_through_headers 字段状态的问题。 现在编辑渠道时,"透传全部请求头"开关会正确显示之前保存的状态。 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
WalkthroughAdds a boolean PassThroughHeaders to channel settings, forwards a whitelist of client headers to upstream when enabled, surfaces a UI toggle to control it, adds debug logging of client/upstream headers, and updates a CI workflow image repository name. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant Channel
participant ReqHandler as Request Handler
participant Upstream
Client->>Channel: HTTP request (with headers)
Channel->>ReqHandler: SetupApiRequestHeader(info, req)
Note right of ReqHandler: Debug log client headers (if DebugEnabled)
alt PassThroughHeaders = true
ReqHandler->>ReqHandler: Select headers where name starts with "anthropic-" or name == "x-app" or name == "user-agent"
ReqHandler->>ReqHandler: Copy selected headers to upstream request (preserve values)
else
ReqHandler->>ReqHandler: Forward default headers (Content-Type, Accept)
end
alt Streaming and Accept missing
ReqHandler->>ReqHandler: Set Accept: text/event-stream
end
Note right of ReqHandler: Debug log upstream headers (if DebugEnabled)
ReqHandler->>Upstream: Execute request
Upstream-->>Channel: Response
Channel-->>Client: Return response
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes
Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
web/src/components/table/channels/modals/EditChannelModal.jsx (1)
130-166: Consider adding explicit initialization and cleanup for consistency.For consistency with other
channelOtherSettingsfields likeallow_service_tier:
- Add
pass_through_headers: falsetooriginInputs(around line 166)- Add
delete localInputs.pass_through_headersin the submit cleanup section (around line 1223)While the feature works correctly via implicit preservation in the settings JSON, explicit handling improves code maintainability and follows the established pattern for similar fields.
Suggested additions:
In originInputs (around line 166):
allow_service_tier: false, disable_store: false, // false = 允许透传(默认开启) allow_safety_identifier: false, + pass_through_headers: false, };In submit cleanup (around line 1223):
delete localInputs.allow_service_tier; delete localInputs.disable_store; delete localInputs.allow_safety_identifier; + delete localInputs.pass_through_headers;Also applies to: 1208-1223
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
dto/channel_settings.go(1 hunks)relay/channel/api_request.go(3 hunks)web/src/components/table/channels/modals/EditChannelModal.jsx(4 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-08-27T02:15:25.448Z
Learnt from: AAEE86
Repo: QuantumNous/new-api PR: 1658
File: web/src/components/table/channels/modals/EditChannelModal.jsx:555-569
Timestamp: 2025-08-27T02:15:25.448Z
Learning: In EditChannelModal.jsx, the database stores mapped keys (display names) in the models field after applying model mapping transformations. When loading a channel, data.models contains the mapped keys, not the original model names. The filtering logic if (data.models.includes(key)) in the initialization is correct.
Applied to files:
web/src/components/table/channels/modals/EditChannelModal.jsx
📚 Learning: 2025-08-27T02:15:25.448Z
Learnt from: AAEE86
Repo: QuantumNous/new-api PR: 1658
File: web/src/components/table/channels/modals/EditChannelModal.jsx:555-569
Timestamp: 2025-08-27T02:15:25.448Z
Learning: In EditChannelModal.jsx, the applyModelMapping function transforms the models list by replacing original model names (mapping values) with display names (mapping keys). The database stores this transformed list containing mapped keys. On channel load, data.models contains these mapped display names, making the initialization filter if (data.models.includes(key)) correct.
Applied to files:
web/src/components/table/channels/modals/EditChannelModal.jsx
🧬 Code graph analysis (1)
relay/channel/api_request.go (3)
dto/channel_settings.go (1)
ChannelOtherSettings(26-35)common/constants.go (1)
DebugEnabled(71-71)logger/logger.go (1)
LogDebug(69-76)
🔇 Additional comments (4)
dto/channel_settings.go (1)
34-34: LGTM! Field addition follows Go conventions.The new
PassThroughHeadersfield is correctly structured with proper json tags and clear documentation explaining the default behavior.relay/channel/api_request.go (1)
97-101: Debug logging appropriately placed.The debug logging hooks at both ends of the request pipeline (client headers and final upstream headers) will aid troubleshooting when the passthrough feature is enabled.
Also applies to: 115-118
web/src/components/table/channels/modals/EditChannelModal.jsx (2)
574-575: LGTM! Settings load logic correctly handles the new field.The code properly reads
pass_through_headersfrom the parsed settings and provides sensible defaults (false) for error cases and legacy data, consistent with the backend default.Also applies to: 586-586, 596-596
2964-2978: UI switch implementation is correct.The Form.Switch is properly wired using
handleChannelOtherSettingsChange, which correctly updates the settings JSON, form state, and inputs. The help text clearly explains the feature behavior.
Replace the website logo with a Hatsune Miku themed icon (120x120px). 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
Change the PassThroughHeaders feature from blacklist mode (passing all headers except excluded ones) to whitelist mode (only passing specific extension headers). Now when PassThroughHeaders is enabled, only these headers are passed through: - anthropic-* prefix headers (anthropic-version, anthropic-beta, etc.) - x-app header (application identifier) - User-Agent header (for statistics) This change prevents performance issues caused by passing unnecessary headers (like Accept-Encoding, Cache-Control, etc.) to upstream APIs. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
relay/channel/api_request.go (1)
33-70: Whitelist-based passthrough is safer but diverges from the “pass all headers” semantics and omits Origin/Referer.The new whitelist (anthropic-*, x-app, user-agent) in
SetupApiRequestHeaderis a good move from a security standpoint and avoids leaking things likeCookieandAuthorization. However:
- The field
ChannelOtherSettings.PassThroughHeadersis still documented as “透传全部客户端请求头(默认false,仅透传Content-Type和Accept)`, while the actual behavior now only passes a small subset of headers. This mismatch can confuse operators configuring channels.- The PR description mentions upstreams needing
OriginandReferer, but those headers are not included in the whitelist, so they still won’t be forwarded even whenPassThroughHeadersis true.Please double-check the intended behavior:
- If the goal is truly “all headers except a sensitive blocklist”, consider implementing that (with a strong denylist) instead of the current whitelist; or
- If the intended behavior is “only specific extensions needed for Anthropic and friends”, consider updating the DTO comment / UI label to reflect that narrower scope and decide explicitly whether
Origin/Referershould be included.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
web/public/logo.pngis excluded by!**/*.png
📒 Files selected for processing (1)
relay/channel/api_request.go(3 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
relay/channel/api_request.go (4)
dto/request_common.go (1)
Request(8-12)dto/channel_settings.go (1)
ChannelOtherSettings(26-35)common/constants.go (1)
DebugEnabled(71-71)logger/logger.go (1)
LogDebug(69-76)
| // 记录客户端原始请求头(用于调试) | ||
| if common2.DebugEnabled { | ||
| logger.LogDebug(c.Request.Context(), fmt.Sprintf("Client headers: %v", c.Request.Header)) | ||
| } | ||
|
|
There was a problem hiding this comment.
Avoid logging full client/upstream headers; redact sensitive values before logging.
These debug logs will include sensitive headers such as Authorization, X-API-Key, Cookie / Set-Cookie, and X-Forwarded-*. Even behind DebugEnabled, that’s risky for log storage, incident exports, and multi-tenant environments.
Recommend logging a sanitized copy of headers with sensitive keys redacted, e.g.:
- if common2.DebugEnabled {
- logger.LogDebug(c.Request.Context(), fmt.Sprintf("Client headers: %v", c.Request.Header))
- }
+ if common2.DebugEnabled {
+ logger.LogDebug(c.Request.Context(), fmt.Sprintf("Client headers: %v", sanitizeHeadersForLog(c.Request.Header)))
+ }
…
- if common2.DebugEnabled {
- logger.LogDebug(c.Request.Context(), fmt.Sprintf("Upstream headers: %v", headers))
- }
+ if common2.DebugEnabled {
+ logger.LogDebug(c.Request.Context(), fmt.Sprintf("Upstream headers: %v", sanitizeHeadersForLog(headers)))
+ }And add a helper like:
func sanitizeHeadersForLog(h http.Header) http.Header {
sanitized := http.Header{}
for k, values := range h {
lower := strings.ToLower(k)
if lower == "authorization" ||
lower == "proxy-authorization" ||
lower == "x-api-key" ||
lower == "cookie" ||
lower == "set-cookie" ||
strings.HasPrefix(lower, "x-forwarded-") {
sanitized[k] = []string{"***REDACTED***"}
} else {
sanitized[k] = append([]string(nil), values...)
}
}
return sanitized
}This keeps the debugging value while avoiding leaking raw secrets into logs.
Also applies to: 125-128
🤖 Prompt for AI Agents
In relay/channel/api_request.go around lines 108-112 (and similarly 125-128),
the debug logging prints full client/upstream headers which can leak sensitive
values; create a helper function sanitizeHeadersForLog(h http.Header) that
returns a copy with sensitive keys redacted (at minimum: authorization,
proxy-authorization, x-api-key, cookie, set-cookie and any header with prefix
x-forwarded-) and then replace direct logging of c.Request.Header (and upstream
headers) with logging of the sanitized copy so headers remain visible for
debugging but secrets are replaced with a constant like "***REDACTED***".
在渠道添加和管理页面,新增开关:用于透传用户其他的全部请求头给上游
目的:避免因上游可能的客户端限制等其他head部分限制导致客户无法通过中转使用目标服务
----------以下内容为ai总结⬇️
PR 描述
问题描述 / Problem
部分上游供应商(如 Anthropic Claude)会对客户端请求头进行检查,当发现缺少关键请求头(如
User-Agent、Origin、Referer)时,会返回 403 错误。目前 New-API 默认只转发 Content-Type 和 Accept
请求头,导致这些供应商的客户端限制无法通过。
Some upstream providers (e.g., Anthropic Claude) check client request headers and return 403 errors when key
headers (User-Agent, Origin, Referer) are missing. Currently, New-API only forwards Content-Type and Accept
headers by default, causing issues with providers that have client restrictions.
解决方案 / Solution
在渠道管理界面的"渠道额外设置"区块中新增"透传全部请求头"开关,启用后会转发所有客户端请求头(排除敏感头如
Authorization、Host、X-Forwarded-* 等),帮助解决上游供应商的客户端限制问题。
Added a "pass-through all request headers" toggle in the channel management interface. When enabled, it
forwards all client request headers (excluding sensitive ones like Authorization, Host, X-Forwarded-*) to
resolve upstream provider client restrictions.
主要改动 / Changes
后端 Backend
dto/channel_settings.go: 在ChannelOtherSettings中新增PassThroughHeaders字段relay/channel/api_request.go:SetupApiRequestHeader()函数,增加条件判断逻辑前端 Frontend
web/src/components/table/channels/modals/EditChannelModal.jsx:设计考虑 / Design Considerations
测试 / Testing
Summary by CodeRabbit
New Features
Security
Diagnostics
Chores
✏️ Tip: You can customize this high-level summary in your review settings.