Go's http.Client follows up to 10 redirects to any host, https to http
included, and on a hop to another domain drops only Authorization,
Cookie and WWW-Authenticate. So a vendor (or anything answering at its
URL) that redirected elsewhere got x-api-key, x-goog-api-key, api-key
and a provider's own headers sent there; Authorization too when only
the port differed, and all of them in the clear on an https to http
hop on the same host.
The class is fixed where the requests leave:
- provider.KeepsCredentials is a CheckRedirect that follows a redirect
only to the request's own origin (scheme, host, port; or http to
https on the same host and default ports), at most 10, and gives any
other 3xx back as the answer (http.ErrUseLastResponse).
- provider.Keyed(c) is a copy of c with c's own CheckRedirect, then
KeepsCredentials. Provider.do, the choke point of every p.Do, sends
through it, and every http.DefaultClient.Do in internal/provider that
carries a credential is Keyed(http.DefaultClient).Do. A copy per
call, since netproxy.Install sets the default client's transport at
run time. Left alone: Grok's public download, Antigravity's version
URL and cline.go's unsigned read.
- the gateway's client (s.client, every vendor call), the Codex relay's
and the Codex websocket's take KeepsCredentials, and so does
chatgpt_api's siwcClient.
The native route needs nothing more: the vendor's 3xx comes back to
the caller as it came, Location included, and the caller decides.
Translated routes don't follow either, rather than following with
credentials stripped: it is the rule search_api.go had already (#1580),
no vendor magpie speaks to was found redirecting its API to another
origin, a stripped request elsewhere would only fail with a confusing
401, and the vendor-URL downloads (video, images) are fetched unsigned
through vendorClient, so they are not affected.
Tests: TestRedirectKeepsTheKeyAtItsOrigin (307 and 302 elsewhere with
Authorization, x-api-key, x-goog-api-key, api-key and a custom header;
a same-origin redirect followed with every key; three clients),
TestRedirectNeverDowngrades (an https vendor's redirect to http on its
own host and port), TestSameOrigin, TestKeyedKeepsTheClientsRule,
TestNativeRedirectKeepsTheKey (Anthropic and Gemini providers with an
own header) and TestChatRedirectKeepsTheKey.
Broken by hand: with Provider.do back on client.Do and s.client
without CheckRedirect, the thief got every key header, /away answered
200, the https vendor's /plain was followed (400 from the TLS port
spoken to in http), the native route's claudeish and gem answered the
thief's {"stolen":true} with Authorization, X-Api-Key and
X-Relay-Secret sent there, and the chat route sent Api-Key,
Authorization and X-Relay-Secret to it. TestSameOrigin and
TestKeyedKeepsTheClientsRule don't depend on the wiring and passed.
Run on mote at the pushed head 883690a0b (this commit and the next,
on origin/main 9a0aab32c): gofmt -l clean, go vet, GOOS=windows go vet
and GOOS=linux -tags nogui go vet all clean. go test ./... -timeout 45m
-count=1: 84 packages ok, including internal/gateway. 3 red, each filed
and none in this change's path:
- TestMainWindowCorners/macOS_26_SDK (gui, macOS 27, #3949)
- TestRenewLoginsKeepsClaudeReading (provider, #5481). It is red 3 of 3
at the base 49c9491b7 without either commit.
- TestHostEndedEndsWhatItsPluginStarted/own_end (plugin, a 30s wait in
a full run; passes 3 of 3 alone at this head, #5515)
This commit alone, at its first base 49c9491b7, ran the same way with
TestUnroutedHeldReportSaved (gateway, #4300) red besides.
Rebased then onto origin/main 303a31dd6 (which fixed#5481) and run
again at that tree: gofmt and the three vets clean, and internal/gateway,
internal/provider, internal/plugin and internal/netproxy all ok.
Rebased on 19c45d5d4, which changes gateway.go (kept_error), Codex's
usage_limit_reached, Cursor's mover min, sessions and the GUI; ran
gofmt, go vet ./internal/..., GOOS=windows go vet of gateway and
provider, and go test ./internal/gateway ./internal/provider: both ok.
Rebased on 94d4866b5, which changes only internal/sessions; ran gofmt,
go vet of gateway, provider and sessions, and this change's own tests
(-run Redirect|DropsProxyIdentity|SameOrigin|Keyed): ok.
Rebased on cd77c725d, which changes only internal/provider's check-in;
ran gofmt, go vet of gateway and provider, and this change's own
tests again: ok.
Not tried: a real vendor's redirect (none found that does), and the
plugin host's fetch (host.js; Bun follows redirects by default), which
is filed as #5508.
Gearclickist on Discord: magpie connects ZCode without an error, but
ZCode on Windows never lists magpie as a provider; on a Mac it does.
ZCode 3.14.3 (the same JS in the Mac and Windows builds, diff -rq of the
extracted app.asar) picks its data folder from setting.json's dataBaseDir,
then ZCODE_DATA_BASE_DIR, then process.env.HOME, and only then
os.homedir() (USERPROFILE). magpie used Go's home, which on Windows is
USERPROFILE. With HOME set (Git Bash, MSYS2, Emacs and the like), ZCode
reads %HOME%\.zcode\v2\provider_config.json and magpie wrote
%USERPROFILE%\.zcode\v2\..., a folder ZCode never opens. On a Mac HOME is
Go's home too, so the two always met.
appdir.ZCodeHome gives %HOME% on Windows when it is set, absolute, and
the folder asked about is USERPROFILE (a folder given on purpose is
kept). The agent target, the ZCode credential and team readers and the
library target use it. ZCode's CLI database stays under USERPROFILE (seen
on Windows below), so the sessions reader is unchanged; its comment says
why.
Run:
- go test ./internal/agent/ -run TestZCode; the new
TestZCodeOnWindowsUsesTheHomeZCodeReads forces zcodeOS=windows with
HOME and USERPROFILE apart. Broken by hand (ZCodeDataIn(home) back in
zcode()): red, "ZCode's folder on Windows with HOME set: .../001/.zcode
... want .../003/.zcode".
- gofmt -l; go vet for darwin, linux (-tags nogui) and windows.
- Windows box, sandbox folders only, HOME and USERPROFILE set apart:
ZCode 3.14.3 for Windows, extracted and started there, kept its logs,
workspace and provider_config.json under HOME\.zcode\v2 and only
cli\db under USERPROFILE. The old magpie.exe's `zcode provider magpie`
wrote profile\.zcode\v2\{config,provider_config}.json (the bug); this
build's wrote home\.zcode\v2\..., beside ZCode's own files, and nothing
under the profile.
- Full suite (go test -timeout 45m ./..., one at a time on the box):
68 packages ok, exit 0, at d87be7f13 and again after rebasing onto
b00c82acf (tree of this commit).
Not tried: the reporter's own machine (their HOME is inferred, not
confirmed); ZCode's picker on the Windows box (it ran over ssh, without
a desktop, and exited with the session), so "lists magpie" is read from
where ZCode keeps its files, not seen; the provider and library siblings
have no forced-OS test of their own; ZCODE_DATA_BASE_DIR and
ZCODE_DESKTOP_HOME_DIR are not followed.
"factory" joins retiredBuiltins: every Factory account is served by
@magpie-community/opencode-factory-auth, and the hourly MoveRetiring
moves the ones still on the built-in.
Removed: the built-in's sign-in (factory_signin.go, WorkOS's device
flow), keeping the sign-in (renew, lapse, org reconcile and mend,
headers, factoryGet), its provider and account (factoryProvider,
factoryAccount, factoryAlsoOn), its login list, switch, on/off and
forget, its usage card (factoryLoginQuota), droid's prompt and body
rewriting (factory_client.go), and its rows in signin.go, logins.go,
logins_on.go, login_usage.go, subscription_usage.go and account.go.
zcodeDecode/Encode, kept in zcode.go only for factory_client.go, go
with it. An API key always goes to the plugin now (factoryAddKey), and
`magpie accounts import factory` keeps saying to add it with accounts
add factory; its dead import branches are gone.
Kept: the mover and what it reads (factoryLogins, factorySaved,
factoryCreds, factoryMu); ImportFactoryKeys, factory_key.go and
factoryWhoami, for "Use an API key instead"; droid's model table with
factoryAPIs and factoryCore, since the plugin's provider is named
"factory" (account.go APIs, FactoryGemini and servedByFactory still
answer for it); factoryAPI for the moved provider's host
(builtinHost); factory_usage.go's limits reader behind
FactoryAllowanceForTest, which the gateway's pool tests use; the
gateway's "factory" lists (estimatedMoved, the account check), as the
Zed commit kept zed's; the parity tests.
Tests:
- git rm'd, built-in only: factory_test.go (sign-in, refresh, accounts,
orgs), factory_client_test.go, gateway factory_agents_test.go
(droid's line on every wire, the generate route to chat) and
factory_think_off_test.go (TestPluginThinkingOff covers the plugin);
TestFactoryAPIKey, TestFactoryKeyAgainReadsUsageAfresh,
TestFactoryServesModelsAddedSinceItsFetch, TestUserAgentAccountUntouched
(TestUserAgentFor still covers an account's User-Agent).
- Changed meaning: TestGeminiEmptyReplyIsAnError,
TestGeminiEmptyRepliesAskedAgain and TestGeminiImageModelReturnsItsImage
used Factory's generate route as a fake-able Gemini upstream; they now
use a Gemini API of the user's own (saveGem), the same decoder, and the
image test checks :streamGenerateContent instead of /api/llm/g/v1/generate.
TestMovedShowsBuiltinHost's first check is now a plain plugin
(fakeco), and a retired Factory with no migration record shows
api.factory.ai. TestFactoryAPIKeyMoved checks factoryLogins() is empty
instead of the removed factoryLookup. factorySite/factoryJSON moved
into factory_key_test.go.
Run in this worktree:
gofmt -l internal: nothing
go vet -tags nogui ./internal/provider ./internal/gateway ./internal/cli
./internal/gui, GOOS=darwin, linux, windows: clean
staticcheck -checks U1000 -tests=false (darwin, windows) on
internal/provider: nothing new
go test -tags nogui -count=1 -run 'Factory|Gemini|PaymentRequired|
ResetsInWords|UserAgent|UsedWindow|Vertex|PayloadTooLarge|UsageCache|
AnthropicImage|ThinkingOff|Moved|Retired|Mover|Migrat|Move|
SayTheirPlugin|Allowance|Discovery|ClaudeModels|GrokPrice|
LoopbackSignIns|AsksOwnBackend|SideLogin|Import|Accounts|ZCode|MiMo'
on the four packages: ok (all four); TestFactoryAPIKeyMoved ran with
Bun (PASS), not skipped.
Not run: whole packages, the full suite, the GUI suite (machine load
~300). Not tried with a real Factory account. docs/subsystems not
changed, as for Zed.
"zcode" joins retiredBuiltins, as zed and mimo-app did: every ZCode
account is served by @magpie-community/opencode-zcode-auth, and the
hourly MoveRetiring moves the ones still on the built-in.
Removed: the built-in's sign-in (startZCodeSignIn, the team sign-in and
its route/key caches), Start Plan (zcode_start.go and its blocked hint,
which account.go Explain and test.go EdgeBlocked named), its client and
prompt (zcode_client.go, zcode_prompt.json), the models list
(zcode_models.go), the OS place readers (zcode_os_*.go), and its rows in
signin.go, logins.go (list, switch, forget), logins_on.go,
login_usage.go, subscription_usage.go and account.go. Tests that covered
only that code are git rm'd (zcode_accounts, _blocked, _client,
_device, _place, _quota, _start, _startmodels) with TestZCodeAccounts,
TestZCodeTeamSignIn, TestZCodeTeamNoSeat and TestZCodeFetchModels.
Kept: the mover (migrate_zcode.go) and what it reads (zcodeLogins,
zcodeSaved, the credential store readers, zcode_device.go's
zcodeDeviceMid); zcodeOwn, the plugin's own account; the Zhipu plan and
team-seat readers planquota.go uses (zcode_team.go, zcodeCall/Get);
zcodeDecode/Encode, moved into zcode.go because factory_client.go uses
them; the gateway's zcode countOn condition and zcode_blocked_test.go
(which builds its Provider directly), as the Zed commit kept zed's; the
StartSignInAt site parameter (generic); plugin_accounts and
account_seats cases; the parity tests.
Tests whose meaning changed: TestZCodePlanKeyFromConfig and
TestZCodeOwnTeam keep only their zcodeOwn checks (the quota, Start Plan
server, provider/Sign/LoginUsage parts were the built-in's).
TestZhipuKeyTeamWindows builds the team key directly instead of signing
in through the removed team sign-in. zcodeTestJWT moved to zcode_test.go
for migrate_movers_c_test.go.
Run in this worktree:
gofmt -l internal: nothing
go vet -tags nogui ./internal/provider ./internal/gateway ./internal/cli
./internal/gui, GOOS=darwin, linux, windows: clean
staticcheck -checks U1000 -tests=false (darwin, windows) on
internal/provider: nothing new (only the pre-existing unused ones)
go test -tags nogui -count=1 -run 'ZCode|Zcode|Zhipu|Migrat|Move|Moved|
Retired|LoopbackSignIns|AsksOwnBackend|Mover|SayTheirPlugin|SideLogin|
PlanKey' ./internal/provider ./internal/gateway ./internal/cli
./internal/gui: ok (all four)
Not run: whole packages, the full suite, the GUI suite (machine load
~300). Not tried with a real ZCode account.
ZCode 3.15 keeps no coding plan key in credentials.json any more. The key
it uses is in config.json, at provider["builtin:bigmodel-coding-plan" /
"builtin:zai-coding-plan"].options.apiKey (ZCode 3.15.3's host reads that
value as it is). zcodeOwn found no key, so a signed-in BigModel GLM Coding
Pro account went on to the Start Plan and read as "this account has no GLM
Coding Plan, and ZCode's Start Plan has ended or was never started".
zcodeOwn now falls back to config.json when credentials.json has no key:
Z.ai's first, as before, then BigModel. It also accepts the provider ids
ZCode 3.15 normalizes to (account:*-individual-coding-plan) and a value
written encrypted. A value that isn't a key, such as "{env:...}", is
skipped. A key in credentials.json still comes first, and so does a team
switch.
What was run:
- TestZCodePlanKeyFromConfig uses the reporter's layout: credentials.json
with BigModel sign-in data and no key, and config.json with the key under
builtin:bigmodel-coding-plan. The account reads as GLM Coding Pro with
two windows and never asks the Start Plan. Without the zcode.go change
it fails, with the key empty.
- gofmt -l; go vet for darwin, linux (nogui) and windows.
- go test ./internal/provider/ passes.
Not tried: a real ZCode 3.15 account. The fix rests on the reporter's
account of their config.json, which they verified against the plan
endpoints with the key, and on ZCode 3.15.3's extracted host code.
Moved users get the same fix through the plugin, in a separate commit.
Copilot, Factory and ZCode's device sign-ins wait at least a second
between polls, whatever interval the vendor gives. The tests' fakes give
0, so each poll in a test cost a full second, and these tests were 56.5s
of the provider package's 399s of test time.
The floor is now devicePollFloor, read through devicePoll(seconds) at the
three call sites, and the provider package's TestMain lowers it to 10ms.
Real sign-ins still wait max(vendor's interval, 1s), as before.
TestDevicePollKeepsItsFloor checks 0, -1 and 1 give 1s and 5 gives 5s.
Run:
- go test ./internal/provider (full, -count=1, load avg ~100): pass,
403s -> 316s of package time; the Copilot/Factory/ZCode tests 56.5s
-> 22.5s.
- A/B on -run 'Copilot|Factory|ZCode', base vs this: 45-58s vs 15-16s
(32s once, under load).
- Removing the floor from devicePoll turns TestDevicePollKeepsItsFloor red.
- gofmt -l clean; go vet darwin, linux (-tags nogui), windows; linux and
windows builds.
One A/B round failed on both base and this change at load over 200; the
cause wasn't captured, and the next 4 rounds passed on both.
Not done: the other slow causes in the package. The 1.2s sleeps waiting
for the callback port to be let go (signin_test.go:137,
signin_proxy_test.go:92, signin_usage_afresh_test.go:70), Cursor's
linkWait, MoveToPlugin (7-9s) and WarmAtSeveralTimes (6-10s).
A sign-in checked canceled/finished only when its callback was claimed.
The token exchange after that went on to addLogin / addGoogleLogin /
addSideLogin and only then called finish, a no-op after CancelSignIn, so
a sign-in the user canceled while its token was in flight still added
the account, or replaced an existing account's tokens. Sibling of #1750
(mcpauth's flow.keep, 1a7aa76b4).
Every built-in sign-in's write of its account now goes through one gate:
keepLogin(ctx, store), which finds the flow s.via put on the sign-in's
context and runs store under the flow's lock only while the flow is
live (signInFlow.keep). The CLI-run sign-ins (Claude, Grok, Cursor),
whose context isn't the flow's, call s.keep directly. Cancel takes the
same lock in finish, so either it comes first and nothing is written
(the flow stays "canceled"), or the account is kept and a cancel after
that is too late (kept): the flow then goes on to "done", matching the
account list.
Routed through it: Codex and Devin callbacks (Devin's own credentials
file and its side home), Gemini/Antigravity, ChatGPT API, Claude Code,
Copilot, Command Code (callback and pasted key), Factory, Kiro, MiMo,
Qoder, WorkBuddy, Zed, ZCode, and runCLISignIn's identity (Grok's second
account). Plugin sign-ins are kept by the plugin host and aren't
covered here.
Run:
- TestCanceledSignInAddsNoAccount (Codex: browser callback and pasted
address, the token endpoint's reply held until CancelSignIn) and
TestCanceledDeviceSignInAddsNoAccount (Copilot device code, GitHub's
answer held, read whole, until after the cancel). On the old code all
three FAIL: "the canceled sign-in wrote ~/.codex/auth.json", "the
canceled sign-in added cx@example.com", "the canceled sign-in added
late-user". With the fix they pass, -race -count=5.
- go test -tags nogui -timeout 45m ./internal/provider/... ok (sandbox
HOME, private GOCACHE).
- gofmt -l clean; go vet ./internal/provider (darwin), GOOS=linux and
GOOS=windows go vet -tags nogui ./internal/provider ok.
Rerun after rebasing on origin/main f71155591 (#2052, which touches
provider/models.go): gofmt and the three vets ok; the provider suite
(-timeout 45m) ended once in a bare FAIL with no test named, then passed
3 runs in a row (one -v). Filed as #2061. Rebased again on 8da304767:
gofmt, the three vets and the provider suite ok.
Not tried against a real vendor's sign-in.
What changed: ZCode 3.14 has a 数据存储路径 (data storage path) setting.
Changing it copies ~/.zcode/v2 to <folder>/.zcode/v2, and from the next
start ZCode reads its providers (provider_config.json, config.json),
credentials.json and runtime/provider from there. The choice stays in the
home folder's .zcode/v2/setting.json as dataBaseDir, which ZCode's main
process reads first (readBootstrapDataBaseDirFromDisk, then setDataBaseDir;
getDataBaseDir is that, else ZCODE_DATA_BASE_DIR, else HOME). magpie always
wrote ~/.zcode/v2, so for such a user it said ZCode was connected while
ZCode's 模型设置 showed only BigModel and Start Plan and no magpie.
appdir.ZCodeDataIn reads dataBaseDir the way ZCode does (trimmed, ignored
when empty or relative); the ZCode agent target, the ZCode subscription's
credentials.json and its zcode-builtin.json glob use it. Skills, AGENTS.md
and the CLI's cli/config.json stay under the home folder: ZCode reads
those from HOME/USERPROFILE (getUserZcodeSkillRoot, the MCP config path),
so internal/library is unchanged. ZCode's session database
(internal/sessions) is not changed here: where ZCode's CLI keeps it under a
moved folder was not checked.
Read from ZCode 3.14.3's app.asar (copied to the scratchpad):
out/main/index.js (bootstrap, setDataBaseDir, buildHostProcessEnv passing
ZCODE_DATA_BASE_DIR), out/host/chunk-*.js (getAppConfigDir =
<base>/.zcode/v2) and out/host/index.js (provider_config.json under it).
flower hasn't said they moved the folder; this is the one way found in
ZCode's code for "magpie says connected, ZCode has no magpie" with a
provider_config.json magpie wrote. That file, and the one this build
writes, decode with ZCode's own decodeProviderConfigFile (run from a copy
of glm/zcode.cjs): providers ["magpie"].
What was run:
- TestZCodeMovedDataFolder (new): with dataBaseDir set, Set("magpie")
writes both files under the moved folder and none in ~/.zcode/v2; an
empty, blank or relative dataBaseDir keeps ~/.zcode. On the old
zcode.go it fails: "no magpie in the moved folder's
provider_config.json".
- Sandbox, built binary: HOME=<sandbox>, setting.json dataBaseDir=<sandbox>/D,
`magpie zcode magpie` wrote D/.zcode/v2/{config,provider_config}.json
and nothing under the home folder's .zcode/v2 but setting.json.
- go test -tags nogui ./internal/agent ./internal/appdir ./internal/provider
under a temp HOME; gofmt -l; GOOS=linux and GOOS=windows go vet -tags
nogui on the three packages.
- Not run: the ZCode app itself with a moved folder (not launched against
any config), and Windows.
What changed: every sign-in started in magpie now leaves through the
account's own proxy (ProxyOfLogin: the account's, else the
subscription's, else the global one). Before, the sign-in's token
exchange and checks went through the global proxy while the account's
later refresh and usage calls went through its own (ViaLogin), so the
vendor saw one account come from two exits.
- signin.go: SignInOptions{Site, Proxy, User}, StartSignInWith; the flow
picks its proxy (pickProxy, validated with settings.CheckProxy) and
every request goes through s.via. Each built-in sign-in (Claude,
Codex/ChatGPT, Grok, Zed, WorkBuddy, Copilot, ZCode, Factory, MiMo,
Qoder, Command Code, Kiro) uses s.via; Claude Code's own login gets the
proxy as *_PROXY (netproxy.EnvWith).
- proxy.go keepSignInProxy: a proxy picked for the sign-in is kept as
the subscription's when the account is its only one, else as that
account's own entry. "" (global) is refused while the subscription has
a proxy and other accounts, since nothing could keep it.
- plugin host: authorize and callback run under via.run(proxy), so a
plugin's sign-in fetches go through the same proxy; plugins_cli.go
does the same for `magpie plugins login`. PluginAPIKey goes through Via.
- gui: POST /api/signin and /api/plugin-signin take proxy and user.
What was run:
- go test -tags nogui ./... (sandbox HOME), all packages ok.
- gofmt -l, GOOS=linux and GOOS=windows go vet -tags nogui on the
touched packages.
- Red without the change (each broken by hand, then restored):
TestSignInGoesThroughItsProxy, TestDeviceSignInGoesThroughItsProxy,
TestPluginSignInGoesThroughItsProxy, TestClaudeSignInGoesThroughItsProxy
(internal/provider) and TestPluginSignInProxy (internal/plugin) each
fail with the s.via / EnvWith / via.run / keepSignInProxy removed.
Not tried: a real vendor account through a real proxy. The browser's own
leg of an OAuth sign-in goes through the browser's network, not magpie's.
Devin's CLI probes still use the global proxy.
The list is asked with the plan's key, bare in Authorization, at the host its
term (subscription/list) is asked at, so open.bigmodel.cn and api.z.ai alike;
a ZCode account on the built-in gets the same. The tooltip says "The plan's
resets" for a person's own, "The team plan's" for a team's (ResetCredits.Team).
Tested: the reporter's literal reply (ids and times filled in, same shape)
in TestZhipuPersonalResets, TestPlanQuotas and TestZCodeAccounts, each
failing with the change reverted; reset-each-title in Chromium and WebKit,
en/zh/ja/de; a real Z.ai key through zhipuPersonalResets (1 five-hour,
1 weekly). Not tried: a real bigmodel.cn key.