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).
This commit is contained in:
yetone
2026-10-03 12:07:22 +08:00
parent 9b434a5ed3
commit 0af8500c08
4 changed files with 189 additions and 9 deletions
+14 -3
View File
@@ -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
+49 -5
View File
@@ -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 {}
+1 -1
View File
@@ -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",
+125
View File
@@ -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()
})