plugin host: a plugin's node:http2 connection goes through magpie's proxy like its fetch does (#1035, cataglyphis: Cursor opus-5-5 high ends after ~148s with "Cursor: 502 Bad Gateway" cursor_error) — the Cursor plugin runs agent.v1.AgentService/Run over node:http2, which Bun connects directly and ignores the proxy that host.js gives every fetch; the built-in sent the same request through s.client, so a user who needs magpie's proxy (setting, env or the system's) to reach Cursor had their sign-in, models and usage proxied but every Run went out directly. host.js now wraps http2.connect: for a URL proxyFor gives a proxy to (provider/account via, global, SOCKS bridged), it opens an HTTP CONNECT tunnel (Proxy-Authorization from the URL) and runs TLS with ALPN h2 over it; "direct", a caller's own createConnection and unproxied URLs keep Bun's connect; a tunnel that fails ends the session with "proxyconnect tcp: …". TestPluginHTTP2TakesTheProxy (an HTTP/2 vendor at an unresolvable host reached only through a CONNECT proxy; direct and a dead proxy fail with the reason) fails without the change ("h2: getaddrinfo ENOTFOUND h2vendor.invalid"; it carried 0) and passes -race -count=10. With the owner's Cursor account in a sandbox HOME and a logging proxy set, Claude Code's captured request on cursor/claude-opus-5-5 high: before, the proxy saw api2.cursor.sh only; after, it also sees agentn.global.api5.cursor.sh and the reply streams. The reporter's 502 wasn't reproduced here (direct runs answer in 4–20s). go test -race ./internal/plugin, the gateway/provider Plugin|Proxy|Cursor tests, gofmt and vet pass.

This commit is contained in:
yetone
2026-10-06 22:16:24 +08:00
parent a0cc4562e7
commit 51d2cf88ea
3 changed files with 236 additions and 0 deletions
+92
View File
@@ -27,9 +27,11 @@
import { AsyncLocalStorage } from "node:async_hooks"
import fs from "node:fs"
import http2 from "node:http2"
import net from "node:net"
import path from "node:path"
import readline from "node:readline"
import { Duplex } from "node:stream"
import tls from "node:tls"
import { pathToFileURL } from "node:url"
@@ -422,6 +424,96 @@ globalThis.fetch = Object.assign(function fetch(input, init) {
)
}, bunFetch)
// An HTTP/2 session a plugin opens itself goes through the proxy its
// fetches take, as a built-in's requests on Go's transport did. Cursor's
// plugin runs agent.v1.AgentService/Run on node:http2, which Bun connects
// directly, *_PROXY or not: where Cursor is reached only through magpie's
// proxy (the system's, or one set in magpie), its sign-in, models and
// usage came through and every chat went out without it (#1035).
const h2connect = http2.connect
http2.connect = function connect(authority, options, listener) {
if (typeof options === "function") [listener, options] = [options, undefined]
let u
try {
u = typeof authority === "string" ? new URL(authority) : authority instanceof URL ? authority : new URL(`${authority.protocol ?? "https:"}//${authority.host ?? authority.hostname}`)
} catch {
return h2connect.call(this, authority, options, listener)
}
const p = options?.createConnection ? "" : proxyFor(u.href)
if (!p) return h2connect.call(this, authority, options, listener)
const host = u.hostname.replace(/^\[|\]$/g, "")
const port = Number(u.port || (u.protocol === "http:" ? 80 : 443))
const raw = tunnel(p, host, port)
const createConnection = () =>
u.protocol === "http:" ? raw : tls.connect({ ...options, socket: raw, servername: options?.servername || (net.isIP(host) ? undefined : host), ALPNProtocols: ["h2"] })
const session = h2connect.call(this, authority, { ...options, createConnection }, listener)
// the tunnel's failure is the session's: Bun's TLS over a stream leaves
// the stream's errors unheard (one unheard ends the host), and says a
// tunnel that never came as "h2 is not supported"
raw.on("error", (e) => session.destroy(e))
return session
}
// tunnel is a connection to host:port through the HTTP proxy p (a SOCKS
// one is handed to the host as an HTTP bridge to it, netproxy.ForBun): its
// CONNECT is asked first, and what is written waits for the tunnel. A proxy
// that turns it away fails it in Go's words ("proxyconnect …").
function tunnel(p, host, port) {
const pu = new URL(p)
const ph = pu.hostname.replace(/^\[|\]$/g, "")
const pp = Number(pu.port || (pu.protocol === "https:" ? 443 : 80))
const target = `${host.includes(":") ? `[${host}]` : host}:${port}`
let ready = false
const queued = []
const sock = pu.protocol === "https:" ? tls.connect({ host: ph, port: pp, servername: net.isIP(ph) ? undefined : ph }) : net.connect({ host: ph, port: pp })
const conn = new Duplex({
read() {},
write(chunk, enc, cb) {
if (ready) sock.write(chunk, cb)
else queued.push([chunk, cb])
},
final(cb) {
sock.end()
cb()
},
destroy(err, cb) {
sock.destroy()
cb(err)
},
})
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")
})
let got = Buffer.alloc(0)
const head = (chunk) => {
got = Buffer.concat([got, chunk])
const end = got.indexOf("\r\n\r\n")
if (end < 0) {
if (got.length > 8192) conn.destroy(new Error(`proxyconnect tcp: ${ph}:${pp} answered CONNECT with no HTTP`))
return
}
sock.off("data", head)
const status = got.subarray(0, got.indexOf("\r\n")).toString("latin1").replace(/^HTTP\/\d(\.\d)?\s+/, "")
if (!/^2\d\d/.test(status)) {
const body = got.subarray(end + 4, end + 304).toString("utf8").trim()
return conn.destroy(new Error(`proxyconnect tcp: ${body ? `${status}: ${body}` : status}`))
}
ready = true
if (got.length > end + 4) conn.push(got.subarray(end + 4))
sock.on("data", (d) => conn.push(d))
for (const [c, cb] of queued.splice(0)) sock.write(c, cb)
}
sock.on("data", head)
sock.on("end", () => conn.push(null))
sock.on("error", (e) => conn.destroy(ready ? e : new Error(`proxyconnect tcp: dial tcp ${ph}:${pp}: ${e?.message || e?.code || e}`)))
return conn
}
// ---- auth.json ---------------------------------------------------------------
function readAuth() {
+121
View File
@@ -0,0 +1,121 @@
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"
)
// connectTo is an HTTP proxy that tunnels every CONNECT to addr, whatever
// host it is asked for, counting them and keeping the last host asked.
func connectTo(t *testing.T, addr string) (string, *atomic.Int32, *atomic.Value) {
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
var asked atomic.Value
go func() {
for {
c, err := ln.Accept()
if err != nil {
return
}
go func(c net.Conn) {
defer c.Close()
var head []byte
b := make([]byte, 1)
for !strings.HasSuffix(string(head), "\r\n\r\n") {
if _, err := c.Read(b); err != nil {
return
}
head = append(head, b[0])
}
f := strings.Fields(string(head))
if len(f) < 2 || f[0] != "CONNECT" {
fmt.Fprint(c, "HTTP/1.1 405 Method Not Allowed\r\n\r\n")
return
}
asked.Store(f[1])
up, err := net.Dial("tcp", addr)
if err != nil {
fmt.Fprint(c, "HTTP/1.1 502 Bad Gateway\r\n\r\n")
return
}
defer up.Close()
n.Add(1)
fmt.Fprint(c, "HTTP/1.1 200 Connection established\r\n\r\n")
go io.Copy(up, c)
io.Copy(c, up)
}(c)
}
}()
return "http://" + ln.Addr().String(), &n, &asked
}
// #1035: Cursor's plugin runs its chats on node:http2, which Bun connects
// directly whatever the proxy: where Cursor is reached only through
// magpie's proxy, the plugin's fetches (sign-in, models, usage) came
// through it and its chats didn't. A session a plugin opens goes through
// the proxy its fetches take, as the built-in's requests did; one for a
// provider set to "direct" goes through none.
func TestPluginHTTP2TakesTheProxy(t *testing.T) {
sandbox(t)
vendor := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "vendor %s %s", r.Proto, r.URL.Path)
}))
vendor.EnableHTTP2 = true
vendor.StartTLS()
defer vendor.Close()
proxy, carried, asked := connectTo(t, strings.TrimPrefix(vendor.URL, "https://"))
// a host that resolves nowhere: reached only through the proxy
t.Setenv("FAKE_H2", "https://h2vendor.invalid:8443")
t.Setenv("FAKE_BASE", "https://h2vendor.invalid:8443/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 string) (int, string) {
res, err := Fetch(netproxy.With(ctx, proxy), FetchRequest{Provider: "fakeco", Model: "fake-1", NPM: "@ai-sdk/openai-compatible",
URL: "https://h2vendor.invalid:8443/v1/chat/completions", Method: "POST", Body: []byte(`{}`)})
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
b, _ := io.ReadAll(res.Body)
return res.StatusCode, string(b)
}
if code, b := fetch(proxy); code != 200 || b != "vendor HTTP/2.0 /v1/chat/completions" || carried.Load() != 1 {
t.Fatalf("an HTTP/2 session through the proxy: %d %q; it carried %d", code, b, carried.Load())
}
if got := asked.Load(); got != "h2vendor.invalid:8443" {
t.Fatalf("the proxy was asked for %v, want h2vendor.invalid:8443", got)
}
if code, b := fetch("direct"); code != 502 || carried.Load() != 1 {
t.Fatalf("a provider set to direct: %d %q; the proxy carried %d, want it untouched", code, b, carried.Load())
}
dead := "http://" + closedPort(t)
if code, b := fetch(dead); code != 502 || !strings.Contains(b, "proxyconnect tcp: dial tcp 127.0.0.1:") {
t.Fatalf("through a proxy that is down: %d %q, want it said as Go's transport says it", code, b)
}
}
+23
View File
@@ -10,6 +10,26 @@ function fakeWho(team) {
return uid ? { accountId: name + "@fake", uid } : { accountId: name + "@fake" }
}
// h2 POSTs path on an HTTP/2 session to origin, a test server's
// certificate taken, and answers with what it said; one that fails is a
// 502 saying why.
async function h2(origin, path) {
const http2 = (await import("node:http2")).default
return new Promise((resolve) => {
const s = http2.connect(origin, { rejectUnauthorized: false })
const fail = (e) => (s.destroy(), resolve(new Response("h2: " + (e?.message || e?.code || e), { status: 502 })))
s.on("error", fail)
const req = s.request({ ":method": "POST", ":path": path })
req.on("error", fail)
let status = 0
const body = []
req.on("response", (h) => (status = h[":status"]))
req.on("data", (c) => body.push(c))
req.on("end", () => (s.close(), resolve(new Response(Buffer.concat(body), { status }))))
req.end()
})
}
export const FakePlugin = async ({ client }) => ({
config: async (cfg) => {
cfg.provider = cfg.provider ?? {}
@@ -76,6 +96,9 @@ export const FakePlugin = async ({ client }) => ({
h.set("authorization", "Bearer " + (a.type === "oauth" ? a.access : a.key))
h.set("x-models", Object.keys(provider.models).sort().join(","))
h.set("x-body-type", typeof init.body)
// $FAKE_H2: the request goes on node:http2 to that origin, as
// Cursor's plugin runs its chats
if (process.env.FAKE_H2) return h2(process.env.FAKE_H2, new URL(url).pathname)
return fetch(url, { ...init, headers: h })
},
}),