Files
yetone 1c9ade6c81 loomy 0.1.12: a 401/403 from a proxy no longer signs an account out
jenxingyoung on X: four Loomy accounts behind a proxy, a different one
signed out each day, none used anywhere else.

Loomy's gateway never answers a dead session with a 401 or 403. A made-up,
dropped or missing token gets HTTP 200 with code 100002 on every path
(chat, draw, models, points records, first-login; probed 2026-11-16 and
2026-11-17). The plugin still read any 401/403 as "signed out": chat and
draw returned a bare 401 (magpie's host marks the account lapsed on that),
and usage and check-in threw an expired error. So a proxy or firewall
turning one request away marked a good account for sign-in again, a
different account each time.

- 401/403 is a sign-in verdict only when its body carries 020002/100002.
  Otherwise chat and draw answer 502 with x-magpie-sign-in: kept (magpie
  tries the next account and leaves this one signed in), usage reports
  the error with signIn "kept", check-in reports "failed". The message
  names the status, says it isn't a sign-out, and quotes the body.
- A lapsed account's message gives the day it was signed in (signedInAt,
  kept at SMS sign-in; older accounts from expires - 14 days). No
  lifetime is claimed: the client asks for 14 days, but agent2api found
  sessions served past that.
- SMS sign-in returns uid (the vendor's userid) beside the masked phone.
- A pasted session is named by its last six characters instead of the
  one name "手动粘贴" every paste shared, which made a second pasted
  account replace the first in magpie's account list.

No renewal exists to add: Loomy's client 0.9.39, its web app,
magpie-providers-hub and agent2api only sign in again. A truly lapsed
account still needs an SMS code; magpie's "Sign in again" on the row is
one click.

Run (mote, HEAD afe4c086 + this change):
- HOME=<temp> bun test packages/loomy: 46 pass, 0 fail.
- HOME=$(mktemp -d) bun test (root): packages/loomy 46 pass, 0 fail.
  Other packages red on mote only (7910 pass, 563 fail: kimi-desktop,
  zen-free, inkstone, zcode, qoder ...), none touched here; CI's test
  job is green at afe4c086 on ubuntu. bun scripts/check.mjs: ok.
Broken by hand: index.mjs at afe4c086 with the new tests and fake: 9 of
the 10 new or changed tests fail (37 pass, 9 fail). The pasted-session
"names no day" test is a guard and passes on both.
Not tried: a real Loomy account (none here), so the session's real
lifetime is unmeasured, and the user's proxy's actual 401/403 body is
not seen; the fix holds for any body without a sign-in code.
2026-11-17 10:08:33 +08:00

726 lines
35 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { describe, test, expect, beforeAll, afterAll, beforeEach } from "bun:test"
import { LoomyAuthPlugin, _internal } from "./index.mjs"
import { fakeLoomy } from "./fake.mjs"
// every test runs against the fake upstream in fake.mjs: no network, no real
// token ever leaves this process
let fake
let plugin
let saved = {}
const client = { auth: { set: async ({ body }) => (saved = body) } }
const getAuth = async () => saved
beforeAll(async () => {
fake = fakeLoomy()
process.env.LOOMY_POINTS_BASE_URL = fake.gatewayUrl
process.env.LOOMY_XFYUN_BASE_URL = fake.accountUrl
})
afterAll(() => {
fake.account.stop(true)
fake.gateway.stop(true)
})
beforeEach(async () => {
fake.state.reset()
saved = { type: "oauth", access: fake.state.session, expires: 0, accountId: "138****8000", name: "138****8000", source: "manual" }
plugin = await LoomyAuthPlugin({ client })
})
describe("sign-in methods", () => {
test("SMS: sends the code, then trades it for a 14-day session", async () => {
const method = plugin.auth.methods.find((m) => m.label.includes("SMS"))
const flow = await method.authorize({ phone: "138 0013 8000" }) // spaces tolerated
expect(flow.method).toBe("code")
expect(flow.instructions).toContain("已发送")
expect(fake.state.smsSent).toBeTruthy()
// wrong code fails with a reason
expect((await flow.callback("000000")).type).toBe("failed")
const result = await flow.callback("123456")
expect(result.type).toBe("success")
expect(result.access).toBe("sess-1")
expect(result.expires).toBeGreaterThan(Date.now() + 13 * 86400e3)
expect(result.accountId).toBe("138****8000")
// the vendor's user id beside the masked phone, so two phones masked
// alike stay two accounts in magpie's host; and when it was signed in
expect(result.uid).toBe("261014155255771375")
expect(Math.abs(result.signedInAt - Date.now())).toBeLessThan(60e3)
})
test("SMS: an invalid phone is refused before anything is sent", async () => {
const method = plugin.auth.methods.find((m) => m.label.includes("SMS"))
const bad = await method.authorize({ phone: "12345" })
expect(bad.type).toBe("failed")
expect(fake.state.smsSent).toBeNull()
})
test("manual paste works through the host's authorize → callback contract", async () => {
const method = plugin.auth.methods.find((m) => m.label.includes("Paste"))
const flow = await method.authorize({ session: "pasted" })
expect(flow.method).toBe("auto")
expect(typeof flow.callback).toBe("function")
const result = await flow.callback()
expect(result.type).toBe("success")
expect(result.access).toBe("pasted")
expect(await method.authorize({ session: "" })).toMatchObject({ type: "failed" })
})
// magpie's host keeps one account per accountId: one name for every paste
// put a second pasted account over the first
test("two pasted sessions are two accounts", async () => {
const method = plugin.auth.methods.find((m) => m.label.includes("Paste"))
const one = await (await method.authorize({ session: "session-aaaaaa111111" })).callback()
const two = await (await method.authorize({ session: "session-bbbbbb222222" })).callback()
expect(one.accountId).not.toBe(two.accountId)
expect(one.accountId).toContain("111111")
expect(one.accountId).not.toContain("session-aaaaaa")
})
})
// The real gateway refuses a session with HTTP 200 and code 100002 on every
// path, never with a 401 or 403 (measured 2026-11-16 and 2026-11-17). A 401
// or 403 without that code came from a proxy or firewall on the way, and
// read as "signed out" it marked a good account for sign-in again
// (jenxingyoung on X: four accounts on a proxy, a different one dropped
// each day).
describe("a 401 or 403 from something on the way", () => {
const waf = (status) => ({ status, type: "text/html", body: "<html><body>403 Forbidden - Access denied</body></html>" })
test("a chat or a draw fails this try and leaves the sign-in as it is", async () => {
for (const status of [401, 403]) {
fake.state.denied = waf(status)
const loader = await plugin.auth.loader(getAuth)
for (const [path, body] of [
["/api/v1/chat/completions", JSON.stringify({ model: "spark-x", stream: true, messages: [{ role: "user", content: "hi" }] })],
["/api/v1/images/generations", JSON.stringify({ model: "doubao-seedream-5-lite", prompt: "a cat" })],
]) {
const res = await loader.fetch(`${fake.gatewayUrl}${path}`, { method: "POST", body })
expect(res.status).toBe(502)
expect(res.headers.get("x-magpie-sign-in")).toBe("kept")
const msg = (await res.json()).error.message
expect(msg).toContain(`HTTP ${status}`)
expect(msg).toContain("不是登录失效")
expect(msg).toContain("Access denied")
}
}
})
test("one that carries the sign-in code still says the sign-in expired", async () => {
fake.state.denied = { status: 401, type: "application/json", body: JSON.stringify({ code: "100002", desc: "登录已失效,请重新登录" }) }
const loader = await plugin.auth.loader(getAuth)
const res = await loader.fetch(`${fake.gatewayUrl}/api/v1/chat/completions`, {
method: "POST",
body: JSON.stringify({ model: "spark-x", stream: true, messages: [{ role: "user", content: "hi" }] }),
})
expect(res.status).toBe(401)
expect(res.headers.get("x-magpie-sign-in")).toBe("expired")
const usage = await plugin.auth.usage(getAuth)
expect(usage.signIn).toBe("expired")
expect(usage.error).toContain("登录已失效")
})
test("a usage read is an error that keeps the sign-in", async () => {
for (const status of [401, 403]) {
fake.state.denied = waf(status)
const usage = await plugin.auth.usage(getAuth)
expect(usage.signIn).toBe("kept")
expect(usage.error).toContain(`HTTP ${status}`)
expect(usage.error).toContain("不是登录失效")
}
})
test("a check-in fails, it doesn't say the sign-in expired", async () => {
fake.state.denied = waf(403)
const result = await plugin.auth.checkin(getAuth)
expect(result.outcome).toBe("failed")
expect(result.message).toContain("HTTP 403")
})
})
describe("a lapsed account says when it was signed in", () => {
// 2026-11-03 10:00 Beijing
const at = Date.UTC(2026, 10, 3, 2, 0, 0)
test("from the time an SMS sign-in kept", async () => {
saved = { type: "oauth", access: "dropped", expires: at + 14 * 86400e3, signedInAt: at, accountId: "138****8000" }
const usage = await plugin.auth.usage(getAuth)
expect(usage.signIn).toBe("expired")
expect(usage.error).toContain("11 月 3 日")
const loader = await plugin.auth.loader(getAuth)
const res = await loader.fetch(`${fake.gatewayUrl}/api/v1/chat/completions`, {
method: "POST",
body: JSON.stringify({ model: "spark-x", stream: true, messages: [{ role: "user", content: "hi" }] }),
})
expect(res.status).toBe(401)
expect((await res.json()).error.message).toContain("11 月 3 日")
})
test("from the 14-day end of an account signed in before 0.1.12", async () => {
saved = { type: "oauth", access: "dropped", expires: at + 14 * 86400e3, accountId: "138****8000" }
expect((await plugin.auth.usage(getAuth)).error).toContain("11 月 3 日")
})
test("a pasted session, whose day isn't known, names none", async () => {
saved = { type: "oauth", access: "dropped", expires: 0, accountId: "手动粘贴 ···ropped" }
const usage = await plugin.auth.usage(getAuth)
expect(usage.signIn).toBe("expired")
expect(usage.error).not.toContain("月")
})
})
describe("chat", () => {
test("forwards with the double auth headers and streams through", async () => {
const loader = await plugin.auth.loader(getAuth)
const res = await loader.fetch(`${fake.gatewayUrl}/api/v1/v1/chat/completions`.replace("/v1/v1/", "/api/v1/"), {
method: "POST",
body: JSON.stringify({ model: "spark-x", stream: true, messages: [{ role: "user", content: "hi" }] }),
})
expect(res.status).toBe(200)
const text = await res.text()
expect(text).toContain('"content":"你"')
expect(text).toContain("data: [DONE]")
expect(fake.state.chatCalls.length).toBe(1)
expect(fake.state.chatCalls[0].body.model).toBe("spark-x")
})
test("a genuinely over-length Kimi-k2.6 request still comes back 400", async () => {
// 150 万 ASCII 字符 ≈ 37.5 万 token,对 262,144 窗口的 Kimi-k2.6 是真超长。
// 旧实现按固定 200 万字符阈值判成「上游瞬时故障」并改成 502,magpie 会换号重试到整轮失败。
fake.state.chatRefusal = "内容太长了,请精简输入或开启新对话"
const loader = await plugin.auth.loader(getAuth)
const huge = "word ".repeat(300_000)
const res = await loader.fetch(`${fake.gatewayUrl}/api/v1/chat/completions`, {
method: "POST",
body: JSON.stringify({ model: "kimi-k2.6", stream: false, messages: [{ role: "user", content: huge }] }),
})
expect(res.status).toBe(400)
expect(await res.text()).toContain("上下文超出长度限制")
})
test("reasoning effort folds to low/medium/high", async () => {
const loader = await plugin.auth.loader(getAuth)
await loader.fetch(`${fake.gatewayUrl}/api/v1/chat/completions`, {
method: "POST",
body: JSON.stringify({ model: "spark-x", stream: false, reasoning_effort: "minimal", messages: [] }),
})
await loader.fetch(`${fake.gatewayUrl}/api/v1/chat/completions`, {
method: "POST",
body: JSON.stringify({ model: "spark-x", stream: false, reasoning_effort: "max", messages: [] }),
})
await loader.fetch(`${fake.gatewayUrl}/api/v1/chat/completions`, {
method: "POST",
body: JSON.stringify({ model: "spark-x", stream: false, reasoning_effort: "none", messages: [] }),
})
expect(fake.state.chatCalls[0].body.reasoning_effort).toBe("low")
expect(fake.state.chatCalls[1].body.reasoning_effort).toBe("high")
expect(fake.state.chatCalls[2].body.reasoning_effort).toBeUndefined()
})
test("deepseek images become base64 markers merged into the text", async () => {
const loader = await plugin.auth.loader(getAuth)
await loader.fetch(`${fake.gatewayUrl}/api/v1/chat/completions`, {
method: "POST",
body: JSON.stringify({
model: "deepseek-v4-flash",
stream: false,
messages: [
{ role: "user", content: [
{ type: "text", text: "看这张图" },
{ type: "image_url", image_url: { url: "data:image/png;base64,QUJD" } },
{ type: "image_url", image_url: { url: "https://example.com/x.png" } },
] },
],
}),
})
const content = fake.state.chatCalls[0].body.messages[0].content
expect(content).toHaveLength(2)
expect(content[0].text).toContain("看这张图")
expect(content[0].text).toContain("<image_base64>data:image/png;base64,QUJD</image_base64>")
// an http(s) URL stays as it was (no evidence the marker accepts URLs)
expect(content[1].type).toBe("image_url")
})
test("DeepSeek-V4.1-Flash keeps its image_url parts (plugins#811)", async () => {
const loader = await plugin.auth.loader(getAuth)
const parts = [
{ type: "text", text: "图里写的数字是多少" },
{ type: "image_url", image_url: { url: "data:image/png;base64,QUJD" } },
]
await loader.fetch(`${fake.gatewayUrl}/api/v1/chat/completions`, {
method: "POST",
body: JSON.stringify({ model: "DeepSeek-V4.1-Flash", stream: false, messages: [{ role: "user", content: parts }] }),
})
const content = fake.state.chatCalls[0].body.messages[0].content
expect(content).toEqual(parts)
expect(JSON.stringify(content)).not.toContain("<image_base64>")
})
test("which models get the base64 marker", () => {
// the reporter's ids: V4.1 reads image_url parts, 0731 is the model the
// marker was added for
expect(_internal.prefersTagFormat("DeepSeek-V4.1-Flash")).toBe(false)
expect(_internal.prefersTagFormat("deepseek-v4.1-flash")).toBe(false)
expect(_internal.prefersTagFormat("deepseek-v4-flash-0731")).toBe(true)
expect(_internal.prefersTagFormat("deepseek-v4-flash")).toBe(true)
expect(_internal.prefersTagFormat("loomy/deepseek-v4-flash-0731")).toBe(true)
// plugins#1139: 1017 reads image_url parts (232 vs 7,368 prompt tokens)
expect(_internal.prefersTagFormat("deepseek-v4-flash-1017")).toBe(false)
expect(_internal.prefersTagFormat("DeepSeek-V4-Flash-1017")).toBe(false)
expect(_internal.prefersTagFormat("GLM-5.3-Flash")).toBe(false)
expect(_internal.prefersTagFormat(undefined)).toBe(false)
})
test("a refused session says 401", async () => {
saved = { type: "oauth", access: "gone", expires: 0 }
const loader = await plugin.auth.loader(getAuth)
const res = await loader.fetch(`${fake.gatewayUrl}/api/v1/chat/completions`, {
method: "POST",
body: JSON.stringify({ model: "spark-x", stream: false, messages: [] }),
})
expect(res.status).toBe(401)
})
// the real gateway refuses a dropped session with HTTP 200 and code
// 100002, a stream asked for too; passed through as a 200 it was a
// success to magpie, which took the account's signed-out mark off until
// the next usage read put it back (jenxingyoung on X, "轮着掉登录")
test("a dropped session's 200 with code 100002 is a 401 that says the sign-in expired", async () => {
for (const stream of [true, false]) {
saved = { type: "oauth", access: "dropped", expires: 0 }
const loader = await plugin.auth.loader(getAuth)
const res = await loader.fetch(`${fake.gatewayUrl}/api/v1/chat/completions`, {
method: "POST",
body: JSON.stringify({ model: "spark-x", stream, messages: [{ role: "user", content: "hi" }] }),
})
expect(res.status).toBe(401)
expect(res.headers.get("x-magpie-sign-in")).toBe("expired")
expect((await res.json()).error.message).toContain("登录已失效")
}
})
test("another business code in a 200 is a 502 with the vendor's words, the sign-in left alone", async () => {
fake.state.chatCode = { code: "100005", desc: "积分不足" }
const loader = await plugin.auth.loader(getAuth)
const res = await loader.fetch(`${fake.gatewayUrl}/api/v1/chat/completions`, {
method: "POST",
body: JSON.stringify({ model: "spark-x", stream: true, messages: [{ role: "user", content: "hi" }] }),
})
expect(res.status).toBe(502)
expect(res.headers.get("x-magpie-sign-in")).toBeNull()
const msg = (await res.json()).error.message
expect(msg).toContain("积分不足")
expect(msg).toContain("100005")
})
test("a completion that isn't streamed comes back whole", async () => {
const loader = await plugin.auth.loader(getAuth)
const res = await loader.fetch(`${fake.gatewayUrl}/api/v1/chat/completions`, {
method: "POST",
body: JSON.stringify({ model: "spark-x", stream: false, messages: [{ role: "user", content: "hi" }] }),
})
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ id: "c1", model: "spark-x", choices: [{ index: 0, message: { role: "assistant", content: "你好" }, finish_reason: "stop" }] })
})
test("only chat completions and image generations are served", async () => {
const loader = await plugin.auth.loader(getAuth)
for (const path of ["/api/v1/embeddings", "/api/v1/images/edits"]) {
const res = await loader.fetch(`${fake.gatewayUrl}${path}`, { method: "POST", body: "{}" })
expect(res.status).toBe(404)
}
expect(fake.state.imageCalls).toHaveLength(0)
})
})
describe("images (#609)", () => {
// the request magpie's gateway writes for a draw (internal/gateway/draw.go
// drawImages), as the reporter sent it by hand
const drawBody = JSON.stringify({ model: "doubao-seedream-5-lite", prompt: "a red apple", n: 1, size: "1024x1024" })
test("a draw goes to /images/generations with the session, asking for JSON", async () => {
const loader = await plugin.auth.loader(getAuth)
const res = await loader.fetch(`${fake.gatewayUrl}/api/v1/images/generations`, { method: "POST", body: drawBody })
expect(res.status).toBe(200)
// the reply is the upstream's own JSON, passed through
expect(await res.text()).toBe('{"created":1793554989,"data":[{"url":"https://aigc-output-image-...png"}],"points_consumed":110}')
expect(fake.state.imageCalls).toHaveLength(1)
const call = fake.state.imageCalls[0]
expect(call.token).toBe(fake.state.session)
expect(call.bearer).toBe(fake.state.session)
expect(call.accept).toBe("application/json")
expect(call.body).toEqual(JSON.parse(drawBody))
expect(fake.state.chatCalls).toHaveLength(0)
})
test("a Request object's body is sent as well", async () => {
const loader = await plugin.auth.loader(getAuth)
const req = new Request(`${fake.gatewayUrl}/api/v1/images/generations`, { method: "POST", body: drawBody })
const res = await loader.fetch(req)
expect(res.status).toBe(200)
expect(fake.state.imageCalls[0].body.model).toBe("doubao-seedream-5-lite")
})
test("a bare 401 or 403 is no sign-in verdict: the vendor's is code 100002", async () => {
for (const status of [401, 403]) {
fake.state.imageStatus = status
const loader = await plugin.auth.loader(getAuth)
const res = await loader.fetch(`${fake.gatewayUrl}/api/v1/images/generations`, { method: "POST", body: drawBody })
expect(res.status).toBe(502)
expect(res.headers.get("x-magpie-sign-in")).toBe("kept")
expect((await res.json()).error.message).toContain(`refused ${status}`)
}
})
test("a dropped session's 200 with code 100002 is a 401 that says the sign-in expired", async () => {
saved = { type: "oauth", access: "dropped", expires: 0 }
const loader = await plugin.auth.loader(getAuth)
const res = await loader.fetch(`${fake.gatewayUrl}/api/v1/images/generations`, { method: "POST", body: drawBody })
expect(res.status).toBe(401)
expect(res.headers.get("x-magpie-sign-in")).toBe("expired")
expect(fake.state.imageCalls).toHaveLength(0)
})
test("another upstream error keeps its status and says what came back", async () => {
fake.state.imageStatus = 400
const loader = await plugin.auth.loader(getAuth)
const res = await loader.fetch(`${fake.gatewayUrl}/api/v1/images/generations`, { method: "POST", body: drawBody })
expect(res.status).toBe(400)
expect((await res.json()).error.message).toContain("refused 400")
})
test("a chat still streams after a draw", async () => {
const loader = await plugin.auth.loader(getAuth)
await loader.fetch(`${fake.gatewayUrl}/api/v1/images/generations`, { method: "POST", body: drawBody })
const res = await loader.fetch(`${fake.gatewayUrl}/api/v1/chat/completions`, {
method: "POST",
body: JSON.stringify({ model: "spark-x", stream: true, messages: [{ role: "user", content: "hi" }] }),
})
expect(res.status).toBe(200)
expect(await res.text()).toContain("data: [DONE]")
expect(fake.state.chatCalls).toHaveLength(1)
expect(fake.state.imageCalls).toHaveLength(1)
})
})
describe("checkin", () => {
test("the day's first call claims the grant, a repeat is done", async () => {
// the daily wallet moves 3000 → 5000 on the day's first call: claimed
const result = await plugin.auth.checkin(getAuth)
expect(result.outcome).toBe("claimed")
expect(result.credit).toBe(2000)
expect(result.message).toContain("5000")
expect(fake.state.firstLoginCalls).toBe(1)
// the endpoint answers success on a repeat too, but the wallet is flat:
// done, not a second claim
const again = await plugin.auth.checkin(getAuth)
expect(again.outcome).toBe("done")
expect(again.credit).toBeUndefined()
expect(fake.state.firstLoginCalls).toBe(2)
})
test("a refused session says the sign-in expired", async () => {
saved = { type: "oauth", access: "gone", expires: 0 }
await expect(plugin.auth.checkin(getAuth)).rejects.toThrow(/失效/)
})
test("a failed pre-read is failed, not silently done", async () => {
const realFetch = globalThis.fetch
globalThis.fetch = (input, init) => {
const url = typeof input === "string" ? input : String(input?.url ?? input)
// fail only the records read; the first-login POST still goes through
if (String(url).includes("/api/v2/points/records")) return new Response("boom", { status: 502 })
return realFetch(input, init)
}
try {
const result = await plugin.auth.checkin(getAuth)
expect(result.outcome).toBe("failed")
expect(result.message).toContain("无法读取签到前余额")
expect(fake.state.firstLoginCalls).toBe(0)
} finally {
globalThis.fetch = realFetch
}
})
})
describe("models", () => {
test("the catalog, with rates split out of the names", async () => {
const p = { models: {} }
const list = await plugin.provider.models(p, { auth: saved })
expect(Object.keys(list)).toEqual(["spark-x", "deepseek-v4-flash", "glm-5.3-flash", "plain"])
expect(list["spark-x"].rate).toBe("x0.1")
expect(list["spark-x"].name).toBe("Spark X2.5")
expect(list["spark-x"].reasoning).toBe(true)
expect(list["spark-x"].tool_call).toBe(true)
expect(list["deepseek-v4-flash"].rate).toBe("x3.0")
expect(list["glm-5.3-flash"].modalities).toEqual({ input: ["text", "image"], output: ["text"] })
expect(list["plain"].rate).toBeUndefined()
expect(list["plain"].name).toBe("No Suffix At All")
expect(list[Symbol.for("magpie.fellBack")]).toBeUndefined()
})
// Archivemylife on X (agy-cli's sibling): a list that isn't the account's
// own, handed back as if it were, dropped the models the user picked
test("a refusal in a 200 gives the static table marked as not the account's", async () => {
fake.state.modelsCode = "100500"
const p = { models: { ..._internal.STATIC_MODELS } }
const list = await plugin.provider.models(p, { auth: saved })
expect(Object.keys(list)).toEqual(Object.keys(_internal.STATIC_MODELS))
expect(list[Symbol.for("magpie.fellBack")]).toBe(true)
})
// plugins#1141: the host reads a listed model by OpenCode's shape
// (capabilities.input.image, capabilities.reasoning, capabilities.toolcall),
// so the vendor's vision and reasoning go there too.
test("the vendor's capabilities, in the shape the host reads", async () => {
const p = { models: { "deepseek-v4-flash": { id: "deepseek-v4-flash", name: "DS", limit: { context: 1000000, output: 64000 }, capabilities: { temperature: true, reasoning: false, attachment: false, toolcall: true, input: { text: true, image: false }, output: { text: true } }, api: { id: "deepseek-v4-flash", npm: "@ai-sdk/openai-compatible" } } } }
const list = await plugin.provider.models(p, { auth: saved })
expect(list["glm-5.3-flash"].capabilities.input.image).toBe(true)
expect(list["glm-5.3-flash"].capabilities.attachment).toBe(true)
expect(list["spark-x"].capabilities.reasoning).toBe(true)
expect(list["spark-x"].capabilities.toolcall).toBe(true)
expect(list["spark-x"].capabilities.input.image).toBe(false)
// what the vendor doesn't say keeps what was known of the model
expect(list["deepseek-v4-flash"].limit.context).toBe(1000000)
expect(list["deepseek-v4-flash"].api.npm).toBe("@ai-sdk/openai-compatible")
expect(list["deepseek-v4-flash"].rate).toBe("x3.0")
})
})
describe("usage", () => {
test("the two wallets as windows", async () => {
const usage = await plugin.auth.usage(getAuth)
// a clean read says nothing about the sign-in, so magpie can clear a lapse
expect(usage.signIn).toBeUndefined()
const daily = usage.windows.find((w) => w.name === "每日赠送积分")
// the vendor's own numbers: spent = dailyLimitPoints - dailyRemainingPoints
// magpie reads `used` as the share spent (0–100) and `amount` as the
// credits spent of `limit` (plugins#889)
expect(daily.limit).toBe(5000)
expect(daily.amount).toBe(5000 - fake.state.dailyBalance)
expect(daily.used).toBe((100 * (5000 - fake.state.dailyBalance)) / 5000)
expect(daily.unit).toBe("credits")
expect(daily.resetsAt).toBeGreaterThan(Date.now())
const permanent = usage.windows.find((w) => w.name === "永久积分")
expect(permanent.display).toBe("5000 credits")
})
test("routing reads the two wallets added up, so permanent credits keep an account going after the daily ones run out (gocccy0 on X)", async () => {
const realFetch = globalThis.fetch
const reply = (data) => (input, init) => {
const url = typeof input === "string" ? input : String(input?.url ?? input)
if (String(url).includes("/api/v2/points/records"))
return new Response(JSON.stringify({ code: "000000", desc: "ok", data: { ...data, list: [], total: 0 } }), { status: 200 })
return realFetch(input, init)
}
const read = async (data) => {
globalThis.fetch = reply(data)
return (await plugin.auth.usage(getAuth)).windows
}
// routing skips a window set aside: exactly one may stop the account
const counted = (ws) => ws.filter((w) => !w.aside)
try {
// the daily credits all spent, 1,200 permanent left: not used up
let ws = await read({ balance: 1200, dailyBalance: 0, dailyLimitPoints: 5000, dailyRemainingPoints: 0 })
expect(counted(ws)).toHaveLength(1)
let total = counted(ws)[0]
expect(total).toMatchObject({ name: "积分合计", amount: 5000, limit: 6200, unit: "credits" })
expect(total.used).toBeCloseTo((100 * 5000) / 6200)
expect(total.used).toBeLessThan(100)
// the daily wallet at 100% is shown, set aside
expect(ws.find((w) => w.name === "每日赠送积分")).toMatchObject({ used: 100, aside: true })
expect(ws.find((w) => w.name === "永久积分")).toMatchObject({ display: "1200 credits", aside: true })
// nothing of the daily wallet left: nothing lapses at midnight, so the
// total names no reset and smart routing puts accounts whose reset
// loses credits ahead of it (plugins#1153); the daily wallet beside it
// still shows midnight
expect(total.runsOutAt).toBeUndefined()
expect(total.resetsAt).toBeUndefined()
expect(total.span).toBeUndefined()
expect(ws.find((w) => w.name === "每日赠送积分").resetsAt).toBe(_internal.beijingMidnight())
// both gone: used up, back at Beijing midnight
ws = await read({ balance: 0, dailyBalance: 0, dailyLimitPoints: 5000, dailyRemainingPoints: 0 })
expect(counted(ws)[0]).toMatchObject({ used: 100, amount: 5000, limit: 5000 })
expect(counted(ws)[0].resetsAt).toBe(_internal.beijingMidnight())
// 3,000 daily credits left are lost at midnight: runsOutAt / runsOut
ws = await read({ balance: 1200, dailyBalance: 3000, dailyLimitPoints: 5000, dailyRemainingPoints: 3000 })
total = counted(ws)[0]
expect(total).toMatchObject({ amount: 2000, limit: 6200, runsOut: 3000, span: 86400 })
expect(total.runsOutAt).toBe(_internal.beijingMidnight())
// without the limit pair the daily wallet is what is left: the total
// is a balance, used up only when both are 0
ws = await read({ balance: 1200, dailyBalance: 0 })
expect(counted(ws)).toHaveLength(1)
expect(counted(ws)[0]).toMatchObject({ name: "积分合计", used: 0, amount: 0, limit: 1200 })
ws = await read({ balance: 0, dailyBalance: 0 })
expect(counted(ws)[0]).toMatchObject({ used: 100, limit: 0 })
ws = await read({ balance: 1200, dailyBalance: 800 })
expect(counted(ws)[0]).toMatchObject({ used: 0, limit: 2000, runsOut: 800 })
// only the permanent balance told: it alone is the total, no reset
ws = await read({ balance: 1200 })
total = counted(ws)[0]
expect(total).toMatchObject({ used: 0, limit: 1200 })
expect(total.resetsAt).toBeUndefined()
expect(total.runsOutAt).toBeUndefined()
} finally {
globalThis.fetch = realFetch
}
})
test("a fresh daily wallet reads as nothing spent, and an empty one as all of it (plugins#889)", async () => {
const realFetch = globalThis.fetch
const reply = (limit, remaining) => (input, init) => {
const url = typeof input === "string" ? input : String(input?.url ?? input)
if (String(url).includes("/api/v2/points/records"))
return new Response(JSON.stringify({ code: "000000", desc: "ok", data: { balance: 5000, dailyBalance: remaining, dailyLimitPoints: limit, dailyRemainingPoints: remaining, list: [], total: 0 } }), { status: 200 })
return realFetch(input, init)
}
const daily = async (limit, remaining) => {
globalThis.fetch = reply(limit, remaining)
return (await plugin.auth.usage(getAuth)).windows.find((w) => w.name === "每日赠送积分")
}
try {
// a cap of 4 credits must not hold an account that has spent none
expect(await daily(5000, 5000)).toMatchObject({ used: 0, amount: 0, limit: 5000 })
expect(await daily(5000, 0)).toMatchObject({ used: 100, amount: 5000, limit: 5000 })
// a zero allowance is no share spent, never NaN
expect(await daily(0, 0)).toMatchObject({ used: 0, amount: 0, limit: 0 })
} finally {
globalThis.fetch = realFetch
}
})
test("a daily wallet without the limit pair is an amount without a limit", async () => {
const realFetch = globalThis.fetch
globalThis.fetch = (input, init) => {
const url = typeof input === "string" ? input : String(input?.url ?? input)
if (String(url).includes("/api/v2/points/records"))
return new Response(JSON.stringify({ code: "000000", desc: "ok", data: { balance: 5000, dailyBalance: 3000, list: [], total: 0 } }), { status: 200 })
return realFetch(input, init)
}
try {
const usage = await plugin.auth.usage(getAuth)
const daily = usage.windows.find((w) => w.name === "每日赠送积分")
expect(daily.limit).toBeUndefined()
expect(daily.display).toBe("3000 credits")
// a reply with only the limit/remaining pair still shows the daily
// wallet (remaining IS its number), without dailyBalance
globalThis.fetch = (input, init) => {
const url = typeof input === "string" ? input : String(input?.url ?? input)
if (String(url).includes("/api/v2/points/records"))
return new Response(JSON.stringify({ code: "000000", desc: "ok", data: { dailyLimitPoints: 5000, dailyRemainingPoints: 4200, list: [] } }), { status: 200 })
return realFetch(input, init)
}
try {
const pairOnly = await plugin.auth.usage(getAuth)
const dw = pairOnly.windows.find((w) => w.name === "每日赠送积分")
expect(dw).toBeTruthy()
// 800 spent of 5,000: 16% used, 800 credits spent (plugins#889) —
// not 800% and not the 4,200 left
expect(dw.used).toBe(16)
expect(dw.amount).toBe(800)
expect(dw.limit).toBe(5000)
expect(pairOnly.windows.find((w) => w.name === "永久积分")).toBeUndefined()
} finally {
globalThis.fetch = realFetch
}
// a reply with neither balance field is an error, not a confident zero
globalThis.fetch = (input, init) => {
const url = typeof input === "string" ? input : String(input?.url ?? input)
if (String(url).includes("/api/v2/points/records"))
return new Response(JSON.stringify({ code: "000000", desc: "ok", data: { records: [] } }), { status: 200 })
return realFetch(input, init)
}
try {
const missing = await plugin.auth.usage(getAuth)
expect(missing.error).toContain("没有返回余额字段")
} finally {
globalThis.fetch = realFetch
}
} finally {
globalThis.fetch = realFetch
}
})
})
describe("signature", () => {
test("the 9-part HMAC string matches the client's shape", () => {
const headers = _internal.signHeaders("POST", "/login/phone/sendMsgCode", '{"a":1}')
expect(headers.Authorization).toMatch(/^account 2thryby66wxi53sk:[A-Za-z0-9+/=]+$/)
expect(headers.Date).toMatch(/GMT$/)
expect(headers.Nonce).toMatch(/^[0-9a-f-]{36}$/)
expect(headers["Content-MD5"]).toBe(_internal.contentMD5('{"a":1}'))
// no body: no MD5 header, and the empty part sits in the string
const empty = _internal.signHeaders("GET", "/x", "")
expect(empty["Content-MD5"]).toBeUndefined()
})
test("paths are escaped and trailing slashes dropped", () => {
expect(_internal.escapedPath("/login/phone/sendMsgCode")).toBe("/login/phone/sendMsgCode")
expect(_internal.escapedPath("a/b/")).toBe("/a/b")
expect(_internal.escapedPath("/带中文/段")).toBe(`/${encodeURIComponent("带中文")}/${encodeURIComponent("段")}`)
})
})
describe("helpers", () => {
test("phone normalization", () => {
expect(_internal.normalizePhone("13800138000")).toBe("13800138000")
expect(_internal.normalizePhone("+86 138-0013-8000")).toBe("13800138000")
expect(_internal.normalizePhone("8613800138000")).toBe("13800138000")
expect(_internal.normalizePhone("12345")).toBeNull()
expect(_internal.normalizePhone("12800138000")).toBeNull() // second digit not 3-9
})
test("rate suffix split", () => {
expect(_internal.splitRateSuffix("DeepSeek V4 Flash 0731 (x3.0)")).toEqual({ name: "DeepSeek V4 Flash 0731", rate: "x3.0" })
expect(_internal.splitRateSuffix("GLM 5.3 Flash(x0.8)")).toEqual({ name: "GLM 5.3 Flash", rate: "x0.8" })
expect(_internal.splitRateSuffix("Spark X2.5 (x0.1)")).toEqual({ name: "Spark X2.5", rate: "x0.1" })
expect(_internal.splitRateSuffix("限时免费")).toEqual({ name: "限时免费", rate: undefined })
expect(_internal.splitRateSuffix("Model (free)")).toEqual({ name: "Model (free)", rate: undefined })
})
})
// ── 「内容太长了」的分流 ────────────────────────────────────────────────
//
// 上游这条 400 不含「上下文」:v0.1.2189 之前的 magpie 的 tooLongRe 认不出,
// 这笔 try 就被当成错误、账号被休息、组里其它成员一次没被问,整轮失败。
// 这里只改写文案(状态码不变),让旧宿主也能认成 overflow;
// v0.1.2189 起宿主自己认得,这是给旧宿主的兜底。
describe("a 400 that says the content is too long", () => {
// magpie `internal/gateway/gateway.go` 的 tooLongRe 中文两条 —— 逐字抄,改这里等于改契约
const tooLongRe = /上下文(长度)?(超|过长)|超(过|出)(了)?(模型)?(的)?(最大)?上下文/
const vendor = "内容太长了,请精简输入或开启新对话"
test("改写成 tooLongRe 认得的说法,状态码保持 400", async () => {
const out = _internal.retryableRefusal(400, JSON.stringify({ error: { message: vendor } }))
expect(out).not.toBeNull()
expect(out.status).toBe(400)
const body = await out.text()
expect(body).toMatch(tooLongRe)
expect(body).not.toContain("内容太长")
})
test("413 与 422 同办,状态码不变", async () => {
for (const status of [413, 422]) {
const out = _internal.retryableRefusal(status, vendor)
expect(out.status).toBe(status)
expect(await out.text()).toMatch(tooLongRe)
}
})
test("别的 400 不碰", () => {
expect(_internal.retryableRefusal(400, JSON.stringify({ error: { message: "invalid api key" } }))).toBeNull()
})
test("不是 400/413/422 的不碰(2xx 是 SSE 干流)", () => {
expect(_internal.retryableRefusal(200, vendor)).toBeNull()
expect(_internal.retryableRefusal(429, vendor)).toBeNull()
expect(_internal.retryableRefusal(500, vendor)).toBeNull()
})
})