jipairamen on X (v0.1.4212): a Chrome translation extension pointed at magpie's gateway address got, for every request, 403 "magpie's Codex relay serves Codex on this computer only". Cause: that answer is not the gateway's. When magpie quits with Codex running, it leaves `magpie codex-relay` at the gateway's port for the Codex threads still open (codexrelay,4534561f6). The relay judged who asks before what is asked: any request with an Origin was refused with the line above, so an extension's /v1/chat/completions never reached the "magpie isn't running ... Open magpie" answer (relayGone) that every other non-Codex call gets, and the doc already promised. The message read as a permission rule, not as "magpie is closed". Now a path other than /backend-api/codex/* gets relayGone (503) from any caller, Origin or not; it passes nothing on, so who asks doesn't matter. On Codex's own path a page, an extension, a null frame or a rebound name is still refused (403), with a message that says magpie isn't running and to open it. No origin rule changed: the relay still forwards only loopback, Origin-less Codex requests, and the running gateway's corsGuard is untouched (an unlisted chrome-extension:// origin was already served keyless there by design; a listed one needs a key). Siblings: the relay's LeavePath answers only the next magpie (token); its "forbidden" there is not seen by users. No other handler holds the gateway's port while magpie is quit. Tests: TestCodexRelayTellsExtensionToOpenMagpie (chrome-extension://, moz-extension://, https page, null; four paths; with and without a key: 503 relayGone, nothing sent to OpenAI) and TestCodexRelayOnlyThisComputer (now with an extension origin and the "Open magpie" text). With the old codex_relay.go both FAIL: --- FAIL: TestCodexRelayOnlyThisComputer --- FAIL: TestCodexRelayTellsExtensionToOpenMagpie and pass with the change. Real use: built magpie (nogui) on mote, ran `magpie codex-relay --addr 127.0.0.1:34871 --pids <sleep>` under a sandbox HOME and curled it as the extension: POST /v1/chat/completions with Origin chrome-extension://... -> 503 "magpie isn't running: ... Open magpie for everything else."; POST /backend-api/codex/responses with that Origin -> 403 with the new text. Run on mote at a9c98d8de (baseb754cb095): gofmt -l (nothing), go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./..., go build, GOOS=linux go build -tags nogui, GOOS=windows go build: all rc 0; go test -tags nogui -timeout 45m ./...: 101 packages ok, no FAIL (internal/gateway 1081s). After rebasing ontodcb0f3dcd(gateway, provider and app.js changed upstream), at e27f946cf: go vet ./..., GOOS=linux and GOOS=windows go vet, go build rc 0; go test -tags nogui -timeout 45m ./internal/gateway ./internal/provider ./internal/gui ./internal/codexrelay: all ok (gateway 1086s, provider 335s, gui 296s). Rebased ontof1c9014cd(agent/wsl, gateway fallback, masking, provider; none of this change's files) before the push; at abaa78247 only go build, go vet of gateway and codexrelay, and their TestCodexRelay*, TestLeave*, TestEnds* were run: ok. The full suite was not rerun there. Not tried: the user's own extension in Chrome; magpie's Settings page doesn't change.
148 lines
6.1 KiB
Go
148 lines
6.1 KiB
Go
package gateway
|
||
|
||
import (
|
||
"bytes"
|
||
"net/http"
|
||
"strings"
|
||
|
||
"github.com/yetone/magpie/internal/masking"
|
||
"github.com/yetone/magpie/internal/provider"
|
||
"github.com/yetone/magpie/internal/settings"
|
||
)
|
||
|
||
// CodexRelay is what serves Codex's own ChatGPT sign-in at the gateway's
|
||
// address once magpie has quit, for the Codex threads still open then
|
||
// (codexrelay). magpie takes the failover base URL out of Codex's config
|
||
// at quit (agent.EndCodexFailover), but a thread open in the Codex app,
|
||
// and the app-server holding it, keep the URL they started with: every
|
||
// turn after went to a port nobody listened on, and a system proxy in
|
||
// between answered 503 "Unknown error" until magpie was opened again
|
||
// (idkatbro on X). The relay passes those turns on to the ChatGPT backend
|
||
// as the gateway does a turn on one of Codex's own models, signed by the
|
||
// caller's own Authorization; it adds no credential of its own. What only
|
||
// the running magpie could do is refused with a reason Codex shows: a
|
||
// magpie model, a turn on one of magpie's accounts, masking (Settings ›
|
||
// Privacy) that would have masked it. Its answer at "/" never says it is
|
||
// magpie (ServedBy), so the next magpie starting asks it to leave.
|
||
func CodexRelay() http.Handler {
|
||
// the caller's sign-in goes to the ChatGPT backend's origin only
|
||
client := &http.Client{Transport: upstreamTransport(), CheckRedirect: provider.KeepsCredentials}
|
||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
// anything but Codex's own path is told magpie isn't running
|
||
// before who asks is judged: a browser extension or a page calling
|
||
// the gateway's address while magpie is quit was told the relay
|
||
// "serves Codex on this computer only", which said nothing of
|
||
// opening magpie (jipairamen on X, a translation extension). The
|
||
// answer passes nothing on, so it is the same for every caller.
|
||
if !strings.HasPrefix(r.URL.Path, CodexPath+"/") {
|
||
relayError(w, http.StatusServiceUnavailable, relayGone)
|
||
return
|
||
}
|
||
if !loopbackHost(r.Host) || r.Header.Get("Origin") != "" {
|
||
// as the gateway's corsGuard: a rebound or foreign page, an
|
||
// extension, or a frame's null, never reaches the sign-in
|
||
// Codex sends
|
||
relayError(w, http.StatusForbidden, relayNoPages)
|
||
return
|
||
}
|
||
if strings.EqualFold(r.Header.Get("Upgrade"), "websocket") {
|
||
http.Error(w, "magpie speaks HTTP", http.StatusUpgradeRequired)
|
||
return
|
||
}
|
||
rest := strings.TrimPrefix(r.URL.Path, CodexPath)
|
||
body, status, err := readBoundedRequestBody(w, r, requestLimits{body: codexBodyLimit()})
|
||
if err != nil {
|
||
relayError(w, status, err.Error())
|
||
return
|
||
}
|
||
if r.Method == http.MethodPost && (rest == "/responses" || rest == "/responses/compact") {
|
||
if msg := relayRefuses(r, body); msg != "" {
|
||
// 400, not 503: Codex retries a 5xx five times over for
|
||
// a refusal that a retry doesn't change (seen with codex
|
||
// 0.162.1), and shows a 4xx's message at once
|
||
relayError(w, http.StatusBadRequest, msg)
|
||
return
|
||
}
|
||
// as codexBackend sends a turn of Codex's own to its sign-in
|
||
body = plainItemIDs(boundCallIDs(callItemIDs(body)))
|
||
body, _ = codexInput(body, false)
|
||
}
|
||
body = withoutClaudeSeals(body)
|
||
base := provider.CodexBase
|
||
if apiKey(r.Header) && rest != "/models" {
|
||
base = codexAPIBase
|
||
}
|
||
if r.Method == http.MethodPost && rest == "/responses" && base == provider.CodexBase {
|
||
body = provider.DeclareSearch(body, strings.EqualFold(r.Header.Get("X-OpenAI-Internal-Codex-Responses-Lite"), "true"))
|
||
}
|
||
u := base + rest
|
||
if r.URL.RawQuery != "" {
|
||
u += "?" + r.URL.RawQuery
|
||
}
|
||
req, err := http.NewRequestWithContext(provider.ViaSignedIn(r.Context(), "codex"), r.Method, u, bytes.NewReader(body))
|
||
if err != nil {
|
||
relayError(w, http.StatusBadGateway, err.Error())
|
||
return
|
||
}
|
||
copyHeaders(req.Header, r.Header)
|
||
req.Header.Del("Accept-Encoding")
|
||
provider.CodexCompressed(req, body)
|
||
res, err := client.Do(req)
|
||
if err != nil {
|
||
relayError(w, http.StatusBadGateway, "OpenAI can't be reached ("+err.Error()+"). magpie isn't running, so this thread goes to OpenAI on Codex's own sign-in.")
|
||
return
|
||
}
|
||
defer res.Body.Close()
|
||
for k, vs := range res.Header {
|
||
if !hopHeader(k) {
|
||
w.Header()[k] = vs
|
||
}
|
||
}
|
||
w.WriteHeader(res.StatusCode)
|
||
flush := http.NewResponseController(w)
|
||
buf := make([]byte, 32<<10)
|
||
for {
|
||
n, err := res.Body.Read(buf)
|
||
if n > 0 {
|
||
if _, werr := w.Write(buf[:n]); werr != nil {
|
||
return
|
||
}
|
||
flush.Flush()
|
||
}
|
||
if err != nil {
|
||
return
|
||
}
|
||
}
|
||
})
|
||
}
|
||
|
||
// relayGone is the relay's answer to anything but Codex's own turns.
|
||
const relayGone = "magpie isn't running: only Codex threads open when it quit are passed on, on Codex's own ChatGPT sign-in. Open magpie for everything else."
|
||
|
||
// relayNoPages is its answer to a web page's or an extension's call on
|
||
// Codex's path, or one at a name other than this computer's.
|
||
const relayNoPages = "magpie isn't running: only Codex threads on this computer that were open when it quit are passed on, never a web page's or a browser extension's call. Open magpie for everything else."
|
||
|
||
// relayRefuses says why a turn can't be passed on with magpie gone, ""
|
||
// when it can: what only the running gateway serves, and a turn masking
|
||
// would have masked, which never goes unmasked.
|
||
func relayRefuses(r *http.Request, body []byte) string {
|
||
model := modelOf(body)
|
||
if strings.Contains(model, "/") {
|
||
return model + " is one of magpie's models, and magpie isn't running. Open magpie to go on with this thread, or pick one of Codex's own models."
|
||
}
|
||
if r.Header.Get(AccountHeader) != "" {
|
||
return AccountHeader + " names one of magpie's Codex accounts, and magpie isn't running. Open magpie to go on with this thread."
|
||
}
|
||
if masking.Wanted(settings.Load()) {
|
||
return "magpie isn't running, and Settings › Privacy masks what is sent: this turn is not sent unmasked. Open magpie to go on with this thread."
|
||
}
|
||
return ""
|
||
}
|
||
|
||
// relayError answers as the ChatGPT backend words an error, so Codex
|
||
// shows the message (an empty body reads "Unknown error").
|
||
func relayError(w http.ResponseWriter, status int, msg string) {
|
||
writeError(w, provider.Responses, status, msg)
|
||
}
|