diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 695167b7f..1d2a9c914 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -91,7 +91,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | Local servers | A preset of `KindLocal` (Ollama, LM Studio, oMLX, MLX-Serve) is at its server's default port on this machine. Another address — a port, or another computer — is given in the window's editor, in its Server address field, shown first above the key and never folded (a folded one read as an LM Studio whose base URL can't be changed, mengxiangziyou on X), or in the TUI (asked on adding, `w` after); on the command line with `address=` (`atAddress` in `providers_cli.go`: every URL moves, from the preset's when the provider was saved with none, and `address=` alone puts a local server back at its preset's), or the URLs themselves (`url=`, `anthropic=`, `responses=`). `AtAddress` replaces only each URL's scheme, host and port, each API keeping its path; `AddressOf` is the address an editor starts from. The window sends the URLs moved only when the address was changed, so a Save doesn't move URLs set apart (another app's import). A provider of the user's own (no preset) has `w` in the TUI too: each base URL it has is asked in turn, typed in as it is, Enter alone keeping one (`customURLsAsk`). | [`local_address.go`](../../internal/provider/local_address.go), [`providers_cli.go`](../../internal/cli/providers_cli.go) | | Protocol detection | Works out which of Chat, Responses, Anthropic Messages and Gemini generateContent a base URL speaks when a provider is added. Each is asked at the URL as it takes it (`DetectBase`); Gemini's at the `…/v1beta` beside a typed `…/v1` or bare host, a Gemini model from the list picked for it, with the key in `x-goog-api-key` (#1346). Each API is asked with a model that chats, if the list has one; an embedding or rerank model (`catalog.ServesOf`) is asked only on Chat's URL, at its `/embeddings` or `/rerank` with the smallest body and no extra body, as the gateway's `retrieve` asks it, and the other APIs say why they weren't asked (heatonz on Discord: a vendor of only those detected nothing, asked to chat; `TestDetectEmbeddingOnly`). A saved provider whose list has nothing to chat with tests on such a model (`testModel`, `TestTestEmbeddingOnly`), and its editor and the add form's Fetch models say the models need no pick (`retrieval` in the list's answer and the provider's JSON, `provider-retrieval-only.test.cjs`). A model's test (Test models, a model's right-click, `magpie provider test`) asks the account or key a request for it goes to: `provider.AccountsFor` and `provider.KeysFor` ([`route_accounts.go`](../../internal/provider/route_accounts.go)), which the gateway's `perKeyEvery` routes by too, its usage and spend caps aside (one the user lets serve it, `AccountModels`; whose own list or plan has it, `Account.Lists`, `PlanServing`, `Serving`; in the user's order, `AccountsOn`), so a pool whose accounts list different models (a newapi plugin's) asks the one whose list has it, and one every account is barred from isn't asked. The provider's Test picks each endpoint's model from every account's and asks it of the account that serves it (`routedTo`), and with keys the first key with a model of its own to test (`testWith`). The request log's row names the account asked (`loggedAs`; #4992, `TestModelTestAsksTheAccountThatServesIt`). A model's right-click *Test on account…* (tmr11235 on X; a provider with two or more accounts or keys that are on, `TestPicks`) pins its test to one of them (`TestOn`, `accountNamed`, `keyNamed`, the GUI's `account`; `TestModelTestPinnedToAKey`, `TestModelTestPinnedToAnAccount`, `model-test-account.test.cjs`), and every result names the account or key it went to (`Result.Account`, `testedAccount`), so the status line says which one answered. Test models and `magpie providers` still test with routing's pick. Detection, endpoint tests and model tests share `probe`, which adds `anthropic-version` only for Anthropic Messages; OpenAI probes omit that default so a relay that refuses it can answer. A Chat or Responses URL typed without its version (CRS's `…/openai`, Cyrus_4433 on X: CRS serves `/openai/v1/chat/completions` and `/openai/responses`, and answers anything else 404 `Not Found`) that is answered 404 is asked once more under `/v1` (`missingV1`, not for an account, Azure, Bedrock or Vertex); answered there, the saved provider's URL takes the `/v1` (`setV1`), the result carries it (`Result.V1`), Detect hands it on as the base, and the editor's URL field follows (`draft.onV1`), so Save doesn't put it back. A model's own 404 at both stays a 404 and changes nothing. CRS lists at `/api/v1/models`, which `catalog.RelayOpenAIList` adds to an unversioned `…/openai` base's list URLs, and a list answered there adds `/v1` as `fixV1` does (`TestCRSOpenAIBaseTestsUnderV1`, `TestCRSOpenAIBaseListsAtAPI`, `TestCRSOpenAIBaseDetectsV1`, `TestModel404KeepsBase`, `provider-test-v1.test.cjs`). A model's test that the vendor turns away with its word that the model is served on another API (`catalog.WrongEndpoint`, the gateway's words) asks the next API the provider has a URL for, as the gateway's `usable` takes it (the model's picked or listed API, else each API it isn't named-only on), with a key that sees the model there (`keySeeing`); that API's answer is the model's, and with none left, or every one saying it, the first stays. As Codex the next API is asked with Codex's headers, as the gateway sends them on Responses and Chat; as Claude Code it isn't, since the gateway sends Claude Code's on Messages alone (#3766, `TestTestModelsMovesToTheAPIServingIt`, `TestTestModelsKeepsAModelOnItsAPI`, `TestTestModelsAsAClientMovesAsTheGatewayDoes`). User-supplied headers still apply through `Sign`. The editor asks with the form as it stands, before any Save (#1545): the URL, key and models typed (`picked`, else the saved picks, else the vendor list); a key not typed again is the saved provider's, or for an unsaved copy the copied one's (`copyOf`). The probe writes nothing and adds no provider, and the route stays behind `magpie web`'s key. An endpoint or model test fails fast and can be stopped (RIck on Discord: 测试模型 took long to fail and couldn't be cancelled): a probe on magpie's own client that has no connection in `connectWait` (10s) fails then (`connecting`, an httptrace `GotConn`), and a host that couldn't be reached (no connection, DNS, refused, a bad certificate) fails the run's other models at once (`withUnreached`, `TestTestModelsUnreachedHostFailsOnce`); a stream that breaks off before an answer is a failure. While a test runs its Test models and endpoints' Test read Stop, which aborts the window's request and posts `provider/teststop` with the test's `run`, ending the vendor's request on the server too (`testRuns` in [`providers.go`](../../internal/gui/providers.go), since WebView2 doesn't end the request when a fetch is aborted; `TestProviderTestStops`, `model-test-stop.test.cjs`). | [`detect.go`](../../internal/provider/detect.go), [`test.go`](../../internal/provider/test.go) | | A pasted curl command | A curl command from a vendor's docs pasted into a custom provider's Base URL or API key fills the editor in (@mark_li21 on X). `curlOf` reads it as a shell would (lines joined by `\`, cmd's `^` or PowerShell's backtick; `curl.exe`; quotes and escapes), and takes: the API its URL's endpoint names (`…/chat/completions` Chat, `…/messages` Anthropic Messages, `…/responses` Responses) with the base URL before it, spelled as that API wants it (`respellURL`: Anthropic at its root, `/v1` after a bare host); the key from `Authorization: Bearer`, `x-api-key` or `api-key`, unless it only stands for one (`$OPENAI_API_KEY`, `${X}`, `%X%`, ``, `YOUR_API_KEY`), when the key's box is left empty and focused; and the `model` of its JSON body, added to a new provider's models (a saved one's picks are left alone, since adding to none would narrow what it serves). A preset's editor takes only the key. A note (`editorError`, kind `note`) says what was taken, a placeholder like `{WorkspaceId}` left in the URL, and a URL with no known endpoint. Text that isn't a curl command pastes as before, several keys included. Tested on the docs' own examples (`fixtures/curl`). | [`app.js`](../../internal/gui/assets/app.js) (`curlOf`, `fromCurl`), [`provider-curl-paste.test.cjs`](../../internal/gui/tests/provider-curl-paste.test.cjs) | -| Saved proxies | `settings.Proxies` holds named proxies (`NamedProxy`: id, name, address, optional login), kept in Settings › Network. Wherever a proxy is chosen (global, plugin downloads, app updates, a provider, a key, a Claude account) the value is "" (inherit), `direct`, an address as typed, or `@` for a saved one (@tsingchao on X). Addresses as typed are untouched. App updates take a proxy of their own, Settings › Network › App updates (`settings.UpdateProxy`, `magpie settings set updateProxy `; moonlityu on X: models direct, updates through a proxy): "" follows the global proxy as before, a proxy given to one `magpie update --proxy` run comes first, and it covers the feed, the notes and the release's file (`updateProxy` in [`update.go`](../../internal/update/update.go); `TestUpdateTakesItsOwnProxy`, `settings-update-proxy.test.cjs`). Per-model proxies within one provider are not offered: a proxy belongs to a provider, an account or a key, and a model that needs the other route is a second provider on the same URL. `netproxy.Parse`, `Resolve`, `Redact`, `EnvWith` and `Dispatch` resolve an `@id` at the lowest layer, so an edit reaches every user at the next request; a Claude Code `settings.json` env is a snapshot and is rewritten after an edit (`provider.ProxyEdited`). An `@id` this computer lacks fails closed (`netproxy.DeadProxy`, the request error and the provider row say "Proxy missing: {name}", `provider.ProxyGone`); it never goes direct. The password is written to settings.json (0600) and never read back by the page, logged or put in `Settings` sync; the list rides with the providers part of a sync (`backup.Bundle.Proxies`, `settings.MergeProxies`, passwords only with keys). A proxy in use cannot be deleted (409). A saved proxy can be an SSH server (`ssh://host:port`, a user, a password and/or a private key; @laiuuui on X, whose VPS gives only SSH): magpie logs in itself with golang.org/x/crypto/ssh, no ssh command, and resolves the `@id` to a SOCKS5 server of its own on loopback (`socks5h://magpie:@127.0.0.1:`, which takes only that login), carrying each CONNECT as a direct-tcpip channel, as `ssh -D` does. It logs in on the first request, keeps the connection with keepalive@openssh.com every 20s (15s with no answer ends it), and logs in again once when a channel finds it dead (`sshTunnel` in [`ssh.go`](../../internal/netproxy/ssh.go)). Save logs in first, so a refused login is said there and nothing is kept; the host key is trusted on first use and kept as `HostKey` (authorized_keys form, the page shows its SHA256 fingerprint), and a server showing another key is refused (`HostKeyChangedError`) until Advanced › Trust a new key. The key is a secret as the password is: `WithoutProxyPasswords`, `MergeProxies`, `KeepSecretsOf`. An `ssh://` typed as an address is refused: its login belongs to a saved proxy. Every request to the server needs it to allow forwarding: macOS 27's sshd hangs up on a forward (also with OpenSSH's own `ssh -W`), and that is said as "won't forward connections" (`SSHForwardWhy`). A failed proxy says why (`netproxy.Why`: an English template the page translates, its `{addr}`, `{was}`, `{now}` filled; `fail` in api.go sends it as `code: proxy_why`, a check as `why`/`addr`): `Explain` reads Go's error, and `ExplainServer`, for a check the user asked for only, reads the server's first bytes when the text can't tell, since Go reads a real OpenSSH banner ("SSH-2.0-OpenSSH_9.6p1 Ubuntu-3ubuntu13.20") as an HTTP status line with a bad code. Each save is tested at once. A Test (Settings, and the provider editor's Saved mode) asks Cloudflare's trace page through the proxy, only on a click: its latency runs from the request written to the answer's first byte, so a new connection's dial, tunnel and TLS don't count and a second Test reads like the first, and the exit's region is named in the reader's language (IcyLiqu1d on X). An editor opened before Settings was read draws its picker again once the saved proxies are in. `TestSavedProxyLatencyIsTheRoundTrip`, `provider-proxy-pick-test.test.cjs`, `TestSavedProxyChoice`, `TestDanglingProxyReferenceFailsClosed`, `TestSavedProxiesTravelWithProviders`, `TestSSHProxyCarriesRequests`, `TestSSHProxyRefusesAChangedHostKey`, `TestSSHProxySaysWhyItFailed`, `TestProxyFailureNamesAnSSHServer`, `TestSavedSSHProxyAPI`, `TestSavedSSHProxyThatWontForward` (an SSH server in the test, `netproxy/sshtest`, never the network), `saved-proxies.test.cjs`, `saved-ssh-proxy.test.cjs`, `provider-proxy-missing.test.cjs`. | [`proxies.go`](../../internal/settings/proxies.go), [`netproxy.go`](../../internal/netproxy/netproxy.go), [`ssh.go`](../../internal/netproxy/ssh.go), [`why.go`](../../internal/netproxy/why.go), [`proxies.go`](../../internal/gui/proxies.go) | +| Saved proxies | `settings.Proxies` holds named proxies (`NamedProxy`: id, name, address, optional login), kept in Settings › Network. Wherever a proxy is chosen (global, plugin downloads, app updates, a provider, a key, a Claude account) the value is "" (inherit), `direct`, an address as typed, or `@` for a saved one (@tsingchao on X). Addresses as typed are untouched. App updates take a proxy of their own, Settings › Network › App updates (`settings.UpdateProxy`, `magpie settings set updateProxy `; moonlityu on X: models direct, updates through a proxy): "" follows the global proxy as before, a proxy given to one `magpie update --proxy` run comes first, and it covers the feed, the notes and the release's file (`updateProxy` in [`update.go`](../../internal/update/update.go); `TestUpdateTakesItsOwnProxy`, `settings-update-proxy.test.cjs`). Per-model proxies within one provider are not offered: a proxy belongs to a provider, an account or a key, and a model that needs the other route is a second provider on the same URL. `netproxy.Parse`, `Resolve`, `Redact`, `EnvWith` and `Dispatch` resolve an `@id` at the lowest layer, so an edit reaches every user at the next request; a Claude Code `settings.json` env is a snapshot and is rewritten after an edit (`provider.ProxyEdited`). An `@id` this computer lacks fails closed (`netproxy.DeadProxy`, the request error and the provider row say "Proxy missing: {name}", `provider.ProxyGone`); it never goes direct. The password is written to settings.json (0600) and never read back by the page (nor sent in `/api/state`'s settings, with the LAN key, Bark key and GitHub token: `stateSettings`, `TestStateSendsNoCredentials`), logged or put in `Settings` sync; the list rides with the providers part of a sync (`backup.Bundle.Proxies`, `settings.MergeProxies`, passwords only with keys). A proxy in use cannot be deleted (409). A saved proxy can be an SSH server (`ssh://host:port`, a user, a password and/or a private key; @laiuuui on X, whose VPS gives only SSH): magpie logs in itself with golang.org/x/crypto/ssh, no ssh command, and resolves the `@id` to a SOCKS5 server of its own on loopback (`socks5h://magpie:@127.0.0.1:`, which takes only that login), carrying each CONNECT as a direct-tcpip channel, as `ssh -D` does. It logs in on the first request, keeps the connection with keepalive@openssh.com every 20s (15s with no answer ends it), and logs in again once when a channel finds it dead (`sshTunnel` in [`ssh.go`](../../internal/netproxy/ssh.go)). Save logs in first, so a refused login is said there and nothing is kept; the host key is trusted on first use and kept as `HostKey` (authorized_keys form, the page shows its SHA256 fingerprint), and a server showing another key is refused (`HostKeyChangedError`) until Advanced › Trust a new key. The key is a secret as the password is: `WithoutProxyPasswords`, `MergeProxies`, `KeepSecretsOf`. An `ssh://` typed as an address is refused: its login belongs to a saved proxy. Every request to the server needs it to allow forwarding: macOS 27's sshd hangs up on a forward (also with OpenSSH's own `ssh -W`), and that is said as "won't forward connections" (`SSHForwardWhy`). A failed proxy says why (`netproxy.Why`: an English template the page translates, its `{addr}`, `{was}`, `{now}` filled; `fail` in api.go sends it as `code: proxy_why`, a check as `why`/`addr`): `Explain` reads Go's error, and `ExplainServer`, for a check the user asked for only, reads the server's first bytes when the text can't tell, since Go reads a real OpenSSH banner ("SSH-2.0-OpenSSH_9.6p1 Ubuntu-3ubuntu13.20") as an HTTP status line with a bad code. Each save is tested at once. A Test (Settings, and the provider editor's Saved mode) asks Cloudflare's trace page through the proxy, only on a click: its latency runs from the request written to the answer's first byte, so a new connection's dial, tunnel and TLS don't count and a second Test reads like the first, and the exit's region is named in the reader's language (IcyLiqu1d on X). An editor opened before Settings was read draws its picker again once the saved proxies are in. `TestSavedProxyLatencyIsTheRoundTrip`, `provider-proxy-pick-test.test.cjs`, `TestSavedProxyChoice`, `TestDanglingProxyReferenceFailsClosed`, `TestSavedProxiesTravelWithProviders`, `TestSSHProxyCarriesRequests`, `TestSSHProxyRefusesAChangedHostKey`, `TestSSHProxySaysWhyItFailed`, `TestProxyFailureNamesAnSSHServer`, `TestSavedSSHProxyAPI`, `TestSavedSSHProxyThatWontForward` (an SSH server in the test, `netproxy/sshtest`, never the network), `saved-proxies.test.cjs`, `saved-ssh-proxy.test.cjs`, `provider-proxy-missing.test.cjs`. | [`proxies.go`](../../internal/settings/proxies.go), [`netproxy.go`](../../internal/netproxy/netproxy.go), [`ssh.go`](../../internal/netproxy/ssh.go), [`why.go`](../../internal/netproxy/why.go), [`proxies.go`](../../internal/gui/proxies.go) | ## Remote magpie diff --git a/internal/gui/api.go b/internal/gui/api.go index 647d5b311..94d006d95 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -3378,8 +3378,17 @@ func held(h http.Handler) http.Handler { }) } +// stateSettings is s without the credentials Settings' own read keeps on +// disk (settingsState), for /api/state, which is polled, and the start's +// read of the last one (lastKnown), which puts today's settings in it +func stateSettings(s settings.Settings) settings.Settings { + s.Proxies, s.LANKey, s.BarkKey, s.GitHubToken = nil, "", "", "" + return s +} + func state() stateJSON { s := stateJSON{Agents: []agentJSON{}, Profiles: []profileJSON{}, Catalog: catalog.Source(), Settings: settings.Shared()} // only encoded, never changed + s.Settings = stateSettings(s.Settings) // state() is asked for after nearly every click, so the rate — a // network fetch once every TTL — is only worth its rare latency when // cny is actually chosen; usd never looks at it diff --git a/internal/gui/laststate.go b/internal/gui/laststate.go index d377a56c4..e260bbd2b 100644 --- a/internal/gui/laststate.go +++ b/internal/gui/laststate.go @@ -130,7 +130,7 @@ func lastKnown() (stateJSON, bool) { if len(b) == 0 || json.Unmarshal(b, &f) != nil || f.Version != Version || f.State.Agents == nil { return stateJSON{}, false } - f.State.Settings = settings.Load() + f.State.Settings = stateSettings(settings.Load()) f.State.Last = true return f.State, true } diff --git a/internal/gui/laststate_test.go b/internal/gui/laststate_test.go index 253a72fbb..96aeb512b 100644 --- a/internal/gui/laststate_test.go +++ b/internal/gui/laststate_test.go @@ -82,8 +82,11 @@ func TestLastKnownState(t *testing.T) { if !last.Last || !hasCodex(last) { t.Fatalf("last-known state: last=%v codex=%v", last.Last, hasCodex(last)) } - if last.Settings.Theme != "dark" || last.Settings.GitHubToken != "ghp_secret1519" { - t.Errorf("last-known state's settings are not today's: theme %q token %q", last.Settings.Theme, last.Settings.GitHubToken) + if last.Settings.Theme != "dark" { + t.Errorf("last-known state's settings are not today's: theme %q", last.Settings.Theme) + } + if last.Settings.GitHubToken != "" { + t.Error("the last-known state sends the GitHub token") } // another version's is not drawn diff --git a/internal/gui/state_secrets_test.go b/internal/gui/state_secrets_test.go new file mode 100644 index 000000000..ffeb82c18 --- /dev/null +++ b/internal/gui/state_secrets_test.go @@ -0,0 +1,51 @@ +package gui + +import ( + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/settings" +) + +// /api/state's settings, polled after nearly every click, carry none of +// the credentials /api/settings keeps on disk: a saved proxy's password, +// the old LAN key, the Bark key and the GitHub token. Neither does the +// last state served at start (?last=1), which has today's settings. +func TestStateSendsNoCredentials(t *testing.T) { + sandboxHome(t) + const pass, lan, bark, gh = "hunter2-proxy-pass", "sk-magpie-statelanstatelanstatelan0123", "bark-state-key-0123", "ghp_statetokenstatetoken0123" + h := Handler(nil, nil) + call := func(method, path, body string) string { + t.Helper() + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(method, path, strings.NewReader(body))) + if rec.Code != 200 { + t.Fatalf("%s %d %s", path, rec.Code, rec.Body) + } + return rec.Body.String() + } + call("POST", "/api/proxies/save", `{"name":"Office","url":"http://10.0.0.1:8080","user":"me","pass":"`+pass+`"}`) + s := settings.Load() + if len(s.Proxies) != 1 || s.Proxies[0].Pass != pass { + t.Fatalf("the proxy wasn't saved: %+v", s.Proxies) + } + s.LANKey, s.BarkKey, s.GitHubToken = lan, bark, gh + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + for _, path := range []string{"/api/state", "/api/state?last=1"} { + body := call("GET", path, "") + if path == "/api/state?last=1" && body == "null\n" { + t.Fatal("no state was kept for the next start") + } + for _, secret := range []string{pass, lan, bark, gh} { + if strings.Contains(body, secret) { + t.Errorf("%s carries %q", path, secret) + } + } + } + if s := settings.Load(); s.Proxies[0].Pass != pass || s.LANKey != lan || s.BarkKey != bark || s.GitHubToken != gh { + t.Fatal("the credentials on disk were changed") + } +}