From 4f9dcb39e58217e898b1fc2c8abc3f01819e8cd1 Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 1 Oct 2026 19:07:12 +0800 Subject: [PATCH] =?UTF-8?q?plugins:=20a=20plugin=20subscription=20goes=20t?= =?UTF-8?q?hrough=20every=20path=20a=20built-in=20one=20does=20(the=20user?= =?UTF-8?q?:=20=E8=A6=81=E4=BF=9D=E8=AF=81=E6=8F=92=E4=BB=B6=E8=AE=A2?= =?UTF-8?q?=E9=98=85=20provider=20=E8=B7=9F=E5=86=85=E7=BD=AE=E7=9A=84?= =?UTF-8?q?=E8=AE=A2=E9=98=85=20provider=E6=89=80=E6=9C=89=E9=80=BB?= =?UTF-8?q?=E8=BE=91=E9=83=BD=E8=A6=81=E4=B8=80=E6=A8=A1=E4=B8=80=E6=A0=B7?= =?UTF-8?q?)=20=E2=80=94=20a=20SOCKS5=20proxy=20on=20a=20plugin=20provider?= =?UTF-8?q?=20or=20account=20now=20carries=20its=20requests:=20Bun=20speak?= =?UTF-8?q?s=20http(s)=20proxies=20only,=20so=20magpie=20stands=20a=20loop?= =?UTF-8?q?back=20http=20proxy=20in=20front=20of=20the=20SOCKS=20one,=20an?= =?UTF-8?q?d=20a=20proxy=20that=20refuses=20says=20so=20as=20Go's=20transp?= =?UTF-8?q?ort=20does.=20A=20plugin's=20model=20list=20and=20its=20loader?= =?UTF-8?q?=20are=20asked=20through=20the=20account's=20own=20proxy,=20as?= =?UTF-8?q?=20a=20built-in's=20list=20is=20fetched=20through=20it.=20The?= =?UTF-8?q?=20Grok=20plugin=20draws=20and=20makes=20videos=20at=20Grok's?= =?UTF-8?q?=20Imagine=20API=20through=20the=20plugin,=20and=20keeps=20Code?= =?UTF-8?q?x's=20namespaced=20tools,=20as=20the=20built-in=20does;=20an=20?= =?UTF-8?q?official=20plugin=20beside=20its=20built-in=20(kiro-plugin,=20z?= =?UTF-8?q?code-plugin)=20counts=20tokens=20by=20estimate=20as=20the=20bui?= =?UTF-8?q?lt-in=20and=20the=20moved=20plugin=20do.=20FetchNew=20no=20long?= =?UTF-8?q?er=20re-lists=20plugin=20providers=20every=20ten=20minutes,=20t?= =?UTF-8?q?heir=20list=20being=20told=20by=20the=20plugin=20host;=20a=20pl?= =?UTF-8?q?ugin=20account's=20usage=20is=20cached=20under=20one=20name=20w?= =?UTF-8?q?hichever=20way=20it=20is=20asked=20for;=20and=20a=20fetch=20hoo?= =?UTF-8?q?k=20that=20throws=20on=20its=20sign-in=20(a=20refused=20refresh?= =?UTF-8?q?)=20marks=20the=20account=20lapsed,=20as=20a=20built-in's=20ref?= =?UTF-8?q?used=20refresh=20does.=20TestPluginSOCKSProxy,=20TestPluginMode?= =?UTF-8?q?lListThroughAccountProxy,=20TestGrokPluginDraws,=20TestPluginBe?= =?UTF-8?q?sideBuiltinCountsByEstimate,=20TestFetchNewLeavesListedPlugins,?= =?UTF-8?q?=20TestPluginUsageReadOnceWhicheverName=20and=20TestPluginFetch?= =?UTF-8?q?SignInExpiredLapses=20fail=20without=20the=20change.=20go=20vet?= =?UTF-8?q?,=20go=20build=20-tags=20nogui=20(darwin,=20GOOS=3Dlinux),=20GO?= =?UTF-8?q?OS=3Dwindows=20go=20build,=20go=20test=20-tags=20nogui=20./...?= =?UTF-8?q?=20pass=20(the=20known=20load=20flakes=20pass=20alone);=20inter?= =?UTF-8?q?nal/plugin,=20netproxy=20and=20the=20plugin/proxy=20tests=20of?= =?UTF-8?q?=20provider=20and=20gateway=20pass=20on=20Linux=20and=20Windows?= =?UTF-8?q?.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/gateway/draw.go | 7 +- internal/gateway/gateway.go | 8 +- internal/gateway/plugin_grok_parity_test.go | 166 +++++++++++ internal/gateway/plugin_listing_proxy_test.go | 97 +++++++ internal/gateway/plugin_proxy_down_test.go | 107 +++++++ internal/netproxy/bridge.go | 266 ++++++++++++++++++ internal/netproxy/bridge_test.go | 195 +++++++++++++ internal/plugin/host.go | 17 +- internal/plugin/host.js | 82 +++++- internal/plugin/plugin_socks_test.go | 131 +++++++++ internal/plugin/providers.go | 32 ++- internal/plugin/testdata/fake/index.js | 4 + internal/provider/login_usage.go | 7 +- internal/provider/models.go | 3 +- internal/provider/plugin_fetch_lapse_test.go | 66 +++++ internal/provider/plugin_fetchnew_test.go | 108 +++++++ internal/provider/plugins.go | 28 ++ 17 files changed, 1299 insertions(+), 25 deletions(-) create mode 100644 internal/gateway/plugin_grok_parity_test.go create mode 100644 internal/gateway/plugin_listing_proxy_test.go create mode 100644 internal/gateway/plugin_proxy_down_test.go create mode 100644 internal/netproxy/bridge.go create mode 100644 internal/netproxy/bridge_test.go create mode 100644 internal/plugin/plugin_socks_test.go create mode 100644 internal/provider/plugin_fetch_lapse_test.go create mode 100644 internal/provider/plugin_fetchnew_test.go diff --git a/internal/gateway/draw.go b/internal/gateway/draw.go index 1a3727cbc..0659cd6ba 100644 --- a/internal/gateway/draw.go +++ b/internal/gateway/draw.go @@ -77,9 +77,10 @@ var grokDrawers = []catalog.Model{ } // drawsGrok is whether p is a Grok subscription, which draws at the Imagine -// API of the backend Grok Build talks to. +// API of the backend Grok Build talks to: the built-in's, or the Grok +// plugin's, which signs what it is sent there as the built-in does. func drawsGrok(p provider.Provider) bool { - return p.Account != nil && p.Account.Agent == "grok" && p.Base(provider.Responses) != "" + return p.Account != nil && (p.Account.Agent == "grok" || p.PluginProvider() == "grok") && p.Base(provider.Responses) != "" } // drawsCodex is whether p is a ChatGPT account, which draws at its Codex @@ -542,7 +543,7 @@ func (s *Server) sendAs(ctx context.Context, p provider.Provider, method, url, c req.Header[k] = []string{v} } } - res, err := s.client.Do(req) + res, err := p.Do(s.client, req) // a plugin's through the plugin if err != nil { if ctx.Err() != nil { return nil, 504, fmt.Errorf("%s didn't answer in %s", p.Name, drawTimeout) diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 221696297..3d749993a 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -556,8 +556,8 @@ func unprefixed(id string) string { } // estimatedMoved are the built-ins that estimated a count, as their -// plugins do once moved; Command Code's whatever its plan, as the plugin -// alone knows a Go key. +// plugins do, moved or beside the built-in (kiro-plugin); Command Code's +// whatever its plan, as the plugin alone knows a Go key. var estimatedMoved = []string{"cursor", "grok", "devin", "kiro", "qoder", "zed", "factory", "zcode", provider.CommandCodePlanID} // countTokens answers Anthropic's count_tokens: through the provider when @@ -591,7 +591,7 @@ func (s *Server) countOn(w http.ResponseWriter, r *http.Request, p provider.Prov // with an error every time: one more request its firewall weighs p.Account.Agent == "zcode") || ok && p.Account != nil && p.Account.Agent == provider.CommandCodePlanID && cmdGoing(r.Context(), p) || - ok && p.IsPlugin() && slices.Contains(estimatedMoved, p.ID) { + ok && p.IsPlugin() && (slices.Contains(estimatedMoved, p.ID) || slices.Contains(estimatedMoved, p.PluginProvider())) { req, err := parseAnthropic(body) if err != nil { writeError(w, provider.Anthropic, 400, err.Error()) @@ -1720,7 +1720,7 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. // a Grok subscription is given Codex's namespaced functions flat // (grokBody); a call to one goes back under its namespace (#404) var named map[string]nsTool - if proto == provider.Responses && p.Account != nil && p.Account.Agent == "grok" { + if proto == provider.Responses && p.Account != nil && (p.Account.Agent == "grok" || p.PluginProvider() == "grok") { named = namespacedIn(body) } res, err := s.forward(r.Context(), p, proto, path, p.Prepare(body), r.Header) diff --git a/internal/gateway/plugin_grok_parity_test.go b/internal/gateway/plugin_grok_parity_test.go new file mode 100644 index 000000000..3bcc9f937 --- /dev/null +++ b/internal/gateway/plugin_grok_parity_test.go @@ -0,0 +1,166 @@ +package gateway + +import ( + "context" + "encoding/base64" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os/exec" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/provider" +) + +// besideFake installs the fake plugin as the plugin of the built-in id, +// not moved onto it (id-plugin beside the built-in), signed in with a +// key, its requests going to up; it gives the provider's id. +func besideFake(t *testing.T, id string, up http.Handler) string { + t.Helper() + bun, err := exec.LookPath("bun") + if err != nil { + t.Skip("no bun on PATH") + } + fresh(t) + t.Setenv("MAGPIE_BUN", bun) + t.Setenv("FAKE_ID", id) + t.Setenv("FAKE_RESPONSES", "1") + t.Cleanup(plugin.Settle) + srv := httptest.NewServer(up) + t.Cleanup(srv.Close) + t.Setenv("FAKE_BASE", srv.URL+"/v1") + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + abs, _ := filepath.Abs("../plugin/testdata/fake/index.js") + if _, err := plugin.Add(ctx, abs); err != nil { + t.Fatal(err) + } + if _, err := plugin.Providers(ctx); err != nil { + t.Fatal(err) + } + if _, err := plugin.APIKey(ctx, id, 0, nil, "k1", plugin.NewAccount); err != nil { + t.Fatal(err) + } + pid := provider.PluginID(id) + if p, err := provider.Find(pid); err != nil || !p.IsPlugin() || p.PluginProvider() != id { + t.Fatalf("Find(%s) = %+v, %v", pid, p, err) + } + return pid +} + +// The Grok plugin draws at Grok's Imagine API as the built-in does +// (TestGrokAccountDraws): the same models, the same request, sent through +// the plugin, which signs it. +func TestGrokPluginDraws(t *testing.T) { + var mu sync.Mutex + var paths, bodies []string + pid := besideFake(t, "grok", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + mu.Lock() + paths, bodies = append(paths, r.URL.Path), append(bodies, string(b)) + mu.Unlock() + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"data":[{"b64_json":"`+base64.StdEncoding.EncodeToString(pngBytes)+`"}]}`) + })) + p, err := provider.Find(pid) + if err != nil { + t.Fatal(err) + } + if ds := Drawers(*p); len(ds) != 2 || ds[0].ID != "grok-imagine-image" || ds[0].Provider != pid { + t.Fatalf("drawers %v", ds) + } + if vs := Videomakers(*p); len(vs) == 0 { + t.Fatal("the Grok plugin makes no videos") + } + code, a, raw := postImages(t, New(), "/v1/images/generations", "application/json", `{"model":"`+pid+`/grok-imagine-image","prompt":"a magpie","size":"1792x1024"}`) + if code != 200 || len(a.Data) != 1 { + t.Fatalf("%d %s", code, raw) + } + mu.Lock() + defer mu.Unlock() + if len(paths) != 1 || paths[0] != "/v1/images/generations" || !strings.Contains(bodies[0], `"model":"grok-imagine-image"`) || !strings.Contains(bodies[0], `"aspect_ratio":"16:9"`) { + t.Fatalf("asked %v %v", paths, bodies) + } +} + +// Codex's namespaced tools reach the Grok plugin flat, and its call comes +// back under the namespace, as with the built-in (TestGrokGetsNamespacedTools). +func TestGrokPluginGetsNamespacedTools(t *testing.T) { + var mu sync.Mutex + var sent []map[string]any + call := `{"type":"function_call","id":"fc_1","call_id":"c9","name":"collaboration__spawn_agent","arguments":"{\"message\":\"go\"}","status":"completed"}` + pid := besideFake(t, "grok", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + var q map[string]any + json.Unmarshal(b, &q) + mu.Lock() + sent = append(sent, q) + mu.Unlock() + done := `{"id":"r1","object":"response","status":"completed","output":[` + call + `],"usage":{"input_tokens":5,"output_tokens":3}}` + if q["stream"] != true { + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, done) + return + } + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse( + `event: response.created`+"\n"+`data: {"type":"response.created","response":{"id":"r1","object":"response","status":"in_progress","output":[]}}`, + `event: response.output_item.added`+"\n"+`data: {"type":"response.output_item.added","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"c9","name":"collaboration__spawn_agent","arguments":""}}`, + `event: response.output_item.done`+"\n"+`data: {"type":"response.output_item.done","output_index":0,"item":`+call+`}`, + `event: response.completed`+"\n"+`data: {"type":"response.completed","response":`+done+`}`)) + })) + body := `{"model":"` + pid + `/fake-resp","stream":false,` + namespacedTools + `,"input":[ + {"type":"message","role":"user","content":"go"}, + {"type":"function_call","call_id":"c1","name":"spawn_agent","namespace":"collaboration","arguments":"{}"}, + {"type":"function_call_output","call_id":"c1","output":"ok"}]}` + rec := httptest.NewRecorder() + New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(body))) + if rec.Code != 200 { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + mu.Lock() + if len(sent) != 1 { + t.Fatalf("asked %d times", len(sent)) + } + q := sent[0] + mu.Unlock() + var names []string + for _, tl := range q["tools"].([]any) { + tm := tl.(map[string]any) + names = append(names, tm["type"].(string)+":"+tm["name"].(string)) + } + if got := strings.Join(names, ","); got != "function:exec_command,function:collaboration__spawn_agent" { + t.Fatalf("Grok was offered %s", got) + } + if c := q["input"].([]any)[1].(map[string]any); c["name"] != "collaboration__spawn_agent" || c["namespace"] != nil { + t.Fatalf("the call handed back went as %v", c) + } + var res struct { + Output []map[string]any `json:"output"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &res); err != nil || len(res.Output) != 1 { + t.Fatalf("%v: %s", err, rec.Body) + } + if it := res.Output[0]; it["name"] != "spawn_agent" || it["namespace"] != "collaboration" { + t.Fatalf("Codex was given %v", it) + } +} + +// Kiro's plugin beside the built-in (kiro-plugin) counts by estimate, as +// the built-in and the moved plugin do: the vendor isn't asked. +func TestPluginBesideBuiltinCountsByEstimate(t *testing.T) { + up := &countAsked{} + pid := besideFake(t, "kiro", up) + rec := httptest.NewRecorder() + New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/messages/count_tokens", + strings.NewReader(`{"model":"`+pid+`/fake-claude","messages":[{"role":"user","content":"hello there"}]}`))) + if n := estimated(t, rec); n == 999 || len(up.asked()) > 0 { + t.Fatalf("the vendor was asked to count: %v, %d", up.asked(), n) + } +} diff --git a/internal/gateway/plugin_listing_proxy_test.go b/internal/gateway/plugin_listing_proxy_test.go new file mode 100644 index 000000000..99665ca8b --- /dev/null +++ b/internal/gateway/plugin_listing_proxy_test.go @@ -0,0 +1,97 @@ +package gateway + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "os/exec" + "path/filepath" + "slices" + "testing" + "time" + + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/provider" +) + +// A plugin account's model list is asked through the account's own proxy, +// as a built-in account's is fetched through its: each of two accounts +// behind its own proxy is told the list its proxy carried. +func TestPluginModelListThroughAccountProxy(t *testing.T) { + bun, err := exec.LookPath("bun") + if err != nil { + t.Skip("no bun on PATH") + } + fresh(t) + for _, k := range []string{"HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy", "NO_PROXY", "no_proxy"} { + t.Setenv(k, "") + } + t.Setenv("MAGPIE_BUN", bun) + t.Cleanup(plugin.Settle) + // each proxy answers the vendor's list with a model of its own + proxyOf := func(name string) *httptest.Server { + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Host != "models.invalid" { + http.Error(w, "not the list: "+r.URL.String(), 400) + return + } + fmt.Fprint(w, name) + })) + } + pa, pb := proxyOf("via-a"), proxyOf("via-b") + defer pa.Close() + defer pb.Close() + t.Setenv("FAKE_BASE", "http://vendor.invalid/v1") + t.Setenv("FAKE_MODELS", "http://models.invalid/list") + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + abs, _ := filepath.Abs("../plugin/testdata/fake/index.js") + if _, err := plugin.Add(ctx, abs); err != nil { + t.Fatal(err) + } + if _, err := plugin.Providers(ctx); err != nil { + t.Fatal(err) + } + for _, team := range []string{"a", "b"} { + st, err := provider.StartPluginSignIn("fakeco", 1, map[string]string{"where": "work", "team": team}) + if err != nil { + t.Fatal(err) + } + if err := provider.SubmitSignInCallback(st.ID, "good"); err != nil { + t.Fatal(err) + } + } + if _, err := plugin.Providers(ctx); err != nil { + t.Fatal(err) + } + p, err := provider.Find("fakeco") + if err != nil { + t.Fatal(err) + } + p.AccountProxies = map[string]string{"a@fake": pa.URL, "b@fake": pb.URL} + if err := provider.Save(*p); err != nil { + t.Fatal(err) + } + ps, err := plugin.Providers(ctx) + if err != nil { + t.Fatal(err) + } + got := map[string][]string{} + for _, pp := range ps { + if pp.ID == "fakeco" { + for _, a := range pp.Accounts { + got[a.AccountID] = a.Models + } + } + } + for who, want := range map[string]string{"a@fake": "fake-via-a", "b@fake": "fake-via-b"} { + if !slices.Contains(got[who], want) { + t.Fatalf("%s's models %v, want %s among them (all: %v)", who, got[who], want, got) + } + } + if slices.Contains(got["a@fake"], "fake-via-b") || slices.Contains(got["b@fake"], "fake-via-a") { + t.Fatalf("an account's list came through the other's proxy: %v", got) + } +} diff --git a/internal/gateway/plugin_proxy_down_test.go b/internal/gateway/plugin_proxy_down_test.go new file mode 100644 index 000000000..8ff05133d --- /dev/null +++ b/internal/gateway/plugin_proxy_down_test.go @@ -0,0 +1,107 @@ +package gateway + +import ( + "context" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/plugin" + "github.com/yetone/magpie/internal/provider" +) + +// A plugin account whose proxy is down, HTTP or SOCKS5, never reached its +// vendor: as for a built-in's (TestProxyDownDoesNotRest), the next account +// answers and the first isn't set aside. +func TestPluginProxyDownDoesNotRest(t *testing.T) { + bun, err := exec.LookPath("bun") + if err != nil { + t.Skip("no bun on PATH") + } + for _, scheme := range []string{"http", "socks5"} { + t.Run(scheme, func(t *testing.T) { + fresh(t) + for _, k := range []string{"HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy", "NO_PROXY", "no_proxy"} { + t.Setenv(k, "") + } + t.Setenv("MAGPIE_BUN", bun) + t.Cleanup(plugin.Settle) + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + down := l.Addr().String() + l.Close() + // the proxy b goes through, which answers as the vendor + good := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.ReadAll(r.Body) + who := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer fresh-r-") + w.Header().Set("Content-Type", "text/event-stream") + fmt.Fprint(w, `data: {"id":"c","object":"chat.completion.chunk","model":"fake-1","choices":[{"index":0,"delta":{"role":"assistant","content":"from `+who+`"},"finish_reason":null}]}`+"\n\n") + fmt.Fprint(w, `data: {"id":"c","object":"chat.completion.chunk","model":"fake-1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`+"\n\ndata: [DONE]\n\n") + })) + defer good.Close() + t.Setenv("FAKE_BASE", "http://vendor.invalid/v1") + + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + abs, _ := filepath.Abs("../plugin/testdata/fake/index.js") + if _, err := plugin.Add(ctx, abs); err != nil { + t.Fatal(err) + } + if _, err := plugin.Providers(ctx); err != nil { + t.Fatal(err) + } + for _, team := range []string{"a", "b"} { + st, err := provider.StartPluginSignIn("fakeco", 1, map[string]string{"where": "work", "team": team}) + if err != nil { + t.Fatal(err) + } + if err := provider.SubmitSignInCallback(st.ID, "good"); err != nil { + t.Fatal(err) + } + } + if _, err := plugin.Providers(ctx); err != nil { + t.Fatal(err) + } + if err := provider.SwitchLogin("fakeco", "a@fake"); err != nil { + t.Fatal(err) + } + p, err := provider.Find("fakeco") + if err != nil { + t.Fatal(err) + } + p.AccountProxies = map[string]string{"a@fake": scheme + "://" + down, "b@fake": good.URL} + if err := provider.Save(*p); err != nil { + t.Fatal(err) + } + s := New() + for i := 0; i < 2; i++ { + code, body := postAs(t, s, "", `{"model":"fakeco/fake-1","messages":[{"role":"user","content":"hi"}]}`) + if code != 200 || !strings.Contains(body, "from b") { + t.Fatalf("request %d: %d %s", i, code, body) + } + r := s.trace.routes[len(s.trace.routes)-1] + if len(r.Tries) != 2 { + t.Fatalf("request %d: tries %+v", i, r.Tries) + } + if f := r.Tries[0]; f.Fail != "proxy" || f.Rest != nil || !strings.Contains(f.Error, down) { + t.Fatalf("request %d: a's try %+v", i, f) + } + } + restingUntil.Lock() + n := len(restingUntil.m) + restingUntil.Unlock() + if n != 0 { + t.Fatalf("%d set aside over a proxy that was down", n) + } + }) + } +} diff --git a/internal/netproxy/bridge.go b/internal/netproxy/bridge.go new file mode 100644 index 000000000..7fe9a7fbc --- /dev/null +++ b/internal/netproxy/bridge.go @@ -0,0 +1,266 @@ +package netproxy + +// The plugin host's Bun speaks http:// and https:// proxies only: a fetch +// given socks5:// fails as UnsupportedProxyProtocol. Bridge stands an +// http:// proxy on loopback in front of a SOCKS5 one, so a plugin's +// requests go through the SOCKS proxy a built-in's go through. + +import ( + "bufio" + "context" + "encoding/binary" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "strconv" + "sync" + "time" +) + +var ( + bridgesMu sync.Mutex + bridges = map[string]string{} +) + +// IsSOCKS is whether the proxy's address is a SOCKS5 one. +func IsSOCKS(u *url.URL) bool { return u != nil && (u.Scheme == "socks5" || u.Scheme == "socks5h") } + +// Bridge is the http:// address of a proxy on loopback carrying what it is +// given through the SOCKS5 proxy socks, one for each, kept while magpie +// runs. +func Bridge(socks *url.URL) (string, error) { + key := socks.String() + bridgesMu.Lock() + defer bridgesMu.Unlock() + if a, ok := bridges[key]; ok { + return a, nil + } + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + return "", err + } + s := *socks + go func() { + for { + c, err := ln.Accept() + if err != nil { + return + } + go bridgeConn(c, &s) + } + }() + a := "http://" + ln.Addr().String() + bridges[key] = a + return a, nil +} + +// bridgeConn serves one client of a bridge: a CONNECT is tunnelled, a +// plain http:// request sent on and answered. +func bridgeConn(c net.Conn, socks *url.URL) { + defer c.Close() + br := bufio.NewReader(c) + _ = c.SetReadDeadline(time.Now().Add(time.Minute)) + req, err := http.ReadRequest(br) + if err != nil { + return + } + _ = c.SetReadDeadline(time.Time{}) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + if req.Method == http.MethodConnect { + up, err := DialSOCKS(ctx, socks, req.Host) + if err != nil { + refuse(c, err) + return + } + defer up.Close() + if _, err := io.WriteString(c, "HTTP/1.1 200 Connection established\r\n\r\n"); err != nil { + return + } + done := make(chan struct{}, 2) + go func() { _, _ = io.Copy(up, br); closeWrite(up); done <- struct{}{} }() + go func() { _, _ = io.Copy(c, up); closeWrite(c); done <- struct{}{} }() + <-done + <-done + return + } + t := &http.Transport{ + Proxy: nil, + DialContext: func(ctx context.Context, _, addr string) (net.Conn, error) { + return DialSOCKS(ctx, socks, addr) + }, + } + defer t.CloseIdleConnections() + req.RequestURI = "" + req.Header.Del("Proxy-Connection") + req.Header.Del("Proxy-Authorization") + res, err := t.RoundTrip(req.WithContext(context.Background())) + if err != nil { + refuse(c, err) + return + } + defer res.Body.Close() + res.Close = true + _ = res.Write(c) +} + +func closeWrite(c net.Conn) { + if tc, ok := c.(interface{ CloseWrite() error }); ok { + _ = tc.CloseWrite() + } +} + +// refuse answers a client the SOCKS proxy didn't carry: a 502 saying why, +// in the words Go's own transport uses ("socks connect …"). +func refuse(c net.Conn, err error) { + msg := err.Error() + fmt.Fprintf(c, "HTTP/1.1 502 Bad Gateway\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: %d\r\nConnection: close\r\n\r\n%s", len(msg), msg) +} + +// DialSOCKS connects to addr (host:port) through the SOCKS5 proxy socks, +// the user and password in its address used when it has them. The host +// is sent by name, as Go's own transport sends it, so the proxy resolves +// it. +func DialSOCKS(ctx context.Context, socks *url.URL, addr string) (net.Conn, error) { + proxy := socks.Host + if socks.Port() == "" { + proxy = net.JoinHostPort(socks.Hostname(), "1080") + } + fail := func(err error) error { return fmt.Errorf("socks connect tcp %s->%s: %w", proxy, addr, err) } + host, portS, err := net.SplitHostPort(addr) + if err != nil { + return nil, fail(err) + } + port, err := strconv.Atoi(portS) + if err != nil || port < 1 || port > 65535 { + return nil, fail(fmt.Errorf("bad port %q", portS)) + } + c, err := (&net.Dialer{Timeout: 15 * time.Second}).DialContext(ctx, "tcp", proxy) + if err != nil { + return nil, fail(err) + } + if d, ok := ctx.Deadline(); ok { + _ = c.SetDeadline(d) + } else { + _ = c.SetDeadline(time.Now().Add(30 * time.Second)) + } + if err := socksHandshake(c, socks.User, host, port); err != nil { + c.Close() + return nil, fail(err) + } + _ = c.SetDeadline(time.Time{}) + return c, nil +} + +var socksReplies = map[byte]string{ + 1: "general SOCKS server failure", + 2: "connection not allowed by ruleset", + 3: "network unreachable", + 4: "host unreachable", + 5: "connection refused", + 6: "TTL expired", + 7: "command not supported", + 8: "address type not supported", +} + +func socksHandshake(c net.Conn, user *url.Userinfo, host string, port int) error { + methods := []byte{0} + if user != nil { + methods = append(methods, 2) + } + if _, err := c.Write(append([]byte{5, byte(len(methods))}, methods...)); err != nil { + return err + } + var b [2]byte + if _, err := io.ReadFull(c, b[:]); err != nil { + return err + } + if b[0] != 5 { + return errors.New("not a SOCKS5 proxy") + } + switch b[1] { + case 0: + case 2: + if user == nil { + return errors.New("the proxy asks for a user and password") + } + pw, _ := user.Password() + u := user.Username() + if len(u) > 255 || len(pw) > 255 { + return errors.New("user or password too long") + } + msg := append([]byte{1, byte(len(u))}, u...) + msg = append(append(msg, byte(len(pw))), pw...) + if _, err := c.Write(msg); err != nil { + return err + } + if _, err := io.ReadFull(c, b[:]); err != nil { + return err + } + if b[1] != 0 { + return errors.New("the proxy turned the user and password away") + } + default: + return errors.New("no authentication method the proxy takes") + } + req := []byte{5, 1, 0} + if ip := net.ParseIP(host); ip != nil { + if ip4 := ip.To4(); ip4 != nil { + req = append(append(req, 1), ip4...) + } else { + req = append(append(req, 4), ip.To16()...) + } + } else { + if len(host) > 255 { + return errors.New("host name too long") + } + req = append(append(req, 3, byte(len(host))), host...) + } + req = binary.BigEndian.AppendUint16(req, uint16(port)) + if _, err := c.Write(req); err != nil { + return err + } + var h [4]byte + if _, err := io.ReadFull(c, h[:]); err != nil { + return err + } + if h[1] != 0 { + if m, ok := socksReplies[h[1]]; ok { + return errors.New(m) + } + return fmt.Errorf("unknown SOCKS reply %d", h[1]) + } + var skip int + switch h[3] { + case 1: + skip = 4 + case 4: + skip = 16 + case 3: + var n [1]byte + if _, err := io.ReadFull(c, n[:]); err != nil { + return err + } + skip = int(n[0]) + default: + return fmt.Errorf("unknown address type %d", h[3]) + } + _, err := io.CopyN(io.Discard, c, int64(skip+2)) + return err +} + +// ForBun is a proxy's address as the plugin host's Bun can use it: a +// SOCKS5 one is bridged, any other is as it is. +func ForBun(proxy string) string { + u, err := Parse(proxy) + if err != nil || !IsSOCKS(u) { + return proxy + } + if a, err := Bridge(u); err == nil { + return a + } + return proxy +} diff --git a/internal/netproxy/bridge_test.go b/internal/netproxy/bridge_test.go new file mode 100644 index 000000000..eedcc7043 --- /dev/null +++ b/internal/netproxy/bridge_test.go @@ -0,0 +1,195 @@ +package netproxy + +import ( + "encoding/binary" + "io" + "net" + "net/http" + "net/http/httptest" + "net/url" + "os" + "os/exec" + "strconv" + "strings" + "sync/atomic" + "testing" +) + +// fakeSOCKS is a SOCKS5 proxy taking user u and password pw ("" for none), +// counting the connections it carried. +func fakeSOCKS(t *testing.T, u, pw string) (*url.URL, *atomic.Int32) { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ln.Close() }) + var n atomic.Int32 + go func() { + for { + c, err := ln.Accept() + if err != nil { + return + } + go func(c net.Conn) { + defer c.Close() + var h [2]byte + io.ReadFull(c, h[:]) + ms := make([]byte, h[1]) + io.ReadFull(c, ms) + if u != "" { + c.Write([]byte{5, 2}) + var v [2]byte + io.ReadFull(c, v[:]) + got := make([]byte, v[1]) + io.ReadFull(c, got) + var l [1]byte + io.ReadFull(c, l[:]) + p := make([]byte, l[0]) + io.ReadFull(c, p) + if string(got) != u || string(p) != pw { + c.Write([]byte{1, 1}) + return + } + c.Write([]byte{1, 0}) + } else { + c.Write([]byte{5, 0}) + } + var r [4]byte + io.ReadFull(c, r[:]) + var host string + switch r[3] { + case 1: + b := make([]byte, 4) + io.ReadFull(c, b) + host = net.IP(b).String() + case 3: + var l [1]byte + io.ReadFull(c, l[:]) + b := make([]byte, l[0]) + io.ReadFull(c, b) + host = string(b) + } + var pb [2]byte + io.ReadFull(c, pb[:]) + up, err := net.Dial("tcp", net.JoinHostPort(host, strconv.Itoa(int(binary.BigEndian.Uint16(pb[:]))))) + if err != nil { + c.Write([]byte{5, 5, 0, 1, 0, 0, 0, 0, 0, 0}) + return + } + defer up.Close() + n.Add(1) + c.Write([]byte{5, 0, 0, 1, 127, 0, 0, 1, 0, 0}) + go io.Copy(up, c) + io.Copy(c, up) + }(c) + } + }() + s := &url.URL{Scheme: "socks5", Host: ln.Addr().String()} + if u != "" { + s.User = url.UserPassword(u, pw) + } + return s, &n +} + +// A plugin's request goes through a SOCKS5 proxy as a built-in's does: +// the bridge carries a plain http:// request and an https:// one's +// CONNECT tunnel through it, signing in to it when it asks. +func TestBridgeCarriesThroughSOCKS(t *testing.T) { + plain := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "plain "+r.URL.Path) })) + defer plain.Close() + tls := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "tls "+r.URL.Path) })) + defer tls.Close() + for _, auth := range []bool{false, true} { + u, pw := "", "" + if auth { + u, pw = "me", "secret" + } + socks, n := fakeSOCKS(t, u, pw) + b, err := Bridge(socks) + if err != nil { + t.Fatal(err) + } + if again, _ := Bridge(socks); again != b { + t.Fatalf("a second bridge %s for the same proxy, not %s", again, b) + } + if ForBun(socks.String()) != b || !strings.HasPrefix(b, "http://127.0.0.1:") { + t.Fatalf("ForBun(%s) = %s, want %s", socks, ForBun(socks.String()), b) + } + pu, _ := url.Parse(b) + tr := tls.Client().Transport.(*http.Transport).Clone() + tr.Proxy = http.ProxyURL(pu) + c := &http.Client{Transport: tr} + for _, x := range []struct{ url, want string }{{plain.URL + "/a", "plain /a"}, {tls.URL + "/b", "tls /b"}} { + res, err := c.Get(x.url) + if err != nil { + t.Fatalf("auth=%v %s: %v", auth, x.url, err) + } + got, _ := io.ReadAll(res.Body) + res.Body.Close() + if string(got) != x.want { + t.Fatalf("auth=%v %s: %q, want %q", auth, x.url, got, x.want) + } + } + if n.Load() != 2 { + t.Fatalf("auth=%v: the SOCKS proxy carried %d connections, want 2", auth, n.Load()) + } + } + for _, p := range []string{"http://127.0.0.1:7890", "direct", ""} { + if got := ForBun(p); got != p { + t.Fatalf("ForBun(%q) = %q, want it as it is", p, got) + } + } +} + +// A SOCKS proxy that isn't there is said as Go's transport says it, so +// the gateway takes it for the proxy's failure, not the vendor's. +func TestBridgeSaysTheProxyIsDown(t *testing.T) { + ln, _ := net.Listen("tcp", "127.0.0.1:0") + addr := ln.Addr().String() + ln.Close() + b, err := Bridge(&url.URL{Scheme: "socks5h", Host: addr}) + if err != nil { + t.Fatal(err) + } + c, err := net.Dial("tcp", strings.TrimPrefix(b, "http://")) + if err != nil { + t.Fatal(err) + } + defer c.Close() + io.WriteString(c, "CONNECT example.com:443 HTTP/1.1\r\nHost: example.com:443\r\n\r\n") + got, _ := io.ReadAll(c) + if !strings.HasPrefix(string(got), "HTTP/1.1 502") || !strings.Contains(string(got), "socks connect tcp "+addr) { + t.Fatalf("answered %q", got) + } +} + +// Bun itself, the plugin host's runtime, fetches through the bridge: run +// when a bun is at hand ($MAGPIE_BUN or on PATH). +func TestBunThroughBridge(t *testing.T) { + bun := os.Getenv("MAGPIE_BUN") + if bun == "" { + bun, _ = exec.LookPath("bun") + } + if bun == "" { + t.Skip("no bun") + } + plain := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "plain") })) + defer plain.Close() + tls := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "tls") })) + defer tls.Close() + socks, n := fakeSOCKS(t, "me", "pw") + b, _ := Bridge(socks) + // loopback is never proxied by magpie, but the test's servers are on it: + // Bun is given the proxy outright + js := `for (const u of process.env.URLS.split(" ")) console.log(await (await fetch(u, { proxy: "` + b + `", tls: { rejectUnauthorized: false } })).text())` + cmd := exec.Command(bun, "-e", js) + cmd.Env = append(os.Environ(), "URLS="+plain.URL+" "+tls.URL) + out, err := cmd.CombinedOutput() + if err != nil || strings.TrimSpace(string(out)) != "plain\ntls" { + t.Fatalf("bun: %v %s", err, out) + } + if n.Load() != 2 { + t.Fatalf("the SOCKS proxy carried %d connections, want 2", n.Load()) + } +} diff --git a/internal/plugin/host.go b/internal/plugin/host.go index 45dcb667a..99507acaf 100644 --- a/internal/plugin/host.go +++ b/internal/plugin/host.go @@ -489,14 +489,17 @@ type FetchRequest struct { } // proxyOf is the proxy ctx names for the host: "" when it names none, -// "direct", or the proxy's URL. -func proxyOf(ctx context.Context) string { - switch c := strings.TrimSpace(netproxy.Choice(ctx)); c { +// "direct", or the proxy's URL (a SOCKS5 one bridged, as Bun can't use it). +func proxyOf(ctx context.Context) string { return forHost(netproxy.Choice(ctx)) } + +// forHost is a proxy choice (netproxy.With's) as the host takes it. +func forHost(choice string) string { + switch c := strings.TrimSpace(choice); c { case "", "direct": return c default: if u, err := netproxy.Parse(c); err == nil { - return u.String() + return netproxy.ForBun(u.String()) } return c } @@ -505,13 +508,15 @@ func proxyOf(ctx context.Context) string { // hostEnv is env for the host, its *_PROXY named MAGPIE_*_PROXY: Bun // reads *_PROXY once and puts every fetch through them, so a provider set // to "direct" couldn't go around them. host.js gives each fetch the proxy -// they name instead. +// they name instead. A SOCKS5 one, which Bun can't use, is bridged. func hostEnv(env []string) []string { out := make([]string, 0, len(env)) for _, e := range env { k, v, _ := strings.Cut(e, "=") switch strings.ToUpper(k) { - case "HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY", "NO_PROXY": + case "HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY": + out = append(out, "MAGPIE_"+k+"="+netproxy.ForBun(v)) + case "NO_PROXY": out = append(out, "MAGPIE_"+k+"="+v) default: out = append(out, e) diff --git a/internal/plugin/host.js b/internal/plugin/host.js index 124d60fa9..1d2ccf28d 100644 --- a/internal/plugin/host.js +++ b/internal/plugin/host.js @@ -22,8 +22,10 @@ import { AsyncLocalStorage } from "node:async_hooks" import fs from "node:fs" +import net from "node:net" import path from "node:path" import readline from "node:readline" +import tls from "node:tls" import { pathToFileURL } from "node:url" const rpcWrite = process.stdout.write.bind(process.stdout) @@ -102,7 +104,66 @@ const reach = new AsyncLocalStorage() function sent(input, init) { if (init && "proxy" in init) return bunFetch(input, init) const p = proxyFor(input) - return p ? bunFetch(input, { ...init, proxy: p }) : bunFetch(input, init) + if (!p) return bunFetch(input, init) + return bunFetch(input, { ...init, proxy: p }).catch(async (e) => { + if (e?.name === "AbortError" || init?.signal?.aborted) throw e + const why = await proxyRefuses(p, input) + if (why) throw Object.assign(new Error(`proxyconnect tcp: ${why}`), { code: e?.code, cause: e }) + throw e + }) +} + +// proxyRefuses is why the proxy p won't carry a request to input, "" when +// it will: Bun says a proxy that is down, or that turns the tunnel away, +// only as a connection that failed, which a vendor's own failure is too. +// The tunnel is asked for again, as Go's transport asks for it, so a +// failure is said in its words ("proxyconnect …") and the gateway takes it +// for the proxy's, asking the next account rather than resting this one. +function proxyRefuses(p, input) { + let pu, target + try { + pu = new URL(p) + const u = new URL(typeof input === "string" || input instanceof URL ? input : input.url) + target = `${u.hostname.includes(":") ? `[${u.hostname.replace(/^\[|\]$/g, "")}]` : u.hostname}:${u.port || (u.protocol === "http:" ? 80 : 443)}` + } catch { + return Promise.resolve("") + } + const host = pu.hostname.replace(/^\[|\]$/g, "") + const port = Number(pu.port || (pu.protocol === "https:" ? 443 : 80)) + return new Promise((resolve) => { + let got = "" + let refused + const done = (why) => { + sock.destroy() + resolve(why) + } + const opts = { host, port, servername: net.isIP(host) ? undefined : host } + const sock = pu.protocol === "https:" ? tls.connect(opts) : net.connect(opts) + sock.setTimeout(10_000, () => done(`dial tcp ${host}:${port}: i/o timeout`)) + sock.on("error", (e) => done(`dial tcp ${host}:${port}: ${e?.message ?? e}`)) + sock.once(pu.protocol === "https:" ? "secureConnect" : "connect", () => { + let req = `CONNECT ${target} HTTP/1.1\r\nHost: ${target}\r\n` + if (pu.username) { + const cred = `${decodeURIComponent(pu.username)}:${decodeURIComponent(pu.password)}` + req += `Proxy-Authorization: Basic ${Buffer.from(cred).toString("base64")}\r\n` + } + sock.write(req + "\r\n") + }) + sock.on("data", (d) => { + got += d.toString("latin1") + const end = got.indexOf("\r\n\r\n") + if (end < 0 && got.length < 8192) return + const status = got.slice(0, got.indexOf("\r\n")).replace(/^HTTP\/\d(\.\d)?\s+/, "") + if (/^2\d\d/.test(status)) return done("") + // a bridge to a SOCKS proxy says why after its status + refused ??= () => { + const body = end < 0 ? "" : got.slice(end + 4, end + 304).trim() + return body ? `${status}: ${body}` : status + } + setTimeout(() => done(refused()), 50) + }) + sock.on("end", () => done(refused ? refused() : got ? "" : `${host}:${port} closed the connection`)) + }) } // listing is what a models hook's fetches came to: whether it asked any, @@ -612,17 +673,21 @@ function iconOf(a) { return ok(readJSON(path.join(dir, "package.json"))?.magpie?.icon) } -async function providers() { +// providers lists each provider and its accounts' models, each asked +// through its proxy (proxies[provider][key], "" the provider's own), as a +// built-in fetches each account's list through the account's. +async function providers({ proxies } = {}) { const stored = readAuth() const out = [] for (const [id, a] of auths()) { const keys = accountsOf(stored, id) - const p = await info(id) + const through = (k) => proxies?.[id]?.[k ?? keys[0] ?? ""] ?? proxies?.[id]?.[""] ?? "" + const p = await via.run(through(), () => info(id)) // each account's own models, as the built-ins read each account's: a // plan may serve fewer, or others, than the first account's. One that // can't be read is taken to have them all, or the ones it was last // told to have, as a built-in account whose fetch failed keeps its own. - const own = await Promise.all(keys.slice(1).map((k) => info(id, k, true).catch(() => ({ failed: true })))) + const own = await Promise.all(keys.slice(1).map((k) => via.run(through(k), () => info(id, k, true)).catch(() => ({ failed: true })))) const models = { ...p.models } for (const q of own) for (const [k, m] of Object.entries(q?.models ?? {})) models[k] ??= m const ids = (q) => Object.values(q.models).filter((m) => m.status !== "deprecated").map((m) => m.id) @@ -798,9 +863,9 @@ async function options(provider, key) { return opts } -async function load({ provider, account }) { +async function load({ provider, account, proxy }) { const key = accountKey(provider, account) - const o = await inScope(provider, key, () => options(provider, key)) + const o = await via.run(proxy ?? "", () => inScope(provider, key, () => options(provider, key))) return { baseURL: typeof o.baseURL === "string" ? o.baseURL : "", apiKey: typeof o.apiKey === "string" ? o.apiKey : "", @@ -950,6 +1015,9 @@ async function fetchAs(id, key, { provider, model, npm, url, method, headers, bo } send({ id, result: null }) } catch (e) { + // a fetch hook that threw on its sign-in (a refresh the vendor turned + // away) marks the account, as a built-in's refused refresh marked it + if (["expired", "kept", "renewed"].includes(e?.signIn) && key) send({ event: "signIn", provider, account: key, said: e.signIn }) send({ id, error: { message: String(e?.message ?? e) } }) } finally { inflight.delete(id) @@ -967,7 +1035,7 @@ const handlers = { await loadPlugins(p.plugins ?? []) return { plugins: loaded } }, - providers: () => providers(), + providers: (p) => providers(p ?? {}), prompt: (p) => ({ prompt: nextPrompt(p.provider, p.method, p.inputs ?? {}) }), validate: (p) => ({ error: validate(p.provider, p.method, p.key, p.value) }), authorize, diff --git a/internal/plugin/plugin_socks_test.go b/internal/plugin/plugin_socks_test.go new file mode 100644 index 000000000..0e8281532 --- /dev/null +++ b/internal/plugin/plugin_socks_test.go @@ -0,0 +1,131 @@ +package plugin + +import ( + "context" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/yetone/magpie/internal/netproxy" +) + +// socksTo is a SOCKS5 proxy that carries every connection to addr, +// whatever host it is asked for, counting them. +func socksTo(t *testing.T, addr string) (string, *atomic.Int32) { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ln.Close() }) + var n atomic.Int32 + go func() { + for { + c, err := ln.Accept() + if err != nil { + return + } + go func(c net.Conn) { + defer c.Close() + var h [2]byte + io.ReadFull(c, h[:]) + io.CopyN(io.Discard, c, int64(h[1])) + c.Write([]byte{5, 0}) + var r [4]byte + io.ReadFull(c, r[:]) + switch r[3] { + case 1: + io.CopyN(io.Discard, c, 4+2) + case 3: + var l [1]byte + io.ReadFull(c, l[:]) + io.CopyN(io.Discard, c, int64(l[0])+2) + } + up, err := net.Dial("tcp", addr) + if err != nil { + c.Write([]byte{5, 5, 0, 1, 0, 0, 0, 0, 0, 0}) + return + } + defer up.Close() + n.Add(1) + c.Write([]byte{5, 0, 0, 1, 127, 0, 0, 1, 0, 0}) + go io.Copy(up, c) + io.Copy(c, up) + }(c) + } + }() + return "socks5://" + ln.Addr().String(), &n +} + +func closedPort(t *testing.T) string { + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + a := ln.Addr().String() + ln.Close() + return a +} + +// A plugin's request goes through a SOCKS5 proxy, as a built-in's does, +// though Bun can't use one itself; and a proxy that is down, SOCKS or +// HTTP, is said as Go's transport says it ("proxyconnect …"), so the +// gateway asks the next account and rests none, as for a built-in's. +func TestPluginSOCKSProxy(t *testing.T) { + sandbox(t) + vendor := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, "vendor "+r.Host) + })) + defer vendor.Close() + socks, carried := socksTo(t, strings.TrimPrefix(vendor.URL, "http://")) + t.Setenv("FAKE_BASE", "http://vendor.invalid/v1") + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + abs, _ := filepath.Abs("testdata/fake/index.js") + if _, err := Add(ctx, abs); err != nil { + t.Fatal(err) + } + if _, err := Providers(ctx); err != nil { + t.Fatal(err) + } + if _, err := APIKey(ctx, "fakeco", 0, nil, "k1", NewAccount); err != nil { + t.Fatal(err) + } + fetch := func(proxy, url string) (int, string, error) { + res, err := Fetch(netproxy.With(ctx, proxy), FetchRequest{Provider: "fakeco", Model: "fake-1", NPM: "@ai-sdk/openai-compatible", + URL: url, Method: "POST", Body: []byte(`{}`)}) + if err != nil { + return 0, "", err + } + defer res.Body.Close() + b, err := io.ReadAll(res.Body) + return res.StatusCode, string(b), err + } + if _, b, err := fetch(socks, "http://vendor.invalid/v1/chat/completions"); err != nil || b != "vendor vendor.invalid" || carried.Load() != 1 { + t.Fatalf("through the SOCKS proxy: %q, %v; it carried %d", b, err, carried.Load()) + } + deadHTTP, deadSOCKS := "http://"+closedPort(t), "socks5://"+closedPort(t) + for _, x := range []struct{ proxy, url, says string }{ + {deadHTTP, "http://vendor.invalid/v1/chat/completions", "proxyconnect tcp: dial tcp 127.0.0.1:"}, + {deadHTTP, "https://vendor.invalid/v1/chat/completions", "proxyconnect tcp: dial tcp 127.0.0.1:"}, + } { + if _, b, err := fetch(x.proxy, x.url); err == nil || !strings.Contains(err.Error(), x.says) { + t.Fatalf("%s through %s, which is down: %q, %v; want it to say %q", x.url, x.proxy, b, err, x.says) + } + } + // through a SOCKS proxy that is down, the bridge answers as Go's + // transport fails: a 502 saying "socks connect", which the gateway + // takes for the proxy's failure + for _, url := range []string{"http://vendor.invalid/v1/chat/completions", "https://vendor.invalid/v1/chat/completions"} { + if code, b, err := fetch(deadSOCKS, url); err != nil || code != 502 || !strings.HasPrefix(b, "socks connect tcp 127.0.0.1:") { + t.Fatalf("%s through a SOCKS proxy that is down: %d %q, %v", url, code, b, err) + } + } +} diff --git a/internal/plugin/providers.go b/internal/plugin/providers.go index b50402124..7b285bb5b 100644 --- a/internal/plugin/providers.go +++ b/internal/plugin/providers.go @@ -130,7 +130,7 @@ func forgetProviders() { // need be, and keeps the answer for Cached. func Providers(ctx context.Context) ([]Provider, error) { var ps []Provider - if err := Call(ctx, "providers", nil, &ps); err != nil { + if err := Call(ctx, "providers", map[string]any{"proxies": listingProxies()}, &ps); err != nil { return nil, err } provMu.Lock() @@ -144,6 +144,34 @@ func Providers(ctx context.Context) ([]Provider, error) { return ps, nil } +// ProxyFor is the proxy choice (netproxy.With's) of the provider's +// account at key, or of the provider for key "": set by the providers +// magpie keeps, which know them. +var ProxyFor func(provider, key string) string + +// listingProxies are the proxies each provider's model list is asked +// through, by provider and account key ("" the provider's own): a +// built-in's list is fetched through the account's proxy, so a plugin's +// is too. +func listingProxies() map[string]map[string]string { + out := map[string]map[string]string{} + if ProxyFor == nil { + return out + } + var m map[string]json.RawMessage + if b, err := steady.ReadFile(AuthPath()); err == nil { + _ = json.Unmarshal(b, &m) + } + for k := range m { + id := ProviderOf(k) + if out[id] == nil { + out[id] = map[string]string{"": forHost(ProxyFor(id, ""))} + } + out[id][k] = forHost(ProxyFor(id, k)) + } + return out +} + // keepListed is ps with a list a plugin fell back to replaced by the one // it told last: a built-in whose fetch fails keeps the list it fetched // last too, so a vendor's hiccup never shrinks the models to the plugin's @@ -534,7 +562,7 @@ func LoaderOptions(ctx context.Context, provider, account string) (Options, erro if ok { return o, nil } - if err := Call(ctx, "load", map[string]any{"provider": provider, "account": account}, &o); err != nil { + if err := Call(ctx, "load", map[string]any{"provider": provider, "account": account, "proxy": proxyOf(ctx)}, &o); err != nil { return Options{}, err } optMu.Lock() diff --git a/internal/plugin/testdata/fake/index.js b/internal/plugin/testdata/fake/index.js index f144f997c..d635048cc 100644 --- a/internal/plugin/testdata/fake/index.js +++ b/internal/plugin/testdata/fake/index.js @@ -16,6 +16,8 @@ export const FakePlugin = async ({ client }) => ({ "fake-gemini": { name: "Fake Gemini", provider: { npm: "@ai-sdk/google" }, reasoning: true, modalities: { input: ["text"], output: ["text"] }, limit: { context: 3000, output: 300 } }, }, } + // $FAKE_RESPONSES: one model more, on OpenAI's Responses (Grok's) + if (process.env.FAKE_RESPONSES) cfg.provider[ID].models["fake-resp"] = { name: "Fake Responses", provider: { npm: "@ai-sdk/openai" }, limit: { context: 4000, output: 400 } } }, auth: { provider: ID, @@ -46,6 +48,8 @@ export const FakePlugin = async ({ client }) => ({ baseURL: process.env.FAKE_BASE, async fetch(url, init) { let a = await getAuth() + // "r-revoked": the vendor turned the refresh away, said as Zed's says it + if (a.type === "oauth" && a.refresh === "r-revoked") throw Object.assign(new Error("FakeCo turned the sign-in away"), { signIn: "expired" }) if (a.type === "oauth" && a.expires < Date.now()) { a = { ...a, access: "fresh-" + a.refresh, expires: Date.now() + 3600e3 } await client.auth.set({ path: { id: ID }, body: a }) diff --git a/internal/provider/login_usage.go b/internal/provider/login_usage.go index 661176951..99d2c481d 100644 --- a/internal/provider/login_usage.go +++ b/internal/provider/login_usage.go @@ -28,8 +28,11 @@ type loginUsageEntry struct { func LoginUsage(ctx context.Context, agent string) map[string]SubscriptionQuota { out := map[string]SubscriptionQuota{} var logins []Login + // a plugin's accounts are asked for by the provider's id or as + // plugin:, read once a minute whichever names them + known := agent if pp, ok := pluginOfAgent(agent); ok { - logins = pluginUsageLogins(pp) + logins, known = pluginUsageLogins(pp), pluginAgent(pp) } else if agent == "grok" { return grokLoginUsage(ctx) } else if logins, ok = builtinLogins(agent); !ok { @@ -39,7 +42,7 @@ func LoginUsage(ctx context.Context, agent string) map[string]SubscriptionQuota var mu sync.Mutex var wg sync.WaitGroup for _, l := range logins { - key := agent + "/" + strings.ToLower(l.User) + key := known + "/" + strings.ToLower(l.User) c.Lock() e, ok := c.m[key] c.Unlock() diff --git a/internal/provider/models.go b/internal/provider/models.go index 4d02d090f..a0a0d2dff 100644 --- a/internal/provider/models.go +++ b/internal/provider/models.go @@ -175,7 +175,8 @@ func FetchNew(timeout time.Duration) { if p.Account == nil || !p.Ready() { continue } - if _, ok := p.Fetched(); ok { + // a plugin's accounts were listed with the plugin's providers + if _, ok := p.Listed(); ok { continue } if t, ok := newFetches.m[p.ID]; ok && time.Since(t) < newFetchRetry { diff --git a/internal/provider/plugin_fetch_lapse_test.go b/internal/provider/plugin_fetch_lapse_test.go new file mode 100644 index 000000000..a4460a8d2 --- /dev/null +++ b/internal/provider/plugin_fetch_lapse_test.go @@ -0,0 +1,66 @@ +package provider + +import ( + "context" + "net/http" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/plugin" +) + +// A plugin's fetch hook that throws on its sign-in (the vendor turned the +// refresh away) marks the account lapsed, as a built-in's refused refresh +// marked it; the other account is left alone. +func TestPluginFetchSignInExpiredLapses(t *testing.T) { + bun, err := exec.LookPath("bun") + if err != nil { + t.Skip("no bun on PATH") + } + claudeHome(t) + t.Setenv("MAGPIE_BUN", bun) + t.Setenv("FAKE_BASE", "http://127.0.0.1:9/v1") + t.Cleanup(plugin.Settle) + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + abs, _ := filepath.Abs("../plugin/testdata/fake/index.js") + if _, err := plugin.Add(ctx, abs); err != nil { + t.Fatal(err) + } + keys := map[string]string{} + var rows []savedLogin + for user, refresh := range map[string]string{"revoked@fake": "r-revoked", "ok@fake": "r-ok"} { + k, err := plugin.Import(ctx, "fakeco", map[string]any{"type": "oauth", "refresh": refresh, "access": "a", "expires": 9e15, "accountId": user}) + if err != nil { + t.Fatal(err) + } + keys[user] = k + rows = append(rows, savedLogin{Agent: "plugin:fakeco", User: user, Home: k, On: true}) + } + saveLogins(t, rows...) + if _, err := plugin.Providers(ctx); err != nil { + t.Fatal(err) + } + pp := mustPlugin(t) + req, _ := http.NewRequestWithContext(ctx, "POST", pluginBase+pp.ID+"/v1/chat/completions", strings.NewReader(`{"model":"fake-claude","messages":[]}`)) + if _, err := pluginFetch(pp, keys["revoked@fake"], req); err == nil { + t.Fatal("the fetch went through") + } + deadline := time.Now().Add(10 * time.Second) + for { + lapsed := map[string]bool{} + for _, l := range pluginLogins(mustPlugin(t)) { + lapsed[l.User] = l.Lapsed != "" + } + if lapsed["revoked@fake"] && !lapsed["ok@fake"] { + return + } + if time.Now().After(deadline) { + t.Fatalf("lapsed: %v", lapsed) + } + time.Sleep(50 * time.Millisecond) + } +} diff --git a/internal/provider/plugin_fetchnew_test.go b/internal/provider/plugin_fetchnew_test.go new file mode 100644 index 000000000..e6b225aee --- /dev/null +++ b/internal/provider/plugin_fetchnew_test.go @@ -0,0 +1,108 @@ +package provider + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "sync/atomic" + "testing" + "time" + + "github.com/yetone/magpie/internal/plugin" +) + +// A plugin's account listed with the plugin's providers is not asked for +// its list again by FetchNew, as a built-in account fetched once isn't: +// the Providers page built its state through FetchNew, and every ten +// minutes asked every plugin's vendors for their lists again. +func TestFetchNewLeavesListedPlugins(t *testing.T) { + bun, err := exec.LookPath("bun") + if err != nil { + t.Skip("no bun on PATH") + } + claudeHome(t) + t.Setenv("MAGPIE_BUN", bun) + t.Cleanup(plugin.Settle) + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + abs, _ := filepath.Abs("../plugin/testdata/fake/index.js") + if _, err := plugin.Add(ctx, abs); err != nil { + t.Fatal(err) + } + if _, err := PluginAPIKey(ctx, "fakeco", 0, nil, "k-123456"); err != nil { + t.Fatal(err) + } + if _, err := plugin.Providers(ctx); err != nil { + t.Fatal(err) + } + if p, err := Find("fakeco"); err != nil || !p.IsPlugin() || !p.Ready() { + t.Fatalf("Find(fakeco) = %+v, %v", p, err) + } + was := newFetchRetry + newFetchRetry = 0 + t.Cleanup(func() { newFetchRetry = was }) + listed := filepath.Join(filepath.Dir(plugin.AuthPath()), "plugin-providers.json") + old := time.Now().Add(-time.Hour).Truncate(time.Second) + if err := os.Chtimes(listed, old, old); err != nil { + t.Fatal(err) + } + FetchNew(20 * time.Second) + if st, err := os.Stat(listed); err != nil || !st.ModTime().Equal(old) { + t.Fatalf("the plugins were asked for their lists again: %v %v", st.ModTime(), err) + } +} + +// A plugin's usage asked for by the provider's id (the Usage page) and as +// plugin: (routing) is read from the vendor once, as a built-in's, +// asked for by one name, is. +func TestPluginUsageReadOnceWhicheverName(t *testing.T) { + bun, err := exec.LookPath("bun") + if err != nil { + t.Skip("no bun on PATH") + } + claudeHome(t) + t.Setenv("MAGPIE_BUN", bun) + t.Cleanup(plugin.Settle) + var asked atomic.Int32 + vendor := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + asked.Add(1) + fmt.Fprint(w, "Fake Max") + })) + defer vendor.Close() + t.Setenv("FAKE_USAGE", vendor.URL) + clear := func() { + loginUsageCache.Lock() + loginUsageCache.m = nil + loginUsageCache.Unlock() + } + clear() + t.Cleanup(clear) + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + abs, _ := filepath.Abs("../plugin/testdata/fake/index.js") + if _, err := plugin.Add(ctx, abs); err != nil { + t.Fatal(err) + } + if _, err := plugin.Providers(ctx); err != nil { + t.Fatal(err) + } + st, err := StartPluginSignIn("fakeco", 1, map[string]string{"where": "work", "team": "a"}) + if err != nil { + t.Fatal(err) + } + if err := SubmitSignInCallback(st.ID, "good"); err != nil { + t.Fatal(err) + } + for _, agent := range []string{"fakeco", "plugin:fakeco"} { + if q := LoginUsage(ctx, agent)["a@fake"]; q.Plan != "Fake Max" { + t.Fatalf("%s: %+v", agent, q) + } + } + if n := asked.Load(); n != 1 { + t.Fatalf("the vendor was asked %d times", n) + } +} diff --git a/internal/provider/plugins.go b/internal/provider/plugins.go index 5f5540b7c..ef2249607 100644 --- a/internal/provider/plugins.go +++ b/internal/provider/plugins.go @@ -48,6 +48,15 @@ func PluginID(id string) string { // IsPlugin is whether the provider is a plugin's. func (p Provider) IsPlugin() bool { return p.Account != nil && p.Account.plugin != nil } +// PluginProvider is the id OpenCode knows the plugin's provider p is by +// (grok, kiro), whatever magpie names it; "" for one no plugin gives. +func (p Provider) PluginProvider() string { + if !p.IsPlugin() { + return "" + } + return p.Account.plugin.ID +} + // PluginOf is the plugin provider magpie's provider id is, when it is one. func PluginOf(id string) (plugin.Provider, bool) { for _, pp := range plugin.Cached() { @@ -192,6 +201,11 @@ func pluginProvider(pp plugin.Provider, l pluginLogin) Provider { name = pp.ID } a := &Account{Agent: "plugin", User: user, Plan: l.Plan, Stream: true, plugin: &pp, pluginKey: acct.Key} + if pp.ID == "grok" { + // Codex's namespaced tools go to Grok flat, as the built-in sends + // them (#404): the plugin's own rewrite would leave them out + a.body = grokBody + } a.models = func() []catalog.Model { if cur, ok := PluginOf(id); ok { return pluginAccountCatalog(cur, acct.Key) @@ -365,6 +379,20 @@ func notePluginSaid(pp plugin.Provider, account, said string, status int) { } func init() { + // a plugin's model list is asked through the proxy of the account it + // is the list of, as a built-in's is fetched through the account's + plugin.ProxyFor = func(id, key string) string { + mid := PluginID(id) + if key == "" { + return ProxyOf(mid) + } + for _, l := range readLogins() { + if l.Agent == "plugin:"+id && l.Home == key { + return ProxyOfLogin(mid, l.User) + } + } + return ProxyOf(mid) + } // a models hook saying its account's sign-in expired marks it, as a // built-in whose model list the vendor refused marked the account plugin.OnSignIn(func(id, account, said string) {