WorkBuddy、CodeBuddy 桌面端增强助手:签到猫猫旅行成长计划查询、多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能。
fix(workbuddy): support multichannel auth and issuer routing
Jinhui Zhengc28c2dac5f77
diff --git a/scripts/checkin-result.js b/scripts/checkin-result.jsindex fec7d78..6b4b272 100644--- a/scripts/checkin-result.js+++ b/scripts/checkin-result.js@@ -2,6 +2,12 @@const INACTIVE_MESSAGE = /未开启|未开始|未开放|已过期|无.*活动|活动.*(?:结束|关闭|暂停)/i;const ALREADY_MESSAGE = /已签到|已领取|已经.*(?:签到|领取)|重复签到|already\s*(?:checked[- ]?in|claimed)|already/i;+const CHECKIN_PATHS = ['/billing/meter/daily-checkin', '/v2/billing/meter/daily-checkin'];+const ISSUER_HOST_MAP = new Map([+ ['https://www.workbuddy.ai', 'https://www.workbuddy.ai'],+ ['https://www.workbuddy.cn', 'https://www.workbuddy.cn'],+ ['https://www.codebuddy.cn', 'https://www.codebuddy.cn'],+]);function numericCode(value) {if (value === null || value === undefined || value === '') return null;@@ -20,8 +26,49 @@ function classifyCheckinResult({ httpOk, code, message }) {const text = String(message || '');const inactive = INACTIVE_MESSAGE.test(text);const already = normalizedCode === 10001 && !inactive && ALREADY_MESSAGE.test(text);- const ok = !!httpOk && !inactive && (normalizedCode === 0 || already);+ // The official service returns business code 10001 with HTTP 400 for an+ // already-completed daily check-in. Accept that state only when the message+ // explicitly proves completion; code=0 still requires an HTTP success.+ const ok = !inactive && ((normalizedCode === 0 && !!httpOk) || already);return { ok, already, inactive, code: normalizedCode, message: text };}-module.exports = { classifyCheckinResult, INACTIVE_MESSAGE, ALREADY_MESSAGE };+function tokenIssuerOrigin(accessToken) {+ try {+ const part = String(accessToken || '').split('.')[1];+ if (!part) return null;+ const padded = part.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (part.length % 4)) % 4);+ const payload = JSON.parse(Buffer.from(padded, 'base64').toString('utf8'));+ return new URL(String(payload.iss || '')).origin;+ } catch (_) {+ return null;+ }+}++function checkinEndpointsForToken(accessToken, profile = {}) {+ const issuerOrigin = tokenIssuerOrigin(accessToken);+ const issuerHost = issuerOrigin ? ISSUER_HOST_MAP.get(issuerOrigin) : null;+ const hosts = [];+ if (issuerHost) {+ // A recognized issuer is authoritative. Do not send its bearer token to unrelated hosts.+ hosts.push(issuerHost);+ } else {+ const profileHost = String(profile.apiHost || 'https://www.workbuddy.cn').replace(/\/+$/, '');+ hosts.push(profileHost);+ if (profile.region === 'cn') {+ for (const host of ['https://www.codebuddy.cn', 'https://www.workbuddy.cn']) {+ if (!hosts.includes(host)) hosts.push(host);+ }+ }+ }+ return hosts.flatMap((host) => CHECKIN_PATHS.map((pathname) => host + pathname));+}++module.exports = {+ classifyCheckinResult,+ tokenIssuerOrigin,+ checkinEndpointsForToken,+ INACTIVE_MESSAGE,+ ALREADY_MESSAGE,+ ISSUER_HOST_MAP,+};diff --git a/scripts/daemon.js b/scripts/daemon.jsindex 4fa9d94..56fa4c2 100644--- a/scripts/daemon.js+++ b/scripts/daemon.js@@ -63,6 +63,9 @@ try { wsLib = require('ws'); } catch (_) {const WebSocketCtor = globalThis.WebSocket || (wsLib && (wsLib.WebSocket || wsLib));const {AUTH_FILE,+ authDir,+ listAuthFiles,+ currentAuthFile,defaultDataDir,logFile,ensureDirs,@@ -105,7 +108,7 @@ const { extractCreditSegments, sortCreditSegments, mergeCreditSegments, parseEntconst { buildCreditResourceBody } = require('./credit-resource-queries.js');const { fetchUsageSinceAnchor, startOfLocalDay } = require('./credit-request-usage.js');const { createCreditUsageStore } = require('./credit-usage-store.js');-const { classifyCheckinResult } = require('./checkin-result.js');+const { classifyCheckinResult, checkinEndpointsForToken } = require('./checkin-result.js');const {captureException,captureMessage,@@ -1423,12 +1426,26 @@ function scheduleBackup(reason) {}, BACKUP_DEBOUNCE);}-// 兜底:登录文件本身变化(每次打开/刷新 WorkBuddy 都会重写该文件)-if (AUTH_FILE) fs.watchFile(AUTH_FILE, { interval: WATCH_INTERVAL }, (cur, prev) => {- // 文件被移走(如"假退出登录")时不应触发备份;仅当文件存在且 mtime 变化才备份- if (!fs.existsSync(AUTH_FILE)) return;- if (cur.mtimeMs !== prev.mtimeMs) scheduleBackup('file-change');-});+// 兜底:5.4.x 可能按登录渠道创建不同 <authenticationId>.info。+// 监听整个 auth 目录,真正备份时仍由 lib.js 校验 profile/文件结构,避免误收其他产品文件。+if (AUTH_FILE) {+ const dir = authDir();+ if (dir) {+ try {+ fs.watch(dir, (event, filename) => {+ if (filename && !/\.info$/i.test(String(filename))) return;+ scheduleBackup('auth-directory-change');+ });+ } catch (e) {+ log(`[sync] 无法监听认证目录,保留固定文件轮询兜底: ${e.message}`);+ }+ }+ // 保留旧固定文件轮询,兼容部分平台/网络盘上 fs.watch 不可靠的情况。+ fs.watchFile(AUTH_FILE, { interval: WATCH_INTERVAL }, (cur, prev) => {+ if (!fs.existsSync(AUTH_FILE)) return;+ if (cur.mtimeMs !== prev.mtimeMs) scheduleBackup('file-change');+ });+}/* ================= CDP 客户端(Node 22 内置 WebSocket,零依赖) ================= */@@ -1442,8 +1459,19 @@ const cdp = {id: 0,pending: new Map(),manualClose: false,+ everConnected: false,};+const CDP_HEAL_GRACE_MS = 90 * 1000;+const CDP_HEAL_COOLDOWN_MS = 3 * 60 * 1000;+let cdpLostAt = 0;+let cdpHealSuppressedUntil = 0;+let cdpHealInFlight = false;++function suppressCdpHeal(ms = CDP_HEAL_COOLDOWN_MS) {+ cdpHealSuppressedUntil = Math.max(cdpHealSuppressedUntil, Date.now() + ms);+}+const DIAGNOSTICS_FILE = path.join(DATA_DIR, 'diagnostics-latest.json');const DAEMON_LOCK_FILE = path.join(DATA_DIR, '.daemon.lock');// Windows 上旧版可能以不同权限创建锁文件,导致当前用户无法覆盖;临时锁按数据目录哈希隔离。@@ -1613,6 +1641,8 @@ async function connectCdp() {ws.onopen = () => {cdp.ws = ws;cdp.connected = true;+ cdp.everConnected = true;+ cdpLostAt = 0;cdp.error = null;cdp.targetUrl = target.url || '';cdp.targetTitle = target.title || '';@@ -1657,6 +1687,7 @@ async function connectCdp() {ws.onclose = () => {cdp.connected = false;cdp.ws = null;+ if (cdp.everConnected && !cdpLostAt) cdpLostAt = Date.now();log('[cdp] 连接已断开,5 秒后重连');};});@@ -1715,11 +1746,51 @@ async function cdpLoop() {} catch (e) {log(`[cdp] 连接异常: ${e.message}`);}+ if (!cdp.connected) {+ try { await maybeHealCdp(); } catch (e) { log(`[heal] CDP 自愈检查失败: ${e.message}`); }+ }}await new Promise((r) => setTimeout(r, CDP_RECONNECT_MS));}}+async function maybeHealCdp() {+ if (cdp.connected || cdpHealInFlight) return false;+ const coldStartEligible = IS_WIN && process.env.WBSWITCH_NATIVE_LAUNCHER === '1';+ if (!cdp.everConnected && !coldStartEligible) return false;+ const now = Date.now();+ if (!cdpLostAt) cdpLostAt = now;+ if (now - cdpLostAt < CDP_HEAL_GRACE_MS || now < cdpHealSuppressedUntil) return false;++ // Re-check the endpoint immediately before any lifecycle action to avoid racing a slow restart.+ if (await findCdpEndpoint()) return false;+ let running = false;+ try { running = workBuddyRunning(); } catch (e) {+ log(`[heal] 无法安全确认 WorkBuddy 进程归属,跳过自动重启: ${e.message}`);+ suppressCdpHeal();+ return false;+ }+ if (!running) {+ // User closed WorkBuddy intentionally; never reopen it from the reconnect loop.+ cdpLostAt = 0;+ return false;+ }++ cdpHealInFlight = true;+ suppressCdpHeal();+ try {+ log('[heal] WorkBuddy 仍在运行但 CDP 端口持续缺失,正在以受管 CDP 配置重启');+ await quitWorkBuddy();+ await sleep(1200);+ await relaunchWorkBuddy();+ cdpLostAt = Date.now();+ log('[heal] 已触发 WorkBuddy CDP 自愈重启');+ return true;+ } finally {+ cdpHealInFlight = false;+ }+}+async function reloadWorkBuddyPage() {if (!cdp.connected) throw new Error('CDP 未连接,无法自动刷新窗口');await cdpSend('Page.reload', { ignoreCache: false });@@ -2201,23 +2272,6 @@ async function waitPageLoaded(timeoutMs = 6000) {*//* ================= 积分自动领取(直接调接口,带每日缓存) ================= */-// 签到接口按 profile 归属域名生成:国际版(WorkBuddy AI)命中 www.workbuddy.ai,-// 国内版保留多域名兜底(workbuddy.cn / codebuddy.cn 账号体系互通)。-function profileCheckinEndpoints() {- const host = PROFILE.apiHost || 'https://www.workbuddy.cn';- const eps = [- `${host}/billing/meter/daily-checkin`,- `${host}/v2/billing/meter/daily-checkin`,- ];- if (PROFILE.region === 'cn') {- eps.push(- 'https://www.codebuddy.cn/billing/meter/daily-checkin',- 'https://www.codebuddy.cn/v2/billing/meter/daily-checkin'- );- }- return Array.from(new Set(eps));-}-const CHECKIN_ENDPOINTS = profileCheckinEndpoints();const CHECKIN_CACHE_FILE = path.join(DATA_DIR, 'checkin-cache.json');const CHECKIN_REQUEST_TIMEOUT_MS = 12000;const CHECKIN_QUEUE_DELAY_MS = 250;@@ -2256,9 +2310,11 @@ function saveCheckinCache(cache) {* 只有明确 code=0,或 code=10001 且文案明确表示已签到/已领取,才视为成功。*/async function dailyCheckin(accessToken) {- const origin = PROFILE.apiHost || 'https://www.workbuddy.cn';let lastErr = null;- for (const url of CHECKIN_ENDPOINTS) {+ let first401 = null;+ const endpoints = checkinEndpointsForToken(accessToken, PROFILE);+ for (const url of endpoints) {+ const origin = new URL(url).origin;const controller = new AbortController();const timeout = setTimeout(() => controller.abort(), CHECKIN_REQUEST_TIMEOUT_MS);try {@@ -2284,8 +2340,15 @@ async function dailyCheckin(accessToken) {const message = o.msg || o.message || (r.ok ? 'ok' : failMsg);const classified = classifyCheckinResult({ httpOk: r.ok, code: o.code, message });const result = { ...classified, status: r.status, url };- // 网络异常或服务端错误才切换兜底域名;认证/参数错误直接返回,避免无意义地重复请求。- if (classified.ok || r.status === 401 || (r.status >= 400 && r.status < 500 && r.status !== 404) || (r.ok && r.status !== 404)) return result;+ if (classified.ok) return result;+ // 同一 issuer 可能同时暴露 legacy/v2 两条路径;第一条 401 不应阻断第二条。+ if (r.status === 401) {+ if (!first401) first401 = result;+ lastErr = result.message;+ continue;+ }+ // 其他明确客户端错误不做跨域猜测;未知 issuer 才会使用 profile 的既有兜底 host。+ if ((r.status >= 400 && r.status < 500 && r.status !== 404) || (r.ok && r.status !== 404)) return result;lastErr = result.message;} catch (e) {lastErr = e.name === 'AbortError' ? '请求超时(' + (CHECKIN_REQUEST_TIMEOUT_MS / 1000) + ' 秒)' : e.message;@@ -2293,7 +2356,8 @@ async function dailyCheckin(accessToken) {clearTimeout(timeout);}}- return { ok: false, already: false, code: -1, message: lastErr || '未知错误', url: CHECKIN_ENDPOINTS[0] };+ if (first401) return first401;+ return { ok: false, already: false, code: -1, message: lastErr || '未知错误', url: endpoints[0] || null };}/** 对单个账号签到(带每日缓存,幂等:今日已成功过则跳过) */@@ -2538,7 +2602,13 @@ async function collectDiagnostics(reason) {generatedAt: new Date().toISOString(),reason: reason || 'manual',daemon: { version: DAEMON_VERSION, buildId: DAEMON_BUILD_ID, pid: process.pid, platform: process.platform, arch: process.arch, node: process.version },- paths: { dataDir: DATA_DIR, logFile: logFile(DATA_DIR), diagnosticsFile: DIAGNOSTICS_FILE, authFile: AUTH_FILE },+ paths: {+ dataDir: DATA_DIR,+ logFile: logFile(DATA_DIR),+ diagnosticsFile: DIAGNOSTICS_FILE,+ authFile: currentAuthFile(),+ authFiles: listAuthFiles(),+ },cdp: { connected: cdp.connected, port: cdp.port, targetUrl: cdp.targetUrl, error: cdp.error, targets: await readCdpTargets() },injection: null,logTail: readLogTail(),@@ -5671,25 +5741,33 @@ function handleApi(req, res) {return (async () => {let quit = false;let relaunched = false;+ const removed = [];try {// 必须先停宿主:优雅退出可能把内存中的旧身份重新写回登录文件。+ suppressCdpHeal(5 * 60 * 1000);await quitWorkBuddy();quit = true;- if (fs.existsSync(AUTH_FILE)) {- fs.unlinkSync(AUTH_FILE); // token 仍保留在 accounts/ 备份里- log('[logout] WorkBuddy 已退出,已删除登录文件(假退出,token 未过期,备份保留)');+ const authFiles = listAuthFiles();+ if (authFiles.length) {+ for (const file of authFiles) {+ if (!fs.existsSync(file)) continue;+ fs.unlinkSync(file); // token 仍保留在 accounts/ 备份里+ removed.push(path.basename(file));+ }+ log(`[logout] WorkBuddy 已退出,已删除 ${removed.length} 个活动登录文件(假退出,token 未过期,备份保留)`);} else {log('[logout] WorkBuddy 已退出,当前无登录文件');}- if (fs.existsSync(AUTH_FILE)) {- throw new Error('删除登录文件后仍然存在');+ const leftovers = authFiles.filter((file) => fs.existsSync(file));+ if (leftovers.length) {+ throw new Error(`删除登录文件后仍有 ${leftovers.length} 个文件存在`);}await relaunchWorkBuddy();relaunched = true;- return json(res, 200, { ok: true, quit, relaunched });+ return json(res, 200, { ok: true, quit, relaunched, removed });} catch (e) {log(`[logout] 退出/删除/重启 WorkBuddy 失败: ${e.message}`);- return json(res, 502, { ok: false, quit, relaunched, error: e.message });+ return json(res, 502, { ok: false, quit, relaunched, removed, error: e.message });}})();}@@ -7345,7 +7423,8 @@ const sessionCwdRepairTimer = setInterval(() => {}, 5000);sessionCwdRepairTimer.unref && sessionCwdRepairTimer.unref();log('WorkBuddy 多账号切换器启动 (CDP 模式)');-log(`登录信息文件: ${AUTH_FILE}`);+log(`登录信息文件: ${currentAuthFile() || AUTH_FILE}`);+if (listAuthFiles().length > 1) log(`[sync] 当前 profile 检测到 ${listAuthFiles().length} 个活动认证文件`);log(`备份目录: ${DATA_DIR}`);updateDebug('daemon-start', { authFile: AUTH_FILE, dataDir: DATA_DIR, appPath: IS_WIN ? WORKDADDY_DIR_WIN : macWorkDaddyAppPath(), apiPort: UI_PORT_BASE });diff --git a/scripts/lib.js b/scripts/lib.jsindex f1cc565..4f39756 100644--- a/scripts/lib.js+++ b/scripts/lib.js@@ -57,7 +57,121 @@ const AUTH_FILE = process.env.WBSWITCH_AUTH_FILE !== undefined'Library/Application Support/CodeBuddyExtension/Data/Public/auth/workbuddy-desktop.info'))));-const LOGOUT_MARKER = `${AUTH_FILE}.logged-out`;+const DYNAMIC_AUTH_PROFILE = ACTIVE_PROFILE.id === 'workbuddy-ai' && process.env.WBSWITCH_AUTH_FILE === undefined;+const WORKBUDDY_AI_AUTH_DOMAINS = new Set(['www.workbuddy.ai', 'www.workbuddy.cn', 'www.codebuddy.cn']);++function authDir() {+ return AUTH_FILE ? path.dirname(AUTH_FILE) : null;+}++function normalizeAuthDomain(value) {+ let text = String(value || '').trim().toLowerCase();+ if (!text) return '';+ try {+ if (!/^https?:\/\//i.test(text)) text = 'https://' + text;+ return new URL(text).hostname.toLowerCase();+ } catch (_) {+ return '';+ }+}++function tokenIssuerOrigin(accessToken) {+ try {+ const part = String(accessToken || '').split('.')[1];+ if (!part) return '';+ const padded = part.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (part.length % 4)) % 4);+ const payload = JSON.parse(Buffer.from(padded, 'base64').toString('utf8'));+ const parsed = new URL(String(payload.iss || ''));+ return parsed.origin;+ } catch (_) {+ return '';+ }+}++function isTimestampedAuthSnapshot(name) {+ return /\.\d{4}-\d{2}-\d{2}T[\d-]+Z\./i.test(String(name || ''));+}++function safeAuthFileName(name) {+ const value = String(name || '');+ return value.length > 0 && value.length <= 255 && path.basename(value) === value &&+ /\.info$/i.test(value) && !isTimestampedAuthSnapshot(value);+}++function parseAuthFile(file) {+ let json;+ try {+ json = JSON.parse(fs.readFileSync(file, 'utf8'));+ } catch (_) {+ return null;+ }+ if (!json || typeof json !== 'object' || Array.isArray(json)) return null;+ const acct = json.account || (Array.isArray(json.accounts) && json.accounts[0]) || null;+ if (!acct || !acct.uid) return null;+ const auth = json.auth && typeof json.auth === 'object' ? json.auth : {};+ let mtimeMs = 0;+ try { mtimeMs = fs.statSync(file).mtimeMs; } catch (_) {}+ return {+ uid: String(acct.uid),+ nickname: acct.nickname || '',+ uin: acct.uin || '',+ phone: acct.phoneNumber || '',+ type: acct.type || '',+ raw: json,+ file,+ authFileName: path.basename(file),+ authDomain: normalizeAuthDomain(auth.domain),+ authIssuer: tokenIssuerOrigin(auth.accessToken),+ lastLogin: acct.lastLogin === true,+ lastRefreshTime: Number(auth.lastRefreshTime) || 0,+ mtimeMs,+ };+}++function dynamicAuthFileAllowed(file, info) {+ if (!DYNAMIC_AUTH_PROFILE) return samePath(file, AUTH_FILE);+ if (samePath(file, AUTH_FILE)) return true;+ const name = path.basename(file).toLowerCase();+ // The domestic WorkBuddy profile owns this stable file. Do not mix it into WorkDaddy AI.+ if (name === 'workbuddy-desktop.info') return false;+ return !!info && WORKBUDDY_AI_AUTH_DOMAINS.has(info.authDomain);+}++function listAuthFiles() {+ if (!AUTH_FILE) return [];+ if (process.env.WBSWITCH_AUTH_FILE !== undefined || !DYNAMIC_AUTH_PROFILE) {+ return fs.existsSync(AUTH_FILE) ? [AUTH_FILE] : [];+ }+ const dir = authDir();+ let names = [];+ try { names = fs.readdirSync(dir); } catch (_) { return []; }+ const records = [];+ for (const name of names) {+ if (!safeAuthFileName(name)) continue;+ const file = path.join(dir, name);+ let stat;+ try { stat = fs.statSync(file); } catch (_) { continue; }+ if (!stat.isFile()) continue;+ const info = parseAuthFile(file);+ if (!info || !dynamicAuthFileAllowed(file, info)) continue;+ records.push(info);+ }+ records.sort((a, b) => {+ const aScore = (a.lastLogin ? 1e15 : 0) + (a.lastRefreshTime || a.mtimeMs || 0);+ const bScore = (b.lastLogin ? 1e15 : 0) + (b.lastRefreshTime || b.mtimeMs || 0);+ return aScore - bScore;+ });+ return records.map((item) => item.file);+}++function currentAuthFile() {+ const files = listAuthFiles();+ return files.length ? files[files.length - 1] : AUTH_FILE;+}++function logoutMarkerFor(file = AUTH_FILE) {+ return file ? `${file}.logged-out` : null;+}function defaultDataDir() {// 旧版 launchd 可能把 WBSWITCH_DATA_DIR 设成 HelloBuddy;新版本始终落到 WorkDaddy,@@ -781,11 +895,12 @@ function backupPath(dataDir, uid) {}/** WorkBuddy ignores auth files while this marker exists; retire it after a switch. */-function retireLogoutMarker(log = () => {}) {- if (!fs.existsSync(LOGOUT_MARKER)) return false;+function retireLogoutMarker(log = () => {}, authFile = AUTH_FILE) {+ const marker = logoutMarkerFor(authFile);+ if (!marker || !fs.existsSync(marker)) return false;try {- const retired = `${LOGOUT_MARKER}.retired.${process.pid}.${Date.now()}`;- fs.renameSync(LOGOUT_MARKER, retired);+ const retired = `${marker}.retired.${process.pid}.${Date.now()}`;+ fs.renameSync(marker, retired);try {fs.unlinkSync(retired);} catch (_) {@@ -800,12 +915,12 @@ function retireLogoutMarker(log = () => {}) {// WorkBuddy may launch the daemon in a sandbox that cannot unlink auth files.try {const { execFileSync } = require('child_process');- const markerQ = LOGOUT_MARKER.replace(/"/g, '\\"');+ const markerQ = marker.replace(/"/g, '\\"');execFileSync('osascript', ['-e', `do shell script "rm -f \\\"${markerQ}\\\""`], {timeout: 15000,stdio: 'pipe',});- if (fs.existsSync(LOGOUT_MARKER)) throw new Error('标记仍然存在');+ if (fs.existsSync(marker)) throw new Error('标记仍然存在');log('[switch] 已通过系统授权清理 WorkBuddy 登录退出标记');return true;} catch (e2) {@@ -874,27 +989,14 @@ function ensureDirs(dataDir, log = () => {}) {}/** 读取登录信息文件并抽取账号关键字段(不返回令牌内容) */-function readAuthFile() {+function readAuthFile(file = currentAuthFile()) {if (!ACTIVE_PROFILE.authFile && !process.env.WBSWITCH_AUTH_FILE) {throw new Error(`${ACTIVE_PROFILE.name} 没有可读取的明文认证文件`);}- const raw = fs.readFileSync(AUTH_FILE, 'utf8');- const json = JSON.parse(raw);- if (!json || typeof json !== 'object') {- throw new Error('auth 文件不是有效的 JSON 对象');- }- const acct = json.account || (Array.isArray(json.accounts) && json.accounts[0]) || null;- if (!acct || !acct.uid) {- throw new Error('auth 文件中未找到 account.uid');- }- return {- uid: acct.uid,- nickname: acct.nickname || '',- uin: acct.uin || '',- phone: acct.phoneNumber || '',- type: acct.type || '',- raw: json,- };+ if (!file) throw new Error('未找到登录信息文件');+ const info = parseAuthFile(file);+ if (!info) throw new Error(`auth 文件无效或缺少 account.uid: ${path.basename(file)}`);+ return info;}/** 更新 meta.json(uid -> nickname/uin/phone/时间) */@@ -907,6 +1009,9 @@ function updateMeta(dataDir, info) {nickname: info.nickname || prev.nickname || '',uin: info.uin || prev.uin || '',phone: info.phone || prev.phone || '',+ authFileName: info.authFileName || prev.authFileName || '',+ authDomain: normalizeAuthDomain(info.authDomain || prev.authDomain || ''),+ authIssuer: info.authIssuer || prev.authIssuer || '',firstSeen: prev.firstSeen || now,lastSeen: now,};@@ -914,23 +1019,33 @@ function updateMeta(dataDir, info) {return meta;}-/** 把当前登录信息备份到 accounts/<uid>.info(原子写入,0600) */-function backupCurrent(dataDir, log = () => {}) {- if (!ACTIVE_PROFILE.capabilities.accounts) throw new Error(`${ACTIVE_PROFILE.name} 暂不支持账号文件备份`);- ensureDirs(dataDir, log);- const info = readAuthFile();+function backupAuthFile(dataDir, file, log = () => {}) {+ const info = readAuthFile(file);const dest = backupPath(dataDir, info.uid);const tmp = dest + '.tmp';- fs.writeFileSync(tmp, fs.readFileSync(AUTH_FILE), { mode: 0o600 });+ fs.writeFileSync(tmp, fs.readFileSync(file), { mode: 0o600 });fs.renameSync(tmp, dest);fs.chmodSync(dest, 0o600);updateMeta(dataDir, info);- log(- `[sync] 已备份账号 ${info.nickname || info.uid} (${info.uid}) -> ${dest}`- );+ log(`[sync] 已备份账号 ${info.nickname || info.uid} (${info.uid}) <- ${info.authFileName}`);return info;}+/** 把当前 profile 的活动登录信息备份到 accounts/<uid>.info(原子写入,0600)。 */+function backupCurrent(dataDir, log = () => {}) {+ if (!ACTIVE_PROFILE.capabilities.accounts) throw new Error(`${ACTIVE_PROFILE.name} 暂不支持账号文件备份`);+ ensureDirs(dataDir, log);+ const files = listAuthFiles();+ if (!files.length) throw new Error(`未找到登录信息文件${authDir() ? `(${authDir()})` : ''}`);+ const current = currentAuthFile();+ let result = null;+ for (const file of files) {+ const info = backupAuthFile(dataDir, file, log);+ if (!result || samePath(file, current)) result = info;+ }+ return result;+}+/** 列出所有已备份账号(直接读备份文件提取展示字段,按最近刷新时间倒序) */function listAccounts(dataDir) {if (!ACTIVE_PROFILE.capabilities.accounts) return [];@@ -1004,6 +1119,42 @@ function deleteAccount(dataDir, uid) {return { deleted: deletedFile, uid };}+function knownAuthFileNameForDomain(domain) {+ const host = normalizeAuthDomain(domain);+ if (!DYNAMIC_AUTH_PROFILE) return path.basename(AUTH_FILE || '');+ if (host === 'www.workbuddy.ai') return path.basename(AUTH_FILE);+ if (host === 'www.codebuddy.cn') return 'Tencent-Cloud.coding-copilot.info';+ return '';+}++function resolveAuthTarget(dataDir, uid, authJson) {+ if (!AUTH_FILE || !DYNAMIC_AUTH_PROFILE) return AUTH_FILE;+ const meta = readMeta(dataDir);+ const record = meta.accounts[uid] || {};+ const backupDomain = normalizeAuthDomain(authJson && authJson.auth && authJson.auth.domain);+ const recordDomain = normalizeAuthDomain(record.authDomain);+ const recordedNameAllowed = safeAuthFileName(record.authFileName) &&+ String(record.authFileName).toLowerCase() !== 'workbuddy-desktop.info' &&+ (!recordDomain || WORKBUDDY_AI_AUTH_DOMAINS.has(recordDomain)) &&+ (!backupDomain || !recordDomain || backupDomain === recordDomain);+ if (recordedNameAllowed) {+ return path.join(authDir(), record.authFileName);+ }+ const domain = backupDomain || recordDomain;+ if (domain) {+ const matches = listAuthFiles()+ .map((file) => parseAuthFile(file))+ .filter((info) => info && info.authDomain === domain);+ if (matches.length) return matches[matches.length - 1].file;+ const knownName = knownAuthFileNameForDomain(domain);+ if (knownName) return path.join(authDir(), knownName);+ if (WORKBUDDY_AI_AUTH_DOMAINS.has(domain)) {+ throw new Error(`账号认证域 ${domain} 缺少可确认的 authenticationId;请先通过该渠道登录一次再切换`);+ }+ }+ return AUTH_FILE;+}+/** 切换登录账号:把备份文件复制回登录信息文件(先校验 uid 匹配) */function switchTo(dataDir, uid, log = () => {}) {if (!ACTIVE_PROFILE.capabilities.accounts) throw new Error(`${ACTIVE_PROFILE.name} 暂不支持账号切换`);@@ -1018,11 +1169,13 @@ function switchTo(dataDir, uid, log = () => {}) {if (!acct || acct.uid !== uid) {throw new Error('备份文件校验失败:uid 不匹配,已中止切换');}- const tmp = AUTH_FILE + '.wbswitch.tmp';+ const target = resolveAuthTarget(dataDir, uid, json);+ if (!target) throw new Error('当前 profile 没有可写入的认证文件');+ const tmp = target + '.wbswitch.tmp';try {fs.writeFileSync(tmp, raw, { mode: 0o600 });- fs.renameSync(tmp, AUTH_FILE);- fs.chmodSync(AUTH_FILE, 0o600);+ fs.renameSync(tmp, target);+ fs.chmodSync(target, 0o600);} catch (e) {// 沙箱环境(如从 WorkBuddy 托管后台运行)直接写系统目录会 EPERM。// macOS 回退:osascript 委托 GUI 会话复制(不涉及内容转义,只传路径)。@@ -1034,9 +1187,9 @@ function switchTo(dataDir, uid, log = () => {}) {}log(`[switch] 直写失败(${e.code}),改用 osascript 委托写入`);const bridge = path.join(dataDir, '.auth-switch-bridge.tmp');- const authBridge = AUTH_FILE + '.wbswitch.tmp';+ const authBridge = target + '.wbswitch.tmp';const bridgeQ = bridge.replace(/"/g, '\\"');- const authQ = AUTH_FILE.replace(/"/g, '\\"');+ const authQ = target.replace(/"/g, '\\"');const tmpQ = authBridge.replace(/"/g, '\\"');try {// 1) 本进程写 bridge(数据目录可写)@@ -1050,14 +1203,30 @@ function switchTo(dataDir, uid, log = () => {}) {throw new Error(`写入登录文件失败: ${(e2.message || e2).toString().slice(0, 200)}`);}}- retireLogoutMarker(log);- log(`[switch] 已切换登录账号为 ${acct.nickname || uid} (${uid})`);- return { uid: acct.uid, nickname: acct.nickname || '', uin: acct.uin || '' };+ retireLogoutMarker(log, target);+ updateMeta(dataDir, {+ uid: acct.uid,+ nickname: acct.nickname || '',+ uin: acct.uin || '',+ phone: acct.phoneNumber || '',+ authFileName: path.basename(target),+ authDomain: normalizeAuthDomain(json.auth && json.auth.domain),+ authIssuer: tokenIssuerOrigin(json.auth && json.auth.accessToken),+ });+ log(`[switch] 已切换登录账号为 ${acct.nickname || uid} (${uid}) -> ${path.basename(target)}`);+ return { uid: acct.uid, nickname: acct.nickname || '', uin: acct.uin || '', authFile: target };}module.exports = {AUTH_FILE,ACTIVE_PROFILE,+ authDir,+ listAuthFiles,+ currentAuthFile,+ parseAuthFile,+ normalizeAuthDomain,+ tokenIssuerOrigin,+ resolveAuthTarget,defaultDataDir,migrateLegacyDataDir,accountsDir,diff --git a/test/cdp-heal.test.js b/test/cdp-heal.test.jsnew file mode 100644index 0000000..d89dad8--- /dev/null+++ b/test/cdp-heal.test.js@@ -0,0 +1,33 @@+'use strict';++const assert = require('node:assert/strict');+const fs = require('fs');+const path = require('path');+const test = require('node:test');++const daemon = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'daemon.js'), 'utf8');++test('CDP reconnect loop has a bounded managed restart path after WorkBuddy drops the debug port', () => {+ assert.match(daemon, /const CDP_HEAL_GRACE_MS = 90 \* 1000;/);+ assert.match(daemon, /const CDP_HEAL_COOLDOWN_MS = 3 \* 60 \* 1000;/);+ assert.match(daemon, /everConnected:\s*false/);+ assert.match(daemon, /cdp\.everConnected = true/);+ assert.match(daemon, /coldStartEligible = IS_WIN && process\.env\.WBSWITCH_NATIVE_LAUNCHER === '1'/);++ const start = daemon.indexOf('async function maybeHealCdp()');+ assert.notEqual(start, -1);+ const source = daemon.slice(start, start + 2600);+ assert.match(source, /await findCdpEndpoint\(\)/);+ assert.match(source, /workBuddyRunning\(\)/);+ assert.match(source, /if \(!running\)[\s\S]*cdpLostAt = 0[\s\S]*return false/);+ assert.match(source, /await quitWorkBuddy\(\)[\s\S]*await relaunchWorkBuddy\(\)/);+});++test('planned logout suppresses the CDP auto-heal loop before stopping WorkBuddy', () => {+ const start = daemon.indexOf("p === '/api/logout'");+ assert.notEqual(start, -1);+ const source = daemon.slice(start, start + 1800);+ const suppress = source.indexOf('suppressCdpHeal(5 * 60 * 1000)');+ const quit = source.indexOf('await quitWorkBuddy()');+ assert.ok(suppress >= 0 && quit > suppress);+});diff --git a/test/checkin-result.test.js b/test/checkin-result.test.jsindex 8936100..276feb3 100644--- a/test/checkin-result.test.js+++ b/test/checkin-result.test.js@@ -2,7 +2,12 @@const assert = require('node:assert/strict');const test = require('node:test');-const { classifyCheckinResult } = require('../scripts/checkin-result.js');+const { classifyCheckinResult, tokenIssuerOrigin, checkinEndpointsForToken } = require('../scripts/checkin-result.js');++function jwtWithIssuer(issuer) {+ const payload = Buffer.from(JSON.stringify({ iss: issuer }), 'utf8').toString('base64url');+ return `header.${payload}.signature`;+}test('check-in requires an explicit successful response code', () => {assert.equal(classifyCheckinResult({ httpOk: true, code: undefined, message: 'OK' }).ok, false);@@ -12,6 +17,31 @@ test('check-in requires an explicit successful response code', () => {test('code 10001 is cached only when it explicitly means already checked in', () => {assert.equal(classifyCheckinResult({ httpOk: true, code: 10001, message: '今日已签到' }).ok, true);+ assert.equal(classifyCheckinResult({ httpOk: false, code: 10001, message: '今天已签到,请明天再来' }).ok, true);assert.equal(classifyCheckinResult({ httpOk: true, code: 10001, message: '活动未开启' }).ok, false);+ assert.equal(classifyCheckinResult({ httpOk: false, code: 10001, message: '签到活动未开启或已过期' }).ok, false);assert.equal(classifyCheckinResult({ httpOk: true, code: 10001, message: '请求成功' }).ok, false);});++test('known JWT issuer selects its matching check-in host instead of the profile host', () => {+ const token = jwtWithIssuer('https://www.codebuddy.cn/auth/realms/copilot');+ assert.equal(tokenIssuerOrigin(token), 'https://www.codebuddy.cn');+ assert.deepEqual(checkinEndpointsForToken(token, {+ apiHost: 'https://www.workbuddy.ai',+ region: 'intl',+ }), [+ 'https://www.codebuddy.cn/billing/meter/daily-checkin',+ 'https://www.codebuddy.cn/v2/billing/meter/daily-checkin',+ ]);+});++test('unknown JWT issuer never becomes a request host and falls back to profile routing', () => {+ const token = jwtWithIssuer('https://untrusted.example/auth/realms/copilot');+ assert.deepEqual(checkinEndpointsForToken(token, {+ apiHost: 'https://www.workbuddy.ai',+ region: 'intl',+ }), [+ 'https://www.workbuddy.ai/billing/meter/daily-checkin',+ 'https://www.workbuddy.ai/v2/billing/meter/daily-checkin',+ ]);+});diff --git a/test/multichannel-auth.test.js b/test/multichannel-auth.test.jsnew file mode 100644index 0000000..73a3480--- /dev/null+++ b/test/multichannel-auth.test.js@@ -0,0 +1,67 @@+'use strict';++const assert = require('node:assert/strict');+const fs = require('fs');+const os = require('os');+const path = require('path');+const test = require('node:test');++const root = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-multichannel-auth-'));+const local = path.join(root, 'Local');+const roaming = path.join(root, 'Roaming');+process.env.WBSWITCH_PROFILE = 'workbuddy-ai';+process.env.LOCALAPPDATA = local;+process.env.APPDATA = roaming;+delete process.env.WBSWITCH_AUTH_FILE;++const lib = require('../scripts/lib.js');++function authPayload(uid, domain, lastRefreshTime) {+ return {+ account: { uid, nickname: uid, type: 'personal', lastLogin: true },+ auth: { domain, lastRefreshTime },+ };+}++function writeAuth(name, payload) {+ const file = path.join(lib.authDir(), name);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, JSON.stringify(payload));+ return file;+}++test('WorkBuddy AI discovers and restores channel-specific auth files without mixing domestic WorkBuddy', (t) => {+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));++ const aiFile = writeAuth('workbuddy-desktop-ai.info', authPayload('uid-ai', 'www.workbuddy.ai', 100));+ const tencentFile = writeAuth('Tencent-Cloud.coding-copilot.info', authPayload('uid-tencent', 'www.codebuddy.cn', 200));+ writeAuth('workbuddy-desktop.info', authPayload('uid-domestic', 'www.codebuddy.cn', 300));+ writeAuth('workbuddy-desktop-ai.2026-09-02T01-02-03-004Z.1234.snapshot.info', authPayload('uid-snapshot', 'www.workbuddy.ai', 400));++ assert.deepEqual(lib.listAuthFiles().map((file) => path.basename(file)), [+ 'workbuddy-desktop-ai.info',+ 'Tencent-Cloud.coding-copilot.info',+ ]);+ assert.equal(lib.currentAuthFile(), tencentFile);++ const dataDir = path.join(roaming, 'WorkDaddy', 'profiles', 'workbuddy-ai');+ const current = lib.backupCurrent(dataDir);+ assert.equal(current.uid, 'uid-tencent');+ assert.equal(fs.existsSync(lib.backupPath(dataDir, 'uid-ai')), true);+ assert.equal(fs.existsSync(lib.backupPath(dataDir, 'uid-tencent')), true);++ const meta = JSON.parse(fs.readFileSync(lib.metaFile(dataDir), 'utf8'));+ assert.equal(meta.accounts['uid-ai'].authFileName, 'workbuddy-desktop-ai.info');+ assert.equal(meta.accounts['uid-tencent'].authFileName, 'Tencent-Cloud.coding-copilot.info');+ assert.equal(meta.accounts['uid-tencent'].authDomain, 'www.codebuddy.cn');++ fs.writeFileSync(aiFile, JSON.stringify(authPayload('temporary-ai', 'www.workbuddy.ai', 500)));+ lib.switchTo(dataDir, 'uid-ai');+ assert.equal(JSON.parse(fs.readFileSync(aiFile, 'utf8')).account.uid, 'uid-ai');+ assert.equal(JSON.parse(fs.readFileSync(tencentFile, 'utf8')).account.uid, 'uid-tencent');++ fs.writeFileSync(tencentFile, JSON.stringify(authPayload('temporary-tencent', 'www.codebuddy.cn', 600)));+ lib.switchTo(dataDir, 'uid-tencent');+ assert.equal(JSON.parse(fs.readFileSync(tencentFile, 'utf8')).account.uid, 'uid-tencent');+ assert.equal(JSON.parse(fs.readFileSync(aiFile, 'utf8')).account.uid, 'uid-ai');+});diff --git a/test/windows-privilege-boundary.test.js b/test/windows-privilege-boundary.test.jsindex 63972e3..f574e9d 100644--- a/test/windows-privilege-boundary.test.js+++ b/test/windows-privilege-boundary.test.js@@ -293,8 +293,9 @@ test('logout and restart paths refuse unverified profile processes', () => {assert.match(quitFunction, /revalidateWindowsWorkBuddyProcess[\s\S]*taskkill[\s\S]*revalidateWindowsWorkBuddyProcess[\s\S]*taskkill/);const logoutStart = daemonSource.indexOf("p === '/api/logout'");const quitIndex = daemonSource.indexOf('await quitWorkBuddy()', logoutStart);- const unlinkIndex = daemonSource.indexOf('fs.unlinkSync(AUTH_FILE)', logoutStart);- assert.ok(logoutStart >= 0 && quitIndex > logoutStart && unlinkIndex > quitIndex);+ const listIndex = daemonSource.indexOf('const authFiles = listAuthFiles()', logoutStart);+ const unlinkIndex = daemonSource.indexOf('fs.unlinkSync(file)', logoutStart);+ assert.ok(logoutStart >= 0 && quitIndex > logoutStart && listIndex > quitIndex && unlinkIndex > listIndex);});test('Windows self-check includes the shared boundary and old admin comments are removed', () => {