minimax: device sign-in polling asks again after a transient failure (#382)
MiniMax's device sign-in no longer ends on a connection reset, a non-JSON HTTP 400, a 408/429/5xx, or a body read that fails while polling. It asks again with the same device code and verifier, up to three times in a row and within the code's deadline. A pending answer resets the count. Denied, expired and bad-client answers still stop at once, and refresh stays single-attempt.
Run at 4b17063, merged onto main d2ada16:
- bun test in packages/minimax: 81 pass, 0 fail. bun scripts/check.mjs minimax passes.
- poll-retry.test.mjs on main's index.mjs: 12 of 19 fail.
- Probe with Bun's real fetch against a local socket server: a reset, then an HTML 400, then pending, then a reset mid-body, then a token. The PR signs in after 8s, and every poll carried the same device_code and verifier. Main fails on the first reset (ECONNRESET).
- Bun reports a reset as code ECONNRESET, which is in the retried list. It reports a refused connection as ConnectionRefused, which isn't, so that is not retried.
Not tried: a real MiniMax account (none used in review). The version goes to 0.1.7 in a following commit, since 0.1.6 is already published from #393.
This commit is contained in:
+42
-17
@@ -211,16 +211,17 @@ class OAuthError extends Error {
|
||||
|
||||
// postForm posts an OAuth form, as MiniMax Code's client does; ok is false
|
||||
// when the answer is an HTTP error or carries an "error".
|
||||
async function postForm(url, fields) {
|
||||
async function postForm(url, fields, timeoutMs = 30000) {
|
||||
const res = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: { Accept: "application/json", "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams(fields).toString(),
|
||||
signal: AbortSignal.timeout(30000),
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
})
|
||||
const text = await res.text() // preserve transport errors while reading the body
|
||||
let body
|
||||
try {
|
||||
body = obj(JSON.parse(await res.text()))
|
||||
body = obj(JSON.parse(text))
|
||||
} catch {}
|
||||
if (!body) throw new OAuthError("invalid_json_response", res.status)
|
||||
const error = str(body, "error")
|
||||
@@ -283,30 +284,54 @@ async function startDevice(site) {
|
||||
}
|
||||
}
|
||||
|
||||
// Only device-code polling is retried. Refresh tokens may be single-use.
|
||||
function transientDeviceError(e) {
|
||||
const code = e?.code ?? e?.cause?.code
|
||||
if (["ECONNRESET", "ETIMEDOUT", "EPIPE", "ECONNREFUSED", "EAI_AGAIN"].includes(code) || e?.name === "TimeoutError") return true
|
||||
if (!(e instanceof OAuthError)) return false
|
||||
const status = e.httpStatus
|
||||
if (["invalid_grant", "access_denied", "expired_token", "invalid_client", "unauthorized_client"].includes(e.code)) return false
|
||||
return status === 408 || status === 429 || status >= 500 && status <= 599 ||
|
||||
e.code === "invalid_json_response" && status === 400
|
||||
}
|
||||
|
||||
async function pollDevice(site, d) {
|
||||
let wait = d.intervalMs
|
||||
let failures = 0
|
||||
let delay = wait
|
||||
while (Date.now() < d.deadline) {
|
||||
await sleep(wait)
|
||||
const r = await postForm(site.account + "/oauth2/token", {
|
||||
grant_type: DEVICE_GRANT,
|
||||
...d.poll,
|
||||
client_id: CLIENT_ID,
|
||||
code_verifier: d.verifier,
|
||||
})
|
||||
await sleep(Math.min(delay, Math.max(0, d.deadline - Date.now())))
|
||||
if (Date.now() >= d.deadline) break
|
||||
let r
|
||||
try {
|
||||
r = await postForm(site.account + "/oauth2/token", {
|
||||
grant_type: DEVICE_GRANT,
|
||||
...d.poll,
|
||||
client_id: CLIENT_ID,
|
||||
code_verifier: d.verifier,
|
||||
}, Math.max(1, Math.min(30000, d.deadline - Date.now())))
|
||||
if (!r.ok && r.error !== "authorization_pending" && r.error !== "slow_down") {
|
||||
throw new OAuthError(r.error ?? "device_authorization_failed", r.status)
|
||||
}
|
||||
} catch (e) {
|
||||
if (!transientDeviceError(e) || ++failures > 3) throw e
|
||||
delay = Math.max(wait, Math.min(30000, Math.max(wait, 1000) * 2 ** failures))
|
||||
// Fixed text and numeric status only: never log forms, URLs or tokens.
|
||||
console.warn(`MiniMax device authorization: temporary transport/response failure${e.httpStatus ? ` (HTTP ${e.httpStatus})` : ""}; retry ${failures}/3`)
|
||||
continue
|
||||
}
|
||||
failures = 0
|
||||
delay = wait
|
||||
const status = str(r.body, "status")
|
||||
if (r.ok && status === "pending") continue
|
||||
if (r.ok && status === "slow_down") {
|
||||
if (r.ok && status === "pending" || r.error === "authorization_pending") continue
|
||||
if (r.ok && status === "slow_down" || r.error === "slow_down") {
|
||||
wait += 5000
|
||||
delay = wait
|
||||
continue
|
||||
}
|
||||
if (r.ok && (status === "denied" || status === "access_denied")) throw new OAuthError("access_denied", 0, "the sign-in was turned down")
|
||||
if (r.ok && (status === "expired" || status === "expired_token")) throw new OAuthError("expired_token", 0, "the sign-in code expired")
|
||||
if (r.ok) return token(r.body)
|
||||
if (r.error === "authorization_pending") continue
|
||||
if (r.error === "slow_down") {
|
||||
wait += 5000
|
||||
continue
|
||||
}
|
||||
throw new OAuthError(r.error ?? "device_authorization_failed", r.status)
|
||||
}
|
||||
throw new OAuthError("expired_token", 0, "the sign-in code expired")
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
// Device polling tolerates transient failures without restarting authorization.
|
||||
// Every response and clock is local; no account or network is used.
|
||||
import "./nonet.mjs"
|
||||
import { expect, test } from "bun:test"
|
||||
import { _internal } from "./index.mjs"
|
||||
|
||||
const success = () => ({ body: { access_token: "test-access", refresh_token: "test-refresh", expires_in: 3600 } })
|
||||
const reset = () => Object.assign(new Error("reset"), { code: "ECONNRESET" })
|
||||
|
||||
async function poll(replies, { deadline = 600_000 } = {}) {
|
||||
const saved = { fetch: globalThis.fetch, setTimeout: globalThis.setTimeout, now: Date.now, warn: console.warn }
|
||||
let now = 1_000_000
|
||||
let calls = 0
|
||||
const waits = []
|
||||
const requests = []
|
||||
const warnings = []
|
||||
Date.now = () => now
|
||||
globalThis.setTimeout = (fn, ms) => {
|
||||
waits.push(ms)
|
||||
now += ms
|
||||
queueMicrotask(fn)
|
||||
return 0
|
||||
}
|
||||
console.warn = (message) => warnings.push(message)
|
||||
globalThis.fetch = async (url, init) => {
|
||||
requests.push({ url, form: Object.fromEntries(new URLSearchParams(init.body)) })
|
||||
const reply = replies[calls++]
|
||||
if (reply instanceof Error) throw reply
|
||||
if (reply?.readError) return { ok: true, status: 200, text: async () => { throw reply.readError } }
|
||||
if (!reply) throw new Error("unexpected request")
|
||||
return new Response(typeof reply.body === "string" ? reply.body : JSON.stringify(reply.body), { status: reply.status ?? 200 })
|
||||
}
|
||||
try {
|
||||
const value = await _internal.pollDevice({ account: "http://127.0.0.1" }, {
|
||||
intervalMs: 3000,
|
||||
deadline: now + deadline,
|
||||
poll: { device_code: "test-device" },
|
||||
verifier: "test-verifier",
|
||||
})
|
||||
return { value, calls, waits, requests, warnings }
|
||||
} catch (error) {
|
||||
return { error, calls, waits, requests, warnings }
|
||||
} finally {
|
||||
globalThis.fetch = saved.fetch
|
||||
globalThis.setTimeout = saved.setTimeout
|
||||
Date.now = saved.now
|
||||
console.warn = saved.warn
|
||||
}
|
||||
}
|
||||
|
||||
test("HTTP 400 authorization_pending remains pending", async () => {
|
||||
const r = await poll([{ status: 400, body: { error: "authorization_pending" } }, success()])
|
||||
expect(r.error).toBeUndefined()
|
||||
expect(r.value.access).toBe("test-access")
|
||||
expect(r.calls).toBe(2)
|
||||
expect(r.waits).toEqual([3000, 3000])
|
||||
})
|
||||
|
||||
test("a reset retries the same device code and verifier with backoff", async () => {
|
||||
const r = await poll([reset(), success()])
|
||||
expect(r.error).toBeUndefined()
|
||||
expect(r.value.refresh).toBe("test-refresh")
|
||||
expect(r.calls).toBe(2)
|
||||
expect(r.waits).toEqual([3000, 6000])
|
||||
expect(r.requests[1]).toEqual(r.requests[0])
|
||||
expect(r.requests[0].form).toMatchObject({ device_code: "test-device", code_verifier: "test-verifier" })
|
||||
expect(r.warnings.join(" ")).not.toContain("test-device")
|
||||
expect(r.warnings.join(" ")).not.toContain("test-verifier")
|
||||
})
|
||||
|
||||
test("a non-JSON HTTP 400 can recover", async () => {
|
||||
const r = await poll([{ status: 400, body: "<html>Bad Request</html>" }, success()])
|
||||
expect(r.error).toBeUndefined()
|
||||
expect(r.value.access).toBe("test-access")
|
||||
})
|
||||
|
||||
for (const status of [408, 429, 500, 503]) {
|
||||
test(`a temporary HTTP ${status} can recover`, async () => {
|
||||
const r = await poll([{ status, body: { error: "temporarily_unavailable" } }, success()])
|
||||
expect(r.error).toBeUndefined()
|
||||
expect(r.calls).toBe(2)
|
||||
})
|
||||
}
|
||||
|
||||
for (const error of ["invalid_grant", "access_denied", "expired_token", "invalid_client", "unauthorized_client"]) {
|
||||
test(`${error} is not retried`, async () => {
|
||||
const r = await poll([{ status: 400, body: { error } }, success()])
|
||||
expect(r.error.code).toBe(error)
|
||||
expect(r.calls).toBe(1)
|
||||
})
|
||||
}
|
||||
|
||||
test("an unknown error is not retried", async () => {
|
||||
const r = await poll([new Error("bug"), success()])
|
||||
expect(r.error.message).toBe("bug")
|
||||
expect(r.calls).toBe(1)
|
||||
})
|
||||
|
||||
test("three consecutive retries exhaust the budget", async () => {
|
||||
const r = await poll(Array.from({ length: 20 }, reset))
|
||||
expect(r.error.code).toBe("ECONNRESET")
|
||||
expect(r.calls).toBe(4)
|
||||
expect(r.waits).toEqual([3000, 6000, 12000, 24000])
|
||||
})
|
||||
|
||||
test("no request starts after the device deadline while sleeping", async () => {
|
||||
const r = await poll([success()], { deadline: 1000 })
|
||||
expect(r.error.code).toBe("expired_token")
|
||||
expect(r.calls).toBe(0)
|
||||
expect(r.waits).toEqual([1000])
|
||||
})
|
||||
|
||||
test("a pending response resets the consecutive-failure budget", async () => {
|
||||
const r = await poll([reset(), reset(), reset(), { status: 400, body: { error: "authorization_pending" } }, reset(), success()])
|
||||
expect(r.error).toBeUndefined()
|
||||
expect(r.calls).toBe(6)
|
||||
expect(r.waits).toEqual([3000, 6000, 12000, 24000, 3000, 6000])
|
||||
})
|
||||
|
||||
test("slow_down increases the normal interval after a retry", async () => {
|
||||
const r = await poll([reset(), { status: 400, body: { error: "slow_down" } }, success()])
|
||||
expect(r.error).toBeUndefined()
|
||||
expect(r.waits).toEqual([3000, 6000, 8000])
|
||||
})
|
||||
|
||||
for (const readError of [reset(), Object.assign(new Error("timeout"), { name: "TimeoutError" })]) {
|
||||
test(`a response body ${readError.code ?? readError.name} can recover`, async () => {
|
||||
const r = await poll([{ readError }, success()])
|
||||
expect(r.error).toBeUndefined()
|
||||
expect(r.calls).toBe(2)
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user