From 0af8500c0892381017fc206f3ac171bc31f9241f Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 3 Oct 2026 12:07:22 +0800 Subject: [PATCH] grok 0.1.6: magpie renews the sign-in ahead of time through auth.refresh auth.refresh with refreshLead 5 minutes (the in-fetch margin): the CLI renews the sign-in in the account's home (grok models), once per home however many ask, and the token is read back. A token the CLI renewed already is given without running it; no credential left (grok logout) is signIn "expired"; a token the CLI couldn't renew throws and is retried. The check before each request stays for OpenCode, which doesn't call the hook (magpie 0.1.684+ does). refresh.test.mjs fails without the change; HOME=$(mktemp -d) bun test passes (396 across the repo). --- packages/grok/README.md | 17 ++++- packages/grok/index.mjs | 54 ++++++++++++-- packages/grok/package.json | 2 +- packages/grok/refresh.test.mjs | 125 +++++++++++++++++++++++++++++++++ 4 files changed, 189 insertions(+), 9 deletions(-) create mode 100644 packages/grok/refresh.test.mjs diff --git a/packages/grok/README.md b/packages/grok/README.md index e488cdc..86a52ed 100644 --- a/packages/grok/README.md +++ b/packages/grok/README.md @@ -29,9 +29,20 @@ The CLI keeps the sign-in in its home, as `auth.json`. OpenCode (or magpie) keeps where that home is, the token and its expiry. The plugin only reads `auth.json`: the CLI's refresh gives a new token -each time. When the token is 5 minutes from expiring, or a request is -refused with 401, the plugin runs `grok models` in that home, so the CLI -renews it, then reads it again. +each time. The plugin runs `grok models` in that home, so the CLI renews +it, then reads it again: + +- magpie renews the token 5 minutes before it ends, through the plugin's + `auth.refresh`, once for the account and before its requests, models + and usage need it. magpie saves what the CLI gave. +- OpenCode doesn't call that hook: there the token is renewed when it is + 5 minutes from expiring, before a request. +- The CLI runs once for a home at a time: a request or renewal that + comes while it runs waits for it and reads what it gave. A token the + CLI already renewed is taken as it is. +- When the CLI no longer holds a sign-in in that home (`grok logout`), + the account has to be signed in again. When it couldn't renew a token + that has ended, magpie tries again later. ## Requests diff --git a/packages/grok/index.mjs b/packages/grok/index.mjs index cb873f4..33afb7b 100644 --- a/packages/grok/index.mjs +++ b/packages/grok/index.mjs @@ -17,7 +17,8 @@ import { STATUS_CODES } from "node:http" const PROVIDER = "grok" const BASE = "https://cli-chat-proxy.grok.com/v1" const CLIENT_VERSION = "1.0.41" -const REFRESH_MARGIN = 5 * 60 * 1000 +const REFRESH_MARGIN = 5 * 60 * 1000 // a token this close to its end is renewed before a request +const LEAD_MS = REFRESH_MARGIN // and this close, magpie renews it ahead of time (auth.refresh) const LINK_WAIT = 30 * 1000 const INSTALL = process.platform === "win32" ? "irm https://x.ai/cli/install.ps1 | iex" : "curl -fsSL https://x.ai/cli/install.sh | bash" @@ -119,18 +120,32 @@ function run(file, args, opts) { }) } +// refreshing runs the CLI's renewals one after another; renewing is the one +// asked for each home, which those who come while it is due or running join +// rather than running the CLI there again. let refreshing = Promise.resolve() +const renewing = new Map() + +// renew has the CLI renew the sign-in in home: a `grok models` there renews +// it as any use of the CLI does. +function renew(exe, home) { + let r = renewing.get(home) + if (!r) { + r = refreshing.then(() => run(exe, ["models"], { cwd: dirname(home), env: envFor(home) })).finally(() => renewing.delete(home)) + refreshing = r.catch(() => {}) + renewing.set(home, r) + } + return r +} // token is the CLI's sign-in in home with a token still good. One about to // expire (or that a request found expired) is first renewed by the CLI in -// its own home: a `grok models` there renews it as any use of the CLI does. +// its own home. async function token(home, expired) { let c = credential(home) const exe = executable() if (c && exe && (expired || c.expires - Date.now() < REFRESH_MARGIN)) { - const done = refreshing.then(() => run(exe, ["models"], { cwd: dirname(home), env: envFor(home) })) - refreshing = done.catch(() => {}) - await done + await renew(exe, home) c = credential(home) } if (!c) throw new Error("Grok is not signed in; run `grok login`") @@ -468,6 +483,35 @@ export const GrokAuthPlugin = async ({ client }) => { auth: { provider: PROVIDER, + // magpie renews the sign-in LEAD_MS before its end, once for the + // account, before its requests, models and usage ask for it: the CLI + // renews it in its home, as before a request, and what it gives is + // read back. The check before each request stays for OpenCode, which + // doesn't call this. + refreshLead: LEAD_MS, + async refresh(auth) { + const home = auth?.refresh + if (auth?.type !== "oauth" || !home) return undefined + let c = credential(home) + // renewed already (by the CLI, or before a request), the store not + // yet saying so + const renewed = c && c.key !== auth.access && c.expires - Date.now() >= LEAD_MS + const exe = executable() + if (!renewed && exe) { + await renew(exe, home) + c = credential(home) + } + // the CLI holds no sign-in there any more (`grok logout`): one + // has to be made again + if (!c) throw Object.assign(new Error("Grok is not signed in; run `grok login`"), { signIn: "expired" }) + // the CLI couldn't renew it: tried again later + if (exe && c.expires && c.expires <= Date.now()) throw new Error("Grok's sign-in has expired and Grok Build couldn't renew it") + if (c.key === auth.access && c.expires === auth.expires) return undefined + // magpie saves what this gives + const out = { access: c.key, expires: c.expires } + if (c.email && c.email !== auth.accountId) out.accountId = c.email + return out + }, async loader(getAuth) { const auth = await getAuth() if (!auth || auth.type !== "oauth") return {} diff --git a/packages/grok/package.json b/packages/grok/package.json index 21d84bf..32ecf28 100644 --- a/packages/grok/package.json +++ b/packages/grok/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-grok-auth", - "version": "0.1.5", + "version": "0.1.6", "description": "OpenCode provider plugin: Grok (SuperGrok / X Premium+) through the Grok Build CLI's sign-in", "type": "module", "main": "./index.mjs", diff --git a/packages/grok/refresh.test.mjs b/packages/grok/refresh.test.mjs new file mode 100644 index 0000000..8429083 --- /dev/null +++ b/packages/grok/refresh.test.mjs @@ -0,0 +1,125 @@ +// auth.refresh: magpie renews the sign-in ahead of time by having the CLI +// renew it in the account's home, as a request does, and never runs the +// CLI there twice at once. The CLI here is a fake in GROK_BIN_DIR: on +// `grok models` it counts the run and, by FAKE_GROK, writes a new token +// (renew), drops the sign-in (logout) or fails (anything else). +import { afterAll, afterEach, beforeEach, expect, test } from "bun:test" +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { GrokAuthPlugin } from "./index.mjs" + +const real = globalThis.fetch +const env = { ...process.env } +const root = mkdtempSync(join(tmpdir(), "grok-refresh-")) +afterAll(() => rmSync(root, { recursive: true, force: true })) + +const bin = join(root, "bin") +const later = new Date(Date.now() + 24 * 3600_000).toISOString() +mkdirSync(bin) +writeFileSync( + join(bin, "grok"), + `#!/bin/sh +[ "$1" = models ] || exit 0 +n=$(( $(cat "$GROK_HOME/runs" 2>/dev/null || echo 0) + 1 )) +echo $n > "$GROK_HOME/runs" +sleep 0.2 +case "$FAKE_GROK" in + renew) printf '{"a":{"key":"tok-%s","email":"g@x.ai","expires_at":"${later}"}}' $n > "$GROK_HOME/auth.json" ;; + logout) rm -f "$GROK_HOME/auth.json" ;; + *) exit 1 ;; +esac +`, +) +chmodSync(join(bin, "grok"), 0o755) + +let home +beforeEach(() => { + home = mkdtempSync(join(root, "home-")) + process.env.GROK_BIN_DIR = bin + process.env.FAKE_GROK = "renew" +}) +afterEach(() => { + globalThis.fetch = real + for (const k of Object.keys(process.env)) if (!(k in env)) delete process.env[k] + Object.assign(process.env, env) +}) + +// signedIn writes the CLI's sign-in in home, its token ending at expires +function signedIn(key, expires) { + writeFileSync(join(home, "auth.json"), JSON.stringify({ a: { key, email: "g@x.ai", expires_at: new Date(expires).toISOString() } })) + return { type: "oauth", refresh: home, access: key, expires, accountId: "g@x.ai" } +} +const runs = () => Number(readFileSync(join(home, "runs"), "utf8").trim() || 0) + +async function plugin() { + const saved = [] + const hooks = await GrokAuthPlugin({ client: { auth: { set: async (x) => saved.push(x) } } }) + return { hooks, saved } +} + +test("a token about to end is renewed by the CLI, and what it gives is returned, not saved", async () => { + const auth = signedIn("tok-0", Date.now() + 60_000) + const { hooks, saved } = await plugin() + expect(hooks.auth.refreshLead).toBe(5 * 60 * 1000) + expect(await hooks.auth.refresh(structuredClone(auth))).toEqual({ access: "tok-1", expires: Date.parse(later) }) + expect(runs()).toBe(1) + expect(saved).toEqual([]) +}) + +test("a request renewing meanwhile is joined: the CLI runs once", async () => { + const auth = signedIn("tok-0", Date.now() + 60_000) + const { hooks } = await plugin() + const sent = [] + globalThis.fetch = async (url, init) => { + sent.push(init.headers.get("Authorization")) + return new Response("{}") + } + const opts = await hooks.auth.loader(async () => auth) + const [got, res] = await Promise.all([ + hooks.auth.refresh(structuredClone(auth)), + opts.fetch("https://cli-chat-proxy.grok.com/v1/responses", { method: "POST", body: '{"model":"grok-4.7","input":"hi"}' }), + ]) + expect(res.status).toBe(200) + expect(runs()).toBe(1) + expect(got).toEqual({ access: "tok-1", expires: Date.parse(later) }) + expect(sent).toEqual(["Bearer tok-1"]) +}) + +test("a token the CLI renewed already is returned without running it", async () => { + const auth = signedIn("tok-0", Date.now() + 60_000) + signedIn("tok-9", Date.parse(later)) + const { hooks } = await plugin() + expect(await hooks.auth.refresh(structuredClone(auth))).toEqual({ access: "tok-9", expires: Date.parse(later) }) + expect(() => runs()).toThrow() +}) + +test("a sign-in the CLI dropped is one to make again", async () => { + process.env.FAKE_GROK = "logout" + const auth = signedIn("tok-0", Date.now() + 60_000) + const { hooks } = await plugin() + const e = await hooks.auth.refresh(structuredClone(auth)).catch((e) => e) + expect(e).toBeInstanceOf(Error) + expect(e.signIn).toBe("expired") +}) + +test("a token the CLI couldn't renew past its end is a plain failure, tried again later", async () => { + process.env.FAKE_GROK = "fail" + const auth = signedIn("tok-0", Date.now() - 1000) + const { hooks } = await plugin() + const e = await hooks.auth.refresh(structuredClone(auth)).catch((e) => e) + expect(e).toBeInstanceOf(Error) + expect(e.signIn).toBeUndefined() + expect(runs()).toBe(1) +}) + +test("nothing to renew with: no home, or no CLI", async () => { + const { hooks } = await plugin() + expect(await hooks.auth.refresh({ type: "oauth", access: "tok-0", expires: Date.now() + 60_000 })).toBeUndefined() + expect(await hooks.auth.refresh({ type: "api", key: "k" })).toBeUndefined() + const auth = signedIn("tok-0", Date.now() + 60_000) + process.env.GROK_BIN_DIR = join(root, "none") + process.env.GROK_HOME = join(root, "none") + process.env.PATH = "" + expect(await hooks.auth.refresh(structuredClone(auth))).toBeUndefined() +})