feat(proxy): pin manual keys to direct routes (#113)

This commit is contained in:
Jason Xu committed 2026-11-30 04:40:43 +08:00
1 parent a256090eab
commit a0fbd6b6cb
15 files changed
+81 -12

No files matched your search

+2
View File
@@ -190,6 +190,8 @@ OAuth routes follow separate rules: the selected OAuth tier owns the request, us
Mark a provider-managed rotating endpoint with `pool+https://proxy.example:8443` or `https://proxy.example:8443#pool`. Each attempt then opens a fresh connection without keep-alive/HTTP/2 reuse; these entries do not use static-node cooldown or health eviction. The provider must actually rotate its exits. Static proxies retain connection reuse, health tracking, and key bindings. `proxy_bindings` can pin a key fingerprint to a configured proxy.
`keys_direct: true` pins unbound manual Zen/Go keys to dual-stack `direct`, including model discovery and active probes, without failover to proxies or WARP. Explicit `proxy_bindings` take priority, including `direct4`/`direct6` bindings. The default is `false`. If needed, a key-only direct transport is created at runtime without changing `proxies` or copying `proxyfile` entries into the saved file. This injected route is never added to anonymous or automatic OAuth routing; explicitly configured direct routes remain available to them. OAuth connections retain their own routing policy. This setting does not disable anonymous-first routing for free models; disable `anonymous` separately if all inference must use keys.
To choose a direct address family per upstream key, first include the routes in `proxies` or `proxyfile`, then bind the key fingerprints:
```json
+1
View File
@@ -5,6 +5,7 @@
"go_keys": [],
// Anonymous traffic may be heavily blocked upstream. Prefer a Zen API Key.
"anonymous": false,
"keys_direct": false,
"warp": {
"enabled": false,
"pool_size": 2,
+1
View File
@@ -78,6 +78,7 @@ Common management defaults:
| `logging.ring_size` | `2000`; range 100–50,000. |
| `logging.dump_request_bodies` | `false`; also requires debug logging, capped at 64 KiB per prepared body. |
| `models.active_probes` | `false`; real traffic supplies default availability observations. |
| `keys_direct` | `false`; pins unbound manual Zen/Go keys to dual-stack direct egress; explicit bindings win. Anonymous/OAuth routing is unchanged. |
## Go OAuth and Zen PAYG OAuth
+8 -1
View File
@@ -160,6 +160,7 @@ type ConfigView struct {
ZenKeys []SecretView `json:"zen_keys"`
GoKeys []SecretView `json:"go_keys"`
Anonymous bool `json:"anonymous"`
KeysDirect bool `json:"keys_direct"`
Warp config.WarpConfig `json:"warp"`
Proxies []SecretView `json:"proxies"`
ProxyFile string `json:"proxyfile"`
@@ -209,6 +210,7 @@ type ConfigUpdate struct {
ZenKeys []SecretInput `json:"zen_keys"`
GoKeys []SecretInput `json:"go_keys"`
Anonymous bool `json:"anonymous"`
KeysDirect *bool `json:"keys_direct,omitempty"`
Warp config.WarpConfig `json:"warp"`
Proxies []SecretInput `json:"proxies"`
ProxyFile string `json:"proxyfile"`
@@ -277,6 +279,7 @@ func (a *Server) handlePutConfig(w http.ResponseWriter, r *http.Request) {
ZenOAuth: current.ZenOAuth,
Listen: update.Listen, ServerKeys: serverKeys, ZenKeys: zenKeys, GoKeys: goKeys, Anonymous: update.Anonymous, Warp: update.Warp, Proxies: proxies, ProxyFile: update.ProxyFile,
ProxyBindings: proxyBindings,
KeysDirect: current.KeysDirect,
Upstream: update.Upstream, Retry: update.Retry, Models: update.Models, Performance: update.Performance, Logging: update.Logging, Prefer: update.Prefer,
Reasoning: reasoning,
WebUI: config.WebUIConfig{Enabled: update.WebUI.Enabled, Listen: update.WebUI.Listen, Username: current.WebUI.Username, PasswordHash: current.WebUI.PasswordHash, SessionTTLMinutes: update.WebUI.SessionTTLMinutes},
@@ -289,6 +292,10 @@ func (a *Server) handlePutConfig(w http.ResponseWriter, r *http.Request) {
candidate.ZenOAuth = latest.ZenOAuth
candidate.ServerKeyMetadata = latest.ServerKeyMetadata
candidate.Rotation = latest.Rotation
candidate.KeysDirect = latest.KeysDirect
if update.KeysDirect != nil {
candidate.KeysDirect = *update.KeysDirect
}
candidate.WebUI.Username = latest.WebUI.Username
candidate.WebUI.PasswordHash = latest.WebUI.PasswordHash
if update.Reasoning == nil {
@@ -459,7 +466,7 @@ func (a *Server) configView() ConfigView {
upstream.Anonymous = config.RedactURL(upstream.Anonymous)
return ConfigView{
Listen: cfg.Listen, ServerKeys: maskSecrets(cfg.ServerKeys, false), ZenKeys: maskSecrets(cfg.ZenKeys, false), GoKeys: maskSecrets(cfg.GoKeys, false), Anonymous: cfg.Anonymous, Warp: cfg.Warp,
Proxies: maskSecrets(cfg.Proxies, true), ProxyFile: cfg.ProxyFile, ProxyBindings: proxyBindings, Upstream: upstream, Retry: cfg.Retry, Models: cfg.Models,
Proxies: maskSecrets(cfg.Proxies, true), ProxyFile: cfg.ProxyFile, ProxyBindings: proxyBindings, KeysDirect: cfg.KeysDirect, Upstream: upstream, Retry: cfg.Retry, Models: cfg.Models,
Performance: cfg.Performance, Logging: cfg.Logging, Prefer: cfg.Prefer, Reasoning: cfg.Reasoning,
WebUI: WebUIView{Enabled: cfg.WebUI.Enabled, Listen: cfg.WebUI.Listen, Username: cfg.WebUI.Username, SessionTTLMinutes: cfg.WebUI.SessionTTLMinutes},
Effective: EffectiveView{Listen: effective.API, WebUIListen: effective.WebUI, WebUIEnabled: effective.WebUIEnabled},
+1
View File
@@ -37,6 +37,7 @@ type Config struct {
GoOAuth *oauth.Connection `json:"go_oauth,omitempty"`
ZenOAuth *oauth.Connection `json:"zen_oauth,omitempty"`
Anonymous bool `json:"anonymous"`
KeysDirect bool `json:"keys_direct"`
Warp WarpConfig `json:"warp"`
Proxies []string `json:"proxies"`
ProxyFile string `json:"proxyfile"`
+22 -3
View File
@@ -117,16 +117,35 @@ func New(cfg config.Config, logger *slog.Logger, monitor *telemetry.Metrics, war
if err != nil {
return nil, err
}
transports, err := transportPool(cfg.RuntimeProxies(), cfg.Performance, cfg.Performance.AttemptTimeout(time.Duration(cfg.Retry.TimeoutSeconds)*time.Second))
proxyNames := append([]string(nil), cfg.RuntimeProxies()...)
injectedDirect := false
hasManualKeys := cfg.ZenOAuth == nil && len(cfg.ZenKeys) > 0 || cfg.GoOAuth == nil && len(cfg.GoKeys) > 0
if cfg.KeysDirect && hasManualKeys {
hasDirect := false
for _, name := range proxyNames {
if name == "direct" {
hasDirect = true
break
}
}
if !hasDirect {
proxyNames = append(proxyNames, "direct")
injectedDirect = true
}
}
transports, err := transportPool(proxyNames, cfg.Performance, cfg.Performance.AttemptTimeout(time.Duration(cfg.Retry.TimeoutSeconds)*time.Second))
if err != nil {
return nil, err
}
if injectedDirect {
transports.items[len(transports.items)-1].keysOnly = true
}
cooldown := time.Duration(cfg.Performance.FailureCooldownSeconds) * time.Second
zenKeys := cfg.ZenKeys
if cfg.ZenOAuth != nil {
zenKeys = nil
}
zenNodes, err := nodePool(zenKeys, transports, cooldown, cfg.ProxyBindings)
zenNodes, err := nodePool(zenKeys, transports, cooldown, cfg.ProxyBindings, cfg.KeysDirect)
if err != nil {
return nil, fmt.Errorf("zen node pool: %w", err)
}
@@ -134,7 +153,7 @@ func New(cfg config.Config, logger *slog.Logger, monitor *telemetry.Metrics, war
if cfg.GoOAuth != nil {
goKeys = nil
}
goNodes, err := nodePool(goKeys, transports, cooldown, cfg.ProxyBindings)
goNodes, err := nodePool(goKeys, transports, cooldown, cfg.ProxyBindings, cfg.KeysDirect)
if err != nil {
return nil, fmt.Errorf("go node pool: %w", err)
}
+11
View File
@@ -70,6 +70,12 @@ type healthWarp struct {
func (g *Gateway) handleHealth(w http.ResponseWriter, _ *http.Request) {
_, models := g.availableModels()
proxyTotal, proxyHealthy := g.transports.healthCounts()
sharedHealthy := proxyHealthy
for _, proxy := range g.transports.items {
if proxy.keysOnly && proxy.healthy.Load() {
sharedHealthy--
}
}
zenKeys, goKeys := g.zenNodes.Len(), g.goNodes.Len()
if g.cfg.ZenOAuth != nil {
zenKeys = 1
@@ -130,6 +136,11 @@ func (g *Gateway) handleHealth(w http.ResponseWriter, _ *http.Request) {
// Proxies carry Go-tier traffic whenever Go keys exist, and every lane
// while WARP is off; free-model traffic alone does not need them.
proxyBlocking := proxyHealthy == 0 && (g.warp == nil || goKeys > 0 || g.cfg.ZenOAuth != nil)
sharedRequired := g.cfg.GoOAuth != nil || g.cfg.ZenOAuth != nil || g.cfg.Anonymous && g.warp == nil
if sharedRequired && sharedHealthy == 0 {
proxyBlocking = true
issues = append(issues, "no_healthy_shared_proxies")
}
if proxyHealthy == 0 {
issues = append(issues, "no_healthy_proxies")
}
+12 -3
View File
@@ -207,10 +207,19 @@ func (g *Gateway) oauthProxy(ctx context.Context, connection *oauth.Connection,
if pinned != nil {
return pinned, nil
}
proxies := make([]*proxyTransport, 0, len(g.transports.items))
for _, proxy := range g.transports.items {
if proxy != nil && !proxy.keysOnly {
proxies = append(proxies, proxy)
}
}
if len(proxies) == 0 {
return nil, errProxyUnavailable
}
digest := sha256.Sum256([]byte(oauthAccountID(connection) + "\x00" + affinity))
start := int(binary.LittleEndian.Uint64(digest[:8]) % uint64(len(g.transports.items)))
for step := range len(g.transports.items) {
proxy := g.transports.items[(start+offset+step)%len(g.transports.items)]
start := int(binary.LittleEndian.Uint64(digest[:8]) % uint64(len(proxies)))
for step := range len(proxies) {
proxy := proxies[(start+offset+step)%len(proxies)]
if proxy != nil && proxy.healthy.Load() {
return proxy, nil
}
+8 -1
View File
@@ -33,6 +33,7 @@ type proxyTransport struct {
index int
name string
pool bool
keysOnly bool
client *http.Client
bun *http.Client
healthy atomic.Bool
@@ -116,6 +117,9 @@ func anonymousPool(enabled bool, transports *proxyTransports, cooldown time.Dura
}
pool.nodes = make([]*anonymousNode, 0, len(transports.items))
for _, proxy := range transports.items {
if proxy.keysOnly {
continue
}
if proxy.pool {
pool.hasPool = true
}
@@ -684,7 +688,7 @@ type upstreamNodes struct {
// configured, bound keys are permanently pinned to their specified proxy and
// fail closed if that proxy fails. Unbound keys are distributed in round-robin
// order and can fail over to other proxies.
func nodePool(keys []string, transports *proxyTransports, cooldown time.Duration, bindings map[string]string) (*upstreamNodes, error) {
func nodePool(keys []string, transports *proxyTransports, cooldown time.Duration, bindings map[string]string, keysDirect bool) (*upstreamNodes, error) {
if transports == nil || len(transports.items) == 0 {
return nil, fmt.Errorf("at least one proxy transport is required")
}
@@ -710,6 +714,9 @@ func nodePool(keys []string, transports *proxyTransports, cooldown time.Duration
if !hasBinding {
targetProxy, hasBinding = bindings[key]
}
if !hasBinding && keysDirect {
targetProxy, hasBinding = "direct", true
}
var proxyIndex int
var bound bool
+1 -1
View File
@@ -149,7 +149,7 @@ func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult
}
cursor := g.zenNodes.CursorFor(ids.Session)
if node := cursor.Next(); node != nil {
if g.usesWARP(model, config.TierZen, false) {
if !node.bound && g.usesWARP(model, config.TierZen, false) {
lanes = append(lanes, lane{key: node.key, name: "zen", baseURL: g.cfg.Upstream.Zen, warp: true})
} else if proxy := g.zenNodes.Proxy(node); proxy != nil {
lanes = append(lanes, lane{key: node.key, name: "zen", baseURL: g.cfg.Upstream.Zen, client: g.inferenceClient(proxy, g.cfg.Upstream.Zen, model)})
+1 -1
View File
@@ -251,7 +251,7 @@ func (g *Gateway) refreshProtocolCapabilities(ctx context.Context) (modelcatalog
}
var lastErr error
for _, proxy := range g.transports.items {
if proxy == nil || !proxy.healthy.Load() {
if proxy == nil || proxy.keysOnly || !proxy.healthy.Load() {
continue
}
capabilities, err := modelcatalog.FetchCapabilities(ctx, proxy.client, modelcatalog.CapabilitiesURL)
+2 -2
View File
@@ -110,7 +110,7 @@ func RuntimeManager(root context.Context, configPath string, cfg config.Config,
}
clients := make([]*http.Client, 0, len(runtime.gateway.transports.items))
for _, proxy := range runtime.gateway.transports.items {
if proxy != nil && proxy.healthy.Load() {
if proxy != nil && !proxy.keysOnly && proxy.healthy.Load() {
clients = append(clients, proxy.client)
}
}
@@ -585,7 +585,7 @@ func (m *RuntimeController) Resources() ResourceSnapshot {
goBindings := append([]int(nil), gateway.goNodes.bindingCount...)
gateway.goNodes.bindingsMu.Unlock()
for _, proxy := range gateway.transports.items {
status := ProxyStatus{Index: proxy.index, Address: config.RedactURL(proxy.name), Healthy: proxy.healthy.Load(), Checking: proxy.checking.Load(), Anonymous: gateway.cfg.Anonymous}
status := ProxyStatus{Index: proxy.index, Address: config.RedactURL(proxy.name), Healthy: proxy.healthy.Load(), Checking: proxy.checking.Load(), Anonymous: gateway.cfg.Anonymous && !proxy.keysOnly}
if proxy.index < len(zenBindings) {
status.ZenKeys = zenBindings[proxy.index]
}
+6
View File
@@ -887,6 +887,12 @@
</label>
<p class="config-warning" data-i18n="config.secrets.anonymousWarning">匿名通道默认关闭,可能已被上游重点封堵。建议优先配置 Zen API Key;启用匿名不保证可用,也不会自动修改当前设置。</p>
</div>
<div class="field full">
<label class="check">
<input id="c-keys-direct" type="checkbox" />
<span data-i18n="config.secrets.keysDirect">手动上游密钥默认固定直连(显式代理绑定优先)</span>
</label>
</div>
<div class="field full">
<label for="server_keys-new">Server Keys</label>
<div id="server_keys-chips" class="chips"></div>
+3
View File
@@ -268,6 +268,7 @@ const DICTIONARY = {
"Sensitive values are masked by default; a cleared value only takes effect after saving.",
"config.secrets.reveal": "Reveal after re-verification",
"config.secrets.anonymous": "Enable the Zen anonymous channel",
"config.secrets.keysDirect": "Pin manual upstream keys to direct egress (explicit proxy bindings take priority)",
"config.secrets.anonymousWarning": "Anonymous access is disabled by default and may be heavily blocked upstream. Prefer a Zen API key. Enabling anonymous access does not guarantee availability or automatically change your current settings.",
"config.secrets.add": "One key per line",
"config.proxy.title": "Proxy nodes",
@@ -945,6 +946,7 @@ const DICTIONARY = {
"Giá trị nhạy cảm mặc định chỉ hiện dạng che; chỉ lưu sau khi gỡ bỏ mới có hiệu lực.",
"config.secrets.reveal": "Xem sau khi xác minh lại",
"config.secrets.anonymous": "Bật kênh ẩn danh Zen",
"config.secrets.keysDirect": "Ghim khóa thượng nguồn thủ công vào kết nối trực tiếp (ưu tiên liên kết proxy rõ ràng)",
"config.secrets.add": "Mỗi dòng thêm một key",
"config.proxy.title": "Nút Proxy",
"config.proxy.caption":
@@ -1533,6 +1535,7 @@ const DICTIONARY = {
"I valori sensibili sono mascherati per impostazione predefinita; un valore svuotato ha effetto solo dopo il salvataggio.",
"config.secrets.reveal": "Mostra dopo nuova verifica",
"config.secrets.anonymous": "Abilita il canale anonimo Zen",
"config.secrets.keysDirect": "Vincola le chiavi upstream manuali alla connessione diretta (i vincoli proxy espliciti hanno priorità)",
"config.secrets.add": "Una chiave per riga",
"config.proxy.title": "Nodi proxy",
"config.proxy.caption":
+2
View File
@@ -92,6 +92,7 @@ function fillConfig(value) {
$("#c-session").value = value.webui.session_ttl_minutes;
$("#c-web-enabled").checked = value.webui.enabled;
$("#c-anonymous").checked = !!value.anonymous;
$("#c-keys-direct").checked = !!value.keys_direct;
const warp = value.warp || {};
$("#c-warp-enabled").checked = !!warp.enabled;
$("#c-warp-pool").value = warp.pool_size || 2;
@@ -155,6 +156,7 @@ async function save(event) {
zen_keys: secretInputs("zen_keys"),
go_keys: secretInputs("go_keys"),
anonymous: $("#c-anonymous").checked,
keys_direct: $("#c-keys-direct").checked,
warp: {
enabled: $("#c-warp-enabled").checked,
pool_size: numberValue("#c-warp-pool"),