signin: ChatGPT signs in by device code, the first way from another computer
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.
This commit is contained in:
File diff suppressed because one or more lines are too long
+28
-32
@@ -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 <name>.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 <name>.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…"));
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user