diff --git a/packages/loomy/README.md b/packages/loomy/README.md index 5d3597d..4f66fd7 100644 --- a/packages/loomy/README.md +++ b/packages/loomy/README.md @@ -14,9 +14,9 @@ magpie plugin login loomy # 选「短信验证码登录」或「手动粘贴 ## 能力 - **登录**:`短信验证码登录`(发码 → 输入 6 位码完成,session **14 天**)或 `手动粘贴 session`。 -- **无续期接口**:session 过期(业务码 `020002`/`100002`)需重新登录(短信或粘贴)。网关对失效的 session 回 HTTP 200 加业务码(对话、画图也一样),插件把它报成 401 并告诉 magpie 登录已失效;其它业务码报成 502,带上厂商的原话。 +- **无续期接口**:session 过期(业务码 `020002`/`100002`)需重新登录(短信或粘贴)。网关对失效的 session 回 HTTP 200 加业务码(对话、画图也一样),插件把它报成 401 并告诉 magpie 登录已失效;其它业务码报成 502,带上厂商的原话。HTTP 401/403 只有带着这两个业务码才算登录失效;不带的(代理、防火墙拦下的请求)报成 502 并保留登录,magpie 换下一个账号,不会要求重新登录。登录失效的提示会写上这次登录的日期。 - **聊天**:`POST {modelBase}/chat/completions`,OpenAI 形态基本透传,两处适配(参照实现 `reasoning_patch` / `images.rs`):思考档折进 low/medium/high(超档删除)、旧版 DeepSeek(deepseek-v4-flash-0731)的 data-URI 图片转 `` 标记(只有 deepseek-v4-flash / -0731;DeepSeek-V4.1-Flash 和 deepseek-v4-flash-1017 收 OpenAI `image_url`,不转,#811、#1139);SSE;请求头必须带 `charset=utf-8`(上游对无 charset 的 body 按 GBK 解码)。 -- **画图**:`POST {modelBase}/images/generations`(doubao-seedream-5-lite / qwen-image-3.0-pro / Hy-Image-3.5-preview),body 按 magpie 写的原样透传,`Accept: application/json`(不是 SSE),回答是普通 JSON(`data[].url`、`points_consumed`)。401/403 报登录失效。`/images/edits`(改图)暂不转发:magpie 发给插件的改图是 multipart,Loomy 网关收不收这种改图没有实测过(#609)。 +- **画图**:`POST {modelBase}/images/generations`(doubao-seedream-5-lite / qwen-image-3.0-pro / Hy-Image-3.5-preview),body 按 magpie 写的原样透传,`Accept: application/json`(不是 SSE),回答是普通 JSON(`data[].url`、`points_consumed`)。401/403 同对话:带登录失效业务码才算失效。`/images/edits`(改图)暂不转发:magpie 发给插件的改图是 multipart,Loomy 网关收不收这种改图没有实测过(#609)。 - **模型**:登录前给静态表(2026-10-16 实抓 `/api/v1/models` 的 chat 模型:DeepSeek-V4.1-Flash / deepseek-v4-flash-0731 / MiniMax-M3 / Kimi-k2.6 / qwen-3.8-max / GLM-5.3-Flash / qwen3.8-flash / spark-x / mimo-v2.5 / auto),登录后以 `GET /api/v1/models` 的实时目录为准(能力位读 `capabilities`;展示名尾部倍率 `(x3.0)` 拆为 rate 字段)。 - **余额(usage)**:`GET /api/v2/points/records?...` → 永久积分 + 每日赠送积分两个窗口;每日窗口用厂商自己的 `dailyLimitPoints`/`dailyRemainingPoints` 报「已用/剩余/上限」,厂商未带这一对时按无上限的余额展示(不编造上限)。响应缺余额字段时报 error("未知"不冒充 0)。路由读的是两者合计的「积分合计」窗口(已用 = 每日已用,上限 = 已用 + 每日剩余 + 永久积分),两个钱包作为 aside 并列展示:每日积分用完、永久积分还有时账号仍可路由;每日剩余积分在北京时间零点失效,用 `runsOutAt`/`runsOut` 报出,让路由先花掉它们。 - **签到判定**:`first-login` 接口对"当天首登"与"重复调用"都返回成功,插件用调用前后的每日余额差判定——涨了 = `claimed`(今日首登奖励),没涨 = `done`(已领过/无每日钱包)。 diff --git a/packages/loomy/fake.mjs b/packages/loomy/fake.mjs index 4d171ae..3c4d647 100644 --- a/packages/loomy/fake.mjs +++ b/packages/loomy/fake.mjs @@ -30,6 +30,9 @@ export function fakeLoomy() { chatCode: null, // set to {code, desc} to answer the chat 200 with it imageCalls: [], imageStatus: null, // set to a status to answer it instead of drawing + // set to {status, type, body} to answer every gateway path with it before + // the session is looked at, as a proxy or firewall on the way does + denied: null, firstLoginCalls: 0, dailyBalance: 3000, // the day's first first-login refreshes it to 5000 recordsReads: 0, @@ -47,6 +50,7 @@ export function fakeLoomy() { state.chatCode = null state.imageCalls = [] state.imageStatus = null + state.denied = null state.firstLoginCalls = 0 state.dailyBalance = 3000 state.recordsReads = 0 @@ -106,6 +110,10 @@ export function fakeLoomy() { port: 0, async fetch(req) { const url = new URL(req.url) + if (state.denied) { + const d = state.denied + return new Response(d.body, { status: d.status, headers: { "content-type": d.type ?? "text/html" } }) + } const token = req.headers.get("token") ?? "" const bearer = (req.headers.get("authorization") ?? "").replace(/^Bearer\s+/i, "") // a refused session answers HTTP 200 with the business code, as the diff --git a/packages/loomy/index.mjs b/packages/loomy/index.mjs index b29dbe5..1660099 100644 --- a/packages/loomy/index.mjs +++ b/packages/loomy/index.mjs @@ -35,6 +35,34 @@ const AUTH_CODES = new Set(["020002", "100002"]) const REQUEST_TIMEOUT = 20_000 +// the session the client asks for at sign-in (expire: 1209600, as Loomy's +// own client sends it); there is no endpoint that renews one +const SESSION_TTL = 14 * 86400e3 + +// when an account's session began: the time an SMS sign-in kept, else its +// 14-day end less 14 days (accounts signed in before 0.1.12); 0 when not +// known (a pasted session) +function signedInAt(a) { + const at = Number(a?.signedInAt) + if (Number.isFinite(at) && at > 0) return at + const exp = Number(a?.expires) + return Number.isFinite(exp) && exp > SESSION_TTL ? exp - SESSION_TTL : 0 +} + +// what a lapsed account says: the vendor refused the session, with the day +// it was signed in. No lifetime is claimed: the client asks for 14 days, but +// agent2api found sessions still served past that, so the day is the fact +// and the reader can set it beside the drop +function lapsedText(a, said) { + const at = signedInAt(a) + let when = "" + if (at) { + const d = new Date(at + 8 * 3600e3) // Beijing + when = `;这次登录在 ${d.getUTCMonth() + 1} 月 ${d.getUTCDate()} 日` + } + return `Loomy 登录态已失效(${said || "code=100002"}${when}),请重新登录` +} + // the chat models the live /api/v1/models returned on 2026-10-16 (the image // models come from the live list only; the loader draws with them through @@ -164,7 +192,7 @@ function retryableRefusal(status, body) { // vendor's words. A model's own answer (an SSE stream, or a completion or // a draw, neither of which has a top-level code) goes through as it came. const REFUSAL_MAX = 64 << 10 -async function businessRefusal(res) { +async function businessRefusal(res, a) { const ct = res.headers.get("content-type") ?? "" if (!/json/i.test(ct) || /event-stream/i.test(ct)) return res const text = await res.text() @@ -184,13 +212,48 @@ async function businessRefusal(res) { if (!code || code === OK) return same() const said = messageOf(payload) if (AUTH_CODES.has(code)) { - const r = errorResponse(401, `Loomy 登录态已失效,请重新登录(${said || `code=${code}`})`) + const r = errorResponse(401, lapsedText(a, said || `code=${code}`)) r.headers.set("x-magpie-sign-in", "expired") return r } return errorResponse(502, `Loomy 拒绝了请求:${said || "无错误说明"}(code=${code})`) } +// The gateway's verdict on a session is its business code: a made-up, +// dropped or missing token gets HTTP 200 with 100002 on every path (chat, +// draw, models, points and first-login; measured 2026-11-16 and again +// 2026-11-17), never a 401 or a 403. A 401 or 403 that doesn't carry a +// sign-in code came from something on the way, a proxy or a firewall +// turning the exit address away, and says nothing about the session. +// Read as "signed out", it marked a good account for sign-in again +// whenever the user's proxy was refused, a different account each time +// (jenxingyoung on X: four accounts on a proxy, "今天这个掉,明天那个掉"). +// So such a status is a failure of this try that leaves the sign-in as it +// is ("kept"), and only a sign-in code in its body says the session ended. +async function deniedStatus(res, a) { + const text = await res.text().catch(() => "") + let code = "" + let said = "" + try { + const payload = JSON.parse(text) + code = codeOf(payload) + said = messageOf(payload) + } catch {} + if (AUTH_CODES.has(code)) { + const r = errorResponse(401, lapsedText(a, said || `code=${code}`)) + r.headers.set("x-magpie-sign-in", "expired") + return r + } + const r = errorResponse(502, deniedText(res.status, said || text)) + r.headers.set("x-magpie-sign-in", "kept") + return r +} + +function deniedText(status, said) { + const words = String(said ?? "").replace(/\s+/g, " ").trim().slice(0, 300) + return `Loomy 网关返回 HTTP ${status},不是登录失效(Loomy 的登录失效是 HTTP 200 加业务码 100002),多半是代理或网络拦截了这次请求${words ? `:${words}` : ""}` +} + async function bodyText(input, init) { const b = init.body ?? (input instanceof Request ? await input.clone().text() : undefined) return typeof b === "string" ? b : new TextDecoder().decode(b) @@ -263,7 +326,16 @@ async function tokenRequest(method, path, session, body) { init.body = JSON.stringify(body) } const res = await fetch(integrationBase() + path, init) - if (res.status === 401 || res.status === 403) throw expired("Loomy 登录态已失效,请重新登录") + if (res.status === 401 || res.status === 403) { + // only a sign-in code says the session ended (deniedStatus) + const text = await res.text().catch(() => "") + let payload = null + try { + payload = JSON.parse(text) + } catch {} + if (AUTH_CODES.has(codeOf(payload))) throw expired(messageOf(payload) || `code=${codeOf(payload)}`) + throw new Error(deniedText(res.status, messageOf(payload) || text)) + } const payload = await res.json().catch(() => null) if (!res.ok) throw new Error(`Loomy 接口返回 HTTP ${res.status}`) if (!payload) throw new Error("Loomy 接口返回了无法解析的内容") @@ -271,6 +343,12 @@ async function tokenRequest(method, path, session, body) { } +// a pasted session's account name: its last six characters, as the token +// tails other subscriptions show +function pastedName(session) { + return `手动粘贴 ···${String(session).slice(-6)}` +} + // the phone number as the client normalizes it (agent2api login.rs) function normalizePhone(raw) { const trimmed = String(raw ?? "").replace(/[\s-]/g, "") @@ -453,13 +531,19 @@ export async function LoomyAuthPlugin({ client } = {}) { if (codeOf(answer) !== OK) return { type: "failed", error: `登录失败:${messageOf(answer) || `code=${codeOf(answer)}`}` } const session = String(answer?.data?.session ?? "").trim() if (!session) return { type: "failed", error: "登录成功但上游没有返回 session" } + const userId = String(answer?.data?.userid ?? "") + const now = Date.now() return { type: "success", refresh: "", access: session, - expires: Date.now() + 14 * 86400e3, // the session the client asks for is 14 days + expires: now + SESSION_TTL, // the session the client asks for is 14 days + signedInAt: now, accountId: `${phone.slice(0, 3)}****${phone.slice(-4)}`, - userId: String(answer?.data?.userid ?? ""), + // two phones masked alike stay two accounts (magpie's host + // tells accounts of one name apart by uid) + ...(userId ? { uid: userId } : {}), + userId, source: "sms", } } catch (e) { @@ -483,7 +567,10 @@ export async function LoomyAuthPlugin({ client } = {}) { url: "", instructions: "已取到粘贴的 session,确认即完成登录。", method: "auto", - callback: async () => ({ type: "success", refresh: "", access: session, expires: 0, accountId: "手动粘贴", source: "manual" }), + // each pasted session its own name: magpie's host keeps one account + // per name, so one name for every paste put a second pasted account + // over the first, and signing one in again dropped another + callback: async () => ({ type: "success", refresh: "", access: session, expires: 0, accountId: pastedName(session), source: "manual" }), } }, }) @@ -491,8 +578,10 @@ export async function LoomyAuthPlugin({ client } = {}) { return { auth: { provider: ID, - // Loomy has no renewal: a session lives 14 days, and its end is - // refreshed only by signing in again (SMS or import) + // Loomy has no renewal: its own client (0.9.39), web app and every + // port of it (agent2api, magpie-providers-hub) only sign in again. A + // session is asked for 14 days, and its end is refreshed only by + // signing in again (SMS or paste) async loader(getAuth) { const a = await getAuth() if (a?.type !== "oauth") return {} @@ -503,7 +592,8 @@ export async function LoomyAuthPlugin({ client } = {}) { // the body goes as magpie wrote it (the chat path's rewrites are // about messages, which a draw has none of) const draw = async (body, signal) => { - const session = (await getAuth())?.access ?? a.access + const now = (await getAuth()) ?? a + const session = now?.access ?? a.access if (!session) return errorResponse(401, "Loomy 登录态缺失,请重新登录") let res try { @@ -521,12 +611,12 @@ export async function LoomyAuthPlugin({ client } = {}) { } catch (e) { return errorResponse(502, e?.message ?? String(e)) } - if (res.status === 401 || res.status === 403) return errorResponse(401, "Loomy 登录态已失效,请重新登录") + if (res.status === 401 || res.status === 403) return deniedStatus(res, now) if (!res.ok) { const raw = await res.text().catch(() => "") return errorResponse(res.status, `Loomy 上游返回 ${res.status}: ${raw.slice(0, 4096) || "无错误说明"}`) } - return businessRefusal(res) + return businessRefusal(res, now) } return { baseURL: modelBase(), @@ -546,7 +636,8 @@ export async function LoomyAuthPlugin({ client } = {}) { } catch { return errorResponse(400, "a request that isn't JSON") } - const session = (await getAuth())?.access ?? a.access + const now = (await getAuth()) ?? a + const session = now?.access ?? a.access if (!session) return errorResponse(401, "Loomy 登录态缺失,请重新登录") // the body as Loomy's own client writes it: reasoning folded to @@ -573,7 +664,7 @@ export async function LoomyAuthPlugin({ client } = {}) { } catch (e) { return errorResponse(502, e?.message ?? String(e)) } - if (res.status === 401 || res.status === 403) return errorResponse(401, "Loomy 登录态已失效,请重新登录") + if (res.status === 401 || res.status === 403) return deniedStatus(res, now) if (!res.ok) { const raw = await res.text().catch(() => "") const refusal = retryableRefusal(res.status, raw) @@ -582,17 +673,18 @@ export async function LoomyAuthPlugin({ client } = {}) { } // the answer streams through as it came (OpenAI-shaped); a 200 // that is a refusal in the vendor's envelope is said as one - return businessRefusal(res) + return businessRefusal(res, now) }, } }, async usage(getAuth) { + let a try { - const a = await getAuth() + a = await getAuth() if (a?.type !== "oauth") return { error: "not signed in", signIn: "kept" } const payload = await tokenRequest("GET", "/api/v2/points/records?pageNo=1&pageSize=1&direction=debit&granularity=chat", a.access) const code = codeOf(payload) - if (AUTH_CODES.has(code)) return { error: "Loomy 登录态已失效,请重新登录", signIn: "expired" } + if (AUTH_CODES.has(code)) return { error: lapsedText(a, messageOf(payload) || `code=${code}`), signIn: "expired" } if (code !== OK) return { error: `积分查询失败:${messageOf(payload) || `code=${code}`}`, signIn: "kept" } const data = payload?.data?.data ?? payload?.data ?? {} const daily = toNum(data.dailyBalance) @@ -647,7 +739,8 @@ export async function LoomyAuthPlugin({ client } = {}) { // "kept" here would leave a transient 401's lapse on forever) return { plan: NAME, user: a.name || a.accountId, windows } } catch (e) { - return { error: String(e?.message ?? e), signIn: e?.signIn === "expired" ? "expired" : "kept" } + if (e?.signIn === "expired") return { error: lapsedText(a, e.message), signIn: "expired" } + return { error: String(e?.message ?? e), signIn: "kept" } } }, // the daily grant: the first login of the vendor's day refreshes the diff --git a/packages/loomy/index.test.mjs b/packages/loomy/index.test.mjs index c5314ea..8d975a2 100644 --- a/packages/loomy/index.test.mjs +++ b/packages/loomy/index.test.mjs @@ -42,6 +42,10 @@ describe("sign-in methods", () => { 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 () => { @@ -61,6 +65,108 @@ describe("sign-in methods", () => { 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: "403 Forbidden - Access denied" }) + + 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", () => { @@ -255,13 +361,14 @@ describe("images (#609)", () => { expect(fake.state.imageCalls[0].body.model).toBe("doubao-seedream-5-lite") }) - test("a refused session says 401, as chat does", async () => { + 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(401) - expect((await res.json()).error.message).toContain("登录态已失效") + expect(res.status).toBe(502) + expect(res.headers.get("x-magpie-sign-in")).toBe("kept") + expect((await res.json()).error.message).toContain(`refused ${status}`) } }) diff --git a/packages/loomy/package.json b/packages/loomy/package.json index 5b4d949..447f5f3 100644 --- a/packages/loomy/package.json +++ b/packages/loomy/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-loomy-auth", - "version": "0.1.11", + "version": "0.1.12", "description": "OpenCode & Magpie provider plugin for Loomy (讯飞, loomyad.xunfei.cn): SMS sign-in, chat, models, the two point wallets and the daily first-login grant", "type": "module", "main": "./opencode.mjs",