From 8cdf2d20206dab5071ba15252d3f83fce3d9c666 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 19 Oct 2026 00:22:52 +0800 Subject: [PATCH] grok 0.1.16: a sign-in with no email is kept by its xAI user id, and a login that leaves none says where it looked (llllleo9 on X) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit llllleo9 couldn't add Grok: grok login --device-auth exited 0, and the sign-in failed with "grok login finished without an account". Grok Build 1.0.62 was run in a sandbox HOME. The stand-in auth.x.ai sat behind an HTTPS_PROXY MITM, with its CA passed through GROK_EXTRA_CA_BUNDLE, and sandbox-exec denied opening a browser. The CLI takes email and user_id from the id_token's claims alone. With no email claim (an xAI account signed in through X), it writes "email": null and still prints "✓ Signed in". When Grok Build's own home is already signed in, the plugin signs in beside it and demanded an email, so that sign-in failed. - An account is now told apart by its email, else its user_id, else the token's sub. saved() and the refresh path's remember() use the same account id. - GROK_AUTH_PATH is now left out of the CLI's run. With it set, 1.0.62 keeps the sign-in at that file, and the home the plugin reads stays empty (seen in the same sandbox). The login always runs with envFor(home) now, not process.env. - A login that finishes with nothing readable now says what grok said, which file it read and what was there (no file, not JSON, no token, or no account). It also points to "Use Grok Build's current sign-in". Run: - TMPDIR and HOME set to a scratch dir, bun test packages/grok: 47 pass, 0 fail. The six new login tests FAIL with 0.1.15's index.mjs. - bun scripts/check.mjs grok: ✓. - node --check and git diff --check are clean. - The plugin was run against the real grok 1.0.62 and the stand-in x.ai, with the CLI home already signed in: - id_token without email: 0.1.16 returns success with accountId "user-1". 0.1.15 returns "grok login finished without an account", the reporter's message. - GROK_AUTH_PATH set: 0.1.16 returns success, 0.1.15 fails the same way. - login.test's "a login's link is still handed on" timed out at 5s in 2 of 10 runs alone, on 0.1.15's code too. That is #160, which another session has taken; the data point was added there. Not tried with a real xAI account: whether xAI's token for llllleo9's account lacks the email claim, and whether their Grok Build was already signed in. --- packages/grok/README.md | 5 +++ packages/grok/index.mjs | 71 ++++++++++++++++++++++++-------- packages/grok/login.test.mjs | 79 ++++++++++++++++++++++++++++++++++++ packages/grok/package.json | 2 +- 4 files changed, 138 insertions(+), 19 deletions(-) diff --git a/packages/grok/README.md b/packages/grok/README.md index 01d6c3a..725c62e 100644 --- a/packages/grok/README.md +++ b/packages/grok/README.md @@ -27,6 +27,11 @@ the installer does, before a sign-in that needs it. - If it is signed in, the sign-in goes to a home of this plugin's, `$XDG_CONFIG_HOME/opencode-grok-auth/` (else under `~/.config`). Grok Build's own sign-in stays as it is. + - The account is told apart by its email, else its xAI user id (an + account signed in through X can have no email). `GROK_AUTH_PATH` is + left out of the CLI's run, so the sign-in lands in that home. + - When the CLI finishes but leaves no sign-in there, the failure says + which file it read and what it found. - **Use Grok Build's current sign-in** takes the account the CLI is signed in to, with nothing to approve. - **Import CPA Grok account JSON** copies one enabled xAI OAuth account from diff --git a/packages/grok/index.mjs b/packages/grok/index.mjs index 2b9afe7..d6a57ea 100644 --- a/packages/grok/index.mjs +++ b/packages/grok/index.mjs @@ -97,34 +97,60 @@ function executable() { return "" } -// envFor runs the CLI as the user runs it, in the given home. +// envFor runs the CLI as the user runs it, in the given home. GROK_AUTH_PATH +// goes too: grok 1.0.62 keeps its sign-in at that file instead of +// home/auth.json, where this plugin reads it, so a login with it set +// finished signed in and left nothing here. function envFor(home) { const env = {} for (const [k, v] of Object.entries(process.env)) { - if (["GROK_HOME", "GROK_AUTH_PROVIDER_COMMAND", "GROK_AUTH_EXPIRED"].includes(k.toUpperCase())) continue + if (["GROK_HOME", "GROK_AUTH_PATH", "GROK_AUTH_PROVIDER_COMMAND", "GROK_AUTH_EXPIRED"].includes(k.toUpperCase())) continue env[k] = v } env.GROK_HOME = home return env } -// credential is the sign-in the CLI keeps in home: the first, by key, with a token. -function credential(home) { +// look reads the sign-in the CLI keeps in home: the first, by key, with a +// token. With none, why says what the file held instead. +// +// who is the account it is: its email, else its xAI user id (the token's +// subject when the file has none). grok 1.0.62 takes both from the +// sign-in's id_token and writes "email": null when that +// has no email claim (an xAI account signed in through X has none), and +// still says "✓ Signed in" (llllleo9 on 𝕏; seen with grok 1.0.62 in a +// sandbox, signed in against a stand-in auth.x.ai). +function look(home) { + const file = join(home, "auth.json") + let text + try { + text = readFileSync(file, "utf8") + } catch (e) { + return { c: null, why: e?.code === "ENOENT" ? `there is no ${file}` : `${file} can't be read (${e?.code ?? e?.message})` } + } let all try { - all = JSON.parse(readFileSync(join(home, "auth.json"), "utf8")) + all = JSON.parse(text) } catch { - return null + return { c: null, why: `${file} isn't JSON` } } - if (!all || typeof all !== "object") return null - for (const k of Object.keys(all).sort()) { + if (!all || typeof all !== "object" || Array.isArray(all)) return { c: null, why: `${file} holds no sign-in` } + const keys = Object.keys(all).sort() + for (const k of keys) { const c = all[k] if (c && typeof c.key === "string" && c.key) { const t = Date.parse(c.expires_at ?? "") - return { key: c.key, email: c.email ?? "", expires: Number.isFinite(t) ? t : 0, issuer: c.oidc_issuer ?? "" } + const email = typeof c.email === "string" ? c.email : "" + const sub = cpaClaims(c.key)?.sub + const user = (typeof c.user_id === "string" && c.user_id) || (typeof sub === "string" ? sub : "") + return { c: { key: c.key, email, user, who: email || user, expires: Number.isFinite(t) ? t : 0, issuer: c.oidc_issuer ?? "" }, why: "" } } } - return null + return { c: null, why: keys.length ? `${file} has ${keys.join(", ")}, none with a token` : `${file} holds no sign-in` } +} + +function credential(home) { + return look(home).c } function run(file, args, opts) { @@ -438,10 +464,10 @@ function modelOf(id) { // login runs `grok login --device-auth` in home and hands on the first link // it prints; done is settled when the command is. -function login(exe, home, own) { +function login(exe, home) { const child = spawn(exe, ["login", "--device-auth"], { cwd: homedir(), - env: own ? envFor(home) : process.env, + env: envFor(home), stdio: ["ignore", "pipe", "pipe"], }) const tail = [] @@ -495,7 +521,7 @@ async function signIn() { if (!exe) throw new Error(NO_CLI) const own = !!credential(cliHome()) const home = own ? newHome() : cliHome() - const { child, link, done, tail } = login(exe, home, own) + const { child, link, done, tail } = login(exe, home) const url = await Promise.race([link, new Promise((r) => setTimeout(() => r(""), LINK_WAIT))]) if (!url) { child.kill() @@ -511,10 +537,19 @@ async function signIn() { method: "auto", callback: async () => { const r = await done - const c = r.ok ? credential(home) : null - if (!c || (own && !c.email)) { + const { c, why } = r.ok ? look(home) : { c: null, why: "" } + // a sign-in beside the CLI's own needs to know whose it is, so the + // same account signed in again replaces it instead of adding a second + if (!c || (own && !c.who)) { if (own) rmSync(home, { recursive: true, force: true }) - return { type: "failed", error: r.ok ? "grok login finished without an account" : r.why } + if (!r.ok) return { type: "failed", error: r.why } + const said = tail.at(-1) ? ` (it said "${tail.at(-1)}")` : "" + return { + type: "failed", + error: !c + ? `grok login finished${said}, but left no sign-in where this plugin reads it: ${why}. Run \`grok login\` in a terminal, then add Grok with "Use Grok Build's current sign-in"` + : `grok login finished${said}, but its sign-in in ${join(home, "auth.json")} names no account (no email, user id or token subject), so it can't be told from the Grok Build sign-in in ${cliHome()}. Sign in to that one with \`grok login\` and add it with "Use Grok Build's current sign-in"`, + } } return saved(home, c) }, @@ -596,7 +631,7 @@ async function importCPA(inputs) { // saved is the sign-in as OpenCode keeps it: refresh is the home the CLI // keeps it in, access the token it had then. function saved(home, c) { - return { type: "success", refresh: home, access: c.key, expires: c.expires, accountId: c.email } + return { type: "success", refresh: home, access: c.key, expires: c.expires, accountId: c.who } } // current takes the sign-in the CLI already has, as it is. @@ -751,7 +786,7 @@ export const GrokAuthPlugin = async ({ client }) => { const remember = async (auth, c) => { if (auth.access === c.key && auth.expires === c.expires) return try { - await client.auth.set({ path: { id: PROVIDER }, body: { ...auth, access: c.key, expires: c.expires, accountId: c.email || auth.accountId } }) + await client.auth.set({ path: { id: PROVIDER }, body: { ...auth, access: c.key, expires: c.expires, accountId: c.who || auth.accountId } }) } catch {} } diff --git a/packages/grok/login.test.mjs b/packages/grok/login.test.mjs index 95696e7..1981ed7 100644 --- a/packages/grok/login.test.mjs +++ b/packages/grok/login.test.mjs @@ -61,3 +61,82 @@ test.skipIf(process.platform === "win32")("a login's link is still handed on", a const a = await signIn(`echo 'To sign in, open this URL in your browser:'; echo ' https://accounts.x.ai/oauth2/device?user_code=AB12-CD34'; exit 1`) expect(a.url).toBe("https://accounts.x.ai/oauth2/device?user_code=AB12-CD34") }) + +// A login that ends signed in is kept, or says where it looked and what it +// found (llllleo9 on 𝕏: "grok login finished without an account"). Run in a +// sandbox against a stand-in auth.x.ai, grok 1.0.62 writes "email": null +// when the sign-in's id_token has no email (an xAI account signed in +// through X), and keeps its sign-in at GROK_AUTH_PATH when that is set. +const LINK = "https://accounts.x.ai/oauth2/device?user_code=AB12-CD34" +const later = new Date(Date.now() + 24 * 3600_000).toISOString() +const scope = "https://auth.x.ai::b1a00492-073a-47ea-816f-4c329264a828" +const jwt = (claims) => ["e30", Buffer.from(JSON.stringify(claims)).toString("base64url"), "sig"].join(".") +const theirs = { [scope]: { key: "cli-tok", email: "cli@x.ai", user_id: "u-cli", expires_at: later } } + +// finish runs a login that prints the link, writes what (if anything) where +// grok 1.0.62 does, says it signed in and exits 0. With cli, the CLI's own +// home already holds that sign-in, so the plugin signs in beside it. +async function finish({ what, cli, env = {} }) { + const bin = mkdtempSync(join(dir, "bin-")) + symlinkSync("/bin/sh", join(bin, "grok")) + const write = what ? `printf '%s' '${JSON.stringify(what)}' > "\${GROK_AUTH_PATH:-$GROK_HOME/auth.json}"` : ":" + writeFileSync(script, `echo 'To sign in, open this URL in your browser:'\necho ' ${LINK}'\n${write}\necho '✓ Signed in'\n`) + const cliHome = mkdtempSync(join(dir, "home-")) + if (cli) writeFileSync(join(cliHome, "auth.json"), JSON.stringify(cli)) + const set = { GROK_BIN_DIR: bin, GROK_HOME: cliHome, XDG_CONFIG_HOME: mkdtempSync(join(dir, "cfg-")), ...env } + const was = Object.fromEntries(Object.keys(set).map((k) => [k, process.env[k]])) + Object.assign(process.env, set) + try { + const hooks = await GrokAuthPlugin({ client: { auth: { set: async () => {} } } }) + const a = await hooks.auth.methods[0].authorize() + expect(a.url).toBe(LINK) + return { r: await a.callback(), cliHome } + } finally { + for (const [k, v] of Object.entries(was)) v === undefined ? delete process.env[k] : (process.env[k] = v) + } +} + +test.skipIf(process.platform === "win32")("a sign-in beside the CLI's own with no email is kept by its user id", async () => { + const { r } = await finish({ cli: theirs, what: { [scope]: { key: "tok", email: null, user_id: "u-1", expires_at: later } } }) + expect(r.type).toBe("success") + expect(r.accountId).toBe("u-1") + expect(r.access).toBe("tok") +}) + +test.skipIf(process.platform === "win32")("with no user id either, it is kept by the token's subject", async () => { + const key = jwt({ sub: "u-2", iss: "https://auth.x.ai" }) + const { r } = await finish({ cli: theirs, what: { [scope]: { key, email: null, user_id: "", expires_at: later } } }) + expect(r.type).toBe("success") + expect(r.accountId).toBe("u-2") +}) + +test.skipIf(process.platform === "win32")("one that names no account at all says so, and where", async () => { + const { r, cliHome } = await finish({ cli: theirs, what: { [scope]: { key: "tok", email: null, expires_at: later } } }) + expect(r.type).toBe("failed") + expect(r.error).toContain('grok login finished (it said "✓ Signed in")') + expect(r.error).toContain("names no account") + expect(r.error).toContain(cliHome) +}) + +test.skipIf(process.platform === "win32")("a login that leaves nothing says where it looked", async () => { + const { r, cliHome } = await finish({}) + expect(r.type).toBe("failed") + expect(r.error).toContain(`left no sign-in where this plugin reads it: there is no ${join(cliHome, "auth.json")}`) + expect(r.error).toContain("Use Grok Build's current sign-in") +}) + +test.skipIf(process.platform === "win32")("one that leaves a file with no token says what it holds", async () => { + const { r } = await finish({ what: { [scope]: { email: "g@x.ai" } } }) + expect(r.type).toBe("failed") + expect(r.error).toContain(`has ${scope}, none with a token`) +}) + +// GROK_AUTH_PATH moves the CLI's sign-in out of its home: the login runs +// without it, so the sign-in lands where the plugin reads it +test.skipIf(process.platform === "win32")("GROK_AUTH_PATH doesn't take the sign-in elsewhere", async () => { + const away = join(mkdtempSync(join(dir, "away-")), "auth.json") + const { r, cliHome } = await finish({ what: { [scope]: { key: "tok", email: "g@x.ai", expires_at: later } }, env: { GROK_AUTH_PATH: away } }) + expect(r.type).toBe("success") + expect(r.accountId).toBe("g@x.ai") + expect(r.refresh).toBe(cliHome) +}) diff --git a/packages/grok/package.json b/packages/grok/package.json index 9525147..c1a0511 100644 --- a/packages/grok/package.json +++ b/packages/grok/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-grok-auth", - "version": "0.1.15", + "version": "0.1.16", "description": "OpenCode provider plugin: Grok (SuperGrok / X Premium+) through the Grok Build CLI's sign-in", "type": "module", "main": "./index.mjs",