curtinp118 on Discord runs magpie on a VPS and opens its web UI from home. ChatGPT's browser sign-in comes back to localhost:1455, which is the viewer's own computer. The page there won't load, and the box's main line said "The account shows up here as soon as you're done", so the sign-in looked broken. The fix until now was to copy the dead page's address back by hand. ChatGPT now also signs in by device code, as `codex login --device-auth` does (codex-rs login/src/device_code_auth.rs). This is startCodexDeviceSignIn, with StartSignInWith site "device": - magpie asks auth.openai.com/api/accounts/deviceauth/usercode for a code with Codex's client id and headers; - the box shows the code and https://auth.openai.com/codex/device; - magpie polls deviceauth/token, where 403/404 means not entered yet, for up to 15 minutes; - it then trades the authorization code at the token endpoint with the returned verifier and the /deviceauth/callback redirect. Nothing listens on this computer. The window starts this way when magpie web is opened from a host other than localhost or loopback (remotePage in app.js). Either way, the box has a link to the other way: "Sign in with a code instead" or "Sign in in the browser instead". A device code that ChatGPT turns away (404) fails, and that box links to the browser's way. Strings are in zh, zh-TW, ja and de. providers-accounts.md describes the flow. This went over TestCoreScriptBudget. It now fits with no raise (1,533,700 of 1,533,802, on main's 1,533,789). The two way-switch buttons share one helper (codexWay), and eight comments on the sign-in code are cut down: openSignInPage, signingKept, startPluginSignIn, the sign-in proxy, signInProxyChoices, Copilot's GHE.com, dropSigningIn and renderStepPlan. Run on mote (the pushed head is rebased onae060550b): - go test ./internal/provider: the new TestCodexSignInByDeviceCode, TestCodexDeviceSignInCanceled and TestCodexDeviceSignInOff, against a fake auth server that answers with the bytes auth.openai.com gave on 11-03; - go test -tags nogui ./internal/provider ./internal/backup (before the comment trim, which touched app.js only): ok; ./internal/gui ./internal/cli after it: ok; - GUI at this head: signin-codex-device.test.cjs (new; Chromium and WebKit, en and zh, 420px wide), signin-paste-codex, signin-callback, signin-port-blocked, signin-paste-plugin, signin-paste-import, the sign-in proxy files and i18n-keys, 40 files: 591 pass, 0 fail; - the whole GUI suite one commit earlier (base c86fa2a34; the rebase onto6a6e4fefaonly brought in internal/sessions): two runs, each cut short when mote rebooted or by the owner's call not to wait. They got through 1075 and 1395 cases, with 0 not ok; - go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./..., the Linux nogui and Windows builds, and gofmt -l (basec86fa2a34). Rebased on4cd01c964at last: go test -tags nogui ./internal/gui ok and signin-codex-device, signin-paste-codex, signin-callback and i18n-keys 21 of 21. Before that, rebased onae060550bwith the comments cut: go test -tags nogui ./internal/gui ok, ./internal/provider ok, and 40 sign-in, proxy, i18n-keys and desktop-tiers GUI files: 594 pass, 1 fail. The red was signin-proxy's chromium ja 380 proxy test. That file alone then passed 3 runs, 120 of 120. It is #1814, open since 10-12 for this test under load, and noted there. The step that failed wasn't kept. The full go test ./... was not run, by the owner's rule. On Linux (WSL magpie-desktop, sandbox HOME), magpie web listened on 0.0.0.0:3561 and was reached at the WSL IP. POST /api/signin {"agent":"codex","site":"device"} got a real code from auth.openai.com with url https://auth.openai.com/codex/device. The sign-in stayed waiting across real polls for 12s, nothing listened on 1455, and cancel ended it. Broken by hand: - Taking the device branch out of begin() turned TestCodexSignInByDeviceCode and TestCodexDeviceSignInOff red. - Taking the remotePage default out of startSignIn turned 8 of the 12 signin-codex-device cases red. Not tried: - Entering the code with a real ChatGPT account, so a real token trade through the device callback hasn't been seen. - Business/Enterprise workspaces that turn device codes off. Also not changed: WorkBuddy's plugin sign-in already finishes by itself from a remote browser (server-side poll; checked on the same WSL setup). A backup still carries no sign-ins. Reported by curtinp118 on Discord.
175 lines
5.2 KiB
Go
175 lines
5.2 KiB
Go
package provider
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// A ChatGPT sign-in by device code, as `codex login --device-auth` does it
|
|
// (codex-rs login/src/device_code_auth.rs): magpie asks for a code, the
|
|
// user enters it on ChatGPT's device page in any browser, and magpie asks
|
|
// until the page is done. Nothing comes back to localhost:1455, so magpie
|
|
// on a server or in Docker, its window in a browser elsewhere, signs in
|
|
// with no address to copy back (curtinp118 on Discord).
|
|
|
|
// codexIssuer is where Codex's device sign-in is; a var so tests can point
|
|
// it elsewhere.
|
|
var codexIssuer = "https://auth.openai.com"
|
|
|
|
// CodexDeviceSite is the "site" of a ChatGPT sign-in by device code
|
|
// (StartSignInWith): the window asks for it when it is opened from
|
|
// another computer.
|
|
const CodexDeviceSite = "device"
|
|
|
|
// codexDeviceWait is how long Codex keeps a device code: 15 minutes.
|
|
var codexDeviceWait = 15 * time.Minute
|
|
|
|
// codexDevicePollMisses is how many failed polls in a row end the sign-in.
|
|
var codexDevicePollMisses = 5
|
|
|
|
// errCodexDeviceOff is the vendor turning device codes away for Codex's client.
|
|
var errCodexDeviceOff = errors.New("ChatGPT doesn't take a device code for this sign-in now; use the browser sign-in")
|
|
|
|
// codexDevicePost posts body as JSON with Codex's own headers. It answers
|
|
// the status and the reply.
|
|
func codexDevicePost(ctx context.Context, u string, body any) (int, []byte, error) {
|
|
b, err := json.Marshal(body)
|
|
if err != nil {
|
|
return 0, nil, err
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, bytes.NewReader(b))
|
|
if err != nil {
|
|
return 0, nil, err
|
|
}
|
|
codexClientHeaders(req.Header, codexVersion())
|
|
req.Header.Set("Content-Type", "application/json")
|
|
resp, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
return 0, nil, err
|
|
}
|
|
defer resp.Body.Close()
|
|
out, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
|
return resp.StatusCode, out, nil
|
|
}
|
|
|
|
// startCodexDeviceSignIn asks ChatGPT for a device code and waits, in the
|
|
// background, for the user to enter it.
|
|
func startCodexDeviceSignIn(s *signInFlow) error {
|
|
base := strings.TrimSuffix(codexIssuer, "/")
|
|
ctx, cancel := context.WithCancel(s.via(context.Background()))
|
|
code, b, err := codexDevicePost(ctx, base+"/api/accounts/deviceauth/usercode", map[string]string{"client_id": codexClientID})
|
|
if err != nil {
|
|
cancel()
|
|
return fmt.Errorf("couldn't reach ChatGPT for a sign-in code: %w", err)
|
|
}
|
|
if code == http.StatusNotFound {
|
|
cancel()
|
|
return errCodexDeviceOff
|
|
}
|
|
if code != http.StatusOK {
|
|
cancel()
|
|
return fmt.Errorf("ChatGPT gave no sign-in code (%d): %s", code, APIError(b, http.StatusText(code)))
|
|
}
|
|
var uc struct {
|
|
ID string `json:"device_auth_id"`
|
|
Code string `json:"user_code"`
|
|
Code2 string `json:"usercode"`
|
|
Interval any `json:"interval"` // a string of seconds, "5"
|
|
}
|
|
if err := json.Unmarshal(b, &uc); err != nil {
|
|
cancel()
|
|
return fmt.Errorf("ChatGPT's sign-in code didn't read: %w", err)
|
|
}
|
|
uc.Code = firstNonEmpty(uc.Code, uc.Code2)
|
|
if uc.ID == "" || uc.Code == "" {
|
|
cancel()
|
|
return errors.New("ChatGPT gave no sign-in code")
|
|
}
|
|
secs := 0
|
|
switch v := uc.Interval.(type) {
|
|
case string:
|
|
secs, _ = strconv.Atoi(strings.TrimSpace(v))
|
|
case float64:
|
|
secs = int(v)
|
|
}
|
|
s.mu.Lock()
|
|
s.st.URL, s.st.Code = base+"/codex/device", uc.Code
|
|
s.stop = cancel
|
|
s.mu.Unlock()
|
|
interval := devicePoll(secs)
|
|
go func() {
|
|
fail := func(msg string) {
|
|
log.Printf("codex device sign-in failed: %s", msg)
|
|
s.finish(SignInState{State: "failed", Error: msg})
|
|
}
|
|
deadline := time.Now().Add(codexDeviceWait)
|
|
misses := 0
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-time.After(interval):
|
|
}
|
|
if time.Now().After(deadline) {
|
|
fail("the code expired; start again")
|
|
return
|
|
}
|
|
code, b, err := codexDevicePost(ctx, base+"/api/accounts/deviceauth/token",
|
|
map[string]string{"device_auth_id": uc.ID, "user_code": uc.Code})
|
|
switch {
|
|
case ctx.Err() != nil:
|
|
return
|
|
case err != nil:
|
|
// a hiccup: ask again, unless it keeps failing
|
|
if misses++; misses >= codexDevicePollMisses {
|
|
fail("couldn't ask ChatGPT whether the code was entered: " + err.Error())
|
|
return
|
|
}
|
|
continue
|
|
case code == http.StatusForbidden || code == http.StatusNotFound:
|
|
// not entered yet
|
|
misses = 0
|
|
continue
|
|
case code != http.StatusOK:
|
|
fail(fmt.Sprintf("ChatGPT refused the sign-in (%d): %s", code, APIError(b, http.StatusText(code))))
|
|
return
|
|
}
|
|
var ok struct {
|
|
Code string `json:"authorization_code"`
|
|
Verifier string `json:"code_verifier"`
|
|
}
|
|
if json.Unmarshal(b, &ok) != nil || ok.Code == "" || ok.Verifier == "" {
|
|
fail("ChatGPT finished the sign-in but sent no code")
|
|
return
|
|
}
|
|
ectx, ecancel := context.WithTimeout(ctx, 30*time.Second)
|
|
l, err := codexExchange(ectx, ok.Code, ok.Verifier, base+"/deviceauth/callback")
|
|
if err == nil {
|
|
var using bool
|
|
err = keepLogin(ectx, func() (err error) { using, err = addLogin(l); return err })
|
|
if err == nil {
|
|
ecancel()
|
|
s.finish(SignInState{State: "done", User: l.User, Plan: l.Plan, Using: using})
|
|
return
|
|
}
|
|
}
|
|
ecancel()
|
|
if ctx.Err() != nil {
|
|
return
|
|
}
|
|
fail(err.Error())
|
|
return
|
|
}
|
|
}()
|
|
return nil
|
|
}
|