diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 2f9ae231f..dd8b746fb 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -48,7 +48,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | A revoked sign-in | A 401 whose words say the sign-in itself is gone (`SignInRevoked`: ChatGPT's `token_revoked`, `invalid_grant`, `refresh_token_reused`; never `token_expired`, a 403, a 5xx or a network error) marks the account for the credential it was sent with (`NoteRevokedSignIn`, #1793). A saved ChatGPT account is refreshed first, as Codex does on a 401, and a refresh that goes through marks nothing. The mark is a hash of the header, never the credential, kept in `logins.json` as `Refused: "revoked:"` with the account's `Lapsed`, and read back after a restart. While the account has that credential, the gateway doesn't send its requests (`RevokedSignIn`); its row says Sign-in required with Sign in again. A ChatGPT account's usage read marks it too (`codexSignInRead` in `loginQuota`, charliepu on Discord: an account OpenAI signed out showed only a blank allowance): `/wham/usage` answering 401 with those words is refreshed once (`codexWindowsRenewing`), and the account is marked for the token turned away when the refreshed read is turned away the same (`codexSignInGone`), or, for the one Codex is signed in to, when its refresh is refused (its row used to say nothing, its allowance line "run codex login"; a saved one's refused refresh is `savedRefreshFailed`'s). Any other 401, a 403, a 5xx or a network error is unknown and marks nothing. Each failed read says why on the account's row (`codexUsageWords`, `codex_usage_words.go`; hmy on Discord: five ChatGPT accounts each said only "Allowance unavailable", the error being Go's bare status text or decode error, which the GUI read none of): Cloudflare's challenge page in place of an answer (a proxy or VPN address, usually), `HTTP ` with the backend's own `detail` or `error` words, chatgpt.com not reached, or a reply magpie doesn't read; `quotaError` in app.js turns each into a line of the card's language, the raw error in the row's tooltip. The words keep what was matched before: the status text that `passing` (`quota_last.go`) reads to keep the last reading over a 429 or a 5xx, and the answer itself under `Unwrap` for `codexExpired`. An error with no words of its own says "Allowance unavailable — hover for why". A ChatGPT API account (`chatgpt-api`, `chatgpt_api.go`) has no usage read: OpenAI's API tells none, only chatgpt.com/settings/usage does. `loginQuota` says so (`siwcNoUsage`, with that page as `SeeAt`) and asks nothing; it used to read the account as a Codex one, so an active one read Codex's own sign-in ("Codex is signed out; run codex login", or another account's allowance under its name) and the card said only that it couldn't be read (danzi002 on Discord). Guarded by `TestChatGPTAPIUsageSaysWhere`. Sign in again runs magpie's own sign-in for the account (`addLogin`), which replaces its tokens, in Codex's `auth.json` too when Codex is signed in to it. Signed in anew (`upsertLogin` with another credential, `addSideLogin`), refreshed, served a request (`ServedSignIn`), or its usage read going through, it is clear. Claude (`claude_auth.go`), Copilot (`copilot_lapsed.go`: GitHub's 401/403 on the token exchange, the CLI's stand-in or the usage read, cleared when a token is served) and plugins keep their own marks. | [`signin_revoked.go`](../../internal/provider/signin_revoked.go), [`copilot_lapsed.go`](../../internal/provider/copilot_lapsed.go) | | A token called expired | A ChatGPT 401 whose words say the access token has expired and ask for a refresh (`SignInExpired`: `token_expired`, "Provided authentication token is expired. Please try refreshing it."; never `refresh_token_expired`, which is revoked) while the token's own `exp` is still ahead (willz on Discord, #2973: two saved Team accounts) is mended by one refresh. `codexToken` refreshes only as `exp` nears, so before this the token went out as it was until the user signed in again, and the card said only Unauthorized. The usage read (`codexWindowsRenewing`: `loginQuota`, `codexSubscriptionUsage`, and the reset spenders through `codexUserWindows`) refreshes once and reads once more, never again: a refresh refused says to sign in again (a saved account is marked lapsed, `savedRefreshFailed`; Codex's own is marked revoked, see A revoked sign-in, through `loginQuota`, while `codexSubscriptionUsage`'s card still says `codex login`), and a token refreshed for it and still called expired says so too (`errCodexStillExpired`) and is marked revoked the same. The gateway renews the account a request went with (`NoteExpiredSignIn` from `noteSignIn`, 20s at most); the request itself fails over as before, and the next goes with the new token. Each refresh is keyed on the token turned away (`codexTokenRenewing`, `renewSavedLoginFrom`), under the lock signing waits on: a sign-in holding another token by then, renewed by Codex or another reply, is used as it is, so two replies for one token spend one rotation. Codex's own sign-in is read from its store afresh for it and written back through `codexStore.write` (temp and rename), a saved one's through `writeLogins`. Not tried against the real backend. | [`codex_expired.go`](../../internal/provider/codex_expired.go), [`account.go`](../../internal/provider/account.go), [`logins_on.go`](../../internal/provider/logins_on.go) | | Saved accounts | `logins.json` remembers every Codex and Claude Code account seen signed in. A switch moves the credentials into the agent's own store and saves the ones it replaces. A saved account that is on (`SetLoginOn`) stands behind the agent's own. Its tokens stay in `logins.json`. While Claude Code is signed out, a saved Claude account stands in for its own (`claudeStandIn`); with every saved account's sign-in gone, Claude Code is still listed, on the one seen last, signed out (`claudeListed`), its accounts each saying to sign in again, so it never leaves the Providers list (LeeHom on Discord). Claude Code's own account while still `Held` is never listed that way, since the sign-in it may have left on disk would be served. An account whose every login in use has lapsed is `Provider.SignedOut`: `magpie providers` and the TUI say " is signed out", as the app's row does. | [`logins.go`](../../internal/provider/logins.go), [`logins_on.go`](../../internal/provider/logins_on.go), [`claude_dirs.go`](../../internal/provider/claude_dirs.go) | -| Sign-in in magpie | `StartSignIn` runs the vendor's own browser OAuth with its client and takes the tokens at a callback on this machine. A browser that can't reach that callback (magpie on a server or in Docker) ends on a page that won't load; its address, pasted (`SubmitSignInCallback`), goes through the same callback handler (`pastedCallback`). ChatGPT's sign-in comes back only to port 1455; when that port can't be opened, the sign-in still starts and waits for the pasted address alone, and says why in `CallbackBlocked` with the port in `CallbackPort`: `reserved` for Windows' WSAEACCES on a port in a range it excludes for Hyper-V, WSL or Docker, `busy` for anything else, such as another program holding it (`callbackBlocked`, #1782). A plugin's browser sign-in (`auto`) whose page names a port on this machine to come back to takes its pasted address too: magpie opens it there on 127.0.0.1, for the plugin's own listener (`pluginCallback`, `loopbackPorts`); Command Code's page posts its key from script, so it offers the API key way instead. A Claude account is signed in by Claude Code itself. Signing in brings back an account removed from magpie (`ShowAccount`). A sign-in started in magpie (`StartSignIn`, `StartPluginSignIn`) reads as done (`SignInStatus`, `WaitSignIn`) only after `finish` has run `ShowAccount` for its account, so the window, which opens the account as soon as it sees done, finds it listed. If providers.json can't be written then, the account stays hidden and the sign-in still ends done. Signing in to a plugin's provider from the command line (`pluginLogin`, with a key or the browser) brings it back too. It also takes off the mark a sign-in its vendor turned away left on the account (`Lapsed`) and shows again the agent's own account removed in magpie (`clearPluginLapse`). The window's plugin sign-in does the same with the browser (`pluginDone`, then `finish`) or with a key (`PluginAPIKey`); a key and the command line share these steps in `PluginSignedIn`. A sign-in leaves through the proxy the account's own requests will use (#1663): `ProxyOfLogin` (the account's, else the subscription's, else the global one) for the account being signed in again, the subscription's for a new one. Every request of the flow goes through `signInFlow.via`, Claude Code's own login gets it as *_PROXY (`netproxy.EnvWith`), and a plugin's sign-in runs its fetch under that proxy (`via` in `host.js`; `plugins_cli.go` for the command line). The window's sign-in box shows it as a "Proxy: …" link (`signInProxyLink`, the app menu, no userinfo shown) with Global, Direct, the subscription's and each account's proxy, or a typed one; picking one starts the sign-in again through it (`SignInOptions.Proxy`), and when it ends the pick is kept as the account's (`keepSignInProxy`: the subscription's own when it is its only account, else the account's entry). Global isn't offered while the subscription has a proxy and other accounts, since nothing could keep it. The browser's own leg goes through the browser's network, not magpie's. The window or `magpie web` opens the sign-in page in the default browser (`openSignIn` in `internal/gui/api.go`; `openSignInPage` in `app.js` for a web tab), and the waiting box always shows the link with Copy link. With Settings › Privacy › Sign-in pages off (`SignInLinkOnly`, max2020 on Discord, who signs in from a separate fingerprint browser), magpie opens nothing: the reply carries `linkOnly`, the box says the page wasn't opened and offers Open, and `magpie accounts add` and a plugin's browser login from the command line (`pluginLogin`) print the link without opening it. A callback on this machine still comes back from another browser on it, and the pasted address covers one that can't reach it. A plugin whose own CLI opens the page (`opened`, Grok Build's device sign-in on macOS and Windows) still opens it. Signing out leaves through the same exit: a ChatGPT account's refresh token is revoked through its own proxy, read before the account is forgotten (`forgetSIWCLogin`), and Devin's CLI, asked who is signed in or for its models, runs with the account's proxy (`devinCommand`, `devinProxy`). | [`signin.go`](../../internal/provider/signin.go), [`claude_signin.go`](../../internal/provider/claude_signin.go), [`pluginsignin.go`](../../internal/provider/pluginsignin.go), [`pluginsignin_paste.go`](../../internal/provider/pluginsignin_paste.go), [`proxy.go`](../../internal/provider/proxy.go), [`plugins_cli.go`](../../internal/cli/plugins_cli.go) | +| Sign-in in magpie | `StartSignIn` runs the vendor's own browser OAuth with its client and takes the tokens at a callback on this machine. A browser that can't reach that callback (magpie on a server or in Docker) ends on a page that won't load; its address, pasted (`SubmitSignInCallback`), goes through the same callback handler (`pastedCallback`). ChatGPT's sign-in comes back only to port 1455; when that port can't be opened, the sign-in still starts and waits for the pasted address alone, and says why in `CallbackBlocked` with the port in `CallbackPort`: `reserved` for Windows' WSAEACCES on a port in a range it excludes for Hyper-V, WSL or Docker, `busy` for anything else, such as another program holding it (`callbackBlocked`, #1782). ChatGPT also signs in by device code, as `codex login --device-auth` does (`CodexDeviceSite`, `startCodexDeviceSignIn` in `codex_device_signin.go`): magpie asks `auth.openai.com/api/accounts/deviceauth/usercode` for a code, the box shows it with ChatGPT's device page, and magpie polls `deviceauth/token` (403 or 404 is not entered yet, up to 15 minutes), then trades the code at the token endpoint with the verifier it got and the `/deviceauth/callback` redirect. Nothing listens on this machine. The window starts this way when `magpie web` is opened from another computer (`remotePage` in `app.js`: a host other than localhost or loopback; curtinp118 on Discord, magpie on a VPS), and the box offers the other way as a link either way; a device code ChatGPT turns away (404) fails with a link to the browser's way. A plugin's browser sign-in (`auto`) whose page names a port on this machine to come back to takes its pasted address too: magpie opens it there on 127.0.0.1, for the plugin's own listener (`pluginCallback`, `loopbackPorts`); Command Code's page posts its key from script, so it offers the API key way instead. A Claude account is signed in by Claude Code itself. Signing in brings back an account removed from magpie (`ShowAccount`). A sign-in started in magpie (`StartSignIn`, `StartPluginSignIn`) reads as done (`SignInStatus`, `WaitSignIn`) only after `finish` has run `ShowAccount` for its account, so the window, which opens the account as soon as it sees done, finds it listed. If providers.json can't be written then, the account stays hidden and the sign-in still ends done. Signing in to a plugin's provider from the command line (`pluginLogin`, with a key or the browser) brings it back too. It also takes off the mark a sign-in its vendor turned away left on the account (`Lapsed`) and shows again the agent's own account removed in magpie (`clearPluginLapse`). The window's plugin sign-in does the same with the browser (`pluginDone`, then `finish`) or with a key (`PluginAPIKey`); a key and the command line share these steps in `PluginSignedIn`. A sign-in leaves through the proxy the account's own requests will use (#1663): `ProxyOfLogin` (the account's, else the subscription's, else the global one) for the account being signed in again, the subscription's for a new one. Every request of the flow goes through `signInFlow.via`, Claude Code's own login gets it as *_PROXY (`netproxy.EnvWith`), and a plugin's sign-in runs its fetch under that proxy (`via` in `host.js`; `plugins_cli.go` for the command line). The window's sign-in box shows it as a "Proxy: …" link (`signInProxyLink`, the app menu, no userinfo shown) with Global, Direct, the subscription's and each account's proxy, or a typed one; picking one starts the sign-in again through it (`SignInOptions.Proxy`), and when it ends the pick is kept as the account's (`keepSignInProxy`: the subscription's own when it is its only account, else the account's entry). Global isn't offered while the subscription has a proxy and other accounts, since nothing could keep it. The browser's own leg goes through the browser's network, not magpie's. The window or `magpie web` opens the sign-in page in the default browser (`openSignIn` in `internal/gui/api.go`; `openSignInPage` in `app.js` for a web tab), and the waiting box always shows the link with Copy link. With Settings › Privacy › Sign-in pages off (`SignInLinkOnly`, max2020 on Discord, who signs in from a separate fingerprint browser), magpie opens nothing: the reply carries `linkOnly`, the box says the page wasn't opened and offers Open, and `magpie accounts add` and a plugin's browser login from the command line (`pluginLogin`) print the link without opening it. A callback on this machine still comes back from another browser on it, and the pasted address covers one that can't reach it. A plugin whose own CLI opens the page (`opened`, Grok Build's device sign-in on macOS and Windows) still opens it. Signing out leaves through the same exit: a ChatGPT account's refresh token is revoked through its own proxy, read before the account is forgotten (`forgetSIWCLogin`), and Devin's CLI, asked who is signed in or for its models, runs with the account's proxy (`devinCommand`, `devinProxy`). | [`signin.go`](../../internal/provider/signin.go), [`codex_device_signin.go`](../../internal/provider/codex_device_signin.go), [`claude_signin.go`](../../internal/provider/claude_signin.go), [`pluginsignin.go`](../../internal/provider/pluginsignin.go), [`pluginsignin_paste.go`](../../internal/provider/pluginsignin_paste.go), [`proxy.go`](../../internal/provider/proxy.go), [`plugins_cli.go`](../../internal/cli/plugins_cli.go) | | Import from files | `ImportLogins` (ChatGPT, Claude), `ImportGoogleAccounts` (Antigravity) and `ImportFactoryKeys` take other tools' files, from the window (`signin/import`) or `magpie accounts import` (#1453). ChatGPT reads Codex's `auth.json`, CLIProxyAPI's and Cockpit Tools' files, Sub2API's export (`sub2apiEntry`) and codexbar's `~/.codexbar/config.json` (`codexbarEntries`: the `openai_oauth` provider's accounts and `openAI.remoteConnectionAccounts`, the workspace from `openAIAccountId`). Each ChatGPT and Google sign-in is refreshed before it is added, so the tool the file came from is signed out of it; both surfaces say so first, and the command imports nothing without `--yes` or a yes. Claude reads CLIProxyAPI's files and Sub2API's export, whose Claude account says its email as Anthropic does, `email_address`, in `credentials` or `extra`, and keeps its `scope`, `account_uuid` and `org_uuid` as Claude Code's scopes, `accountUuid` and `organizationUuid` (#1975); a file with no email is refused, as Claude Code's own `.credentials.json` is. Claude's are kept as the file has them. Claude also reads claude-swap's `cswap export` (format 1, claude-swap 0.29; `cswapEntry`, #4532): each account's `credentials.claudeAiOauth` and `config.oauthAccount`, with its organization name, and its alias becomes the account's name when that account has none and no other account is called or signed in as it (`importNames`). An encrypted export, another format, a Codex entry and an API-key entry are refused with what to do; `testdata/cswap_0.29.0_export.json` is claude-swap's own output. A refresh token magpie holds already is `exists`, never refreshed; accounts are matched by email and workspace, or for Claude organization (`sameLogin`). A Claude sign-in for an account magpie has, Claude Code's own or a saved one that can be used, with another refresh token is taken only when the file's `expiresAt` is later than the one magpie has (the account's own config directory counted, `claudeNewerKept`); otherwise it is `exists` with why, and nothing is written: an export made before Claude Code's last refresh holds a spent refresh token, and written over Claude Code's own it signed the account out (#4532, `TestImportCswapKeepsNewerSignIn`). A file that gives no `expiresAt` never replaces one. A sign-in itself imported and never run since is kept with `expiresAt` 1, so any dated file is taken over it. An entry with an access token and no refresh token is refused (`accessOnly`). One file of several that holds no account is a failed row with its place (`ImportedAccount.File`), never skipped. The files are only read. | [`login_import.go`](../../internal/provider/login_import.go), [`google_import.go`](../../internal/provider/google_import.go), [`factory_key.go`](../../internal/provider/factory_key.go), [`accounts_cli.go`](../../internal/cli/accounts_cli.go) | | Claude setup-token | A Claude account can be added from the long-lived token `claude setup-token` prints (sfss5362 on X), which Claude Code takes in `CLAUDE_CODE_OAUTH_TOKEN` (the window's *Use a setup-token instead…* and *Add an account by setup-token…*, `POST /api/signin/claude-token`). `AddClaudeSetupToken` keeps it in `logins.json` as `{"setupToken":…}`, named `Claude setup-token <6 hex of its hash>` (it tells no email), on beside the others; the same token again is the same account. Such a token has the inference scope only: Claude Code's `auth status` says `oauth_token` with no email or plan, and its `/usage` prints the API cost view, so `/usage` is never run for it and its allowance is unknown (`errClaudeSetupToken`, kept by `passing` as saying nothing about the account) until a reply's rate-limit event tells it. Its config directory (`claudeTokenDir`) holds no `.credentials.json`, which Claude Code could fall back to on a refused token. Claude Code itself is never signed in to it: `addLogin`, `switchLogin`, `putClaudeLogin`, `SetKeepLoginAs`, `NextLogin` and `signInToFirst` pass it over, and the window shows Remove and *magpie only* in place of Use and Make first. Not tried with a real token. | [`claude_setup_token.go`](../../internal/provider/claude_setup_token.go), [`claude_subscription.go`](../../internal/gateway/claude_subscription.go) (`inClaudeDir`), [`providers.go`](../../internal/gui/providers.go) | | Switch accounts only | magpie as a Claude Code (or Codex) account switcher alone, with nothing connected (the owner on X; growaiskills, Rennix7t). In the window, the Agents row of a Claude Code or Codex not connected says the account it is signed in to (`switchEntry` in app.js, from the providers list `prefetchProviders` reads at start, so `/api/state` reads no keychain for it), also when magpie has no models to connect (`switchable`, before the `empty` line). Its menu, headed *Switch accounts only*, lists the agent's saved accounts: a pick goes through `POST /api/login/switch` (`SwitchLogin`), or `provider/keeplogin` with `keepLoginAs` when the agent is kept signed in to an account of the user's choosing, as the account rows do; the button says *Switched* for five seconds and the status line says new sessions use the account, one already open keeps its own until started again. *Only switch {agent}'s sign-in* (`SwitchOnly` above, `provider/switchonly`) is a ticked item there (Codex: with more than one usable account, as under Providers), and the row then says *Not connected · switching accounts only*. *Manage accounts…*, and a pick whose sign-in lapsed, open Providers › the agent. A Codex failing over (#1385) has it in place of the old *ChatGPT accounts* button. In the tray panel (whose Quick panel shortcut opens it from any app, shuizhuyu on X) it is the *account* line of the agent's opened row (`.ag-who`), drawn from the list kept from the last read (`panelAccounts`, `GET /api/providers?last=1`, no keychain read; a fresh read only when none is kept), so opening the panel reads no sign-in. The menu waits for one fresh `/api/providers` read and opens on what it says; *Manage accounts…* and a lapsed pick open the window's Providers (`window/main?view=providers`). The provider and login actions keep their answer as the last list (`keepProviders`), so a switch made anywhere is in the panel's next line at once (`TestKeptProvidersFollowActions`, `panel-switch-accounts.test.cjs`). Not on a WSL twin's row, not on a connected agent's. | [`app.js`](../../internal/gui/assets/app.js), [`logins.go`](../../internal/provider/logins.go) | diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 9c583d1bb..cd5204ebb 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -31,6 +31,8 @@ if (mode === "panel" && !document.body.classList.contains("linux")) $("header.to // `magpie web`: the page in a browser tab, with no window of the app's // around it — it opens links itself, and what is the desktop's is left out const web = !!window.bootPrefs?.web; +// magpie web seen from another computer: localhost is the viewer's (curtinp118) +const remotePage = web && !/^(localhost|127(\.\d+){3}|\[::1\]|::1)$/i.test(location.hostname); // layout.js applies the mode and platform before the header can paint. // Gateway mode (gatewaymode.go): magpie web on a server that is only the // gateway for other computers' agents leaves out this computer's agents' @@ -12278,6 +12280,7 @@ async function startSignIn(agent, risky, site, o = {}) { renderProviders(); return; } + if (agent === "codex" && !site && remotePage) site = "device"; // one on more than one site says which first if (subOf(agent)?.sites && !site) { signing = { agent, state: "site", forUser: o.user, picked: o.proxy }; @@ -12308,12 +12311,8 @@ async function startSignIn(agent, risky, site, o = {}) { } } -// openSignInPage opens a sign-in's page for the window. In a browser tab -// (magpie web: a server, Docker) that's a new tab the viewer's browser may -// block, as it was asked for after the sign-in started, not on the click: -// then it says so, and the page opens from Open again, a click -// (treeMan on Discord). A tab opened without noopener is the one way to -// learn it was blocked, so the page it opens is cut from this one at once. +// openSignInPage: in magpie web a new tab the browser may block, then Open +// again (treeMan); no noopener, the one way to learn it, cut at once. const openBlocked = "\u0000blocked"; function openSignInPage(url) { if (!web) return api("open", { url }); @@ -12347,9 +12346,7 @@ async function followSignIn(id) { } } -// signingKept: what a sign-in under way keeps across its updates, for Try -// again and a proxy picked for it — its site and way, the account signed -// in to again, the proxy picked +// signingKept: a sign-in's site, way, account and proxy across updates function signingKept() { return { site: signing.site, method: signing.method, inputs: signing.inputs, forUser: signing.forUser, picked: signing.picked, askProxy: signing.askProxy, customProxy: signing.customProxy, openError: signing.openError, linkOnly: signing.linkOnly }; } @@ -12384,9 +12381,8 @@ async function signedIn(st) { setTimeout(() => { justAdded = ""; }, 2000); } -// startPluginSignIn: a plugin's provider signed in to as OpenCode's -// `auth login` does — the way to sign in, the questions that way asks, -// then the browser (and the code its page shows, pasted back) or a key. +// startPluginSignIn: as OpenCode's `auth login`: way, questions, then the +// browser (its code pasted back) or a key. async function startPluginSignIn(sub, method, inputs = {}, o = {}) { const ms = sub.plugin.methods || []; if (!ms.length) { @@ -12535,9 +12531,7 @@ function renderPluginAsk(sub) { return box; } -// renderStepPlan: a StepFun provider's platform sign-in, which the user -// makes in their own browser and brings here with magpie's bookmarklet, -// kept for the provider id alone: two on one site can be two accounts +// renderStepPlan: StepFun's platform sign-in by bookmarklet, per provider id function renderStepPlan(sp, id) { const box = el("div", "stepplan"); if (sp.signedIn) { @@ -12600,11 +12594,8 @@ function cancelSignIn() { renderProviders(); } -// A sign-in goes through the proxy its account's requests will go through, -// so the vendor sees the account come from one place (#1663, -// demystify0137): the sheet says which, and another can be picked, which -// starts it again through that one and is kept as the account's proxy. -// proxyShown is a proxy's address without the name and password in it. +// A sign-in goes through its account's proxy (#1663); another can be +// picked. proxyShown hides the name and password. function proxyShown(u) { return String(u || "").replace(/^([a-z][a-z0-9+.-]*:\/\/)[^@/]*@/i, "$1"); } @@ -12621,11 +12612,8 @@ function signInThrough(sub, v) { startPluginSignIn(sub, f?.method, f?.inputs || {}, o); } -// signInProxyChoices: the proxies a sign-in can go through — the global -// one, none, the subscription's, the ones its other accounts go through, -// or one typed in. The global one is left out while the subscription has -// a proxy of its own and other accounts: an account can't be kept on the -// global proxy then. +// signInProxyChoices: global, none, the subscription's, its accounts', or +// typed; no global while the subscription has its own and accounts. function signInProxyChoices(sub) { const p = providers?.providers?.find((x) => x.account?.agent === sub.agent); const own = (p?.proxy || "").trim(); @@ -12696,9 +12684,7 @@ function signInProxyForm(sub) { return form; } -// A Copilot account on GitHub Enterprise Cloud with data residency signs in -// at its enterprise's .ghe.com, not github.com (#723): the device -// code's panel offers that, and the host is asked in place of the code. +// A Copilot account with data residency signs in at .ghe.com (#723). const GHE_HOST = /^(https?:\/\/)?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.ghe\.com\/?$/i; // copilotHostSwitch: the link from a Copilot sign-in to the other place it @@ -12726,10 +12712,8 @@ async function signAsk(flow) { } const startClaudeToken = () => signAsk({ agent: "claude", state: "token", token: "" }); -// dropSigningIn: the editor of provider id closing (Cancel, Save, Remove) -// leaves no sign-in of its account waiting behind it, to come back with the -// editor (#526: 无论我点击底部的移除、取消、保存都没办法); an import being -// read is left to finish. +// dropSigningIn: an editor closing leaves no sign-in waiting (#526); an +// import being read finishes. function dropSigningIn(id) { const p = typeof id === "string" && providers?.providers?.find((x) => x.id === id); if (!p?.account || !signing || signing.agent !== p.account.agent || signing.state === "importing") return; @@ -12739,6 +12723,14 @@ function dropSigningIn(id) { // renderSigning: where a sign-in stands, in place of the button that // started it — waiting on the browser, or what went wrong. +// ChatGPT's other way in: the browser's, or a code on its device page (codex_device_signin.go) +function codexWay(sub, device, o) { + const b = el("button", "link codex-way", device ? t("Sign in in the browser instead") : t("Sign in with a code instead")); + b.dataset.way = device ? "browser" : "device"; + if (!device) b.title = t("For magpie on a server or in Docker: enter a code on ChatGPT's page, with no address to copy back"); + b.onclick = () => startSignIn(sub.agent, true, b.dataset.way, o); + return b; +} function renderSigning(sub) { const box = el("div", "signing" + (signing.state === "failed" ? " failed" : "")); const tt = el("span", "tt"); @@ -12816,6 +12808,7 @@ function renderSigning(sub) { const acts = el("span", "acts"); const ghe = copilotHostSwitch(sub); if (ghe) acts.append(ghe); + if (sub.agent === "codex" && !sub.plugin && signing.site === "device") acts.append(codexWay(sub, true, o)); acts.append(signInProxyLink(sub)); tt.append(acts); if (signing.askProxy) tt.append(signInProxyForm(sub)); @@ -12839,6 +12832,7 @@ function renderSigning(sub) { : signing.openError ? t("magpie couldn't open your browser: {error}. Open the sign-in link below in a browser yourself.", { error: signing.openError }) : sub.plugin ? (signing.instructions || (signing.pasteCode ? t("magpie opened the sign-in page. Paste the code it shows below.") : t("magpie opened the sign-in page. The account shows up here as soon as you're done."))) : signing.pasteCode ? t("magpie opened the sign-in page. Paste the code it shows below.") + : signing.code && sub.agent === "codex" ? t("magpie opened ChatGPT's device page. Enter this code there; the account shows up here as soon as you're done.") : signing.code && sub.agent === "factory" ? t("magpie opened Factory's sign-in page. Check it shows this code and confirm it; the account shows up here as soon as you're done.") : signing.code ? t("magpie opened GitHub's device page. Enter this code there; the account shows up here as soon as you're done.") : t("magpie opened the sign-in page. The account shows up here as soon as you're done."))); if (signing.code) { @@ -12968,6 +12962,8 @@ function renderSigning(sub) { }; acts.append(other); } + if (sub.agent === "codex" && !sub.plugin && signing.state === "waiting") + (tt.querySelector(".acts") || tt.appendChild(el("span", "acts"))).append(codexWay(sub, signing.site === "device", { user: signing.forUser, proxy: signing.picked })); if (sub.importable) { // an account another tool is signed in to comes in from its file const imp = el("button", "link", importSay(sub.agent).instead || t("Import from a file instead…")); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index c2ba7db3d..ffb820a79 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1966,6 +1966,10 @@ const I18N = { "Finish sign-in": "完成登录", "1 provider to bring over": "有 1 个供应商可导入", "{n} providers to bring over": "有 {n} 个供应商可导入", + "magpie opened ChatGPT's device page. Enter this code there; the account shows up here as soon as you're done.": "已打开 ChatGPT 设备登录页,请在其中输入下方验证码;完成后账号会出现在这里。", + "Sign in with a code instead": "改用验证码登录", + "Sign in in the browser instead": "改在浏览器中登录", + "For magpie on a server or in Docker: enter a code on ChatGPT's page, with no address to copy back": "适合 magpie 运行在服务器或 Docker 中时:在 ChatGPT 页面输入验证码,无需复制回调地址", "magpie opened GitHub's device page. Enter this code there; the account shows up here as soon as you're done.": "已打开 GitHub 设备登录页,请在其中输入下方验证码;完成后账号会出现在这里。", "Account on GHE.com?": "账号在 GHE.com 上?", "Sign in on github.com instead": "改为在 github.com 登录", @@ -6401,6 +6405,10 @@ const I18N = { "Finish sign-in": "完成登入", "1 provider to bring over": "有 1 個供應商可匯入", "{n} providers to bring over": "有 {n} 個供應商可匯入", + "magpie opened ChatGPT's device page. Enter this code there; the account shows up here as soon as you're done.": "已開啟 ChatGPT 裝置登入頁,請在其中輸入下方驗證碼;完成後帳號會出現在這裡。", + "Sign in with a code instead": "改用驗證碼登入", + "Sign in in the browser instead": "改在瀏覽器中登入", + "For magpie on a server or in Docker: enter a code on ChatGPT's page, with no address to copy back": "適合 magpie 執行在伺服器或 Docker 中時:在 ChatGPT 頁面輸入驗證碼,無需複製回呼位址", "magpie opened GitHub's device page. Enter this code there; the account shows up here as soon as you're done.": "已開啟 GitHub 裝置登入頁,請在其中輸入下方驗證碼;完成後帳號會出現在這裡。", "Account on GHE.com?": "帳號在 GHE.com 上?", "Sign in on github.com instead": "改為在 github.com 登入", @@ -10812,6 +10820,10 @@ const I18N = { "Finish sign-in": "サインインを完了", "1 provider to bring over": "取り込めるプロバイダが1件あります", "{n} providers to bring over": "取り込めるプロバイダが {n} 件あります", + "magpie opened ChatGPT's device page. Enter this code there; the account shows up here as soon as you're done.": "magpie が ChatGPT のデバイスページを開きました。そこでこのコードを入力してください。完了するとアカウントがここに表示されます。", + "Sign in with a code instead": "代わりにコードでサインイン", + "Sign in in the browser instead": "代わりにブラウザでサインイン", + "For magpie on a server or in Docker: enter a code on ChatGPT's page, with no address to copy back": "magpie がサーバーや Docker で動いている場合:ChatGPT のページでコードを入力するだけで、アドレスをコピーして戻す必要はありません", "magpie opened GitHub's device page. Enter this code there; the account shows up here as soon as you're done.": "magpie が GitHub のデバイスページを開きました。そこでこのコードを入力してください。完了するとすぐにアカウントがここに表示されます。", "Account on GHE.com?": "GHE.com のアカウントですか?", "Sign in on github.com instead": "代わりに github.com でサインイン", @@ -15254,6 +15266,10 @@ const I18N = { "Finish sign-in": "Anmeldung abschließen", "1 provider to bring over": "1 Anbieter zum Übernehmen", "{n} providers to bring over": "{n} Anbieter zum Übernehmen", + "magpie opened ChatGPT's device page. Enter this code there; the account shows up here as soon as you're done.": "magpie hat die Geräteseite von ChatGPT geöffnet. Gib dort diesen Code ein; das Konto erscheint hier, sobald du fertig bist.", + "Sign in with a code instead": "Stattdessen mit einem Code anmelden", + "Sign in in the browser instead": "Stattdessen im Browser anmelden", + "For magpie on a server or in Docker: enter a code on ChatGPT's page, with no address to copy back": "Für magpie auf einem Server oder in Docker: einen Code auf der Seite von ChatGPT eingeben, ohne eine Adresse zurückzukopieren", "magpie opened GitHub's device page. Enter this code there; the account shows up here as soon as you're done.": "magpie hat die Geräteseite von GitHub geöffnet. Geben Sie dort diesen Code ein; das Konto erscheint hier, sobald Sie fertig sind.", "Account on GHE.com?": "Konto auf GHE.com?", "Sign in on github.com instead": "Stattdessen auf github.com anmelden", diff --git a/internal/gui/tests/signin-codex-device.test.cjs b/internal/gui/tests/signin-codex-device.test.cjs new file mode 100644 index 000000000..6f7081bb9 --- /dev/null +++ b/internal/gui/tests/signin-codex-device.test.cjs @@ -0,0 +1,132 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A ChatGPT sign-in by device code (curtinp118 on Discord: magpie on a VPS, +// its web UI in a browser at home; ChatGPT's browser sign-in comes back to +// localhost:1455, the home machine). Opened from another computer, the +// sign-in asks for a device code: the box shows the code and ChatGPT's +// device page, and the account comes in when the code is entered, with no +// address to copy back. "Sign in in the browser instead" goes back to the +// browser's way. Opened on this computer, the browser's way is first and a +// code is a link away. English and Chinese, Chromium and WebKit, narrow; +// no backend, the API is faked here. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const LINK = "https://auth.openai.com/oauth/authorize?client_id=app&redirect_uri=http%3A%2F%2Flocalhost%3A1455%2Fauth%2Fcallback&state=st1"; +const DEVICE = "https://auth.openai.com/codex/device"; + +function server(lang, started) { + let signing = null, polls = 0; + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/providers") return json({ providers: [{ id: "openai", name: "OpenAI", icon: "openai", preset: "openai", models: [], agents: [], key: { set: true, masked: "sk-…ab12" } }], presets: [], excluded: [], gateway: { running: true, window: true } }); + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/groups") return json({ groups: [], pools: [] }); + if (url.pathname === "/api/gateway/trace") return json({ routes: [] }); + if (url.pathname === "/api/signin") { + const body = route.request().postDataJSON(); + started.push(body); + signing = body.site === "device" + ? { id: "dv" + started.length, agent: "codex", state: "waiting", url: DEVICE, code: "WG0E-J29UL" } + : { id: "cx" + started.length, agent: "codex", state: "waiting", url: LINK, pasteCallback: true }; + polls = 0; + return json(signing); + } + if (signing && url.pathname === "/api/signin/" + signing.id) { + // a device code entered after a few polls; the browser's way waits + if (signing.code && ++polls > 3) signing = { ...signing, state: "done", user: "dc@example.com", using: true }; + return json(signing); + } + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + +const W = { + en: { + say: "magpie opened ChatGPT's device page. Enter this code there; the account shows up here as soon as you're done.", + browser: "Sign in in the browser instead", code: "Sign in with a code instead", field: "Callback URL", + }, + zh: { + say: "已打开 ChatGPT 设备登录页,请在其中输入下方验证码;完成后账号会出现在这里。", + browser: "改在浏览器中登录", code: "改用验证码登录", field: "回调 URL", + }, +}; + +async function open(t, engine, lang, host, name) { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const page = await (await browser.newContext({ viewport: { width: 420, height: 800 }, reducedMotion: "reduce" })).newPage(); + t.after(async () => { + if (process.env.ARTIFACT_DIR) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${name}.png`) }); + } + await browser.close(); + }); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = [], started = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", server(lang, started)); + // the vendor's pages, opened in a new window, get an empty page + await page.context().route((url) => url.hostname !== host, (route) => route.fulfill({ contentType: "text/html", body: "" })); + await page.goto(`http://${host}/?view=providers`); + await page.locator("#addProvider").click(); + const sheet = page.locator("#addSheet"); + await sheet.locator('.tile[data-pick="ChatGPT"]').click(); + return { page, box: sheet.locator(".signing"), errors, started }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh"]) { + const w = W[lang]; + test(`${engine} ${lang}: opened from another computer, ChatGPT signs in by a device code`, async (t) => { + const { page, box, errors, started } = await open(t, engine, lang, "vps.example", "signin-codex-device"); + await box.getByText(w.say).waitFor(); + assert.deepEqual(started, [{ agent: "codex", site: "device" }]); + assert(await box.getByText("WG0E-J29UL", { exact: true }).isVisible(), "the code is shown"); + assert(await box.getByText(DEVICE, { exact: true }).isVisible(), "the device page is shown"); + assert.equal(await box.getByRole("textbox", { name: w.field }).count(), 0, "no address to paste back"); + const back = box.getByRole("button", { name: w.browser }); + assert(await back.isVisible()); + // the code and its copy button inside the box at 420px + const fit = await box.evaluate((b) => { + const r = b.getBoundingClientRect(), c = b.querySelector(".devcode").getBoundingClientRect(); + return c.left >= r.left - 0.5 && c.right <= r.right + 0.5; + }); + assert(fit, "the code fits its box"); + await page.waitForFunction(() => document.querySelector("#status").textContent.includes("dc@example.com") && !document.querySelector("#addSheet .devcode")); + assert.equal(started.length, 1, "started once"); + assert.deepEqual(errors, []); + }); + + test(`${engine} ${lang}: the browser's way, from the device code's box`, async (t) => { + const { box, errors, started } = await open(t, engine, lang, "vps.example", "signin-codex-device-back"); + await box.getByText(w.say).waitFor(); + await box.getByRole("button", { name: w.browser }).click(); + await box.getByRole("textbox", { name: w.field }).waitFor(); + assert.deepEqual(started.map((s) => s.site), ["device", "browser"]); + assert(await box.getByRole("button", { name: w.code }).isVisible(), "a code is a link away again"); + assert.deepEqual(errors, []); + }); + + test(`${engine} ${lang}: on this computer, the browser's way first and a code a link away`, async (t) => { + const { box, errors, started } = await open(t, engine, lang, "localhost", "signin-codex-local"); + await box.getByRole("textbox", { name: w.field }).waitFor(); + assert.deepEqual(started, [{ agent: "codex" }]); + await box.getByRole("button", { name: w.code }).click(); + await box.getByText(w.say).waitFor(); + assert.deepEqual(started.map((s) => s.site), [undefined, "device"]); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/provider/codex_device_signin.go b/internal/provider/codex_device_signin.go new file mode 100644 index 000000000..d703439f7 --- /dev/null +++ b/internal/provider/codex_device_signin.go @@ -0,0 +1,174 @@ +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 +} diff --git a/internal/provider/codex_device_signin_test.go b/internal/provider/codex_device_signin_test.go new file mode 100644 index 000000000..2e9754fdf --- /dev/null +++ b/internal/provider/codex_device_signin_test.go @@ -0,0 +1,159 @@ +package provider + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" +) + +// fakeCodexDevice answers Codex's device sign-in as auth.openai.com does: +// a code, 403 until it is entered (polls before entered), then the +// authorization code, traded at the token endpoint with the verifier and +// the device callback. +func fakeCodexDevice(t *testing.T, pending int32) (trades *atomic.Int32) { + t.Helper() + trades = new(atomic.Int32) + var polls atomic.Int32 + fake := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("originator") != "codex_cli_rs" { + http.Error(w, "not Codex", 400) + return + } + switch r.URL.Path { + case "/api/accounts/deviceauth/usercode": + var in struct { + ClientID string `json:"client_id"` + } + if json.NewDecoder(r.Body).Decode(&in) != nil || in.ClientID != codexClientID { + http.Error(w, "bad client", 400) + return + } + // as auth.openai.com answered on 2026-11-03 + w.Write([]byte(`{"device_auth_id":"deviceauth_6ae9","user_code":"WG0E-J29UL","interval":"0","expires_at":"2026-11-03T00:15:14.704241+00:00"}`)) + case "/api/accounts/deviceauth/token": + var in struct { + DeviceAuthID string `json:"device_auth_id"` + UserCode string `json:"user_code"` + } + json.NewDecoder(r.Body).Decode(&in) + if in.DeviceAuthID != "deviceauth_6ae9" || in.UserCode != "WG0E-J29UL" { + http.Error(w, "unknown", 400) + return + } + if polls.Add(1) <= pending { + w.WriteHeader(403) + w.Write([]byte(`{"error":{"message":"Device authorization is unknown. Please try again.","code":"deviceauth_authorization_unknown"}}`)) + return + } + w.Write([]byte(`{"authorization_code":"dc","code_challenge":"ch","code_verifier":"ver-dc"}`)) + case "/oauth/token": + r.ParseForm() + trades.Add(1) + if r.Form.Get("code") != "dc" || r.Form.Get("code_verifier") != "ver-dc" || + r.Form.Get("redirect_uri") != codexIssuer+"/deviceauth/callback" || r.Form.Get("client_id") != codexClientID { + w.WriteHeader(400) + json.NewEncoder(w).Encode(map[string]any{"error": "invalid_grant", "error_description": "bad code"}) + return + } + json.NewEncoder(w).Encode(map[string]any{ + "id_token": fakeJWT(map[string]any{"email": "dc@example.com", + "https://api.openai.com/auth": map[string]any{"chatgpt_plan_type": "pro", "chatgpt_account_id": "acct-dc"}}), + "access_token": fakeJWT(map[string]any{"exp": float64(time.Now().Add(time.Hour).Unix())}), + "refresh_token": "r-dc", + }) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(fake.Close) + oldIss, oldTok := codexIssuer, codexTokenURL + t.Cleanup(func() { codexIssuer, codexTokenURL = oldIss, oldTok }) + codexIssuer, codexTokenURL = fake.URL, fake.URL+"/oauth/token" + return trades +} + +func waitSignIn(t *testing.T, id string) SignInState { + t.Helper() + for end := time.Now().Add(10 * time.Second); time.Now().Before(end); time.Sleep(10 * time.Millisecond) { + if st, _ := SignInStatus(id); st.State != "waiting" { + return st + } + } + st, _ := SignInStatus(id) + t.Fatalf("still waiting: %+v", st) + return st +} + +// curtinp118 on Discord: magpie on a VPS, its web UI in a browser at home. +// The browser sign-in ends on localhost:1455, which is the home machine. +// A device code entered on ChatGPT's page signs in with nothing to bring +// back, and nothing listens on this computer for it. +func TestCodexSignInByDeviceCode(t *testing.T) { + home := claudeHome(t) + trades := fakeCodexDevice(t, 2) + + st, err := StartSignInWith("codex", SignInOptions{Site: CodexDeviceSite}) + if err != nil { + t.Fatal(err) + } + defer CancelSignIn(st.ID) + if st.Code != "WG0E-J29UL" || st.URL != codexIssuer+"/codex/device" { + t.Fatalf("no device code shown: %+v", st) + } + if st.PasteCallback { + t.Fatal("a device sign-in waits on a callback address") + } + st = waitSignIn(t, st.ID) + if st.State != "done" || st.User != "dc@example.com" || !st.Using || st.Code != "WG0E-J29UL" { + t.Fatalf("state %+v", st) + } + var a codexAuth + readJSON(filepath.Join(home, ".codex", "auth.json"), &a) + if a.Tokens.RefreshToken != "r-dc" || a.Tokens.AccountID != "acct-dc" { + t.Fatalf("auth.json %+v", a) + } + if n := trades.Load(); n != 1 { + t.Fatalf("%d trades", n) + } +} + +// Canceled before the code is entered: no account, no trade. +func TestCodexDeviceSignInCanceled(t *testing.T) { + home := claudeHome(t) + trades := fakeCodexDevice(t, 1<<30) + st, err := StartSignInWith("codex", SignInOptions{Site: CodexDeviceSite}) + if err != nil { + t.Fatal(err) + } + CancelSignIn(st.ID) + if st, _ = SignInStatus(st.ID); st.State != "canceled" { + t.Fatalf("state %+v", st) + } + if n := trades.Load(); n != 0 { + t.Fatalf("%d trades", n) + } + var a codexAuth + if readJSON(filepath.Join(home, ".codex", "auth.json"), &a); a.Tokens.RefreshToken != "" { + t.Fatalf("auth.json written: %+v", a) + } +} + +// ChatGPT turning device codes away (404, as Codex reads it) says to use +// the browser's sign-in, not a bare status. +func TestCodexDeviceSignInOff(t *testing.T) { + claudeHome(t) + fake := httptest.NewServer(http.NotFoundHandler()) + defer fake.Close() + old := codexIssuer + codexIssuer = fake.URL + defer func() { codexIssuer = old }() + _, err := StartSignInWith("codex", SignInOptions{Site: CodexDeviceSite}) + if err == nil || !strings.Contains(err.Error(), "browser sign-in") { + t.Fatalf("err %v", err) + } +} diff --git a/internal/provider/signin.go b/internal/provider/signin.go index 224248449..78f5b2606 100644 --- a/internal/provider/signin.go +++ b/internal/provider/signin.go @@ -343,6 +343,11 @@ func (s *signInFlow) begin() error { return err } case "codex": + if s.site == CodexDeviceSite { + // a code entered on ChatGPT's device page: nothing comes back + // to this computer (codex_device_signin.go) + return startCodexDeviceSignIn(s) + } // ChatGPT sends the browser back only to this one port. One that // can't be had (Windows reserves it, or another program holds it) // doesn't stop the sign-in: the page the browser ends on has the