From 0204ca1fdf741b0c8060bb16c394883f12b314a2 Mon Sep 17 00:00:00 2001 From: Empty <131457234+TiaraBasori@users.noreply.github.com> Date: Thu, 15 Oct 2026 01:43:14 +0800 Subject: [PATCH] fix: harden the free-tier gate shape and probe lanes (#81 fallout) (#84) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit OpenCode's 2026-10-14 gate rejects the gateway on every lane again (403 FreeTierError) while the official CLI keeps working. Probing byte-identical CLI v2.0.29 replays against the live endpoint isolated the deltas this changeset fixes on top of #83: - identity: derive the session from the new x-opencode-session-id signal too, and stop forwarding the legacy x-opencode-request header and canonical prj_* project ids upstream — both are instant 403s. - upstream: the x-opencode-project header keeps one conversation pinned to one upstream project but is now hashed into the bare 40-hex shape the client sends (a prj_* value 403s). - refresh: when the configured anonymous upstream has no models route (404), fall back to the legacy Zen console listing so the anonymous catalog still populates. The endpoint move, genuine tool definitions, and UA shape came in with #83; the definitions embedded there were re-verified byte-for-byte against a fresh CLI v2.0.29 capture, including the smallest passing toolset (shell + read) and per-tool definition checks. Validation: live end-to-end against opencode.ai — anonymous lane serves streaming and plain JSON chat completions on big-pickle and step-5-preview-free, tool calls pass through, all nine exposed free models probe available, go vet/build/gofmt clean. --- README.md | 2 +- README.zh-CN.md | 2 +- internal/gateway/probe.go | 2 +- internal/gateway/refresh.go | 5 +++++ internal/gateway/upstream.go | 35 ++++++++++++++++++++++++++++------- internal/httpx/client.go | 4 ++-- internal/identity/request.go | 20 ++++++++++++++++++-- internal/models/discovery.go | 3 +++ 8 files changed, 59 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index e8a7458..ddfabbe 100644 --- a/README.md +++ b/README.md @@ -256,7 +256,7 @@ See [config.example.json](config.example.json) for a complete starting configura | `zen_keys`, `go_keys` | At least one upstream key is required unless anonymous access is enabled. | | `anonymous` | `false`. | | `prefer` | `go`; accepts `go` or `zen`. | -| `upstream.zen` | `https://opencode.ai/zen`. | +| `upstream.zen` | `https://opencode.ai/inference/openai`. | | `upstream.go` | `https://opencode.ai/zen/go`. | | `proxies` | Falls back to `["direct"]` when both proxy sources are empty. | | `proxyfile` | Optional; relative paths resolve beside the configuration file. | diff --git a/README.zh-CN.md b/README.zh-CN.md index 344b8ea..c99a954 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -256,7 +256,7 @@ Key 初始化时均衡分配到代理。真实流量可以触发代理检查、K | `zen_keys`、`go_keys` | 未启用匿名模式时,至少需要一个上游 Key。 | | `anonymous` | `false`。 | | `prefer` | `go`;可选 `go`、`zen`。 | -| `upstream.zen` | `https://opencode.ai/zen`。 | +| `upstream.zen` | `https://opencode.ai/inference/openai`。 | | `upstream.go` | `https://opencode.ai/zen/go`。 | | `proxies` | 两个代理来源都为空时,使用 `["direct"]`。 | | `proxyfile` | 可选;相对路径基于配置文件所在目录解析。 | diff --git a/internal/gateway/probe.go b/internal/gateway/probe.go index 9dccfdb..ed5bbc0 100644 --- a/internal/gateway/probe.go +++ b/internal/gateway/probe.go @@ -73,7 +73,7 @@ func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult if !d.AvailableZen || !g.catalog.Supported(model) { return probeResult{reason: "unsupported_probe"} } - ids := identity.RequestIDs{Session: identity.CanonicalSessionID("availability:" + model), Project: identity.StableID("prj", "opencode2api:default-project")} + ids := identity.RequestIDs{Session: identity.CanonicalSessionID("availability:" + model), Project: "opencode2api:default-project"} type lane struct { key, name, baseURL string client *http.Client diff --git a/internal/gateway/refresh.go b/internal/gateway/refresh.go index 0a404a7..acd5b46 100644 --- a/internal/gateway/refresh.go +++ b/internal/gateway/refresh.go @@ -220,6 +220,11 @@ func (g *Gateway) refreshAnonymousTier(ctx context.Context, base string) []strin } refreshCtx, cancel := context.WithTimeout(ctx, 30*time.Second) models, status, err := modelcatalog.FetchModels(refreshCtx, node.proxy.client, base, anonymousZenKey) + if err != nil && status == 404 { + // The new inference backend does not expose a models listing; + // probe the legacy Zen console origin once before giving up. + models, status, err = modelcatalog.FetchModels(refreshCtx, node.proxy.client, modelcatalog.LegacyZenBase, anonymousZenKey) + } g.syncProxyResult(refreshCtx, node.proxy, status, err) cancel() if err == nil { diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.go index 8c68b8b..19f71ed 100644 --- a/internal/gateway/upstream.go +++ b/internal/gateway/upstream.go @@ -270,10 +270,10 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b return nil, errors.New("no prepared Zen request body"), 0 } // The anonymous free tier only serves agent-shaped streaming requests - // (anything else is rejected with 403 FreeTierError). Normalize the - // wire body here; the gateway collapses the stream back when the - // downstream client asked for a plain JSON reply. Key tiers keep their - // original bodies. + // carrying the official core tool definitions (anything else is rejected + // with 403 FreeTierError). Normalize the wire body here; the gateway + // collapses the stream back when the downstream client asked for a plain + // JSON reply. Key tiers keep their original bodies. body = prepareAnonymousBody(body, route.ProtocolFor(config.TierZen)) for attempts < limit { if ctx.Err() != nil { @@ -346,7 +346,11 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b // "shell" is the name OpenCode 2.x ships; the pre-2.x "bash" spelling is // deliberately not injected because the free tier validates the definition of // every tool it recognises, and a "bash" definition the gateway synthesises -// does not match the one upstream expects. +// does not match the one upstream expects. Since 2026-10-14 name presence is +// not enough either: the upstream compares each recognised tool's description +// and parameter schema against the official CLI's definitions byte-for-byte +// (minimal stand-ins 403), which is why the genuine definitions below are +// embedded. Tool order is irrelevant and extra client tools are allowed. var anonymousCoreTools = []string{"shell", "edit", "glob", "grep", "read"} // opencodeToolsJSON holds the genuine OpenCode tool definitions (description @@ -496,19 +500,25 @@ func anonymousToolName(protocol wire.Protocol, item any) string { return jsonutil.StringAt(entry, "name") } +// anonymousToolset returns the official wire-shaped definitions for the +// given tool names (all core tools when names is nil). func anonymousToolset(protocol wire.Protocol, names []string) []any { if names == nil { names = anonymousCoreTools } tools := make([]any, 0, len(names)) for _, name := range names { - tools = append(tools, anonymousTool(protocol, name)) + if tool := anonymousTool(protocol, name); tool != nil { + tools = append(tools, tool) + } } return tools } // anonymousTool renders one core tool in the shape the given protocol expects, -// using the genuine OpenCode definition whenever one is known. +// using the genuine OpenCode definition whenever one is known. SystemOne +// payloads never reach this path (prepareAnonymousBody forwards them +// verbatim), so it falls back to the Chat shape. func anonymousTool(protocol wire.Protocol, name string) map[string]any { description := "Agent tool " + name parameters := map[string]any{"type": "object", "properties": map[string]any{}} @@ -873,10 +883,18 @@ func newUpstreamRequest(ctx context.Context, baseURL string, protocol wire.Proto // FreeTierError, so the client's header set is mirrored exactly. req.Header.Set("User-Agent", httpx.UserAgent()) req.Header.Set("x-opencode-client", "cli") + // The free tier requires both session headers to carry the same + // descending-encoded id. The x-opencode-request correlation header and + // canonical prj_* project ids are rejected with 403 since 2026-10-14, so + // neither is forwarded; tracing stays local to this gateway. req.Header.Set("x-opencode-session", ids.Session) req.Header.Set("x-opencode-session-id", ids.Session) req.Header.Set("x-session-affinity", ids.Session) req.Header.Set("X-Session-Id", ids.Session) + // A canonical prj_* project id is rejected with 403 since 2026-10-14; the + // client's own bare 40-hex shape (or any non-canonical value, e.g. + // "global") passes. Hash the local project signal into the accepted shape + // so one conversation stays pinned to one upstream project. req.Header.Set("x-opencode-project", clientProjectID(ids.Project)) if ids.ParentSession != "" { req.Header.Set("x-parent-session-id", ids.ParentSession) @@ -886,6 +904,9 @@ func newUpstreamRequest(ctx context.Context, baseURL string, protocol wire.Proto req.Header.Set("anthropic-version", "2023-06-01") req.Header.Set("anthropic-beta", "interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14") } else { + // The anonymous credential is the literal token "public". The 2026-10-14 + // gate rejects keyless requests (an absent header used to pass) and is + // case-sensitive: "Bearer PUBLIC" 401s. req.Header.Set("Authorization", "Bearer "+key) } return req, nil diff --git a/internal/httpx/client.go b/internal/httpx/client.go index 804f2ee..b0e619d 100644 --- a/internal/httpx/client.go +++ b/internal/httpx/client.go @@ -1,8 +1,8 @@ package httpx // clientVersion is the OpenCode release the gateway claims to be. Upstream -// accepts a range of releases, so this only needs bumping when it starts -// rejecting older ones. +// accepts a range of releases (the version number itself is not validated), +// so this only needs bumping when it starts rejecting older ones. const clientVersion = "2.0.29" // UserAgent reports the gateway as an OpenCode client using the shape upstream diff --git a/internal/identity/request.go b/internal/identity/request.go index 497f68e..5c5f0ea 100644 --- a/internal/identity/request.go +++ b/internal/identity/request.go @@ -1,4 +1,11 @@ -// Package identity derives stable session identities and unique request IDs. +// Package identity derives stable session identities. +// +// The 2026-10-14 Zen free-tier gate validates a descending-timestamp session +// id plus a client User-Agent, and it 403s requests that still carry the +// legacy x-opencode-request header. The identity that matters upstream is +// therefore the pair (x-opencode-session, x-opencode-session-id): Session is +// the conversation-affinity key and must keep the descending layout minted by +// CanonicalSessionID. package identity import ( @@ -14,6 +21,10 @@ import ( "opencode2api/internal/jsonutil" ) +// RequestIDs carries the identity headers the upstream free tier inspects. +// Session is sent as both x-opencode-session and x-opencode-session-id; both +// headers are required since the 2026-10-14 gate. Request is retained for +// request-level tracing of this gateway only — it must NOT reach upstream. type RequestIDs struct { Session string Request string @@ -24,6 +35,7 @@ type RequestIDs struct { func DeriveRequestIDs(r *http.Request, body map[string]any) RequestIDs { signal := jsonutil.FirstString( r.Header.Get("x-opencode-session"), + r.Header.Get("x-opencode-session-id"), r.Header.Get("x-session-affinity"), r.Header.Get("X-Session-Id"), r.Header.Get("x-session-id"), @@ -43,6 +55,10 @@ func DeriveRequestIDs(r *http.Request, body map[string]any) RequestIDs { signal = RandomID("fallback", 16) } session := CanonicalSessionID(signal) + // The upstream free tier 403s canonical prj_* project ids (2026-10-14 + // probing) while accepting the literal "global" every official client + // sends. Anything non-canonical also passes, so the project header is only + // used as a local correlation hint and is no longer forwarded upstream. projectSignal := jsonutil.FirstString(r.Header.Get("x-opencode-project"), jsonutil.StringAt(body, "metadata", "project_id")) if projectSignal == "" { projectSignal = "opencode2api:default-project" @@ -54,7 +70,7 @@ func DeriveRequestIDs(r *http.Request, body map[string]any) RequestIDs { return RequestIDs{ Session: session, Request: RandomID("req", 16), - Project: StableID("prj", projectSignal), + Project: projectSignal, ParentSession: parentSession, } } diff --git a/internal/models/discovery.go b/internal/models/discovery.go index 05ac4ff..566fefd 100644 --- a/internal/models/discovery.go +++ b/internal/models/discovery.go @@ -19,6 +19,9 @@ const ( CapabilitiesURL = "https://models.opencode.ai/api.json" ZenDocsURL = "https://raw.githubusercontent.com/anomalyco/opencode/dev/packages/web/src/content/docs/zen.mdx" GoDocsURL = "https://raw.githubusercontent.com/anomalyco/opencode/dev/packages/web/src/content/docs/go.mdx" + // LegacyZenBase is the console origin that still serves the anonymous + // models listing after chat traffic moved to the inference backend. + LegacyZenBase = "https://opencode.ai/zen" ) var protocolDocEndpointPattern = regexp.MustCompile("\\|[^|]+\\|\\s*`?([^|`\\s]+)`?\\s*\\|\\s*`[^`]+/v1/(chat/completions|responses|messages|systemone)`")