diff --git a/packages/qoder/README.md b/packages/qoder/README.md index d94c739..238415a 100644 --- a/packages/qoder/README.md +++ b/packages/qoder/README.md @@ -68,6 +68,14 @@ Refreshing: - Only one refresh runs at a time. A request that reads the sign-in before magpie saved a renewal uses the renewed pair, and a renewal handed a pair a request already spent gives what that request got. +- A job token's end is what Qoder says: `expire_time` or `expires_at` (a + date, or an epoch in seconds or milliseconds), then `expires_in` + (milliseconds), then a day. +- A chat Qoder answers 401 or 403 with no other code ("Login expired") is + sent again once: with the pair saved since, when another request, magpie + or another process renewed it meanwhile, else after one refresh, under the + same lock. A token renewed less than 5 minutes ago and refused again isn't + renewed again; the refusal is the answer. - The device token, which reads usage, has no end on record: it is rotated when Qoder refuses it. On a [Qoder CN](#qoder-cn) device-token account it is the chat token too, and is renewed as above. diff --git a/packages/qoder/busy.test.mjs b/packages/qoder/busy.test.mjs index 8a2c9fe..80b3cf3 100644 --- a/packages/qoder/busy.test.mjs +++ b/packages/qoder/busy.test.mjs @@ -82,8 +82,8 @@ test("Qoder's other codes on a 403 aren't a lapsed sign-in either; 105 and no co expect(f(code, "credits used up")).toEqual({ status: 429, message: "usage limit reached: credits used up", signIn: "" }) for (const code of ["406", "416", "430", "80411", "80412", "100400", "100401", "100403"]) expect(f(code, "no")).toEqual({ status: 400, message: `Qoder refused the request (${code}): no`, signIn: "" }) - expect(f("105", "login expired")).toEqual({ status: 401, message: "the sign-in lapsed — sign in again (Qoder said 403: login expired)" }) - expect(_internal.failure(403, "")).toEqual({ status: 401, message: "the sign-in lapsed — sign in again" }) + expect(f("105", "login expired")).toEqual({ status: 401, message: "the sign-in lapsed — sign in again (Qoder said 403: login expired)", lapsed: true }) + expect(_internal.failure(403, "")).toEqual({ status: 401, message: "the sign-in lapsed — sign in again", lapsed: true }) }) test("a BOM in an SSE error body must not turn a resource limit into expired auth", async () => { diff --git a/packages/qoder/index.mjs b/packages/qoder/index.mjs index 8fb9bf4..7f86d16 100644 --- a/packages/qoder/index.mjs +++ b/packages/qoder/index.mjs @@ -56,6 +56,7 @@ const SIGN_IN_TIMEOUT = 15 * 60 * 1000 const REFRESH_LEAD = 5 * 60 * 1000 // a chat token this close to its end is refreshed before a request const RENEW_LEAD = 10 * 60 * 1000 // and this close, magpie renews it ahead of time (auth.refresh) const KEEP_SPENT_MS = 60 * 60 * 1000 // how long what a spent refresh token gave is remembered +const RELOGIN_GAP = 5 * 60 * 1000 // a token renewed this recently that Qoder refuses isn't renewed again const DAY = 24 * 60 * 60 * 1000 const CHAT = "@ai-sdk/openai-compatible" @@ -234,9 +235,33 @@ async function openapi(site, path, { method = "GET", token, body, query } = {}) return { status: res.status, json, text } } -// expiresAt is when a job token Qoder gave with expires_in (milliseconds) -// runs out; a day when it said none. -const expiresAt = (jt) => Date.now() + (jt.expires_in > 0 ? jt.expires_in : DAY) +// expiresAt is when a job token Qoder gave runs out, read as Qoder's own +// client reads it, for a refreshed token as for an exchanged PAT's: its +// expire_time or expires_at first (a date, or an epoch in seconds or +// milliseconds), then expires_in (milliseconds), then a day. A refreshed +// token was read for expires_in alone, so an end Qoder said as a date was +// put down as a day away, and renewed after it had run out (plugins#474). +// An end already past is no end said. +function expiresAt(jt) { + for (const k of ["expire_time", "expires_at"]) { + const at = whenSaid(jt?.[k]) + if (at > Date.now()) return at + } + if (jt?.expires_in > 0) return Date.now() + jt.expires_in + return Date.now() + DAY +} + +// whenSaid is the time a token's end field names, in milliseconds: a date, +// or an epoch in seconds or milliseconds; 0 for none (absent, 0, unreadable). +function whenSaid(v) { + if (typeof v === "number" || /^\d+$/.test(String(v ?? "").trim())) { + const n = Number(v) + if (!(n > 0)) return 0 + return n < 1e12 ? n * 1000 : n + } + const at = Date.parse(String(v ?? "").trim()) + return isNaN(at) ? 0 : at +} // deviceExpiry is when a device token used for chat runs out: its // expires_at (a date) or expires_in (seconds), as Qoder's CLI reads it; a @@ -382,18 +407,6 @@ async function deviceSignIn(site) { } } -// exchangeExpiry is when a job token from /api/v1/jobToken/exchange runs -// out, as Qoder's own client reads it: expire_time or expires_at (a date) -// first, then expires_in (milliseconds), then a day. -function exchangeExpiry(jt) { - for (const k of ["expire_time", "expires_at"]) { - const at = Date.parse(String(jt?.[k] ?? "").trim()) - if (!isNaN(at)) return at - } - if (jt?.expires_in > 0) return Date.now() + jt.expires_in - return Date.now() + DAY -} - // exchangeToken is the job token from an exchange response, as Qoder's // client reads it: token, device_token or access_token. function exchangeToken(jt) { @@ -413,7 +426,7 @@ async function patSignIn(site, pat) { const token = exchangeToken(r.json) if (!token) throw new Error(`${site.name} PAT exchange: empty token in response`) const refresh = String(r.json?.refresh_token ?? r.json?.refreshToken ?? "").trim() - const chat = { access: token, refresh, expires: exchangeExpiry(r.json) } + const chat = { access: token, refresh, expires: expiresAt(r.json) } let email = "" let name = "" let uid = "" @@ -1185,9 +1198,11 @@ function failure(status, text) { // lapsed: only a refused refresh did (errorResponse says kept). Qoder's // own words go with it: a 401 right after signing in isn't a lapsed // sign-in, and its reason is what says what is (Yayoi_no_yume on X). + // lapsed: the job token the call carried was refused, which the loader + // renews once and asks again with (plugins#474) before it says so. if (status === 401 || status === 403) { const said = msg && msg !== STATUS_CODES[status] ? ` (Qoder said ${status}: ${msg.slice(0, 300)})` : "" - return { status: 401, message: "the sign-in lapsed — sign in again" + said } + return { status: 401, message: "the sign-in lapsed — sign in again" + said, lapsed: true } } if (status === 429 || msg.toLowerCase().includes("quota")) return { status: 429, message: "usage limit reached: " + msg } return { status, message: msg } @@ -2501,6 +2516,32 @@ const makePlugin = (site) => async ({ client }) => { return next }) + // relogin is the account to ask again with once Qoder refused the job + // token refused (a chat's 401/403 "Login expired"), or undefined to say + // the refusal as it is. Under the lock, as fresh: the sign-in as saved + // now (another request, magpie's auth.refresh or another process may + // have renewed it meanwhile, and then that is what is used, with no + // refresh), else the job token renewed once and saved. Qoder has been + // seen to refuse a job token it had put down as a day away for minutes + // before magpie renewed it (plugins#474), and a request then failed + // until the renewal came. A token this process renewed only minutes ago + // that is refused too isn't renewed again: a refusal that isn't about the + // token's end would otherwise spend a refresh token on every request. + const relogin = (getAuth, refused) => + locked(async () => { + const stored = await getAuth() + if (stored?.type !== "oauth" || !stored.access || !stored.uid) throw new SignInGone(`${site.name}: not signed in`) + siteOf(site, stored) + const a = latest(stored) + if (a.access !== refused) return a + const now = Date.now() + for (const v of spent.values()) if (v.got.access === refused && now - v.at < RELOGIN_GAP) return undefined + const next = { ...a, ...(await renew(a)) } + await client.auth.set({ path: { id: ID }, body: next }) + renewals.add(next) + return next + }) + const models = async (cred, again = false) => { const key = listingKey(cred) let l = listings.get(key) @@ -2737,7 +2778,10 @@ const makePlugin = (site) => async ({ client }) => { }) // ask is the answer to a chat completion on the live account cred. - const ask = async (chat, cred, init, named = "", fallback = false) => { + // asked is what ask asked with: the account it ended on, which a refused + // job token's renewal (relogin, given getAuth) changes. + const ask = async (chat, cred, init, named = "", fallback = false, getAuth, asked = {}) => { + asked.cred = cred let m try { m = (await models(cred)).find((x) => x.key === chat.model) ?? (await models(cred, true)).find((x) => x.key === chat.model) @@ -2760,8 +2804,9 @@ const makePlugin = (site) => async ({ client }) => { // resend can be queued again before it is answered. const deadline = QUEUE.now() + QUEUE.budget const ask = { requestSetId: body.request_set_id, requestId: body.request_id, sessionId: body.session_id, modelKey: m.key } - for (let waited = 0; ; waited++) { - if (waited) { + let relogged = false + for (let sent = 0, waited = 0; ; sent++) { + if (sent) { body.request_id = body.chat_record_id = randomUUID() ask.requestId = body.request_id } @@ -2781,6 +2826,21 @@ const makePlugin = (site) => async ({ client }) => { } const f = !res.ok ? failure(res.status, (await res.text()).slice(0, 1 << 20)) : open.first.value?.error if (f) call.abort() + // a refused job token: renewed once (or the one renewed meanwhile) + // and the request sent again, before the refusal is said + if (f?.lapsed && getAuth && !relogged) { + relogged = true + let next + try { + next = await relogin(getAuth, cred.access) + } catch (e) { + return signedInError(e) + } + if (next) { + cred = asked.cred = next + continue + } + } // an answered call moves its task on, as Qoder's client moves it if (!f) task.answered = true // with another account, provider or group member after this one @@ -2792,6 +2852,7 @@ const makePlugin = (site) => async ({ client }) => { } catch (e) { return errorResponse({ status: 502, message: e?.message ?? String(e) }) } + waited++ } } @@ -2860,7 +2921,9 @@ const makePlugin = (site) => async ({ client }) => { } const h = new Headers(input instanceof Request ? input.headers : undefined) new Headers(init.headers ?? {}).forEach((v, k) => h.set(k, v)) - return signed(await ask(chat, cred, init, h.get(SESSION)?.trim().slice(0, 128) ?? "", h.get(FALLBACK) === "1"), renewed(cred)) + const asked = {} + const res = await ask(chat, cred, init, h.get(SESSION)?.trim().slice(0, 128) ?? "", h.get(FALLBACK) === "1", getAuth, asked) + return signed(res, renewed(cred) || (asked.cred !== cred && renewed(asked.cred))) }, } }, diff --git a/packages/qoder/lapsed.test.mjs b/packages/qoder/lapsed.test.mjs new file mode 100644 index 0000000..8d331a1 --- /dev/null +++ b/packages/qoder/lapsed.test.mjs @@ -0,0 +1,201 @@ +// plugins#474 (ahang39): international Qoder answered dfmodel with 403 +// "Login expired" in bursts of ~16 requests over 2–5 minutes, about every +// 24 hours, through magpie's 401 "the sign-in lapsed". The burst began as +// the job token's renewal came due (its saved end less magpie's 10-minute +// lead) and ended once a renewed pair was saved: Qoder refused the job +// token while the plugin still had it as minutes from its end, and nothing +// asked again with a renewed one. +// +// The fake Qoder here keeps its own books: each job token has its own end, +// a refresh token is spent once and the job token it paired with is refused +// from then on, and a chat names its job token inside the COSY envelope, +// which the fake opens with the private half of a key the test puts in place +// of Qoder's. A refused chat is a 403 {"message":"Login expired"}, the +// words the reporter's 401 quotes; its code and the rest of its body aren't +// in the report, so none is sent. +import { afterEach, beforeEach, expect, setSystemTime, test } from "bun:test" +import { constants, createDecipheriv, generateKeyPairSync, privateDecrypt } from "node:crypto" +import { QoderAuthPlugin, _internal } from "./index.mjs" + +const real = globalThis.fetch +const site = _internal.SITES.qoder +const { publicKey, privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 }) +beforeEach(() => (site.rsaKey = publicKey.export({ type: "spki", format: "pem" }))) +afterEach(() => { + globalThis.fetch = real + delete site.rsaKey + setSystemTime() +}) + +const HOUR = 3_600_000 +const json = (v, status = 200) => new Response(JSON.stringify(v), { status, headers: { "Content-Type": "application/json" } }) +const line = (body) => `data:${JSON.stringify({ headers: {}, body: JSON.stringify(body), statusCodeValue: 200 })}\n\n` +const answered = () => + new Response(line({ choices: [{ delta: { content: "hello" } }] }) + line({ choices: [{ delta: {}, finish_reason: "stop" }] }) + `data:${JSON.stringify({ headers: {}, body: "[DONE]", statusCodeValue: 200 })}\n\n`, { + headers: { "Content-Type": "text/event-stream" }, + }) +const LISTING = { chat: [{ key: "dfmodel", display_name: "DeepSeek Flash", enable: true }] } +const CHAT = "https://api3.qoder.sh/v1/chat/completions" +const chat = () => ({ method: "POST", body: JSON.stringify({ model: "dfmodel", messages: [{ role: "user", content: "hi" }] }) }) + +// tokenOf is the job token a COSY-signed call carries +function tokenOf(headers) { + // PKCS#1 v1.5 padding taken off by hand: Bun no longer decrypts with it + const block = privateDecrypt({ key: privateKey, padding: constants.RSA_NO_PADDING }, Buffer.from(headers["Cosy-Key"], "base64")) + const key = block.subarray(block.indexOf(0, 2) + 1) + const [payload] = headers.Authorization.slice("Bearer COSY.".length).split(".") + const { info } = JSON.parse(Buffer.from(payload, "base64").toString()) + const d = createDecipheriv("aes-128-cbc", key, key) + return JSON.parse(Buffer.concat([d.update(Buffer.from(info, "base64")), d.final()]).toString()).security_oauth_token +} + +// qoder is the fake: live job tokens by their end, refresh tokens by the job +// token they pair with. life is a renewed token's lifetime; said is how the +// refresh says its end (expires_in, expire_time, or nothing). +function qoder({ life = 24 * HOUR, said = "expires_in", refuseAll = false, refuseRefresh = false, onRefused } = {}) { + const live = new Map([["jt-1", Date.now() + life]]) + const pairs = new Map([["jrt-1", "jt-1"]]) + const calls = { refresh: [], chats: [] } + let n = 1 + globalThis.fetch = async (url, init = {}) => { + const u = new URL(String(url)) + if (u.pathname === "/api/v1/jobToken/refresh") { + const rt = JSON.parse(init.body).refresh_token + calls.refresh.push(rt) + if (refuseRefresh || !pairs.has(rt)) return json({ message: "invalid refresh token" }, 401) + live.delete(pairs.get(rt)) + pairs.delete(rt) + n++ + const end = Date.now() + life + live.set(`jt-${n}`, end) + pairs.set(`jrt-${n}`, `jt-${n}`) + const at = + said === "expires_in" ? { expires_in: life } : said === "expire_time" ? { expire_time: new Date(end).toISOString() } : said === "epoch" ? { expires_at: Math.floor(end / 1000) } : {} + return json({ token: `jt-${n}`, refresh_token: `jrt-${n}`, ...at }) + } + if (u.pathname.endsWith("/model/list")) return json(LISTING) + const t = tokenOf(init.headers) + calls.chats.push(t) + if (refuseAll || !(live.get(t) > Date.now())) { + await onRefused?.(t) + return json({ message: "Login expired" }, 403) + } + return answered() + } + return { live, calls } +} + +// account is the plugin's view: what magpie saved, through client.auth.set, +// read back as a copy as magpie's getAuth gives it +async function account(over = {}) { + const box = { stored: { type: "oauth", access: "jt-1", refresh: "jrt-1", expires: Date.now() + 24 * HOUR, accountId: "one@x", uid: "u1", machineId: "m1", ...over } } + const hooks = await QoderAuthPlugin({ client: { auth: { set: async ({ body }) => (box.stored = { ...body }) } } }) + const l = await hooks.auth.loader(async () => box.stored) + return { hooks, fetch: l.fetch, box } +} + +test("a job token Qoder refuses as Login expired before its saved end is renewed once and the request asked again", async () => { + const q = qoder() + q.live.set("jt-1", Date.now() - 1) // Qoder's end came first + const a = await account({ expires: Date.now() + 9 * 60_000 }) // inside neither lead + const res = await a.fetch(CHAT, chat()) + expect(res.status).toBe(200) + expect((await res.json()).choices[0].message.content).toBe("hello") + expect(res.headers.get("X-Magpie-Sign-In")).toBe("renewed") + expect(q.calls.refresh).toEqual(["jrt-1"]) + expect(q.calls.chats).toEqual(["jt-1", "jt-2"]) + expect(a.box.stored).toMatchObject({ access: "jt-2", refresh: "jrt-2" }) +}) + +test("a burst of requests on a refused job token spends its refresh token once, and every one is answered", async () => { + const q = qoder() + q.live.delete("jt-1") + const a = await account() + const res = await Promise.all(Array.from({ length: 16 }, () => a.fetch(CHAT, chat()))) + expect(res.map((r) => r.status)).toEqual(Array(16).fill(200)) + expect(q.calls.refresh).toEqual(["jrt-1"]) + expect(a.box.stored.access).toBe("jt-2") +}) + +test("a sign-in renewed elsewhere while the request was out is asked again with, spending no refresh token", async () => { + let a + const q = qoder({ + // another process saved a renewed pair: what magpie's store now says + onRefused: async () => { + q.live.set("jt-9", Date.now() + HOUR) + a.box.stored = { ...a.box.stored, access: "jt-9", refresh: "jrt-9", expires: Date.now() + HOUR } + }, + }) + q.live.delete("jt-1") + a = await account() + const res = await a.fetch(CHAT, chat()) + expect(res.status).toBe(200) + expect(q.calls.refresh).toEqual([]) + expect(q.calls.chats).toEqual(["jt-1", "jt-9"]) +}) + +test("magpie's own renewal, begun as a request meets the refusal, is waited for and not spent again", async () => { + let a, renewal + // magpie's auth.refresh starts while the refused chat is answered, before + // the request asks for a renewal of its own; magpie hasn't saved it yet + const q = qoder({ onRefused: () => void (renewal ??= a.hooks.auth.refresh({ ...a.box.stored })) }) + q.live.delete("jt-1") + a = await account() + const res = await a.fetch(CHAT, chat()) + expect(await renewal).toMatchObject({ access: "jt-2", refresh: "jrt-2" }) + expect(res.status).toBe(200) + expect(q.calls.refresh).toEqual(["jrt-1"]) + expect(q.calls.chats).toEqual(["jt-1", "jt-2"]) +}) + +test("a refusal a renewal doesn't end is said once renewed, and a token renewed minutes ago isn't renewed again", async () => { + const q = qoder({ refuseAll: true }) + const a = await account() + const one = await a.fetch(CHAT, chat()) + expect(one.status).toBe(401) + expect((await one.json()).error.message).toContain("Login expired") + expect(q.calls.refresh).toEqual(["jrt-1"]) + const two = await a.fetch(CHAT, chat()) + expect(two.status).toBe(401) + expect(two.headers.get("X-Magpie-Sign-In")).toBe("kept") + expect(q.calls.refresh).toEqual(["jrt-1"]) + expect(q.calls.chats).toEqual(["jt-1", "jt-2", "jt-2"]) +}) + +test("a refused job token whose refresh Qoder turns away says the sign-in expired", async () => { + qoder({ refuseAll: true, refuseRefresh: true }) + const a = await account() + const res = await a.fetch(CHAT, chat()) + expect(res.status).toBe(401) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("expired") +}) + +for (const said of ["expire_time", "epoch"]) { + test(`a renewed job token's end Qoder says as ${said} is the end magpie renews it before`, async () => { + qoder({ life: 2 * HOUR, said }) + const a = await account({ expires: Date.now() + 60_000 }) + const got = await a.hooks.auth.refresh(a.box.stored) + expect(Math.abs(got.expires - (Date.now() + 2 * HOUR))).toBeLessThan(2_000) + }) +} + +// magpie's host, as host.js renews: before a request, an account whose end +// less the plugin's refreshLead has come is renewed through auth.refresh and +// what it gives saved. Driven across a day of Qoder's 23h tokens, said only +// as expire_time, no request is refused. +test("across a day, a token Qoder says ends at expire_time is renewed before it ends and no request is refused", async () => { + const start = Date.now() + const q = qoder({ life: 23 * HOUR, said: "expire_time" }) + const a = await account({ expires: start + 60_000 }) + const host = async () => { + if (Date.now() >= a.box.stored.expires - a.hooks.auth.refreshLead) Object.assign(a.box.stored, await a.hooks.auth.refresh(a.box.stored)) + } + const statuses = [] + for (let t = 0; t <= 48 * HOUR; t += 13 * 60_000) { + setSystemTime(new Date(start + t)) + await host() + statuses.push((await a.fetch(CHAT, chat())).status) + } + expect(statuses.filter((s) => s !== 200)).toEqual([]) + expect(q.calls.chats.length).toBe(statuses.length) // none asked twice +}, 30_000) diff --git a/packages/qoder/package.json b/packages/qoder/package.json index 41d7e69..edb0f1e 100644 --- a/packages/qoder/package.json +++ b/packages/qoder/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-qoder-auth", - "version": "0.2.47", + "version": "0.2.48", "description": "Qoder and QwenWork (千问办公) subscriptions in OpenCode and magpie: qoder.com, qoder.cn, gateway.qwenwork.cn and the enterprise flagship (VPC)", "type": "module", "main": "./index.mjs", diff --git a/packages/qoder/usage.test.mjs b/packages/qoder/usage.test.mjs index 3042bb1..71c5b42 100644 --- a/packages/qoder/usage.test.mjs +++ b/packages/qoder/usage.test.mjs @@ -177,16 +177,23 @@ test("pools in different units are not added up", () => { // the loader's fetch, as OpenCode's engine calls it, against a listing and // a chat reply +// a refresh is answered with a new pair, counted in refreshes: a refused +// job token is renewed once before the refusal is said (plugins#474) async function chat(listing, reply) { const auth = { ...account(), machineId: "m1", name: "One" } - globalThis.fetch = async (url) => { + const refreshes = [] + globalThis.fetch = async (url, init = {}) => { const u = new URL(String(url)) if (u.pathname.endsWith("/model/list")) return json(listing) + if (u.pathname === "/api/v1/jobToken/refresh") { + refreshes.push(JSON.parse(init.body).refresh_token) + return json({ token: "jt-two", refresh_token: "rt-two", expires_in: 3_600_000 }) + } return reply() } const hooks = await QoderAuthPlugin({ client: { auth: { set: async () => {} } } }) const l = await hooks.auth.loader(async () => auth) - return { fetch: l.fetch, hooks, auth } + return { fetch: l.fetch, hooks, auth, refreshes } } const LISTING = { @@ -200,25 +207,29 @@ const LISTING = { const ASK = { method: "POST", body: JSON.stringify({ model: "qmodel", messages: [{ role: "user", content: "hi" }] }) } +// Refused again after the one renewal a refusal gets: the job token was +// renewed (the account's mark comes off, as the built-in's renewal took it +// off), and the refusal is said as the built-in's 401, never "expired". test("a refused chat, 401 or 403, is the built-in's 401 and leaves the account unmarked", async () => { for (const status of [401, 403]) { - const { fetch } = await chat(LISTING, () => new Response("", { status })) + const { fetch, refreshes } = await chat(LISTING, () => new Response("", { status })) const res = await fetch(API_CHAT, ASK) expect(res.status).toBe(401) - expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") + expect(res.headers.get("X-Magpie-Sign-In")).toBe("renewed") expect((await res.json()).error.message).toBe("the sign-in lapsed — sign in again") + expect(refreshes).toEqual(["rt-one"]) } // what Qoder says of the refusal is kept: a 401 just after signing in // has some other reason, and only Qoder's words tell it const said = await chat(LISTING, () => new Response(JSON.stringify({ message: "device not trusted" }), { status: 401 })) const r = await said.fetch(API_CHAT, ASK) - expect([r.status, r.headers.get("X-Magpie-Sign-In")]).toEqual([401, "kept"]) + expect([r.status, r.headers.get("X-Magpie-Sign-In")]).toEqual([401, "renewed"]) expect((await r.json()).error.message).toBe("the sign-in lapsed — sign in again (Qoder said 401: device not trusted)") // refused in the stream, before any answer: the same const sse = (v) => new Response(`data: ${JSON.stringify(v)}\n\n`, { headers: { "Content-Type": "text/event-stream" } }) const { fetch } = await chat(LISTING, () => sse({ statusCodeValue: 403, body: "" })) const res = await fetch(API_CHAT, ASK) - expect([res.status, res.headers.get("X-Magpie-Sign-In")]).toEqual([401, "kept"]) + expect([res.status, res.headers.get("X-Magpie-Sign-In")]).toEqual([401, "renewed"]) }) test("other refusals keep their status and say nothing of the sign-in", async () => {