Files
plugins/packages/grok/refresh.test.mjs
T
yetone 6f1605f01d grok: the login and refresh tests' fake CLI is /bin/sh, not a script just written, so a busy Mac doesn't time them out (#65)
What waited was not a timer in the tests. On macOS the first run of an
executable just written waits for the system's scan of it: 4-15s each
here on a busy machine (a fresh `#!/bin/sh` file timed at 3.8-15.4s on
its first run, 0.00s after; a hard link or symlink to a scanned file, or
the same file read by sh, 0.00s). login.test.mjs wrote a new fake per
test, refresh.test.mjs one per file, so each paid it inside a test.

The fake grok is now a symlink to /bin/sh, and the plugin's own
`grok models` / `grok login --device-auth` become `sh models` /
`sh login …`, which read a plain script in the folder the plugin runs
the CLI in (root above the account's home; the home folder for login,
which login.test.mjs now only uses when HOME is a temp home). No
timeout was raised; refresh's `sleep 0.2` (for the joined-run test)
stays.

Run:
- With 14 `yes` burners of mine (load ~45): origin/main's two files
  5 and 6 fail (bun's 5s), this commit 0 fail in 1.5-1.9s, 3 runs.
- Idle: 10 pass, ~1.2s, 3 runs. Linux (oven/bun:1.4.2, /bin/sh = dash):
  10 pass.
- Broken by hand: links not taken (1 red), the CLI's last line not the
  reason (2 red), renewals not joined (1 red).
2026-10-12 18:22:47 +08:00

132 lines
5.5 KiB
JavaScript

// 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 { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, 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 }))
// The fake CLI is /bin/sh under grok's name, not a script written here: on
// macOS the first run of a file just written waits for the system's scan
// of it, which took 4-15s on a busy machine and timed these tests out
// (#65). The plugin runs `grok models` in the folder above the account's
// home, so that is `sh models` reading the script `models` in root: a
// plain file, read and never scanned. `grok --version` is sh's own answer
// (bash's version, or dash refusing the flag); no test here checks the
// version a request says.
const bin = join(root, "bin")
const later = new Date(Date.now() + 24 * 3600_000).toISOString()
mkdirSync(bin)
symlinkSync("/bin/sh", join(bin, "grok"))
writeFileSync(
join(root, "models"),
`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
`,
)
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()
})