autoclaw 0.2.6: user-profile carries the account's own device id, not "magpie-plugin" (#355)

fetchUserProfile sent `device_id: "magpie-plugin"`. AutoClaw 1.18.5's own
client (app.asar, getUserInfoWithAccessToken -> withWebInfo) sends the
device id the account signed in with (getAuthState().deviceId), a 64-hex
id. The plugin already generates such an id per login (newDeviceId) and
sends it with the login; the server writes it into the tokens' device_id
claim. user-profile now sends that id: the login's own at sign-in, the
refresh token's claim on refresh (old accounts included), "" only when no
token carries one, as refreshTokens already does.

Found by the new test: the global chat path forwarded magpie's x-magpie-*
hint headers to the vendor. They are now dropped there (the CN path builds
its own headers).

Run:
- bun test (packages/autoclaw): 36 pass, 0 fail
- bun scripts/check.mjs: ok
- no-magpie.test.mjs against HEAD's index.mjs: 2 of 2 red (device_id
  "magpie-plugin", then the hint headers)

Not tried: a live run. There is no AutoClaw account to sign in with.
This commit is contained in:
yetone
2026-10-24 17:37:27 +08:00
parent a5c13b8c7a
commit a9b57b6fb9
3 changed files with 85 additions and 7 deletions
+23 -6
View File
@@ -533,13 +533,28 @@ async function maybeSignin(accessToken, host, options, reason, accountKey) {
// 用户资料(GUI 账户命名:昵称/手机号,替代无意义的 uid 哈希 → 「已登录」)
// ---------------------------------------------------------------------------
/**
* 账号自己的 device_id:登录时生成并随登录请求发出的那个,服务端写进了 token 的 device_id claim。
* 官方 AutoClaw(1.18.5 getUserInfoWithAccessToken → withWebInfo)在 user-profile 里发的就是
* 登录用的设备 id(getAuthState().deviceId),不是固定串。
*/
function accountDeviceId(deviceId, ...tokens) {
const given = nonEmptyString(deviceId);
if (given) return given;
for (const t of tokens) {
const claim = nonEmptyString(jwtClaim(t, "device_id"));
if (claim) return claim;
}
return "";
}
/** POST /userapi/v1/user-profile → { user_name, user_phone, user_id, … };失败返回 null。 */
async function fetchUserProfile(accessToken, base) {
async function fetchUserProfile(accessToken, base, deviceId, refreshToken) {
try {
const res = await fetch(`${base}/userapi/v1/user-profile`, {
method: "POST",
headers: bizHeaders(accessToken),
body: JSON.stringify({ source_id: PRODUCT, device_id: "magpie-plugin" }),
body: JSON.stringify({ source_id: PRODUCT, device_id: accountDeviceId(deviceId, accessToken, refreshToken) }),
signal: AbortSignal.timeout(15_000),
});
if (!res.ok) return null;
@@ -664,7 +679,7 @@ function makeAutoclawPlugin({ providerId, providerName, homeHost, loginMethod })
// 刷新时补拉 user-profile。magpie 的 refresh 返回字段会合并进账号。
const old = String(auth.accountId ?? auth.email ?? "");
if (!old || /^(已登录|[0-9a-f]{24,})$/.test(old)) {
const profile = await fetchUserProfile(t.access, homeHost);
const profile = await fetchUserProfile(t.access, homeHost, jwtClaim(bareToken(auth.refresh), "device_id"), t.refresh);
const name = accountDisplayName(profile, "");
if (name) {
t.accountId = name;
@@ -685,6 +700,8 @@ function makeAutoclawPlugin({ providerId, providerName, homeHost, loginMethod })
async fetch(input, init) {
if (providerId !== "autoclaw-cn") {
const headers = new Headers(init?.headers);
// magpie's own hint headers (x-magpie-*) are for the plugin, never the vendor
for (const k of [...headers.keys()]) if (k.toLowerCase().startsWith("x-magpie-")) headers.delete(k);
headers.set("User-Agent", USER_AGENT);
headers.set("X-Authorization", `Bearer ${accessToken}`);
headers.set("X-Client-Type", "pc");
@@ -898,7 +915,7 @@ const phoneSmsMethod = {
}
const t = tokenFields(res.data);
// GUI 显示名:拉 user-profile 取昵称/手机号(登录响应的 user_name 常为空 → 显示「已登录」)
const profile = await fetchUserProfile(t.access, CN_HOST);
const profile = await fetchUserProfile(t.access, CN_HOST, deviceId);
const displayName = accountDisplayName(profile, phone);
return {
type: "success",
@@ -1155,7 +1172,7 @@ async function startLocalOAuth(vendor, openFn) {
}
const t = tokenFields(res.data);
// GUI 显示名:拉 user-profile 取昵称(Google/z.ai 账号通常有昵称或邮箱)
const profile = await fetchUserProfile(t.access, GLOBAL_HOST);
const profile = await fetchUserProfile(t.access, GLOBAL_HOST, deviceId);
const displayName = accountDisplayName(profile, `${vendor} 账号`);
return {
type: "success",
@@ -1327,7 +1344,7 @@ export const _internal = {
makePluginForTest: makeAutoclawPlugin,
md5Hex, jwtClaim, tokenFields, codeValue, bizHeaders, bareToken, newDeviceId,
dailySignin, signinStatus, maybeSignin, signinAccountKey, signinConfig, checkinOutcome, refreshTokens,
fetchUserProfile, accountDisplayName, startLocalOAuth,
fetchUserProfile, accountDeviceId, accountDisplayName, startLocalOAuth,
FLAGGED, unflagged, unflag, autoclawRewriteBody, explained, OFFICIAL_SYSTEM_PROMPT, REFUSED_HINT,
guidePageHtml, callbackPageHtml,
};
+61
View File
@@ -0,0 +1,61 @@
// 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() {
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 () => {
for (const Plugin of [AutoclawAuthPlugin, AutoclawCnAuthPlugin]) {
const { sent, restore } = record()
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)
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("")
})
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-autoclaw-auth",
"version": "0.2.5",
"version": "0.2.6",
"description": "OpenCode provider plugin for AutoClaw (Zhipu OpenClaw): oversea web sign-in (Google/z.ai) and CN phone SMS, multi-account pool, credit balance and daily check-in",
"type": "module",
"main": "./index.mjs",