grok 0.2.1: a token Grok turns away is renewed once, and one Grok Build can't renew says so (#324)
Grok can reject a token hours before its expires_at. A 401 used to be
passed on (requests) or read as "Grok's sign-in has expired; run `grok
login`" (models), with no renewal tried: token(home, expired) was never
called with expired set. And an auth.json caught while the CLI rewrote
it read as "not signed in", which the refresh hook marks as an expired
sign-in.
- token(home, rejected): rejected is the token Grok turned away. A token
on disk other than that one was renewed already and is used; else the
CLI renews it (`grok models` in the home). A run that leaves the same
token throws "Grok Build couldn't renew the sign-in (grok models
<exited N | ran and left the same token>: <its last line>)", never
"not signed in" or "expired".
- What it says helps: for Grok Build's own home (current()), open Grok
Build and send it a message; for a home of the plugin's (a second
device-code account, a CPA import) add the account in magpie again.
No "run `grok login`" where that signs in a different home. A home of
the plugin's with no sign-in left says to add the account again too.
- Requests: a 401 renews once and resends the same body with the new
token. Unrenewable, the 401 carries that message plus Grok's own words
(JSON error), still X-Magpie-Sign-In: kept. Models: a 401 renews once
and lists again; a renewed token also refused says so. Usage: same
retry once. auth.refresh's unrenewed case uses the same message.
- look(): an empty or non-JSON auth.json is torn. read() tries it again
for ~0.5s (6 x 100ms), then keeps the last sign-in read whole there,
as the CLI does ("auth reload: auth.json unreadable, keeping previous
credentials", in its binary's strings). Torn with nothing read before
is an error saying it couldn't be read, with no signIn mark. No
auth.json.lock is taken: it is the CLI's flock around its renewal,
Node can't take a flock, and holding it could only delay a renewal.
Changed tests: signin.test's 401 now has no CLI and expects the no-CLI
message beside Grok's body; usage.test and models.test the same; a
private home's "not signed in" says to add the account again.
Run (worktree at 59990e1, PATH without ~/.grok/bin and ~/.local/bin so
no real grok is found; TMPDIR and HOME in a fresh temp dir):
- packages/grok: bun test, 82 pass 0 fail
- repo: bun test, 2166 pass 0 fail across 189 files; bun scripts/check.mjs ok
Broken by hand (renew.test.mjs, 9 tests):
- old index.mjs: all 9 red
- TORN_TRIES = 1: the mid-write test red
- no last-good fallback: the stays-torn test red
- unchanged token not caught after renewal: the three couldn't-renew
tests (request private home, request shared home, models) red
- shared() always false: the shared-home message test red
Not tried: the real Grok Build CLI or a real Grok account (the fake CLI is
/bin/sh, fetch is a stand-in); a real 401 from Grok before expires_at; a
CLI writing auth.json in place while it is read (the torn file is
written by the test); a body that is a stream (not resent, as before:
only a string or no body is retried); Windows. magpie's mover min for
grok is not raised here.
This commit is contained in:
@@ -59,9 +59,22 @@ it, then reads it again:
|
||||
- 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.
|
||||
- Grok can turn a token away before its `expires_at`. A request, model
|
||||
list or usage read that gets 401 has the CLI renew the token and asks
|
||||
once more with the new one.
|
||||
- When the CLI's run leaves the token as it was, the 401 or error says
|
||||
Grok Build couldn't renew the sign-in, with what the CLI said. For Grok
|
||||
Build's own home ("Use Grok Build's current sign-in") opening Grok Build
|
||||
and sending it a message renews it. For a home of the plugin's (a second
|
||||
account, an imported one), opening Grok Build doesn't touch it: add the
|
||||
account in magpie again.
|
||||
- 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.
|
||||
- An `auth.json` that is empty or not JSON is most likely one the CLI is
|
||||
writing: it is read again for about half a second, then the last sign-in
|
||||
read whole there stands, as the CLI itself keeps its previous one. It is
|
||||
never taken as signed out. The plugin takes no `auth.json.lock`.
|
||||
|
||||
## Requests
|
||||
|
||||
|
||||
+169
-38
@@ -128,11 +128,15 @@ function look(home) {
|
||||
} catch (e) {
|
||||
return { c: null, why: e?.code === "ENOENT" ? `there is no ${file}` : `${file} can't be read (${e?.code ?? e?.message})` }
|
||||
}
|
||||
// an empty file, or one that isn't JSON, is most likely one the CLI is
|
||||
// writing as it is read (it rewrites auth.json when it renews): torn
|
||||
// says the read tells nothing, which read() tries again
|
||||
if (!text.trim()) return { c: null, why: `${file} is empty`, torn: true }
|
||||
let all
|
||||
try {
|
||||
all = JSON.parse(text)
|
||||
} catch {
|
||||
return { c: null, why: `${file} isn't JSON` }
|
||||
return { c: null, why: `${file} isn't JSON`, torn: true }
|
||||
}
|
||||
if (!all || typeof all !== "object" || Array.isArray(all)) return { c: null, why: `${file} holds no sign-in` }
|
||||
const keys = Object.keys(all).sort()
|
||||
@@ -143,19 +147,91 @@ function look(home) {
|
||||
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: "" }
|
||||
const got = { key: c.key, email, user, who: email || user, expires: Number.isFinite(t) ? t : 0, issuer: c.oidc_issuer ?? "" }
|
||||
lastGood.set(home, got)
|
||||
return { c: got, why: "" }
|
||||
}
|
||||
}
|
||||
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
|
||||
// lastGood is each home's last sign-in read whole.
|
||||
const lastGood = new Map()
|
||||
const TORN_TRIES = 6
|
||||
const TORN_WAIT = 100
|
||||
|
||||
// read is look, a torn read (auth.json caught mid-write) tried again for
|
||||
// about half a second; still torn, it is the last sign-in read whole there,
|
||||
// as the CLI itself keeps its previous credentials when auth.json won't
|
||||
// read ("auth reload: auth.json unreadable, keeping previous credentials").
|
||||
// No lock is taken: the CLI's auth.json.lock is a flock it holds while it
|
||||
// renews, which Node can't take, and a reader holding it could only hold a
|
||||
// renewal back.
|
||||
async function read(home) {
|
||||
let r = look(home)
|
||||
for (let i = 1; r.torn && i < TORN_TRIES; i++) {
|
||||
await new Promise((ok) => setTimeout(ok, TORN_WAIT))
|
||||
r = look(home)
|
||||
}
|
||||
if (r.torn && lastGood.has(home)) return { c: lastGood.get(home), why: "" }
|
||||
return r
|
||||
}
|
||||
|
||||
// credential is the sign-in in home, null when there is none. A file that
|
||||
// stays torn, with nothing read there before, is unknown, not "not signed
|
||||
// in": that is an error saying so.
|
||||
async function credential(home) {
|
||||
const r = await read(home)
|
||||
if (r.torn) throw new Error(`Grok Build's sign-in couldn't be read (${r.why}); it may be mid-write, try again in a moment`)
|
||||
return r.c
|
||||
}
|
||||
|
||||
// shared is whether home is Grok Build's own, which opening Grok Build
|
||||
// renews; a home of this plugin's (a second account, an imported one) only
|
||||
// this plugin's runs of the CLI ever touch.
|
||||
function shared(home) {
|
||||
return resolve(home) === resolve(cliHome())
|
||||
}
|
||||
|
||||
// notSignedIn says a home holds no sign-in, and what makes one.
|
||||
function notSignedIn(home) {
|
||||
return shared(home)
|
||||
? "Grok is not signed in; run `grok login`"
|
||||
: "Grok is not signed in for this account any more; add the account in magpie again"
|
||||
}
|
||||
|
||||
// cliSaid is what a `grok models` that renewed nothing said: how it ended
|
||||
// and its last line.
|
||||
function cliSaid(r) {
|
||||
if (!r) return ""
|
||||
const last = (r.stderr || r.stdout || "").replace(ANSI, "").split("\n").map((l) => l.trim()).filter(Boolean).at(-1)?.slice(0, 200)
|
||||
const how = !r.err ? "ran and left the same token" : r.err.killed ? "timed out" : `exited ${r.err.code ?? "with an error"}`
|
||||
return ` (grok models ${how}${last ? `: ${last}` : ""})`
|
||||
}
|
||||
|
||||
// unrenewed is a token Grok turned away, or one past its end, that Grok
|
||||
// Build, run in its home, didn't replace: the CLI couldn't renew it (xAI's renewal failing, or
|
||||
// a refresh token used up elsewhere), which signing in with `grok login`
|
||||
// in ~/.grok doesn't help where the account's home is the plugin's own.
|
||||
function unrenewed(home, r) {
|
||||
const how = shared(home)
|
||||
? "open Grok Build and send it a message, which renews the sign-in magpie reads"
|
||||
: "this account's sign-in is kept apart from Grok Build's own, so opening Grok Build doesn't renew it: add the account in magpie again"
|
||||
return Object.assign(new Error(`Grok Build couldn't renew the sign-in${cliSaid(r)}; ${how}`), { unrenewed: true })
|
||||
}
|
||||
|
||||
// dead is a token Grok turned away even as Grok Build had just renewed it.
|
||||
function dead(home) {
|
||||
return shared(home)
|
||||
? "Grok turned away Grok Build's sign-in even after renewing it; run `grok login` to sign Grok Build in afresh"
|
||||
: "Grok turned away this account's sign-in even after renewing it; add the account in magpie again"
|
||||
}
|
||||
|
||||
function run(file, args, opts) {
|
||||
return new Promise((resolve) => {
|
||||
execFile(file, args, { timeout: 30000, ...opts }, (err, stdout) => resolve({ err, stdout: String(stdout ?? "") }))
|
||||
execFile(file, args, { timeout: 30000, ...opts }, (err, stdout, stderr) =>
|
||||
resolve({ err, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") }),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -178,17 +254,25 @@ function renew(exe, home) {
|
||||
}
|
||||
|
||||
// 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.
|
||||
async function token(home, expired) {
|
||||
let c = credential(home)
|
||||
// expire is first renewed by the CLI in its own home, and so is one Grok
|
||||
// turned away: rejected is that token (or true for whatever home holds).
|
||||
// A token on disk other than the one turned away was renewed already and
|
||||
// is taken as it is; one the CLI's run leaves as it was is unrenewed,
|
||||
// never "not signed in" nor "expired".
|
||||
async function token(home, rejected = false) {
|
||||
let c = await credential(home)
|
||||
const exe = executable()
|
||||
if (c && exe && (expired || c.expires - Date.now() < REFRESH_MARGIN)) {
|
||||
await renew(exe, home)
|
||||
c = credential(home)
|
||||
const refused = !!c && (rejected === true || (typeof rejected === "string" && c.key === rejected))
|
||||
let r
|
||||
if (c && exe && (refused || c.expires - Date.now() < REFRESH_MARGIN)) {
|
||||
const was = c.key
|
||||
r = await renew(exe, home)
|
||||
c = await credential(home)
|
||||
if (c && refused && c.key === was) throw unrenewed(home, r)
|
||||
}
|
||||
if (!c) throw new Error("Grok is not signed in; run `grok login`")
|
||||
if (c.expires && c.expires <= Date.now()) throw new Error("Grok's sign-in has expired; run `grok login`")
|
||||
if (!c) throw new Error(notSignedIn(home))
|
||||
if (!exe && (refused || (c.expires && c.expires <= Date.now()))) throw new Error(`Grok turned the sign-in away and there is no Grok Build here to renew it; ${NO_CLI}`)
|
||||
if (c.expires && c.expires <= Date.now()) throw unrenewed(home, r)
|
||||
return c
|
||||
}
|
||||
|
||||
@@ -425,10 +509,9 @@ async function listModels(key) {
|
||||
await sign(headers, key)
|
||||
const res = await fetch(`${BASE}/models`, { headers })
|
||||
const text = await res.text()
|
||||
// a token Grok turned away before its time (signed out elsewhere) is a
|
||||
// sign-in gone, said as one past its time is: a move takes it along
|
||||
// untried rather than stopping on it
|
||||
if (res.status === 401) throw new Error("Grok's sign-in has expired; run `grok login`")
|
||||
// a token Grok turned away before its time: the caller has Grok Build
|
||||
// renew it and asks once more (models below)
|
||||
if (res.status === 401) throw Object.assign(new Error("Grok turned the sign-in away"), { status: 401 })
|
||||
if (!res.ok) throw new Error(`Grok models: ${res.status} ${text.slice(0, 200)}`)
|
||||
const out = []
|
||||
for (const d of JSON.parse(text)?.data ?? []) {
|
||||
@@ -548,7 +631,8 @@ function newHome() {
|
||||
async function signIn() {
|
||||
const exe = executable()
|
||||
if (!exe) throw new Error(NO_CLI)
|
||||
const own = !!credential(cliHome())
|
||||
// a sign-in mid-write is one: the CLI's own home is left be
|
||||
const own = await credential(cliHome()).then((c) => !!c, () => true)
|
||||
const home = own ? newHome() : cliHome()
|
||||
const { child, link, done, tail } = login(exe, home)
|
||||
const url = await Promise.race([link, new Promise((r) => setTimeout(() => r(""), LINK_WAIT))])
|
||||
@@ -568,7 +652,7 @@ async function signIn() {
|
||||
method: "auto",
|
||||
callback: async () => {
|
||||
const r = await done
|
||||
const { c, why } = r.ok ? look(home) : { c: null, why: "" }
|
||||
const { c, why } = r.ok ? await read(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)) {
|
||||
@@ -654,7 +738,7 @@ async function importCPA(inputs) {
|
||||
rmSync(home, { recursive: true, force: true })
|
||||
throw error
|
||||
}
|
||||
return saved(home, credential(home))
|
||||
return saved(home, await credential(home))
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -669,8 +753,8 @@ function saved(home, c) {
|
||||
async function current() {
|
||||
if (!executable()) throw new Error(NO_CLI)
|
||||
const home = cliHome()
|
||||
if (!credential(home)) throw new Error("Grok Build is not signed in; run `grok login`, or sign in with the device code")
|
||||
const c = await token(home, false)
|
||||
if (!(await credential(home))) throw new Error("Grok Build is not signed in; run `grok login`, or sign in with the device code")
|
||||
const c = await token(home)
|
||||
return {
|
||||
url: "",
|
||||
instructions: c.email ? `Grok Build is signed in as ${c.email}.` : "Grok Build is signed in.",
|
||||
@@ -729,7 +813,7 @@ async function usage(key) {
|
||||
} catch (e) {
|
||||
return { error: netError(url, e), windows: [] }
|
||||
}
|
||||
if (!res.ok) return { error: statusText(res.status), windows: [] }
|
||||
if (!res.ok) return { error: statusText(res.status), windows: [], status: res.status }
|
||||
let data
|
||||
try {
|
||||
data = JSON.parse(text)
|
||||
@@ -850,20 +934,21 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
|
||||
async refresh(auth) {
|
||||
const home = auth?.refresh
|
||||
if (auth?.type !== "oauth" || !home) return undefined
|
||||
let c = credential(home)
|
||||
let c = await 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()
|
||||
let r
|
||||
if (!renewed && exe) {
|
||||
await renew(exe, home)
|
||||
c = credential(home)
|
||||
r = await renew(exe, home)
|
||||
c = await 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" })
|
||||
if (!c) throw Object.assign(new Error(notSignedIn(home)), { 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 (exe && c.expires && c.expires <= Date.now()) throw unrenewed(home, r)
|
||||
if (c.key === auth.access && c.expires === auth.expires) return undefined
|
||||
// magpie saves what this gives
|
||||
const out = { access: c.key, expires: c.expires }
|
||||
@@ -889,10 +974,9 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
|
||||
parsed = JSON.parse(body) ?? {}
|
||||
} catch {}
|
||||
}
|
||||
const c = await token(home, false)
|
||||
let c = await token(home)
|
||||
await remember(auth, c)
|
||||
const headers = new Headers(req.headers)
|
||||
await sign(headers, c.key)
|
||||
const asked = modelOf(parsed.model)
|
||||
if (asked.model) {
|
||||
headers.set("x-grok-model-override", asked.model)
|
||||
@@ -904,10 +988,35 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
|
||||
if (asked.window) headers.set("x-grok-context-window", String(asked.window))
|
||||
if (typeof parsed.prompt_cache_key === "string" && parsed.prompt_cache_key) headers.set("x-grok-conv-id", parsed.prompt_cache_key)
|
||||
headers.delete("content-length")
|
||||
// sent once, as the built-in sent it: Grok's answer goes on as
|
||||
// it came, the account kept, as the built-in never marked a Grok
|
||||
// account lapsed nor cleared one
|
||||
const res = await fetch(req.url, { ...init, method: req.method, headers, body })
|
||||
const send = async (key) => {
|
||||
await sign(headers, key)
|
||||
return fetch(req.url, { ...init, method: req.method, headers, body })
|
||||
}
|
||||
// Grok's answer goes on as it came, the account kept, as the
|
||||
// built-in never marked a Grok account lapsed nor cleared one.
|
||||
// A token Grok turns away before its time (it can, ahead of
|
||||
// expires_at) is renewed by Grok Build and the request sent once
|
||||
// more; one Grok Build couldn't renew is a 401 saying so, and
|
||||
// what helps.
|
||||
let res = await send(c.key)
|
||||
if (res.status === 401 && (typeof body === "string" || body == null)) {
|
||||
try {
|
||||
c = await token(home, c.key)
|
||||
} catch (e) {
|
||||
const said = (await res.text().catch(() => "")).slice(0, 300)
|
||||
note(home, res)
|
||||
return kept(
|
||||
new Response(JSON.stringify({ error: { message: `${e.message}${said ? `. Grok said: ${said}` : ""}`, type: "authentication_error", code: "sign_in_unrenewed" } }), {
|
||||
status: 401,
|
||||
statusText: res.statusText,
|
||||
headers: { "content-type": "application/json" },
|
||||
}),
|
||||
)
|
||||
}
|
||||
await res.body?.cancel().catch(() => {})
|
||||
await remember(auth, c)
|
||||
res = await send(c.key)
|
||||
}
|
||||
note(home, res)
|
||||
return kept(res)
|
||||
},
|
||||
@@ -947,12 +1056,23 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
|
||||
let c
|
||||
try {
|
||||
if (!auth || auth.type !== "oauth" || !auth.refresh) throw new Error("Grok is not signed in; run `grok login`")
|
||||
c = await token(auth.refresh, false)
|
||||
c = await token(auth.refresh)
|
||||
} catch (e) {
|
||||
return { error: e.message, windows: [], signIn: "kept" }
|
||||
}
|
||||
await remember(auth, c)
|
||||
const u = await usage(c.key)
|
||||
let u = await usage(c.key)
|
||||
// a token turned away is renewed once, as a request's is
|
||||
if (u.status === 401) {
|
||||
try {
|
||||
c = await token(auth.refresh, c.key)
|
||||
} catch (e) {
|
||||
return { error: e.message, windows: [], signIn: "kept" }
|
||||
}
|
||||
await remember(auth, c)
|
||||
u = await usage(c.key)
|
||||
}
|
||||
delete u.status
|
||||
if (!u.error) u.windows = [...rateWindow(auth.refresh), ...u.windows]
|
||||
return { ...u, signIn: "kept" }
|
||||
},
|
||||
@@ -965,7 +1085,18 @@ export const GrokAuthPlugin = async ({ client, magpie }) => {
|
||||
if (!auth || auth.type !== "oauth" || !auth.refresh) return have
|
||||
// a list Grok couldn't give is a failure, not the few configured:
|
||||
// magpie keeps the list it had
|
||||
const list = await listModels((await token(auth.refresh, false)).key)
|
||||
let c = await token(auth.refresh)
|
||||
let list
|
||||
try {
|
||||
list = await listModels(c.key)
|
||||
} catch (e) {
|
||||
if (e?.status !== 401) throw e
|
||||
// turned away before its time: renewed once, as a request's is
|
||||
c = await token(auth.refresh, c.key)
|
||||
list = await listModels(c.key).catch((e) => {
|
||||
throw e?.status === 401 ? new Error(dead(auth.refresh)) : e
|
||||
})
|
||||
}
|
||||
const base = have["grok-4.7"] ?? Object.values(have)[0] ?? {}
|
||||
const out = {}
|
||||
for (const m of list) {
|
||||
|
||||
@@ -63,7 +63,9 @@ test("a window offered without a k asks Grok for that model and that many tokens
|
||||
// A token Grok refuses before its time says the sign-in is gone, as one
|
||||
// past its time does, so magpie's move takes the account along untried;
|
||||
// "Grok models: 401 …" stopped every Grok account's move.
|
||||
test("a refused token says the sign-in has expired", async () => {
|
||||
// with no Grok Build to renew it, a refused token says so, not that the
|
||||
// sign-in has expired (renew.test.mjs has the CLI renewing it)
|
||||
test("a refused token with no Grok Build to renew it says so", async () => {
|
||||
const { mkdtempSync, writeFileSync } = await import("node:fs")
|
||||
const { tmpdir } = await import("node:os")
|
||||
const { join } = await import("node:path")
|
||||
@@ -76,7 +78,8 @@ test("a refused token says the sign-in has expired", async () => {
|
||||
try {
|
||||
const hooks = await GrokAuthPlugin({ client: { auth: { set: async () => {} } } })
|
||||
const err = await hooks.provider.models({ id: "grok", models: {} }, { auth: { type: "oauth", refresh: home } }).catch((e) => e)
|
||||
expect(err?.message).toMatch(/sign-in has expired/)
|
||||
expect(err?.message).toContain("there is no Grok Build here to renew it")
|
||||
expect(err?.message).not.toMatch(/sign-in has expired/)
|
||||
} finally {
|
||||
;[process.env.PATH, process.env.HOME, globalThis.fetch] = [path, h, fetch0]
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-grok-auth",
|
||||
"version": "0.2.0",
|
||||
"version": "0.2.1",
|
||||
"description": "OpenCode provider plugin: Grok (SuperGrok / X Premium+) through the Grok Build CLI's sign-in",
|
||||
"type": "module",
|
||||
"main": "./index.mjs",
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
// A token Grok turns away before its time (plugins#324): Grok can reject a
|
||||
// token hours ahead of its expires_at, so a 401 has Grok Build renew it in
|
||||
// the account's home and the request, model list or usage read asks once
|
||||
// more. Where the CLI's run leaves the token as it was, the failure says
|
||||
// Grok Build couldn't renew it, and what helps: opening Grok Build for its
|
||||
// own home, signing in through magpie for a home of the plugin's. Never
|
||||
// "run `grok login`", which renews neither.
|
||||
//
|
||||
// auth.json caught while the CLI rewrites it is unknown, not "not signed
|
||||
// in": it is read again, else the last sign-in read whole there stands.
|
||||
//
|
||||
// The CLI is a fake as in refresh.test.mjs: /bin/sh under grok's name,
|
||||
// `grok models` being `sh models` reading the script below. FAKE_GROK says
|
||||
// what the run does: renew writes a new token, same exits 0 leaving the
|
||||
// token as it was (the CLI saying "Renewed" with pre_key == post_key), fail
|
||||
// exits 1 as a failed silent refresh. PATH is emptied so no real grok is
|
||||
// ever found, and fetch is a stand-in: nothing reaches the network.
|
||||
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-renew-"))
|
||||
afterAll(() => rmSync(root, { recursive: true, force: true }))
|
||||
|
||||
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"
|
||||
case "$FAKE_GROK" in
|
||||
renew) printf '{"a":{"key":"tok-%s","email":"g@x.ai","expires_at":"${later}"}}' $n > "$GROK_HOME/auth.json" ;;
|
||||
same) ;;
|
||||
*) echo "silent refresh outcome=Failed(SelfHealing)" >&2; exit 1 ;;
|
||||
esac
|
||||
`,
|
||||
)
|
||||
|
||||
let home
|
||||
beforeEach(() => {
|
||||
home = mkdtempSync(join(root, "home-"))
|
||||
process.env.GROK_BIN_DIR = bin
|
||||
process.env.PATH = ""
|
||||
// the CLI's own home is elsewhere unless a test says it is this one
|
||||
process.env.GROK_HOME = join(root, "cli-home")
|
||||
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, good for a day by its own say
|
||||
function signedIn(key) {
|
||||
writeFileSync(join(home, "auth.json"), JSON.stringify({ a: { key, email: "g@x.ai", expires_at: later } }))
|
||||
return { type: "oauth", refresh: home, access: key, expires: Date.parse(later), accountId: "g@x.ai" }
|
||||
}
|
||||
const runs = () => {
|
||||
try {
|
||||
return Number(readFileSync(join(home, "runs"), "utf8").trim() || 0)
|
||||
} catch {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
// grok answers 401 to tok-0 and serves any other token
|
||||
function grok(ok) {
|
||||
const sent = []
|
||||
globalThis.fetch = async (url, init) => {
|
||||
const auth = new Headers(init?.headers).get("Authorization")
|
||||
sent.push(auth)
|
||||
if (auth === "Bearer tok-0") return Response.json({ error: "Invalid or expired credentials" }, { status: 401 })
|
||||
return ok(String(url))
|
||||
}
|
||||
return sent
|
||||
}
|
||||
|
||||
async function plugin() {
|
||||
const saved = []
|
||||
const hooks = await GrokAuthPlugin({ client: { auth: { set: async (x) => saved.push(x) } } })
|
||||
return { hooks, saved }
|
||||
}
|
||||
|
||||
async function chat(auth) {
|
||||
const { hooks, saved } = await plugin()
|
||||
const opts = await hooks.auth.loader(async () => auth)
|
||||
const res = await opts.fetch("https://cli-chat-proxy.grok.com/v1/responses", { method: "POST", body: '{"model":"grok-4.7","input":"hi"}' })
|
||||
return { res, saved }
|
||||
}
|
||||
|
||||
const MODELS = { data: [{ id: "grok-4.7", name: "Grok 4.7", api_backend: "responses", context_window: 256000 }] }
|
||||
|
||||
test("a request Grok turns away is sent once more with the token Grok Build renewed", async () => {
|
||||
const auth = signedIn("tok-0")
|
||||
const sent = grok(() => Response.json({ ok: true }))
|
||||
const { res, saved } = await chat(auth)
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ ok: true })
|
||||
expect(sent).toEqual(["Bearer tok-0", "Bearer tok-1"])
|
||||
expect(runs()).toBe(1)
|
||||
expect(saved.at(-1).body.access).toBe("tok-1")
|
||||
})
|
||||
|
||||
test("a request whose token Grok Build couldn't renew says so, and to add the account again for a home of the plugin's", async () => {
|
||||
process.env.FAKE_GROK = "same"
|
||||
const auth = signedIn("tok-0")
|
||||
const sent = grok(() => Response.json({ ok: true }))
|
||||
const { res } = await chat(auth)
|
||||
expect(res.status).toBe(401)
|
||||
expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept")
|
||||
const msg = (await res.json()).error.message
|
||||
expect(msg).toContain("Grok Build couldn't renew the sign-in (grok models ran and left the same token)")
|
||||
expect(msg).toContain("add the account in magpie again")
|
||||
expect(msg).toContain("Invalid or expired credentials")
|
||||
expect(msg).not.toContain("grok login")
|
||||
expect(msg).not.toMatch(/sign-in has expired/)
|
||||
expect(sent).toEqual(["Bearer tok-0"])
|
||||
expect(runs()).toBe(1)
|
||||
})
|
||||
|
||||
test("for Grok Build's own home, a token it couldn't renew says to open Grok Build, with what the CLI said", async () => {
|
||||
process.env.FAKE_GROK = "fail"
|
||||
const auth = signedIn("tok-0")
|
||||
process.env.GROK_HOME = home
|
||||
grok(() => Response.json({ ok: true }))
|
||||
const { res } = await chat(auth)
|
||||
expect(res.status).toBe(401)
|
||||
const msg = (await res.json()).error.message
|
||||
expect(msg).toContain("Grok Build couldn't renew the sign-in (grok models exited 1: silent refresh outcome=Failed(SelfHealing))")
|
||||
expect(msg).toContain("open Grok Build and send it a message")
|
||||
expect(msg).not.toContain("grok login")
|
||||
})
|
||||
|
||||
test("a model list Grok turns away is asked again with the renewed token", async () => {
|
||||
const auth = signedIn("tok-0")
|
||||
const sent = grok(() => Response.json(MODELS))
|
||||
const { hooks } = await plugin()
|
||||
const got = await hooks.provider.models({ id: "grok", models: {} }, { auth })
|
||||
expect(Object.keys(got)).toEqual(["grok-4.7"])
|
||||
expect(sent).toEqual(["Bearer tok-0", "Bearer tok-1"])
|
||||
expect(runs()).toBe(1)
|
||||
})
|
||||
|
||||
test("a model list whose token Grok Build couldn't renew says so, not that the sign-in expired", async () => {
|
||||
process.env.FAKE_GROK = "same"
|
||||
const auth = signedIn("tok-0")
|
||||
grok(() => Response.json(MODELS))
|
||||
const { hooks } = await plugin()
|
||||
const e = await hooks.provider.models({ id: "grok", models: {} }, { auth }).catch((e) => e)
|
||||
expect(e).toBeInstanceOf(Error)
|
||||
expect(e.message).toContain("Grok Build couldn't renew the sign-in")
|
||||
expect(e.message).not.toMatch(/sign-in has expired|grok login/)
|
||||
expect(e.signIn).toBeUndefined()
|
||||
})
|
||||
|
||||
test("a usage read Grok turns away is read again with the renewed token", async () => {
|
||||
const auth = signedIn("tok-0")
|
||||
const sent = grok(() => Response.json({ config: { creditUsagePercent: 10 } }))
|
||||
const { hooks } = await plugin()
|
||||
const u = await hooks.auth.usage(async () => auth)
|
||||
expect(u).toEqual({ signIn: "kept", windows: [{ name: "Allowance", used: 10 }] })
|
||||
expect(sent).toEqual(["Bearer tok-0", "Bearer tok-1"])
|
||||
})
|
||||
|
||||
test("auth.json caught mid-write is read again, not taken as signed out", async () => {
|
||||
const auth = signedIn("tok-5")
|
||||
writeFileSync(join(home, "auth.json"), '{"a":{"key":"tok-5","em')
|
||||
setTimeout(() => signedIn("tok-5"), 150)
|
||||
const sent = grok(() => Response.json({ ok: true }))
|
||||
const { res } = await chat(auth)
|
||||
expect(res.status).toBe(200)
|
||||
expect(sent).toEqual(["Bearer tok-5"])
|
||||
})
|
||||
|
||||
test("auth.json that stays torn is the last sign-in read whole there", async () => {
|
||||
const auth = signedIn("tok-6")
|
||||
const sent = grok(() => Response.json({ ok: true }))
|
||||
expect((await chat(auth)).res.status).toBe(200)
|
||||
writeFileSync(join(home, "auth.json"), "")
|
||||
expect((await chat(auth)).res.status).toBe(200)
|
||||
expect(sent).toEqual(["Bearer tok-6", "Bearer tok-6"])
|
||||
})
|
||||
|
||||
test("auth.json torn with nothing read before is unknown: no account is marked signed out", async () => {
|
||||
writeFileSync(join(home, "auth.json"), '{"a":{"key":"tok-7"')
|
||||
const auth = { type: "oauth", refresh: home, access: "tok-7", expires: Date.now() + 60_000, accountId: "g@x.ai" }
|
||||
const { hooks } = await plugin()
|
||||
const e = await hooks.auth.refresh(structuredClone(auth)).catch((e) => e)
|
||||
expect(e).toBeInstanceOf(Error)
|
||||
expect(e.signIn).toBeUndefined()
|
||||
expect(e.message).toContain("couldn't be read")
|
||||
expect(e.message).not.toContain("not signed in")
|
||||
})
|
||||
@@ -29,12 +29,25 @@ async function chat(reply) {
|
||||
return { res, sent }
|
||||
}
|
||||
|
||||
// With no Grok Build to renew the token Grok turned away, the 401 says so
|
||||
// beside what Grok said (renew.test.mjs has the CLI renewing it).
|
||||
test("Grok's 401 is passed on once, the account kept", async () => {
|
||||
const { res, sent } = await chat(() => Response.json({ error: "token revoked" }, { status: 401 }))
|
||||
expect(sent).toBe(1)
|
||||
expect(res.status).toBe(401)
|
||||
expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept")
|
||||
expect(await res.json()).toEqual({ error: "token revoked" })
|
||||
const [path, bin] = [process.env.PATH, process.env.GROK_BIN_DIR]
|
||||
process.env.PATH = ""
|
||||
process.env.GROK_BIN_DIR = join(home, "none")
|
||||
try {
|
||||
const { res, sent } = await chat(() => Response.json({ error: "token revoked" }, { status: 401 }))
|
||||
expect(sent).toBe(1)
|
||||
expect(res.status).toBe(401)
|
||||
expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept")
|
||||
const msg = (await res.json()).error.message
|
||||
expect(msg).toContain("there is no Grok Build here to renew it")
|
||||
expect(msg).toContain('Grok said: {"error":"token revoked"}')
|
||||
} finally {
|
||||
process.env.PATH = path
|
||||
if (bin === undefined) delete process.env.GROK_BIN_DIR
|
||||
else process.env.GROK_BIN_DIR = bin
|
||||
}
|
||||
})
|
||||
|
||||
// nor cleared one: an answer that went through leaves the mark as it is
|
||||
|
||||
@@ -67,10 +67,22 @@ test("no current period: the billing period's Allowance; an unknown one has no s
|
||||
expect(u).toEqual({ signIn: "kept", windows: [{ name: "Allowance", used: 0 }] })
|
||||
})
|
||||
|
||||
test("a refused token is the status magpie says; no sign-in says to sign in", async () => {
|
||||
expect((await run(auth, () => new Response("", { status: 401 }))).u).toEqual({ signIn: "kept", error: "Unauthorized", windows: [] })
|
||||
test("a refused token with no Grok Build to renew it says so; no sign-in says to sign in", async () => {
|
||||
const [path, bin] = [process.env.PATH, process.env.GROK_BIN_DIR]
|
||||
process.env.PATH = ""
|
||||
process.env.GROK_BIN_DIR = join(home, "none")
|
||||
try {
|
||||
const { u } = await run(auth, () => new Response("", { status: 401 }))
|
||||
expect(u).toMatchObject({ signIn: "kept", windows: [] })
|
||||
expect(u.error).toContain("there is no Grok Build here to renew it")
|
||||
} finally {
|
||||
process.env.PATH = path
|
||||
if (bin === undefined) delete process.env.GROK_BIN_DIR
|
||||
else process.env.GROK_BIN_DIR = bin
|
||||
}
|
||||
const { u, seen } = await run({ ...auth, refresh: join(home, "none") }, () => Response.json({}))
|
||||
expect(u).toEqual({ signIn: "kept", error: "Grok is not signed in; run `grok login`", windows: [] })
|
||||
// a home of the plugin's: `grok login` signs in ~/.grok, not there
|
||||
expect(u).toEqual({ signIn: "kept", error: "Grok is not signed in for this account any more; add the account in magpie again", windows: [] })
|
||||
expect(seen).toEqual([])
|
||||
})
|
||||
|
||||
|
||||
Reference in New Issue
Block a user