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.
This commit is contained in:
@@ -64,7 +64,11 @@ OpenCode 同样可加载(`opencode auth login`)。登录信息保存在 magp
|
||||
|
||||
**② 旧链路自动补签(默认关)**:查额度(`magpie quota`、GUI 刷新)与 token 刷新时发现未签就补签(服务端幂等,本地按天去重、失败按小时重试)。旧版 magpie / OpenCode 宿主或偏好该行为的用户开启 `signinOnUsage`。
|
||||
|
||||
`magpie quota` 的额度窗口里始终显示**每日签到**状态行(今日已签 ✓ / 今日未签 +N)。
|
||||
`magpie quota` 的额度窗口在查询成功时显示**每日签到**状态行(今日已签 ✓ / 今日未签 +N)。
|
||||
|
||||
> **「登录领积分」类活动奖励**:服务端只为带整套官方桌面端业务头(`X-Channel: AutoClaw20`、`X-Version: 2.2.0`、UA `AutoClaw/2.2.0 (win-x64)`、`X-Tm: win-x64`、`X-Product` 等;所有平台都按这套 Windows 指纹上报)的 `POST /userapi/v1/user-info` 记录 `autoclaw_user_active` 活跃事件——没有这次调用,这类活动就领不到(yetone/magpie#3681)。本次实测到账:国际「AutoClaw Weekly Perks」+4000、国内「AutoClaw 用户登录奖励」+5000。
|
||||
>
|
||||
> **只有 ① 原生签到链路会调用 `user-info`**:用当前 access token 直接请求,access token 被上游拒绝时才刷新重试;`user-info` 本身不完成每日签到,每日签到仍由 `task-complete` 完成,两者相互独立。② 旧链路补签与不执行 `checkin` 钩子的宿主(OpenCode 1.x/2.x)不会领取活动奖励。
|
||||
|
||||
旧链路的开关有**两个通道**(插件 options 优先,配置文件兜底;原生签到开关只在 GUI 的 Settings 里):
|
||||
|
||||
|
||||
+192
-29
@@ -485,6 +485,7 @@ async function callEnvelope(path, { method = "GET", body, base }) {
|
||||
method,
|
||||
headers: bizHeaders(),
|
||||
...(body !== undefined ? { body } : {}),
|
||||
signal: AbortSignal.timeout(20_000),
|
||||
});
|
||||
text = await response.text();
|
||||
} catch (cause) {
|
||||
@@ -665,7 +666,9 @@ async function taskList(accessToken, host) {
|
||||
if (res.status === 401 || res.status === 403) {
|
||||
const banned = bannedText(await res.text().catch(() => ""));
|
||||
if (banned) throw Object.assign(new Error(`AutoClaw: ${banned}`), { banned: true, signIn: "kept" });
|
||||
throw new Error(`登录已失效(HTTP ${res.status})`);
|
||||
// 非封禁的登录失效:标记 expired,让 checkin 能用 refresh token 重试一次,
|
||||
// 也让 magpie 不再把过期账号当成普通失败重试一整天。
|
||||
throw Object.assign(new Error(`登录已失效(HTTP ${res.status})`), { signIn: "expired" });
|
||||
}
|
||||
if (!res.ok) return null;
|
||||
const env = await res.json().catch(() => null);
|
||||
@@ -705,6 +708,49 @@ function checkinOutcome(r) {
|
||||
return { outcome: "failed", message: String(r.message ?? r.msg ?? "签到失败") };
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /userapi/v1/user-info — 官方桌面客户端在建立登录态时会调用的端点。
|
||||
*
|
||||
* 服务端据此记录 `autoclaw_user_active` 活跃事件,并发放「登录领积分」类
|
||||
* 活动奖励。返回体含 `daily_check_in_completed_on_request`——2026-11-06 五个账号
|
||||
* 实测恒为 false,插件不读取该字段;每日签到仍由 task-complete 完成。
|
||||
*
|
||||
* ⚠️ **必须带整套官方桌面端业务头**(`AutoClaw20` 渠道 / 2.2.0 / win-x64,
|
||||
* X-Product / X-Version / X-Tm / X-Trace-Id 齐全)——服务端只在这套指纹下
|
||||
* 记录 `autoclaw_user_active`。2026-11-06 真机对照:极简头
|
||||
* (`X-Channel: official` / UA 2.1.0)与插件 biz 头都 code=0 但**不发奖励**;
|
||||
* `AutoClaw20/2.2.0` 头五个账号全部到账:国际 +4000「AutoClaw Weekly Perks」
|
||||
* (act=autoclaw_weekly_perks_20261013)、国内 +5000「AutoClaw 用户登录奖励」
|
||||
* (act=autoclaw_user_active_reward_202609),流水 metadata:
|
||||
* source=campaign, event_type=autoclaw_user_active,见 yetone/magpie#3681 的复现脚本。
|
||||
*/
|
||||
async function callUserInfo(accessToken, deviceId, base) {
|
||||
const ts = String(Math.floor(Date.now() / 1000));
|
||||
const res = await fetch(`${base}/userapi/v1/user-info`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "*/*",
|
||||
"User-Agent": "AutoClaw/2.2.0 (win-x64)",
|
||||
"X-Version": "2.2.0",
|
||||
"X-Tm": "win-x64",
|
||||
"X-Product": PRODUCT,
|
||||
"X-Auth-Appid": APP_ID,
|
||||
"X-Auth-TimeStamp": ts,
|
||||
"X-Auth-Sign": md5Hex(`${APP_ID}&${ts}&${APP_KEY}`),
|
||||
"X-Trace-Id": randomHex(16),
|
||||
"X-Lang": "zh-CN",
|
||||
"X-Channel": "AutoClaw20",
|
||||
"Authorization": `Bearer ${accessToken}`,
|
||||
},
|
||||
body: JSON.stringify({ source_id: PRODUCT, device_id: deviceId }),
|
||||
signal: AbortSignal.timeout(15_000),
|
||||
});
|
||||
let parsed;
|
||||
try { parsed = JSON.parse(await res.text()); } catch { parsed = null; }
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/** 本地去重键(成功才记;按小时允许重试)。 */
|
||||
const signinTriedLocal = new Map(); // key → hour-stamp of last SUCCESSFUL signin
|
||||
|
||||
@@ -841,6 +887,53 @@ async function refreshTokens(refreshToken, preferredHosts) {
|
||||
return tokenFields(result.data, refreshToken);
|
||||
}
|
||||
|
||||
/**
|
||||
* 同一 refresh_token 的续期单飞 + 轮换结果兜底。
|
||||
*
|
||||
* refresh token 一次一换:同一个 RT 只能换出一次新令牌。插件有两条路会续期:
|
||||
* magpie 自己的 `auth.refresh`,以及 checkin 在当前 access token 被拒时的重试。
|
||||
* 并发时若各打一次网络,后到的会被判 `invalid_grant`,账号可能被标成登录失效。
|
||||
* ⇒ 在途的刷新无条件共享(不能按创建时间过期:一次 refresh 可能打满 3 个 host);
|
||||
* 已完成的结果 60 秒内复用;失败立即摘除允许重试。
|
||||
* 轮换后写回失败时按「已花费的旧 RT」把新令牌记在内存:旧 RT 已被服务端作废,
|
||||
* 不可能再换出别的结果,内存应答严格优于拿着死 RT 再打网络(避免次日静默毁号)。
|
||||
*/
|
||||
const REFRESH_SHARE_MS = 60_000;
|
||||
const ROTATED_MEMO_MAX = 50;
|
||||
const refreshGates = new Map(); // refreshToken → { at, pending, promise }
|
||||
const rotatedMemo = new Map(); // 已花费的 refreshToken → tokenFields(...)
|
||||
function rememberRotated(spent, fresh) {
|
||||
rotatedMemo.delete(spent);
|
||||
rotatedMemo.set(spent, fresh);
|
||||
while (rotatedMemo.size > ROTATED_MEMO_MAX) {
|
||||
const oldest = rotatedMemo.keys().next().value;
|
||||
if (oldest === undefined) break;
|
||||
rotatedMemo.delete(oldest);
|
||||
}
|
||||
}
|
||||
function refreshShared(refreshToken, hosts) {
|
||||
if (!refreshToken) throw new Error("AutoClaw: no refresh token to renew");
|
||||
const memo = rotatedMemo.get(refreshToken);
|
||||
if (memo) return Promise.resolve(memo);
|
||||
const held = refreshGates.get(refreshToken);
|
||||
if (held && (held.pending || Date.now() - held.at < REFRESH_SHARE_MS)) return held.promise;
|
||||
// 顺手淘汰已过期且不在途的条目,避免长驻进程里无限堆积(含令牌)。
|
||||
for (const [k, g] of refreshGates) {
|
||||
if (!g.pending && Date.now() - g.at >= REFRESH_SHARE_MS) refreshGates.delete(k);
|
||||
}
|
||||
const gate = { at: Date.now(), pending: true, promise: null };
|
||||
gate.promise = refreshTokens(refreshToken, hosts).then(
|
||||
(t) => { gate.pending = false; gate.at = Date.now(); return t; },
|
||||
(e) => {
|
||||
// 只摘自己:并发重建的 gate 不能被旧的失败回调误删(第三次烧 RT)。
|
||||
if (refreshGates.get(refreshToken) === gate) refreshGates.delete(refreshToken);
|
||||
throw e;
|
||||
},
|
||||
);
|
||||
refreshGates.set(refreshToken, gate);
|
||||
return gate.promise;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 插件工厂
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -904,7 +997,10 @@ function makeAutoclawPlugin({ providerId, providerName, homeHost, loginMethod })
|
||||
methods: [loginMethod],
|
||||
|
||||
async refresh(auth) {
|
||||
const t = await refreshTokens(bareToken(auth.refresh), [homeHost]);
|
||||
const t = await refreshShared(bareToken(auth.refresh), [homeHost]);
|
||||
// 旧链路自动补签(signinOnUsage,默认关):task-complete 只完成每日签到,
|
||||
// 不影响活动奖励——2026-11-06 实测:task-complete 签到的次日,user-info
|
||||
// 带桌面端指纹仍照常领到 +4000/+5000(见 yetone/magpie#3681)。
|
||||
await maybeSignin(t.access, homeHost, options, "refresh", signinAccountKey(providerId, auth));
|
||||
// 存量账号就地正名:登录响应缺昵称的旧账号(GUI 显示「已登录」),
|
||||
// 刷新时补拉 user-profile。magpie 的 refresh 返回字段会合并进账号。
|
||||
@@ -1094,36 +1190,102 @@ function makeAutoclawPlugin({ providerId, providerName, homeHost, loginMethod })
|
||||
* 契约:返回 {outcome, credit?, streak?, message?};throw → failed(30 分钟后重试)。
|
||||
*/
|
||||
async checkin(getAuth) {
|
||||
const auth = await getAuth();
|
||||
if (auth?.type !== "oauth" || !auth.access) throw new Error("未登录");
|
||||
const token = bareToken(auth.access);
|
||||
const first = await getAuth();
|
||||
if (first?.type !== "oauth" || !first.access) throw new Error("未登录");
|
||||
const hosts = providerId === "autoclaw-cn" ? [CN_HOST, GLOBAL_HOST] : [GLOBAL_HOST, CN_HOST];
|
||||
|
||||
// 先查任务状态:区分「无签到活动」(inactive)与「查询失败」(throw → failed 重试)
|
||||
let task = null;
|
||||
let lastErr = null;
|
||||
for (const h of hosts) {
|
||||
try {
|
||||
const tasks = await taskList(token, h);
|
||||
if (tasks) {
|
||||
task = tasks.find((x) => x?.task_id === "daily_signin") ?? null;
|
||||
break;
|
||||
}
|
||||
} catch (e) {
|
||||
lastErr = e;
|
||||
if (e?.banned) break;
|
||||
}
|
||||
}
|
||||
if (!task && lastErr) throw lastErr;
|
||||
if (!task) return { outcome: "inactive", message: "当前没有签到活动" };
|
||||
if (String(task.status ?? "") === "completed") {
|
||||
return { outcome: "done", credit: optNumber(task.reward_points) };
|
||||
}
|
||||
// ── 活动奖励 + 每日签到 ─────────────────────────────────────────────
|
||||
// 用**当前 access token** 调 user-info(桌面端指纹)触发活动奖励,再走
|
||||
// task-list → task-complete 完成每日签到。2026-11-06 真机:五个账号用
|
||||
// 当期 AT 直接调 user-info 就领到 +4000/+5000,refresh 不是领奖的前提。
|
||||
// 不为了签到去花 refresh token(一次一换,每次消耗都多一分「轮换后写回
|
||||
// 失败 → 次日静默毁号」的风险);只有上游明确拒绝当前 AT(401/403)
|
||||
// 时才 refresh 一次并重试整轮。
|
||||
let auth = first;
|
||||
let token = bareToken(auth.access);
|
||||
|
||||
// 补签:主 host 优先,无响应再试备用 host(服务端幂等)
|
||||
const r = await dailySignin(token, hosts[0]).catch(() => null)
|
||||
?? await dailySignin(token, hosts[1] ?? hosts[0]).catch(() => null);
|
||||
return checkinOutcome(r);
|
||||
const renewOnce = async () => {
|
||||
const spent = bareToken(auth.refresh);
|
||||
if (!spent) throw Object.assign(new Error("AutoClaw: 没有可用的 refresh token"), { signIn: "expired" });
|
||||
const fresh = await refreshShared(spent, [homeHost]);
|
||||
let saved = false;
|
||||
if (client?.auth?.set) {
|
||||
try {
|
||||
// CAS:签到期间用户可能重新登录/登出。只有记录仍是当时那份才写回,
|
||||
// 否则把新令牌交给内存兜底(rememberRotated),不覆盖别人的记录。
|
||||
const now = await getAuth();
|
||||
const unchanged = !now || now.type !== "oauth" || bareToken(now.refresh ?? "") === spent;
|
||||
if (unchanged) {
|
||||
const written = await client.auth.set({
|
||||
path: { id: providerId },
|
||||
body: { ...auth, access: fresh.access, refresh: fresh.refresh, expires: fresh.expires },
|
||||
});
|
||||
saved = !written?.error;
|
||||
}
|
||||
} catch { /* 写回失败:走下面的内存兜底 */ }
|
||||
}
|
||||
if (!saved) rememberRotated(spent, fresh);
|
||||
auth = { ...auth, access: fresh.access, refresh: fresh.refresh, expires: fresh.expires };
|
||||
token = bareToken(fresh.access);
|
||||
};
|
||||
|
||||
// 一轮:活动奖励(尽力而为)→ 每日签到。返回契约里的 outcome。
|
||||
const attempt = async () => {
|
||||
// ① 官方登录事件:user-info 带桌面端指纹。单 host 网络错误不能挡住
|
||||
// 备用 host;全部失败也绝不阻断每日签到(活动奖励领不到要如实告知)。
|
||||
const deviceId = accountDeviceId(undefined, token, auth.refresh);
|
||||
let uiReached = false;
|
||||
for (const h of hosts) {
|
||||
try {
|
||||
const ui = await callUserInfo(token, deviceId, h);
|
||||
if (ui?.code === 0) { uiReached = true; break; }
|
||||
} catch { /* 换下一个 host */ }
|
||||
}
|
||||
|
||||
// ② 每日签到:双 host 都查不到任务时抛错(failed → 30 分钟后重试),
|
||||
// 绝不把查询失败误报成「当前没有签到活动」把当天判死(#3326)。
|
||||
let task = null;
|
||||
let lastErr = null;
|
||||
let answered = false;
|
||||
for (const h of hosts) {
|
||||
try {
|
||||
const tasks = await taskList(token, h);
|
||||
if (tasks) {
|
||||
answered = true;
|
||||
task = tasks.find((x) => x?.task_id === "daily_signin") ?? null;
|
||||
break;
|
||||
}
|
||||
} catch (e) {
|
||||
lastErr = e;
|
||||
if (e?.banned) break;
|
||||
}
|
||||
}
|
||||
if (!task && !answered) throw lastErr ?? new Error("AutoClaw task-list 双 host 无响应");
|
||||
if (!task) return { outcome: "inactive", message: "当前没有签到活动" };
|
||||
if (String(task.status ?? "") === "completed") {
|
||||
return { outcome: "done", credit: optNumber(task.reward_points) };
|
||||
}
|
||||
// 补签(主 host 优先,无响应再试备用 host;服务端幂等)
|
||||
const r = await dailySignin(token, hosts[0]).catch(() => null)
|
||||
?? await dailySignin(token, hosts[1] ?? hosts[0]).catch(() => null);
|
||||
const result = checkinOutcome(r);
|
||||
if (!uiReached && result.message) {
|
||||
result.message = `${result.message}(登录活动奖励未触发)`;
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
try {
|
||||
return await attempt();
|
||||
} catch (e) {
|
||||
// 封禁是账号问题、不是登录失效:不重试,让失败消息(含封禁文案)原样上卡;
|
||||
// 账号状态标记仍由 usage / 请求链路完成。
|
||||
if (e?.banned || e?.signIn === "kept") throw e;
|
||||
if (e?.signIn !== "expired") throw e;
|
||||
// 当前 AT 被拒:refresh 一次(单飞 + CAS 写回 + 轮换兜底),整轮重试一次。
|
||||
await renewOnce();
|
||||
return await attempt();
|
||||
}
|
||||
},
|
||||
},
|
||||
|
||||
@@ -1602,6 +1764,7 @@ export const _internal = {
|
||||
makePluginForTest: makeAutoclawPlugin,
|
||||
platformTm, setOfficialChatHeaders, conversationSessionId, stainlessOs, stainlessArch, md5Hex, jwtClaim, tokenFields, codeValue, bizHeaders, bareToken, newDeviceId,
|
||||
dailySignin, signinStatus, maybeSignin, signinAccountKey, signinConfig, checkinOutcome, refreshTokens,
|
||||
clearRefreshGates: () => refreshGates.clear(),
|
||||
balanceObserve, usageStatePath: () => usageStatePath ?? usageStatePathDefault(), setUsageStatePath, beijingDayOf,
|
||||
fetchUserProfile, accountDeviceId, accountDisplayName, startLocalOAuth,
|
||||
FLAGGED, unflagged, unflag, tidyBody, rewriteManagedBody, autoclawRewriteBody, explained, OFFICIAL_SYSTEM_PROMPT, REFUSED_HINT,
|
||||
|
||||
@@ -1009,7 +1009,8 @@ test("usage and check-in of a banned account say the ban and keep the sign-in",
|
||||
let threw
|
||||
try { await hooks.auth.checkin(async () => ({ type: "oauth", access: "a1", refresh: "r1" })) } catch (e) { threw = e }
|
||||
expect(threw.message).toBe("AutoClaw: The account has been banned")
|
||||
expect(urls.length).toBe(1)
|
||||
expect(threw.signIn).toBe("kept")
|
||||
expect(urls.some((u) => u.includes("autoclaw-task-complete"))).toBe(false)
|
||||
}
|
||||
} finally {
|
||||
globalThis.fetch = realFetch
|
||||
@@ -1148,7 +1149,373 @@ test("usage: the spend window across two reads, and a check-in that reopens the
|
||||
}
|
||||
})
|
||||
|
||||
// Two accounts can carry the same display name (#254), so the ledger key is
|
||||
// ── login event claim(user-info → 活动奖励;每日签到仍是 task-complete)──
|
||||
|
||||
const claimJwt = (deviceId) => jwt({ device_id: deviceId, exp: Math.floor(Date.now() / 1000) + 86400, source_id: "autoclaw" })
|
||||
const claimAuth = (deviceId, extra = {}) => ({
|
||||
type: "oauth", access: `at-${deviceId}`, refresh: claimJwt(deviceId),
|
||||
accountId: "测试账号", uid: `u-${deviceId}`, ...extra,
|
||||
})
|
||||
const okUserInfo = () => Response.json({ code: 0, msg: "SUCCESS", data: { uid: "u1", daily_check_included: false, daily_check_in_completed_on_request: false } })
|
||||
const pendingTask = (reward = 400) => Response.json({ code: 0, data: [{ task_id: "daily_signin", status: "pending", reward_points: reward }] })
|
||||
const completedTask = (reward = 400) => Response.json({ code: 0, data: [{ task_id: "daily_signin", status: "completed", reward_points: reward }] })
|
||||
const signedTask = (reward = 400, streak = 1) => Response.json({ code: 0, data: { success: true, reward_points: reward, continuous_days: streak } })
|
||||
|
||||
// 桌面端指纹是这次修复的全部前提:极简头同样 code=0 却不发奖励(#3681)。
|
||||
// 这个测试直接检查线上请求,任何一处头/令牌/设备号回退都会变红。
|
||||
test("checkin: user-info carries the desktop fingerprint, the current access token and the login device id", async () => {
|
||||
const realFetch = globalThis.fetch
|
||||
const seen = []
|
||||
const auth = claimAuth("qc-fingerprint")
|
||||
globalThis.fetch = async (input, init) => {
|
||||
const url = String(input)
|
||||
if (url.includes("/userapi/v1/user-info")) {
|
||||
seen.push({ host: new URL(url).host, headers: new Headers(init?.headers), body: JSON.parse(String(init?.body ?? "{}")) })
|
||||
return okUserInfo()
|
||||
}
|
||||
if (url.includes("/userapi/v1/refresh") || url.includes("/agent-refresh")) throw new Error("access token 可用时不该花 refresh token")
|
||||
if (url.includes("autoclaw-task-list")) return completedTask()
|
||||
return Response.json({ code: 0, data: {} })
|
||||
}
|
||||
try {
|
||||
const hooks = await AutoclawAuthPlugin({ client: { auth: { set: async () => {} } } }, {})
|
||||
const result = await hooks.auth.checkin(async () => auth)
|
||||
expect(result.outcome).toBe("done")
|
||||
const ui = seen[0]
|
||||
expect(ui).toBeDefined()
|
||||
expect(ui.headers.get("X-Channel")).toBe("AutoClaw20")
|
||||
expect(ui.headers.get("X-Version")).toBe("2.2.0")
|
||||
expect(ui.headers.get("X-Tm")).toBe("win-x64")
|
||||
expect(ui.headers.get("X-Product")).toBe("autoclaw")
|
||||
expect(ui.headers.get("User-Agent")).toBe("AutoClaw/2.2.0 (win-x64)")
|
||||
expect(ui.headers.get("Authorization")).toBe(`Bearer ${auth.access}`)
|
||||
expect(ui.body.device_id).toBe("qc-fingerprint")
|
||||
expect(seen.every((s) => !String(s.headers.get("Authorization")).includes("undefined"))).toBe(true)
|
||||
} finally {
|
||||
globalThis.fetch = realFetch
|
||||
}
|
||||
})
|
||||
|
||||
test("checkin: user-info runs before task-complete and the daily credit comes from task-complete", async () => {
|
||||
const realFetch = globalThis.fetch
|
||||
const calls = []
|
||||
globalThis.fetch = async (input) => {
|
||||
const url = String(input)
|
||||
calls.push(url)
|
||||
if (url.includes("/userapi/v1/user-info")) return okUserInfo()
|
||||
if (url.includes("/userapi/v1/refresh") || url.includes("/agent-refresh")) throw new Error("不该刷新")
|
||||
if (url.includes("autoclaw-task-list")) return pendingTask(999) // 故意与签到奖励不同,验证 credit 来源
|
||||
if (url.includes("autoclaw-task-complete")) return signedTask(400, 3)
|
||||
return Response.json({ code: 0, data: {} })
|
||||
}
|
||||
try {
|
||||
const hooks = await AutoclawAuthPlugin({ client: { auth: { set: async () => {} } } }, {})
|
||||
const result = await hooks.auth.checkin(async () => claimAuth("qc-order"))
|
||||
expect(result.outcome).toBe("claimed")
|
||||
expect(result.credit).toBe(400)
|
||||
expect(result.streak).toBe(3)
|
||||
expect(calls.findIndex((c) => c.includes("/userapi/v1/user-info"))).toBeLessThan(
|
||||
calls.findIndex((c) => c.includes("autoclaw-task-complete")),
|
||||
)
|
||||
expect(calls.some((c) => c.includes("/userapi/v1/refresh"))).toBe(false)
|
||||
} finally {
|
||||
globalThis.fetch = realFetch
|
||||
}
|
||||
})
|
||||
|
||||
test("checkin: task-list already completed → done, without calling task-complete", async () => {
|
||||
const realFetch = globalThis.fetch
|
||||
const calls = []
|
||||
globalThis.fetch = async (input) => {
|
||||
const url = String(input)
|
||||
calls.push(url)
|
||||
if (url.includes("/userapi/v1/user-info")) return okUserInfo()
|
||||
if (url.includes("autoclaw-task-list")) return completedTask()
|
||||
return Response.json({ code: 0, data: {} })
|
||||
}
|
||||
try {
|
||||
const hooks = await AutoclawAuthPlugin({ client: { auth: { set: async () => {} } } }, {})
|
||||
const result = await hooks.auth.checkin(async () => claimAuth("qc-done"))
|
||||
expect(result.outcome).toBe("done")
|
||||
expect(result.credit).toBe(400)
|
||||
expect(calls.some((c) => c.includes("autoclaw-task-complete"))).toBe(false)
|
||||
} finally {
|
||||
globalThis.fetch = realFetch
|
||||
}
|
||||
})
|
||||
|
||||
test("checkin: user-info rejected on host[0] is retried on host[1]", async () => {
|
||||
const realFetch = globalThis.fetch
|
||||
const hosts = []
|
||||
globalThis.fetch = async (input) => {
|
||||
const url = String(input)
|
||||
if (url.includes("/userapi/v1/user-info")) {
|
||||
const host = new URL(url).host
|
||||
hosts.push(host)
|
||||
return host === "autoglm-api.autoglm.ai"
|
||||
? Response.json({ code: 410000, msg: "用户未登录" })
|
||||
: okUserInfo()
|
||||
}
|
||||
if (url.includes("autoclaw-task-list")) return pendingTask()
|
||||
if (url.includes("autoclaw-task-complete")) return signedTask()
|
||||
return Response.json({ code: 0, data: {} })
|
||||
}
|
||||
try {
|
||||
const hooks = await AutoclawAuthPlugin({ client: { auth: { set: async () => {} } } }, {})
|
||||
const result = await hooks.auth.checkin(async () => claimAuth("qc-hostfallback"))
|
||||
expect(hosts).toEqual(["autoglm-api.autoglm.ai", "autoglm-api.zhipuai.cn"])
|
||||
expect(result.outcome).toBe("claimed")
|
||||
} finally {
|
||||
globalThis.fetch = realFetch
|
||||
}
|
||||
})
|
||||
|
||||
test("checkin: a user-info network failure never blocks the daily signin and is reported", async () => {
|
||||
const realFetch = globalThis.fetch
|
||||
const hosts = []
|
||||
globalThis.fetch = async (input) => {
|
||||
const url = String(input)
|
||||
if (url.includes("/userapi/v1/user-info")) {
|
||||
const host = new URL(url).host
|
||||
hosts.push(host)
|
||||
if (host === "autoglm-api.autoglm.ai") throw new TypeError("fetch failed")
|
||||
return Response.json({ code: 410000, msg: "用户未登录" })
|
||||
}
|
||||
if (url.includes("autoclaw-task-list")) return pendingTask()
|
||||
if (url.includes("autoclaw-task-complete")) return signedTask()
|
||||
return Response.json({ code: 0, data: {} })
|
||||
}
|
||||
try {
|
||||
const hooks = await AutoclawAuthPlugin({ client: { auth: { set: async () => {} } } }, {})
|
||||
const result = await hooks.auth.checkin(async () => claimAuth("qc-campaignfail"))
|
||||
expect(hosts).toEqual(["autoglm-api.autoglm.ai", "autoglm-api.zhipuai.cn"])
|
||||
expect(result.outcome).toBe("claimed")
|
||||
expect(result.credit).toBe(400)
|
||||
expect(result.message).toContain("登录活动奖励未触发")
|
||||
} finally {
|
||||
globalThis.fetch = realFetch
|
||||
}
|
||||
})
|
||||
|
||||
// 两个 host 都查不到任务时绝不能报 inactive:那会把当天判死(#3326)。
|
||||
test("checkin: both task-list hosts failing throws (failed), never misreports inactive", async () => {
|
||||
const realFetch = globalThis.fetch
|
||||
globalThis.fetch = async (input) => {
|
||||
const url = String(input)
|
||||
if (url.includes("/userapi/v1/user-info")) return okUserInfo()
|
||||
if (url.includes("autoclaw-task-list")) return new Response('{"message":"oops"}', { status: 500 })
|
||||
return Response.json({ code: 0, data: {} })
|
||||
}
|
||||
try {
|
||||
const hooks = await AutoclawAuthPlugin({ client: { auth: { set: async () => {} } } }, {})
|
||||
let threw
|
||||
try { await hooks.auth.checkin(async () => claimAuth("qc-tasklistfail")) } catch (e) { threw = e }
|
||||
expect(threw).toBeInstanceOf(Error)
|
||||
expect(threw.message).toContain("task-list")
|
||||
} finally {
|
||||
globalThis.fetch = realFetch
|
||||
}
|
||||
})
|
||||
|
||||
test("checkin: an expired access token is refreshed once, then the whole round is retried", async () => {
|
||||
const realFetch = globalThis.fetch
|
||||
const freshAccess = claimJwt("qc-fresh-token")
|
||||
const auth = claimAuth("qc-expired")
|
||||
const sets = []
|
||||
let stage = "old"
|
||||
let refreshes = 0
|
||||
globalThis.fetch = async (input) => {
|
||||
const url = String(input)
|
||||
if (url.includes("/userapi/v1/refresh") || url.includes("/agent-refresh")) {
|
||||
refreshes++
|
||||
stage = "new"
|
||||
return Response.json({ code: 0, msg: "SUCCESS", data: { access_token: freshAccess, refresh_token: "rt-qc-fresh" } })
|
||||
}
|
||||
if (url.includes("/userapi/v1/user-info")) return stage === "new" ? okUserInfo() : Response.json({ code: 410000, msg: "用户未登录" })
|
||||
if (url.includes("autoclaw-task-list")) return stage === "new" ? pendingTask() : new Response("{}", { status: 401 })
|
||||
if (url.includes("autoclaw-task-complete")) return signedTask(400, 2)
|
||||
return Response.json({ code: 0, data: {} })
|
||||
}
|
||||
try {
|
||||
const hooks = await AutoclawAuthPlugin({ client: { auth: { set: async (o) => { sets.push(o); return { data: true } } } } }, {})
|
||||
const result = await hooks.auth.checkin(async () => auth)
|
||||
expect(refreshes).toBe(1)
|
||||
expect(result.outcome).toBe("claimed")
|
||||
expect(result.credit).toBe(400)
|
||||
expect(sets.length).toBe(1)
|
||||
expect(sets[0].path.id).toBe("autoclaw")
|
||||
expect(sets[0].body.refresh).toBe("rt-qc-fresh")
|
||||
expect(sets[0].body.access).toBe(freshAccess)
|
||||
expect(sets[0].body.accountId).toBe(auth.accountId)
|
||||
expect(sets[0].body.uid).toBe(auth.uid)
|
||||
} finally {
|
||||
globalThis.fetch = realFetch
|
||||
}
|
||||
})
|
||||
|
||||
test("checkin: a dead refresh token with an expired access token fails with signIn expired", async () => {
|
||||
const realFetch = globalThis.fetch
|
||||
globalThis.fetch = async (input) => {
|
||||
const url = String(input)
|
||||
if (url.includes("/userapi/v1/refresh") || url.includes("/agent-refresh")) {
|
||||
return Response.json({ code: 400002, msg: "invalid_grant: token has been revoked" })
|
||||
}
|
||||
if (url.includes("/userapi/v1/user-info")) return Response.json({ code: 410000, msg: "用户未登录" })
|
||||
if (url.includes("autoclaw-task-list")) return new Response("{}", { status: 401 })
|
||||
return Response.json({ code: 0, data: {} })
|
||||
}
|
||||
try {
|
||||
const hooks = await AutoclawAuthPlugin({ client: { auth: { set: async () => {} } } }, {})
|
||||
let threw
|
||||
try { await hooks.auth.checkin(async () => claimAuth("qc-deadrt")) } catch (e) { threw = e }
|
||||
expect(threw).toBeInstanceOf(Error)
|
||||
expect(threw.signIn).toBe("expired")
|
||||
} finally {
|
||||
globalThis.fetch = realFetch
|
||||
}
|
||||
})
|
||||
|
||||
// CAS:签到期间用户重新登录,旧轮换绝不能覆盖新记录。
|
||||
test("checkin: a re-sign-in during the refresh is not clobbered by the rotation write", async () => {
|
||||
const realFetch = globalThis.fetch
|
||||
const auth = claimAuth("qc-resignin")
|
||||
const reauth = claimAuth("qc-resignin-new")
|
||||
const sets = []
|
||||
let stage = "old"
|
||||
let reads = 0
|
||||
globalThis.fetch = async (input) => {
|
||||
const url = String(input)
|
||||
if (url.includes("/userapi/v1/refresh") || url.includes("/agent-refresh")) {
|
||||
stage = "new"
|
||||
return Response.json({ code: 0, msg: "SUCCESS", data: { access_token: claimJwt("qc-resignin-fresh"), refresh_token: "rt-qc-resignin-fresh" } })
|
||||
}
|
||||
if (url.includes("/userapi/v1/user-info")) return stage === "new" ? okUserInfo() : Response.json({ code: 410000, msg: "用户未登录" })
|
||||
if (url.includes("autoclaw-task-list")) return stage === "new" ? pendingTask() : new Response("{}", { status: 401 })
|
||||
if (url.includes("autoclaw-task-complete")) return signedTask()
|
||||
return Response.json({ code: 0, data: {} })
|
||||
}
|
||||
try {
|
||||
const hooks = await AutoclawAuthPlugin({ client: { auth: { set: async (o) => { sets.push(o); return { data: true } } } } }, {})
|
||||
const getAuth = async () => (++reads === 1 ? auth : reauth)
|
||||
const result = await hooks.auth.checkin(getAuth)
|
||||
expect(result.outcome).toBe("claimed")
|
||||
expect(sets.length).toBe(0)
|
||||
} finally {
|
||||
globalThis.fetch = realFetch
|
||||
}
|
||||
})
|
||||
|
||||
// 写回失败时,已花费的旧 RT 换出的新令牌必须留在内存供下一次续期取用。
|
||||
test("checkin: a failed rotation write is remembered for the next renewal", async () => {
|
||||
const realFetch = globalThis.fetch
|
||||
const freshAccess = claimJwt("qc-persistfail-fresh")
|
||||
const auth = claimAuth("qc-persistfail")
|
||||
let stage = "old"
|
||||
let refreshes = 0
|
||||
globalThis.fetch = async (input) => {
|
||||
const url = String(input)
|
||||
if (url.includes("/userapi/v1/refresh") || url.includes("/agent-refresh")) {
|
||||
refreshes++
|
||||
stage = "new"
|
||||
return Response.json({ code: 0, msg: "SUCCESS", data: { access_token: freshAccess, refresh_token: "rt-qc-persistfail-fresh" } })
|
||||
}
|
||||
if (url.includes("/userapi/v1/user-info")) return stage === "new" ? okUserInfo() : Response.json({ code: 410000, msg: "用户未登录" })
|
||||
if (url.includes("autoclaw-task-list")) return stage === "new" ? pendingTask() : new Response("{}", { status: 401 })
|
||||
if (url.includes("autoclaw-task-complete")) return signedTask()
|
||||
return Response.json({ code: 0, data: {} })
|
||||
}
|
||||
try {
|
||||
const hooks = await AutoclawAuthPlugin({ client: { auth: { set: async () => { throw new Error("EACCES") } } } }, {})
|
||||
const result = await hooks.auth.checkin(async () => auth)
|
||||
expect(result.outcome).toBe("claimed")
|
||||
// 清掉 60 秒单飞缓存:这一步之后只有 rotatedMemo 能解释「不打网络」,
|
||||
// 删掉 rememberRotated 的改动会立刻让下面两个断言变红。
|
||||
_internal.clearRefreshGates()
|
||||
const before = refreshes
|
||||
const t = await hooks.auth.refresh(auth)
|
||||
expect(refreshes).toBe(before)
|
||||
expect(t.access).toBe(freshAccess)
|
||||
expect(t.refresh).toBe("rt-qc-persistfail-fresh")
|
||||
} finally {
|
||||
globalThis.fetch = realFetch
|
||||
}
|
||||
})
|
||||
|
||||
test("checkin: task-complete already_completed → done, not failed", async () => {
|
||||
const realFetch = globalThis.fetch
|
||||
globalThis.fetch = async (input) => {
|
||||
const url = String(input)
|
||||
if (url.includes("/userapi/v1/user-info")) return okUserInfo()
|
||||
if (url.includes("autoclaw-task-list")) return pendingTask()
|
||||
if (url.includes("autoclaw-task-complete")) {
|
||||
return Response.json({ code: 0, data: { success: false, already_completed: true, reward_points: 400 } })
|
||||
}
|
||||
return Response.json({ code: 0, data: {} })
|
||||
}
|
||||
try {
|
||||
const hooks = await AutoclawAuthPlugin({ client: { auth: { set: async () => {} } } }, {})
|
||||
const result = await hooks.auth.checkin(async () => claimAuth("qc-already"))
|
||||
expect(result.outcome).toBe("done")
|
||||
expect(result.credit).toBe(400)
|
||||
} finally {
|
||||
globalThis.fetch = realFetch
|
||||
}
|
||||
})
|
||||
|
||||
test("checkin: a ban surfacing at task-list keeps the sign-in and propagates the ban", async () => {
|
||||
const realFetch = globalThis.fetch
|
||||
const calls = []
|
||||
globalThis.fetch = async (input) => {
|
||||
const url = String(input)
|
||||
calls.push(url)
|
||||
if (url.includes("/userapi/v1/user-info")) return okUserInfo()
|
||||
if (url.includes("autoclaw-task-list")) return new Response(BANNED, { status: 403 })
|
||||
return Response.json({ code: 0, data: {} })
|
||||
}
|
||||
try {
|
||||
const hooks = await AutoclawAuthPlugin({ client: { auth: { set: async () => {} } } }, {})
|
||||
let threw
|
||||
try { await hooks.auth.checkin(async () => claimAuth("qc-ban")) } catch (e) { threw = e }
|
||||
expect(threw.message).toBe("AutoClaw: The account has been banned")
|
||||
expect(threw.signIn).toBe("kept")
|
||||
expect(calls.some((c) => c.includes("autoclaw-task-complete"))).toBe(false)
|
||||
} finally {
|
||||
globalThis.fetch = realFetch
|
||||
}
|
||||
})
|
||||
|
||||
// 同一个一次性 RT 的并发续期只能打一次网络(单飞);按创建时间过期会烧第二次。
|
||||
test("checkin: two concurrent expired-token checkins share one refresh", async () => {
|
||||
const realFetch = globalThis.fetch
|
||||
const auth = claimAuth("qc-concurrent")
|
||||
let stage = "old"
|
||||
let refreshes = 0
|
||||
globalThis.fetch = async (input) => {
|
||||
const url = String(input)
|
||||
if (url.includes("/userapi/v1/refresh") || url.includes("/agent-refresh")) {
|
||||
refreshes++
|
||||
stage = "new"
|
||||
return Response.json({ code: 0, msg: "SUCCESS", data: { access_token: claimJwt("qc-concurrent-fresh"), refresh_token: "rt-qc-concurrent-fresh" } })
|
||||
}
|
||||
if (url.includes("/userapi/v1/user-info")) return stage === "new" ? okUserInfo() : Response.json({ code: 410000, msg: "用户未登录" })
|
||||
if (url.includes("autoclaw-task-list")) return stage === "new" ? pendingTask() : new Response("{}", { status: 401 })
|
||||
if (url.includes("autoclaw-task-complete")) return signedTask()
|
||||
return Response.json({ code: 0, data: {} })
|
||||
}
|
||||
try {
|
||||
const hooks = await AutoclawAuthPlugin({ client: { auth: { set: async () => ({ data: true }) } } }, {})
|
||||
const [a, b] = await Promise.all([
|
||||
hooks.auth.checkin(async () => auth),
|
||||
hooks.auth.checkin(async () => auth),
|
||||
])
|
||||
expect(refreshes).toBe(1)
|
||||
expect(a.outcome).toBe("claimed")
|
||||
expect(b.outcome).toBe("claimed")
|
||||
} finally {
|
||||
globalThis.fetch = realFetch
|
||||
}
|
||||
})
|
||||
|
||||
// signinAccountKey - uid, or the refresh token when an old account has none -
|
||||
// never the name. Both accounts here have NO uid on purpose: the pre-review
|
||||
// key (uid ?? accountId ?? provider) fell back to the shared display name and
|
||||
@@ -1214,3 +1581,4 @@ test("usage: an unreadable total_balance is unknown, not a drained pool", async
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ 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() {
|
||||
function record(device = DEVICE) {
|
||||
const realFetch = globalThis.fetch
|
||||
const sent = []
|
||||
globalThis.fetch = async (input, init) => {
|
||||
@@ -17,8 +17,8 @@ function record() {
|
||||
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" }),
|
||||
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" } })
|
||||
@@ -28,11 +28,15 @@ function record() {
|
||||
}
|
||||
|
||||
test("a refresh and a chat send nothing upstream that names magpie", async () => {
|
||||
for (const Plugin of [AutoclawAuthPlugin, AutoclawCnAuthPlugin]) {
|
||||
const { sent, restore } = record()
|
||||
// 每次迭代用不同的 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 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 }))
|
||||
@@ -46,10 +50,12 @@ test("a refresh and a chat send nothing upstream that names magpie", async () =>
|
||||
}
|
||||
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)
|
||||
expect(JSON.parse(profile.body).device_id).toBe(device)
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-autoclaw-auth",
|
||||
"version": "0.2.14",
|
||||
"version": "0.2.15",
|
||||
"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": "./opencode.mjs",
|
||||
|
||||
Reference in New Issue
Block a user