Files
plugins/packages/autoclaw/no-magpie.test.mjs
T
我是一条没有名字的区 6fa3f487be autoclaw 0.2.15: campaign rewards need the desktop client's user-info, not task-complete (#769)
autoclaw's native check-in now calls POST /userapi/v1/user-info with the
desktop client's header set (X-Channel AutoClaw20, 2.2.0, win-x64) and the
account's current access token, own host first, before task-list ->
task-complete. That call is what records autoclaw_user_active, which the
login-reward campaigns pay on (yetone/magpie#3681). A user-info failure on
both hosts never blocks the daily check-in; the message says the campaign
wasn't triggered.

Only a 401/403 from task-list (now marked signIn: expired) spends the
refresh token, once, through a per-refresh-token single flight shared with
auth.refresh. The write-back is CAS-guarded against a re-sign-in, and a
rotated pair whose write fails is kept in memory under the spent token for
the next renewal. task-list failing on both hosts now throws (failed, retried
in 30 min) instead of answering inactive (yetone/magpie#3326).
callEnvelope gets a 20s abort. 0.2.14 -> 0.2.15 (dist branch only; the
package isn't on npm).

Run at 15542cb7 on mote (Bun 1.4.2):
- HOME=$(mktemp -d) bun test (whole repo): 6184 pass, 0 fail.
- bun scripts/check.mjs: ok.
- The PR's 13 new tests against main's index.mjs: 9 red (the 4 that pass
  hold behaviour main already had); on the PR all green.
- Five more review tests (not committed): concurrent check-ins whose refresh
  fails share one try and the next run refreshes again; a failed write-back
  is used by the next check-in with no second refresh and then saved; two
  accounts expiring together refresh once each into their own records;
  check-in only reaches AutoClaw's two hosts and user-info never carries the
  refresh token; a CN account asks the CN host first. All green on the PR,
  all red on main.
- Broken by hand, each turned tests red: user-info removed, user-info host
  order reversed, plain X-Channel, refresh token sent to user-info, a
  user-info throw escaping, inactive restored, rememberRotated removed, CAS
  removed, the in-flight join dropped, signIn: expired dropped, refresh on
  every check-in.

Not covered by a test: the 20s abort (removing it stays green), and the
"evict only my own gate" guard, which nothing in production reaches. Not
tried: a real AutoClaw account (the author's live run on 5 accounts is in
the PR); macOS.
2026-11-06 03:48:10 +08:00

68 lines
3.5 KiB
JavaScript
Raw 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.
// Nothing the plugin sends upstream names magpie (#355): a refresh that
// fetches the profile, and a chat carrying magpie's own hint headers, are
// recorded whole (URL, every header, body) and searched for the word.
import { expect, test } from "bun:test"
import { AutoclawAuthPlugin, AutoclawCnAuthPlugin, _internal } from "./index.mjs"
const b64url = (o) => Buffer.from(JSON.stringify(o)).toString("base64url")
const jwt = (claims) => `${b64url({ alg: "none" })}.${b64url(claims)}.sig`
const DEVICE = "ab".repeat(32)
function record(device = DEVICE) {
const realFetch = globalThis.fetch
const sent = []
globalThis.fetch = async (input, init) => {
const url = new URL(String(input))
const headers = [...new Headers(init?.headers)].map(([k, v]) => `${k}: ${v}`).join("\n")
sent.push({ url, text: `${url}\n${headers}\n${String(init?.body ?? "")}`, body: String(init?.body ?? "") })
if (url.pathname.endsWith("/refresh")) {
return Response.json({ code: 0, msg: "ok", data: {
access_token: jwt({ exp: 2_000_000_000, device_id: device }),
refresh_token: jwt({ device_id: device, source_id: "autoclaw" }),
} })
}
if (url.pathname === "/userapi/v1/user-profile") return Response.json({ code: 0, msg: "ok", data: { user_name: "Tester" } })
return Response.json({ code: 0, msg: "ok", data: {} })
}
return { sent, restore: () => { globalThis.fetch = realFetch } }
}
test("a refresh and a chat send nothing upstream that names magpie", async () => {
// 每次迭代用不同的 refresh token:refreshShared 按 RT 单飞,共用会让
// 第二个 provider 的续期请求被缓存吃掉、host 顺序根本没走到网络。
const plugins = [AutoclawAuthPlugin, AutoclawCnAuthPlugin]
for (const [i, Plugin] of plugins.entries()) {
const device = i === 0 ? DEVICE : "cd".repeat(32)
const { sent, restore } = record(device)
try {
const hooks = await Plugin({ client: { auth: { set: async () => {} } } })
const old = { type: "oauth", access: "a0", refresh: jwt({ device_id: device, source_id: "autoclaw" }), accountId: "已登录" }
const t = await hooks.auth.refresh(old)
expect(t.accountId).toBe("Tester")
const loader = await hooks.auth.loader(async () => ({ type: "oauth", access: t.access }))
await loader.fetch("x", {
method: "POST",
headers: { "Content-Type": "application/json", "X-Magpie-Session": "s1", "x-magpie-agent": "codex" },
body: JSON.stringify({ model: "glm-5", messages: [{ role: "user", content: "hi" }] }),
})
} finally {
restore()
}
expect(sent.some((r) => r.url.pathname === "/userapi/v1/user-profile")).toBe(true)
expect(sent.some((r) => r.url.pathname.endsWith("/chat/completions"))).toBe(true)
// 两个 provider 各打一次自己的 refresh(单飞键不同,不能被缓存复用)
expect(sent.filter((r) => r.url.pathname.endsWith("/refresh")).length).toBe(1)
for (const r of sent) expect(r.text.toLowerCase()).not.toContain("magpie")
// user-profile carries the account's own device id, as AutoClaw's client does
const profile = sent.find((r) => r.url.pathname === "/userapi/v1/user-profile")
expect(JSON.parse(profile.body).device_id).toBe(device)
}
})
test("the device id comes from the login, else the account's tokens", () => {
const { accountDeviceId } = _internal
expect(accountDeviceId("d1", jwt({ device_id: "d2" }))).toBe("d1")
expect(accountDeviceId(undefined, "opaque", jwt({ device_id: "d2" }))).toBe("d2")
expect(accountDeviceId(undefined, "opaque")).toBe("")
})