creditdaddy 1.6.6 → 1.6.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -313,7 +313,7 @@ async function main() {
313
313
  const { liveToAccount: traeLive } = await import('../src/traeLocal.js');
314
314
  const { addAccount } = await import('../src/accounts.js');
315
315
  const qa = await readQoderAppAccounts();
316
- const wb = readWorkbuddySessions();
316
+ const wb = await readWorkbuddySessions();
317
317
  const skipped = [];
318
318
  let zAccount = null;
319
319
  try { zAccount = zcodeLive(); } catch (e) { skipped.push({ file: '~/.zcode/v2/credentials.json', error: e.message }); }
package/build.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
- "version": "1.6.6",
3
- "commit": "513d0e0",
2
+ "version": "1.6.7",
3
+ "commit": "643a6b4",
4
4
  "branch": "main",
5
- "builtAt": "2026-11-02T17:20:26.288Z",
5
+ "builtAt": "2026-11-03T01:54:49.168Z",
6
6
  "channel": "local",
7
7
  "dirty": false
8
8
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "creditdaddy",
3
- "version": "1.6.6",
3
+ "version": "1.6.7",
4
4
  "description": "CreditDaddy — Qoder / WorkBuddy / ZCode / mirasim / 妙手 / Trae / MiniMax / ModelScope / 豆包 Doubao / 讯飞 Loomy 多账号本地管理与每日积分自动签到助手,及 10Router 供应商 Cookie 会话捕获与外部配额(Token Harbor / 小米 MiMo / River / ModelScope 魔搭 / LongCat)",
5
5
  "homepage": "https://github.com/techysy/CreditDaddy",
6
6
  "repository": {
package/src/accounts.js CHANGED
@@ -173,8 +173,8 @@ export function refreshContext(account, log) {
173
173
  if (account.provider.startsWith('workbuddy')) {
174
174
  const { currentWorkbuddyUid, writeWorkbuddySession } = await import('./workbuddyLocal.js');
175
175
  try {
176
- if (account.uid && currentWorkbuddyUid() === account.uid) {
177
- writeWorkbuddySession(account);
176
+ if (account.uid && await currentWorkbuddyUid() === account.uid) {
177
+ await writeWorkbuddySession(account);
178
178
  log?.('已同步新 token 到 WorkBuddy 客户端');
179
179
  }
180
180
  } catch (e) { log?.('同步到 WorkBuddy 客户端失败:' + e.message); }
package/src/daemon.js CHANGED
@@ -1113,7 +1113,7 @@ async function handleApi(req, res, url) {
1113
1113
  // Loomy 的切换在上方 provider 链已处理;这里只剩 WorkBuddy 系
1114
1114
  if (!target.provider.startsWith('workbuddy')) return json(res, 400, { error: '只有 WorkBuddy / ZCode / mirasim / 妙手 / Trae / Loomy 账号支持切换' });
1115
1115
  // 先把客户端当前会话的最新 token 收回账号库,避免被覆盖后丢失
1116
- const cur = readWorkbuddySessions().accounts.find((a) => a.current);
1116
+ const cur = (await readWorkbuddySessions()).accounts.find((a) => a.current);
1117
1117
  if (cur && cur.uid !== target.uid) {
1118
1118
  const { file: _f, fileTime: _t, current: _c, ...rec } = cur;
1119
1119
  await addAccount(rec, { trusted: true }).catch((e) => logger.warn('DAEMON', '同步 WorkBuddy 当前会话失败:{err}', { err: e.message }));
@@ -1125,7 +1125,7 @@ async function handleApi(req, res, url) {
1125
1125
  if (!wbDet.installed) {
1126
1126
  return json(res, 400, { error: '本机未安装 WorkBuddy / CodeBuddy 客户端,无法切换(切换是把登录写入客户端凭据,由客户端应用;可先安装客户端后在本机导入再切换)', code: 'WORKBUDDY_NOT_INSTALLED' });
1127
1127
  }
1128
- const r = writeWorkbuddySession(target);
1128
+ const r = await writeWorkbuddySession(target);
1129
1129
  logger.info('DAEMON', 'WorkBuddy 已切换到 {name}', { name: target.name || target.id });
1130
1130
  return json(res, 200, { ok: true, file: r.file, previousUid: r.previousUid });
1131
1131
  } catch (e) {
@@ -1630,7 +1630,7 @@ async function handleApi(req, res, url) {
1630
1630
  }, { source: c.source });
1631
1631
  }
1632
1632
  // 2) WorkBuddy 客户端:当前会话 + 历史会话
1633
- const wb = readWorkbuddySessions();
1633
+ const wb = await readWorkbuddySessions();
1634
1634
  errors.push(...wb.errors);
1635
1635
  for (const c of wb.accounts) {
1636
1636
  const { file: _f, fileTime: _t, current, ...record } = c;
@@ -1904,7 +1904,7 @@ async function handleApi(req, res, url) {
1904
1904
  riskSource: riskIdentitySource(),
1905
1905
  umid: umidInfo(),
1906
1906
  platform: process.platform,
1907
- workbuddyCurrentUid: currentWorkbuddyUid(),
1907
+ workbuddyCurrentUid: await currentWorkbuddyUid(),
1908
1908
  workbuddyClient: (() => { const d = detectWorkbuddy(); return { installed: d.installed, signedIn: d.signedIn, running: false }; })(),
1909
1909
  qoderCurrent: qoderCurrentIds(accounts, qoder),
1910
1910
  qoderCurrentToken: qoder.tokens,
@@ -119,7 +119,7 @@ export async function pollWorkbuddyLogin(data) {
119
119
  auth: data.token,
120
120
  }
121
121
  : { auth: data.token };
122
- const input = sessionToAccount(session, '浏览器登录');
122
+ const input = await sessionToAccount(session, '浏览器登录');
123
123
  if (!input) throw new Error('WorkBuddy 返回的 token 无法识别(签发方不是 CodeBuddy / WorkBuddy)');
124
124
  if (!account) delete input.meta.session;
125
125
  input.source = 'browser';
@@ -63,40 +63,61 @@ export function sealEnvelope(plaintext, key, template = {}) {
63
63
 
64
64
  let cachedMasterKey = null;
65
65
  let masterKeyFailAt = 0;
66
+ let masterKeyInflight = null;
66
67
  const KEY_RETRY_MS = 60000;
67
68
 
68
69
  /**
69
70
  * 经 WorkBuddy 官方 Electron(ELECTRON_RUN_AS_NODE=1)子进程调用原生存储绑定提取密钥。
70
- * 内存缓存,失败 60s 内退避;绝不写盘,绝不写日志。
71
+ * 内存缓存 + 在途去重,失败 60s 内退避;绝不写盘,绝不写日志。
72
+ * 必须 async:spawnSync 会同步卡死事件循环——桌面壳把 daemon 跑在 Electron 主进程里,
71
73
  */
72
- export function getWorkbuddyMasterKey(clientPath) {
74
+ export async function getWorkbuddyMasterKey(clientPath) {
73
75
  if (cachedMasterKey) return cachedMasterKey;
74
76
  if (masterKeyFailAt && Date.now() - masterKeyFailAt < KEY_RETRY_MS) return null;
77
+ if (masterKeyInflight) return masterKeyInflight;
75
78
  const exe = clientPath || detectWorkbuddy().clientPath;
76
79
  if (!exe) return null;
77
80
 
78
- try {
79
- const code = [
80
- "const b = process._linkedBinding('electron_browser_workbuddy_storage');",
81
- "const p = JSON.parse(b.loggerGet());",
82
- "if (p && typeof p.atRestSecretKey === 'string') process.stdout.write(p.atRestSecretKey);",
83
- ].join('\n');
84
- const r = cp.spawnSync(exe, ['-e', code], {
85
- env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
86
- timeout: 5000,
87
- encoding: 'utf8',
88
- });
89
- const keyRaw = String(r.stdout || '').trim();
90
- if (r.status === 0 && keyRaw.length >= 16) {
91
- cachedMasterKey = crypto.createHash('sha256').update(keyRaw, 'utf8').digest();
92
- masterKeyFailAt = 0;
93
- return cachedMasterKey;
81
+ const code = [
82
+ "const b = process._linkedBinding('electron_browser_workbuddy_storage');",
83
+ "const p = JSON.parse(b.loggerGet());",
84
+ "if (p && typeof p.atRestSecretKey === 'string') process.stdout.write(p.atRestSecretKey);",
85
+ ].join('\n');
86
+ masterKeyInflight = new Promise((resolve) => {
87
+ let child = null;
88
+ const settle = (key) => {
89
+ try { child?.kill(); } catch {}
90
+ masterKeyInflight = null;
91
+ if (key) {
92
+ cachedMasterKey = crypto.createHash('sha256').update(key, 'utf8').digest();
93
+ masterKeyFailAt = 0;
94
+ resolve(cachedMasterKey);
95
+ } else {
96
+ masterKeyFailAt = Date.now();
97
+ resolve(null);
98
+ }
99
+ };
100
+ const timer = setTimeout(() => settle(null), 5000);
101
+ try {
102
+ child = cp.spawn(exe, ['-e', code], {
103
+ env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
104
+ stdio: ['ignore', 'pipe', 'ignore'],
105
+ windowsHide: true,
106
+ });
107
+ let out = '';
108
+ child.stdout.on('data', (c) => { out += c; });
109
+ child.on('error', () => { clearTimeout(timer); settle(null); });
110
+ child.on('close', (statusCode) => {
111
+ clearTimeout(timer);
112
+ const keyRaw = out.trim();
113
+ settle(statusCode === 0 && keyRaw.length >= 16 ? keyRaw : null);
114
+ });
115
+ } catch {
116
+ clearTimeout(timer);
117
+ settle(null);
94
118
  }
95
- } catch {
96
- /* 子进程执行异常,进入退避 */
97
- }
98
- masterKeyFailAt = Date.now();
99
- return null;
119
+ });
120
+ return masterKeyInflight;
100
121
  }
101
122
 
102
123
  export function resetMasterKeyCacheForTest(key = null) {
@@ -104,8 +125,8 @@ export function resetMasterKeyCacheForTest(key = null) {
104
125
  masterKeyFailAt = 0;
105
126
  }
106
127
 
107
- /** 深度解密 JSON 中的 $wbEncrypted 信封,返回包含明文的浅拷贝/深拷贝 */
108
- export function decryptSessionJson(session, clientPath) {
128
+ /** 深度解密 JSON 中的 $wbEncrypted 信封,返回包含明文的深拷贝(异步:取钥需起子进程) */
129
+ export async function decryptSessionJson(session, clientPath) {
109
130
  if (!session || typeof session !== 'object') return session;
110
131
  let key = null;
111
132
  const clone = JSON.parse(JSON.stringify(session));
@@ -133,6 +154,20 @@ export function decryptSessionJson(session, clientPath) {
133
154
  };
134
155
 
135
156
  walk(clone);
157
+ // walk 内取到的 key 是 Promise(getWorkbuddyMasterKey 首次异步),等待后再逐信封解密
158
+ const resolvedKey = await key;
159
+ if (resolvedKey) {
160
+ const walkDecrypt = (node) => {
161
+ if (!node || typeof node !== 'object') return;
162
+ if (Array.isArray(node)) { node.forEach(walkDecrypt); return; }
163
+ for (const [k, v] of Object.entries(node)) {
164
+ if (isWbEncrypted(v)) {
165
+ try { node[k] = openEnvelope(v, resolvedKey); } catch { /* 保留原信封 */ }
166
+ } else if (v && typeof v === 'object') walkDecrypt(v);
167
+ }
168
+ };
169
+ walkDecrypt(clone);
170
+ }
136
171
  return clone;
137
172
  }
138
173
 
@@ -151,10 +186,12 @@ export function workbuddyAuthDir() {
151
186
  const CURRENT_RE = /^[a-z0-9-]+\.info$/i; // workbuddy-desktop.info
152
187
  const HISTORY_RE = /^[a-z0-9-]+\.\d{4}-.*\.info$/i; // workbuddy-desktop.<时间戳>.<pid>.<uuid>.info
153
188
 
154
- /** 会话 JSON → 账号记录(供 addAccount),不含网络请求 */
155
- export function sessionToAccount(rawSession, source, clientPath) {
189
+ /** 会话 JSON → 账号记录(供 addAccount),不含网络请求。
190
+ * 异步:含 $wbEncrypted 信封时需起 WorkBuddy 子进程取钥解密——
191
+ * 绝不用 spawnSync(会同步卡死 Electron 主进程事件循环 → 客户端「未响应」)。 */
192
+ export async function sessionToAccount(rawSession, source, clientPath) {
156
193
  // 如果会话包含 $wbEncrypted 信封,先进行安全解密
157
- const session = decryptSessionJson(rawSession, clientPath);
194
+ const session = await decryptSessionJson(rawSession, clientPath);
158
195
  const token = session?.auth?.accessToken;
159
196
  if (typeof token !== 'string' || !token) return null;
160
197
  const info = inspectToken(token);
@@ -199,20 +236,24 @@ export function sessionToAccount(rawSession, source, clientPath) {
199
236
  * 读取本机 WorkBuddy 会话:当前会话 + 历史会话(按 uid 去重,保留最新)。
200
237
  * @returns {{ dir, accounts: Array<{...账号记录, current: boolean, file, fileTime}>, errors }}
201
238
  */
202
- export function readWorkbuddySessions(options = {}) {
239
+ export async function readWorkbuddySessions(options = {}) {
203
240
  const dir = options.dir || workbuddyAuthDir();
204
241
  const clientPath = options.clientPath !== undefined ? options.clientPath : detectWorkbuddy().clientPath;
205
242
  const out = { dir, accounts: [], errors: [] };
206
243
  let names = [];
207
244
  try { names = fs.readdirSync(dir); } catch { return out; }
208
245
  const byUid = new Map();
246
+ // 密钥只取一次给整个目录用:缓存未命中时首个加密文件触发一次子进程(异步不阻塞),
247
+ // 之后的文件全部走内存缓存;明文文件在密钥不可用时仍可正常收割
248
+ let keyPromise = null;
209
249
  for (const name of names) {
210
250
  if (!CURRENT_RE.test(name) && !HISTORY_RE.test(name)) continue;
211
251
  const file = path.join(dir, name);
212
252
  try {
213
253
  const current = !HISTORY_RE.test(name);
214
254
  if (current && fs.existsSync(`${file}.logged-out`)) continue; // 已登出
215
- const rec = sessionToAccount(JSON.parse(fs.readFileSync(file, 'utf8')), current ? 'WorkBuddy 当前登录' : 'WorkBuddy 历史会话', clientPath);
255
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
256
+ const rec = await sessionToAccount(parsed, current ? 'WorkBuddy 当前登录' : 'WorkBuddy 历史会话', clientPath);
216
257
  if (!rec) continue;
217
258
  const fileTime = fs.statSync(file).mtimeMs;
218
259
  const item = { ...rec, current, file, fileTime };
@@ -222,13 +263,14 @@ export function readWorkbuddySessions(options = {}) {
222
263
  out.errors.push({ file, error: e.message });
223
264
  }
224
265
  }
266
+ void keyPromise;
225
267
  out.accounts = [...byUid.values()].sort((a, b) => b.current - a.current || b.fileTime - a.fileTime);
226
268
  return out;
227
269
  }
228
270
 
229
- /** 当前 WorkBuddy 客户端登录的 uid(未登录返回 null) */
230
- export function currentWorkbuddyUid() {
231
- return readWorkbuddySessions().accounts.find((a) => a.current)?.uid || null;
271
+ /** 当前 WorkBuddy 客户端登录的 uid(未登录返回 null)。异步:见 readWorkbuddySessions。 */
272
+ export async function currentWorkbuddyUid() {
273
+ return (await readWorkbuddySessions()).accounts.find((a) => a.current)?.uid || null;
232
274
  }
233
275
 
234
276
  // 客户端可执行文件候选(VS Code 系安装惯例:%LOCALAPPDATA%\Programs\<名>\<名>.exe)。
@@ -270,13 +312,30 @@ export function detectWorkbuddy() {
270
312
  : cand;
271
313
  try { if (fs.existsSync(p)) { clientPath = p; break; } } catch { /* 下一个候选 */ }
272
314
  }
273
- const sessions = dirExists ? readWorkbuddySessions({ dir, clientPath }) : { accounts: [] };
315
+ // signedIn 只做轻量文件判定(当前会话文件存在且无 logged-out 标记):
316
+ // 绝不在此调 readWorkbuddySessions——那会对加密会话起子进程解密(异步),
317
+ // 而 detectWorkbuddy 是同步函数且被 /api/status 每轮调用,解密等待会拖慢状态轮
318
+ let signedIn = false;
319
+ if (dirExists) {
320
+ const curFile = path.join(dir, 'workbuddy-desktop.info');
321
+ try { signedIn = fs.existsSync(curFile) && !fs.existsSync(`${curFile}.logged-out`); } catch { /* 保持 false */ }
322
+ if (!signedIn) {
323
+ // 多认证 ID 形态(Tencent-Cloud.*.info 等非固定名):目录里任一无登出标记的 .info 即视为登录态
324
+ try {
325
+ for (const name of fs.readdirSync(dir)) {
326
+ if (!CURRENT_RE.test(name) || name === 'workbuddy-desktop.info') continue;
327
+ if (HISTORY_RE.test(name)) continue;
328
+ if (!fs.existsSync(path.join(dir, `${name}.logged-out`))) { signedIn = true; break; }
329
+ }
330
+ } catch { /* 保持 false */ }
331
+ }
332
+ }
274
333
  return {
275
334
  dir,
276
335
  dirExists,
277
336
  clientPath,
278
- installed: Boolean(clientPath) || (CLIENT_CANDIDATES.length === 0 && sessions.accounts.length > 0),
279
- signedIn: sessions.accounts.some((a) => a.current),
337
+ installed: Boolean(clientPath) || (CLIENT_CANDIDATES.length === 0 && signedIn),
338
+ signedIn,
280
339
  };
281
340
  }
282
341
 
@@ -285,7 +344,7 @@ export function detectWorkbuddy() {
285
344
  * 如果原模板是 $wbEncrypted 信封格式,写回时将自动封包为合法信封。
286
345
  * @returns {{ file, previousUid }}
287
346
  */
288
- export function writeWorkbuddySession(account, { clientPath } = {}) {
347
+ export async function writeWorkbuddySession(account, { clientPath } = {}) {
289
348
  const s = account.meta?.session;
290
349
  if (!s?.account) throw new Error('该账号缺少 WorkBuddy 会话信息,请从本机重新导入后再切换');
291
350
  const dir = workbuddyAuthDir();
@@ -298,10 +357,10 @@ export function writeWorkbuddySession(account, { clientPath } = {}) {
298
357
  const rawAuth = s.auth || {};
299
358
 
300
359
  // 判断是否需要信封封包写入(原会话 auth 字段包含 $wbEncrypted)
301
- let isEncryptedTemplate = isWbEncrypted(rawAuth.accessToken) || isWbEncrypted(rawAuth.refreshToken);
360
+ const isEncryptedTemplate = isWbEncrypted(rawAuth.accessToken) || isWbEncrypted(rawAuth.refreshToken);
302
361
  let masterKey = null;
303
362
  if (isEncryptedTemplate) {
304
- masterKey = getWorkbuddyMasterKey(clientPath);
363
+ masterKey = await getWorkbuddyMasterKey(clientPath);
305
364
  if (!masterKey) {
306
365
  throw new Error('无法切换账号:目标账号为 WorkBuddy 5.6+ 加密凭据,但未能获取客户端解密密钥');
307
366
  }