creditdaddy 1.6.7 → 1.7.0

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.
@@ -1,395 +1,565 @@
1
- /**
2
- * 本机 WorkBuddy 客户端凭据 — 读取已登录账号、切换当前账号。
3
- *
4
- * WorkBuddy(与 CodeBuddy CLI / 插件共用)把会话存成明文 JSON:
5
- * Windows: %LOCALAPPDATA%\CodeBuddyExtension\Data\Public\auth\<认证ID>.info
6
- * macOS: ~/Library/Application Support/CodeBuddyExtension/Data/Public/auth/
7
- * Linux: ~/.local/share/CodeBuddyExtension/Data/Public/auth/
8
- * 当前会话是 workbuddy-desktop.info(国际版客户端可能用其他认证 ID),带时间戳的同名文件是客户端留下的历史会话。
9
- * 文件结构:{ account: { uid, nickname, phoneNumber, enterpriseId… }, auth: { accessToken, refreshToken, expiresAt, domain… }, accounts: [...] }
10
- *
11
- * 切换账号:原子写入会话文件 + 删除同目录的 "<文件>.logged-out" 登出标记;
12
- * WorkBuddy 监听该文件,外部改动会被直接应用(客户端日志 "External change applied to session")。
13
- */
14
-
15
- import fs from 'node:fs';
16
- import os from 'node:os';
17
- import path from 'node:path';
18
- import crypto from 'node:crypto';
19
- import cp from 'node:child_process';
20
- import { inspectToken } from './workbuddyClient.js';
21
-
22
- // ===================== WorkBuddy 5.6+ $wbEncrypted 信封加解密 =====================
23
-
24
- export function isWbEncrypted(val) {
25
- return !!val && typeof val === 'object' && !Array.isArray(val) && val.$wbEncrypted === 1 && typeof val.envelope === 'string';
26
- }
27
-
28
- export function buildEnvelopeAAD(env) {
29
- const FRAMING_FIELD = 2, FMT_FIELD = 'WBEV1', AAD_DOMAIN = Buffer.from('WB-AAD\0', 'ascii');
30
- const lp = (s) => { const b = Buffer.from(s, 'utf8'); const l = Buffer.alloc(4); l.writeUInt32BE(b.length); return Buffer.concat([l, b]); };
31
- const u32 = (n) => { const b = Buffer.alloc(4); b.writeUInt32BE(n); return b; };
32
- return Buffer.concat([
33
- AAD_DOMAIN, Buffer.from([1]), lp(FMT_FIELD), lp('sym-v1'), u32(env.suite || 1),
34
- lp(env.keyId || ''), Buffer.from([FRAMING_FIELD]), Buffer.from([0]), Buffer.from([0]),
35
- ]);
36
- }
37
-
38
- export function openEnvelope(encObj, key) {
39
- const env = JSON.parse(Buffer.from(encObj.envelope, 'base64').toString('utf8'));
40
- const decipher = crypto.createDecipheriv('aes-256-gcm', key, Buffer.from(env.nonce, 'base64'), { authTagLength: 16 });
41
- decipher.setAAD(buildEnvelopeAAD(env));
42
- decipher.setAuthTag(Buffer.from(env.authTag, 'base64'));
43
- return Buffer.concat([decipher.update(Buffer.from(env.ciphertext, 'base64')), decipher.final()]).toString('utf8');
44
- }
45
-
46
- export function sealEnvelope(plaintext, key, template = {}) {
47
- const nonce = crypto.randomBytes(12);
48
- const cipher = crypto.createCipheriv('aes-256-gcm', key, nonce, { authTagLength: 16 });
49
- const env = {
50
- suite: template.suite || 1,
51
- keyId: template.keyId || '',
52
- nonce: nonce.toString('base64'),
53
- };
54
- cipher.setAAD(buildEnvelopeAAD(env));
55
- const ciphertext = Buffer.concat([cipher.update(String(plaintext || ''), 'utf8'), cipher.final()]);
56
- env.authTag = cipher.getAuthTag().toString('base64');
57
- env.ciphertext = ciphertext.toString('base64');
58
- return {
59
- $wbEncrypted: 1,
60
- envelope: Buffer.from(JSON.stringify(env)).toString('base64'),
61
- };
62
- }
63
-
64
- let cachedMasterKey = null;
65
- let masterKeyFailAt = 0;
66
- let masterKeyInflight = null;
67
- const KEY_RETRY_MS = 60000;
68
-
69
- /**
70
- * 经 WorkBuddy 官方 Electron(ELECTRON_RUN_AS_NODE=1)子进程调用原生存储绑定提取密钥。
71
- * 内存缓存 + 在途去重,失败 60s 内退避;绝不写盘,绝不写日志。
72
- * 必须 async:spawnSync 会同步卡死事件循环——桌面壳把 daemon 跑在 Electron 主进程里,
73
- */
74
- export async function getWorkbuddyMasterKey(clientPath) {
75
- if (cachedMasterKey) return cachedMasterKey;
76
- if (masterKeyFailAt && Date.now() - masterKeyFailAt < KEY_RETRY_MS) return null;
77
- if (masterKeyInflight) return masterKeyInflight;
78
- const exe = clientPath || detectWorkbuddy().clientPath;
79
- if (!exe) return null;
80
-
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);
118
- }
119
- });
120
- return masterKeyInflight;
121
- }
122
-
123
- export function resetMasterKeyCacheForTest(key = null) {
124
- cachedMasterKey = key;
125
- masterKeyFailAt = 0;
126
- }
127
-
128
- /** 深度解密 JSON 中的 $wbEncrypted 信封,返回包含明文的深拷贝(异步:取钥需起子进程) */
129
- export async function decryptSessionJson(session, clientPath) {
130
- if (!session || typeof session !== 'object') return session;
131
- let key = null;
132
- const clone = JSON.parse(JSON.stringify(session));
133
-
134
- const walk = (node) => {
135
- if (!node || typeof node !== 'object') return;
136
- if (Array.isArray(node)) {
137
- for (const item of node) walk(item);
138
- return;
139
- }
140
- for (const [k, v] of Object.entries(node)) {
141
- if (isWbEncrypted(v)) {
142
- if (!key) key = getWorkbuddyMasterKey(clientPath);
143
- if (key) {
144
- try {
145
- node[k] = openEnvelope(v, key);
146
- } catch {
147
- /* 解密失败保留原信封 */
148
- }
149
- }
150
- } else if (v && typeof v === 'object') {
151
- walk(v);
152
- }
153
- }
154
- };
155
-
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
- }
171
- return clone;
172
- }
173
-
174
- // ===================== 凭据与会话管理 =====================
175
-
176
- export function workbuddyAuthDir() {
177
- const home = os.homedir();
178
- const tail = ['CodeBuddyExtension', 'Data', 'Public', 'auth'];
179
- if (process.platform === 'win32') {
180
- return path.join(process.env.LOCALAPPDATA || path.join(home, 'AppData', 'Local'), ...tail);
181
- }
182
- if (process.platform === 'darwin') return path.join(home, 'Library', 'Application Support', ...tail);
183
- return path.join(process.env.XDG_DATA_HOME || path.join(home, '.local', 'share'), ...tail);
184
- }
185
-
186
- const CURRENT_RE = /^[a-z0-9-]+\.info$/i; // workbuddy-desktop.info
187
- const HISTORY_RE = /^[a-z0-9-]+\.\d{4}-.*\.info$/i; // workbuddy-desktop.<时间戳>.<pid>.<uuid>.info
188
-
189
- /** 会话 JSON → 账号记录(供 addAccount),不含网络请求。
190
- * 异步:含 $wbEncrypted 信封时需起 WorkBuddy 子进程取钥解密——
191
- * 绝不用 spawnSync(会同步卡死 Electron 主进程事件循环 → 客户端「未响应」)。 */
192
- export async function sessionToAccount(rawSession, source, clientPath) {
193
- // 如果会话包含 $wbEncrypted 信封,先进行安全解密
194
- const session = await decryptSessionJson(rawSession, clientPath);
195
- const token = session?.auth?.accessToken;
196
- if (typeof token !== 'string' || !token) return null;
197
- const info = inspectToken(token);
198
- if (!info.provider) return null;
199
- const acc = session.account || {};
200
- const auth = session.auth || {};
201
- const iso = (ms) => (Number.isFinite(ms) ? new Date(ms).toISOString() : null);
202
-
203
- // 手机号:优先未脱敏的 phoneNumber;若被客户端脱敏(含 *)或为空,回退到从 JWT 解析的大陆手机号
204
- const rawPhone = typeof acc.phoneNumber === 'string' ? acc.phoneNumber.trim() : '';
205
- const isRedacted = rawPhone.includes('*');
206
- const phone = (!rawPhone || isRedacted) ? (info.phone || rawPhone || null) : rawPhone;
207
-
208
- // 原 rawSession 结构原样保留在 meta.session,便于切换账号时原汁原味还原
209
- const rawAuth = rawSession?.auth || auth;
210
- const { accessToken: _a, refreshToken: _r, ...authRest } = rawAuth;
211
- return {
212
- provider: info.provider,
213
- token,
214
- refreshToken: auth.refreshToken || null,
215
- expiresAt: iso(auth.expiresAt) || info.expiresAt,
216
- uid: acc.uid || info.uid,
217
- name: acc.nickname || acc.name || null,
218
- email: acc.email || null,
219
- source,
220
- meta: {
221
- domain: auth.domain || info.host,
222
- enterpriseId: acc.enterpriseId || null,
223
- phone,
224
- refreshExpiresAt: iso(auth.refreshExpiresAt),
225
- session: {
226
- account: rawSession?.account || acc,
227
- auth: authRest,
228
- accounts: Array.isArray(rawSession?.accounts) ? rawSession.accounts : (session.accounts || []),
229
- ...(Array.isArray(rawSession?.allAccounts || session.allAccounts) ? { allAccounts: rawSession?.allAccounts || session.allAccounts } : {}),
230
- },
231
- },
232
- };
233
- }
234
-
235
- /**
236
- * 读取本机 WorkBuddy 会话:当前会话 + 历史会话(按 uid 去重,保留最新)。
237
- * @returns {{ dir, accounts: Array<{...账号记录, current: boolean, file, fileTime}>, errors }}
238
- */
239
- export async function readWorkbuddySessions(options = {}) {
240
- const dir = options.dir || workbuddyAuthDir();
241
- const clientPath = options.clientPath !== undefined ? options.clientPath : detectWorkbuddy().clientPath;
242
- const out = { dir, accounts: [], errors: [] };
243
- let names = [];
244
- try { names = fs.readdirSync(dir); } catch { return out; }
245
- const byUid = new Map();
246
- // 密钥只取一次给整个目录用:缓存未命中时首个加密文件触发一次子进程(异步不阻塞),
247
- // 之后的文件全部走内存缓存;明文文件在密钥不可用时仍可正常收割
248
- let keyPromise = null;
249
- for (const name of names) {
250
- if (!CURRENT_RE.test(name) && !HISTORY_RE.test(name)) continue;
251
- const file = path.join(dir, name);
252
- try {
253
- const current = !HISTORY_RE.test(name);
254
- if (current && fs.existsSync(`${file}.logged-out`)) continue; // 已登出
255
- const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
256
- const rec = await sessionToAccount(parsed, current ? 'WorkBuddy 当前登录' : 'WorkBuddy 历史会话', clientPath);
257
- if (!rec) continue;
258
- const fileTime = fs.statSync(file).mtimeMs;
259
- const item = { ...rec, current, file, fileTime };
260
- const prev = byUid.get(rec.uid);
261
- if (!prev || (current && !prev.current) || (current === prev.current && fileTime > prev.fileTime)) byUid.set(rec.uid, item);
262
- } catch (e) {
263
- out.errors.push({ file, error: e.message });
264
- }
265
- }
266
- void keyPromise;
267
- out.accounts = [...byUid.values()].sort((a, b) => b.current - a.current || b.fileTime - a.fileTime);
268
- return out;
269
- }
270
-
271
- /** 当前 WorkBuddy 客户端登录的 uid(未登录返回 null)。异步:见 readWorkbuddySessions。 */
272
- export async function currentWorkbuddyUid() {
273
- return (await readWorkbuddySessions()).accounts.find((a) => a.current)?.uid || null;
274
- }
275
-
276
- // 客户端可执行文件候选(VS Code 系安装惯例:%LOCALAPPDATA%\Programs\<名>\<名>.exe)。
277
- // 「已安装」只认 exe:凭据目录不能当依据——CreditDaddy 自己切换时 mkdir 也会把目录建出来
278
- // (无客户端时静默切换留下的空壳目录),拿目录判断会把没装客户端的机器误报成已安装。
279
- const CLIENT_CANDIDATES = process.platform === 'win32'
280
- ? [
281
- ['Programs', 'WorkBuddy', 'WorkBuddy.exe'],
282
- ['Programs', 'WorkBuddyAI', 'WorkBuddyAI.exe'],
283
- ['Programs', 'CodeBuddy CN', 'CodeBuddy CN.exe'],
284
- ['Programs', 'CodeBuddy', 'CodeBuddy.exe'],
285
- ['WorkBuddy', 'WorkBuddy.exe'],
286
- ['WorkBuddyAI', 'WorkBuddyAI.exe'],
287
- ['CodeBuddy CN', 'CodeBuddy CN.exe'],
288
- ['CodeBuddy', 'CodeBuddy.exe'],
289
- ]
290
- : process.platform === 'darwin'
291
- ? [
292
- '/Applications/WorkBuddy.app',
293
- '/Applications/WorkBuddy AI.app',
294
- '/Applications/CodeBuddy CN.app',
295
- '/Applications/CodeBuddy.app',
296
- ]
297
- : [];
298
-
299
- /**
300
- * 本机 WorkBuddy / CodeBuddy 客户端探测(面板「客户端:未安装」提示与切换拦截用)。
301
- * Linux / NAS 没有已知安装路径,退而用「凭据目录里有会话文件」判定——
302
- * 会话文件只有客户端登录后才写,纯 Token 导入的机器不会产生。
303
- */
304
- export function detectWorkbuddy() {
305
- const dir = workbuddyAuthDir();
306
- let dirExists = false;
307
- try { dirExists = fs.statSync(dir).isDirectory(); } catch { /* 未安装 / 从未登录 */ }
308
- let clientPath = null;
309
- for (const cand of CLIENT_CANDIDATES) {
310
- const p = process.platform === 'win32' && Array.isArray(cand)
311
- ? path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'), ...cand)
312
- : cand;
313
- try { if (fs.existsSync(p)) { clientPath = p; break; } } catch { /* 下一个候选 */ }
314
- }
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
- }
333
- return {
334
- dir,
335
- dirExists,
336
- clientPath,
337
- installed: Boolean(clientPath) || (CLIENT_CANDIDATES.length === 0 && signedIn),
338
- signedIn,
339
- };
340
- }
341
-
342
- /**
343
- * 把账号写成 WorkBuddy 当前会话(切换账号)。需要账号带有导入时保存的会话信息。
344
- * 如果原模板是 $wbEncrypted 信封格式,写回时将自动封包为合法信封。
345
- * @returns {{ file, previousUid }}
346
- */
347
- export async function writeWorkbuddySession(account, { clientPath } = {}) {
348
- const s = account.meta?.session;
349
- if (!s?.account) throw new Error('该账号缺少 WorkBuddy 会话信息,请从本机重新导入后再切换');
350
- const dir = workbuddyAuthDir();
351
- fs.mkdirSync(dir, { recursive: true });
352
- const file = path.join(dir, 'workbuddy-desktop.info');
353
- let previousUid = null;
354
- try { previousUid = JSON.parse(fs.readFileSync(file, 'utf8'))?.account?.uid || null; } catch {}
355
-
356
- const ms = (iso) => (iso ? new Date(iso).getTime() : undefined);
357
- const rawAuth = s.auth || {};
358
-
359
- // 判断是否需要信封封包写入(原会话 auth 字段包含 $wbEncrypted)
360
- const isEncryptedTemplate = isWbEncrypted(rawAuth.accessToken) || isWbEncrypted(rawAuth.refreshToken);
361
- let masterKey = null;
362
- if (isEncryptedTemplate) {
363
- masterKey = await getWorkbuddyMasterKey(clientPath);
364
- if (!masterKey) {
365
- throw new Error('无法切换账号:目标账号为 WorkBuddy 5.6+ 加密凭据,但未能获取客户端解密密钥');
366
- }
367
- }
368
-
369
- const accessPayload = isEncryptedTemplate
370
- ? sealEnvelope(account.token, masterKey, isWbEncrypted(rawAuth.accessToken) ? JSON.parse(Buffer.from(rawAuth.accessToken.envelope, 'base64').toString('utf8')) : {})
371
- : account.token;
372
-
373
- const refreshVal = account.refreshToken || rawAuth.refreshToken;
374
- const refreshPayload = isEncryptedTemplate && refreshVal
375
- ? sealEnvelope(refreshVal, masterKey, isWbEncrypted(rawAuth.refreshToken) ? JSON.parse(Buffer.from(rawAuth.refreshToken.envelope, 'base64').toString('utf8')) : {})
376
- : refreshVal;
377
-
378
- const session = {
379
- account: s.account,
380
- auth: {
381
- ...s.auth,
382
- accessToken: accessPayload,
383
- refreshToken: refreshPayload,
384
- expiresAt: ms(account.expiresAt) ?? s.auth?.expiresAt,
385
- lastRefreshTime: Date.now(),
386
- },
387
- accounts: s.accounts || [],
388
- ...(Array.isArray(s.allAccounts) ? { allAccounts: s.allAccounts } : {}),
389
- };
390
- const tmp = `${file}.${process.pid}.${crypto.randomUUID()}.tmp`;
391
- fs.writeFileSync(tmp, JSON.stringify(session, null, 2), { mode: 0o600 });
392
- fs.renameSync(tmp, file);
393
- try { fs.unlinkSync(`${file}.logged-out`); } catch {}
394
- return { file, previousUid };
395
- }
1
+ /**
2
+ * 本机 WorkBuddy 客户端凭据 — 读取已登录账号、切换当前账号。
3
+ *
4
+ * WorkBuddy(与 CodeBuddy CLI / 插件共用)把会话存成明文 JSON:
5
+ * Windows: %LOCALAPPDATA%\CodeBuddyExtension\Data\Public\auth\<认证ID>.info
6
+ * macOS: ~/Library/Application Support/CodeBuddyExtension/Data/Public/auth/
7
+ * Linux: ~/.local/share/CodeBuddyExtension/Data/Public/auth/
8
+ * 当前会话是 workbuddy-desktop.info(国际版客户端可能用其他认证 ID),带时间戳的同名文件是客户端留下的历史会话。
9
+ * 文件结构:{ account: { uid, nickname, phoneNumber, enterpriseId… }, auth: { accessToken, refreshToken, expiresAt, domain… }, accounts: [...] }
10
+ *
11
+ * 切换账号:原子写入会话文件 + 删除同目录的 "<文件>.logged-out" 登出标记;
12
+ * WorkBuddy 监听该文件,外部改动会被直接应用(客户端日志 "External change applied to session")。
13
+ */
14
+
15
+ import fs from 'node:fs';
16
+ import os from 'node:os';
17
+ import path from 'node:path';
18
+ import crypto from 'node:crypto';
19
+ import cp from 'node:child_process';
20
+ import { inspectToken } from './workbuddyClient.js';
21
+
22
+ // ===================== WorkBuddy 5.6+ $wbEncrypted 信封加解密 =====================
23
+
24
+ export function isWbEncrypted(val) {
25
+ return !!val && typeof val === 'object' && !Array.isArray(val) && val.$wbEncrypted === 1 && typeof val.envelope === 'string';
26
+ }
27
+
28
+ export function buildEnvelopeAAD(env) {
29
+ const FRAMING_FIELD = 2, FMT_FIELD = 'WBEV1', AAD_DOMAIN = Buffer.from('WB-AAD\0', 'ascii');
30
+ const lp = (s) => { const b = Buffer.from(s, 'utf8'); const l = Buffer.alloc(4); l.writeUInt32BE(b.length); return Buffer.concat([l, b]); };
31
+ const u32 = (n) => { const b = Buffer.alloc(4); b.writeUInt32BE(n); return b; };
32
+ return Buffer.concat([
33
+ AAD_DOMAIN, Buffer.from([1]), lp(FMT_FIELD), lp('sym-v1'), u32(env.suite || 1),
34
+ lp(env.keyId || ''), Buffer.from([FRAMING_FIELD]), Buffer.from([0]), Buffer.from([0]),
35
+ ]);
36
+ }
37
+
38
+ export function openEnvelope(encObj, key) {
39
+ const env = JSON.parse(Buffer.from(encObj.envelope, 'base64').toString('utf8'));
40
+ const decipher = crypto.createDecipheriv('aes-256-gcm', key, Buffer.from(env.nonce, 'base64'), { authTagLength: 16 });
41
+ decipher.setAAD(buildEnvelopeAAD(env));
42
+ decipher.setAuthTag(Buffer.from(env.authTag, 'base64'));
43
+ return Buffer.concat([decipher.update(Buffer.from(env.ciphertext, 'base64')), decipher.final()]).toString('utf8');
44
+ }
45
+
46
+ export function sealEnvelope(plaintext, key, template = {}) {
47
+ const nonce = crypto.randomBytes(12);
48
+ const cipher = crypto.createCipheriv('aes-256-gcm', key, nonce, { authTagLength: 16 });
49
+ const env = {
50
+ suite: template.suite || 1,
51
+ keyId: template.keyId || '',
52
+ nonce: nonce.toString('base64'),
53
+ };
54
+ cipher.setAAD(buildEnvelopeAAD(env));
55
+ const ciphertext = Buffer.concat([cipher.update(String(plaintext || ''), 'utf8'), cipher.final()]);
56
+ env.authTag = cipher.getAuthTag().toString('base64');
57
+ env.ciphertext = ciphertext.toString('base64');
58
+ return {
59
+ $wbEncrypted: 1,
60
+ envelope: Buffer.from(JSON.stringify(env)).toString('base64'),
61
+ };
62
+ }
63
+
64
+ let cachedMasterKey = null;
65
+ let masterKeyFailAt = 0;
66
+ let masterKeyInflight = null;
67
+ const KEY_RETRY_MS = 60000;
68
+
69
+ /**
70
+ * 经 WorkBuddy 官方 Electron(ELECTRON_RUN_AS_NODE=1)子进程调用原生存储绑定提取密钥。
71
+ * 内存缓存 + 在途去重,失败 60s 内退避;绝不写盘,绝不写日志。
72
+ * 必须 async:spawnSync 会同步卡死事件循环——桌面壳把 daemon 跑在 Electron 主进程里,
73
+ */
74
+ export async function getWorkbuddyMasterKey(clientPath) {
75
+ if (cachedMasterKey) return cachedMasterKey;
76
+ if (masterKeyFailAt && Date.now() - masterKeyFailAt < KEY_RETRY_MS) return null;
77
+ if (masterKeyInflight) return masterKeyInflight;
78
+ const exe = clientPath || detectWorkbuddy().clientPath;
79
+ if (!exe) return null;
80
+
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);
118
+ }
119
+ });
120
+ return masterKeyInflight;
121
+ }
122
+
123
+ export function resetMasterKeyCacheForTest(key = null) {
124
+ cachedMasterKey = key;
125
+ masterKeyFailAt = 0;
126
+ }
127
+
128
+ /** 深度解密 JSON 中的 $wbEncrypted 信封,返回包含明文的深拷贝(异步:取钥需起子进程) */
129
+ export async function decryptSessionJson(session, clientPath) {
130
+ if (!session || typeof session !== 'object') return session;
131
+ let key = null;
132
+ const clone = JSON.parse(JSON.stringify(session));
133
+
134
+ const walk = (node) => {
135
+ if (!node || typeof node !== 'object') return;
136
+ if (Array.isArray(node)) {
137
+ for (const item of node) walk(item);
138
+ return;
139
+ }
140
+ for (const [k, v] of Object.entries(node)) {
141
+ if (isWbEncrypted(v)) {
142
+ if (!key) key = getWorkbuddyMasterKey(clientPath);
143
+ if (key) {
144
+ try {
145
+ node[k] = openEnvelope(v, key);
146
+ } catch {
147
+ /* 解密失败保留原信封 */
148
+ }
149
+ }
150
+ } else if (v && typeof v === 'object') {
151
+ walk(v);
152
+ }
153
+ }
154
+ };
155
+
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
+ }
171
+ return clone;
172
+ }
173
+
174
+ // ===================== 凭据与会话管理 =====================
175
+
176
+ export function workbuddyAuthDir() {
177
+ const home = os.homedir();
178
+ const tail = ['CodeBuddyExtension', 'Data', 'Public', 'auth'];
179
+ if (process.platform === 'win32') {
180
+ return path.join(process.env.LOCALAPPDATA || path.join(home, 'AppData', 'Local'), ...tail);
181
+ }
182
+ if (process.platform === 'darwin') return path.join(home, 'Library', 'Application Support', ...tail);
183
+ return path.join(process.env.XDG_DATA_HOME || path.join(home, '.local', 'share'), ...tail);
184
+ }
185
+
186
+ const CURRENT_RE = /^[a-z0-9-]+\.info$/i; // workbuddy-desktop.info
187
+ const HISTORY_RE = /^[a-z0-9-]+\.\d{4}-.*\.info$/i; // workbuddy-desktop.<时间戳>.<pid>.<uuid>.info
188
+
189
+ /** 会话 JSON → 账号记录(供 addAccount),不含网络请求。
190
+ * 异步:含 $wbEncrypted 信封时需起 WorkBuddy 子进程取钥解密——
191
+ * 绝不用 spawnSync(会同步卡死 Electron 主进程事件循环 → 客户端「未响应」)。 */
192
+ export async function sessionToAccount(rawSession, source, clientPath) {
193
+ // 如果会话包含 $wbEncrypted 信封,先进行安全解密
194
+ const session = await decryptSessionJson(rawSession, clientPath);
195
+ const token = session?.auth?.accessToken;
196
+ if (typeof token !== 'string' || !token) return null;
197
+ const info = inspectToken(token);
198
+ if (!info.provider) return null;
199
+ const acc = session.account || {};
200
+ const auth = session.auth || {};
201
+ const iso = (ms) => (Number.isFinite(ms) ? new Date(ms).toISOString() : null);
202
+
203
+ // 手机号:优先未脱敏的 phoneNumber;若被客户端脱敏(含 *)或为空,回退到从 JWT 解析的大陆手机号
204
+ const rawPhone = typeof acc.phoneNumber === 'string' ? acc.phoneNumber.trim() : '';
205
+ const isRedacted = rawPhone.includes('*');
206
+ const phone = (!rawPhone || isRedacted) ? (info.phone || rawPhone || null) : rawPhone;
207
+
208
+ // 原 rawSession 结构原样保留在 meta.session,便于切换账号时原汁原味还原
209
+ const rawAuth = rawSession?.auth || auth;
210
+ const { accessToken: _a, refreshToken: _r, ...authRest } = rawAuth;
211
+ return {
212
+ provider: info.provider,
213
+ token,
214
+ refreshToken: auth.refreshToken || null,
215
+ expiresAt: iso(auth.expiresAt) || info.expiresAt,
216
+ uid: acc.uid || info.uid,
217
+ name: acc.nickname || acc.name || null,
218
+ email: acc.email || null,
219
+ source,
220
+ meta: {
221
+ domain: auth.domain || info.host,
222
+ enterpriseId: acc.enterpriseId || null,
223
+ phone,
224
+ refreshExpiresAt: iso(auth.refreshExpiresAt),
225
+ session: {
226
+ account: rawSession?.account || acc,
227
+ auth: authRest,
228
+ accounts: Array.isArray(rawSession?.accounts) ? rawSession.accounts : (session.accounts || []),
229
+ ...(Array.isArray(rawSession?.allAccounts || session.allAccounts) ? { allAccounts: rawSession?.allAccounts || session.allAccounts } : {}),
230
+ },
231
+ },
232
+ };
233
+ }
234
+
235
+ /**
236
+ * 读取本机 WorkBuddy 会话:当前会话 + 历史会话(按 uid 去重,保留最新)。
237
+ * @returns {{ dir, accounts: Array<{...账号记录, current: boolean, file, fileTime}>, errors }}
238
+ */
239
+ export async function readWorkbuddySessions(options = {}) {
240
+ const dir = options.dir || workbuddyAuthDir();
241
+ const clientPath = options.clientPath !== undefined ? options.clientPath : detectWorkbuddy().clientPath;
242
+ const out = { dir, accounts: [], errors: [] };
243
+ let names = [];
244
+ try { names = fs.readdirSync(dir); } catch { return out; }
245
+ const byUid = new Map();
246
+ // 密钥只取一次给整个目录用:缓存未命中时首个加密文件触发一次子进程(异步不阻塞),
247
+ // 之后的文件全部走内存缓存;明文文件在密钥不可用时仍可正常收割
248
+ let keyPromise = null;
249
+ for (const name of names) {
250
+ if (!CURRENT_RE.test(name) && !HISTORY_RE.test(name)) continue;
251
+ const file = path.join(dir, name);
252
+ try {
253
+ const current = !HISTORY_RE.test(name);
254
+ if (current && fs.existsSync(`${file}.logged-out`)) continue; // 已登出
255
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
256
+ const rec = await sessionToAccount(parsed, current ? 'WorkBuddy 当前登录' : 'WorkBuddy 历史会话', clientPath);
257
+ if (!rec) continue;
258
+ const fileTime = fs.statSync(file).mtimeMs;
259
+ const item = { ...rec, current, file, fileTime };
260
+ const prev = byUid.get(rec.uid);
261
+ if (!prev || (current && !prev.current) || (current === prev.current && fileTime > prev.fileTime)) byUid.set(rec.uid, item);
262
+ } catch (e) {
263
+ out.errors.push({ file, error: e.message });
264
+ }
265
+ }
266
+ void keyPromise;
267
+ out.accounts = [...byUid.values()].sort((a, b) => b.current - a.current || b.fileTime - a.fileTime);
268
+ return out;
269
+ }
270
+
271
+ /**
272
+ * 国内/国际两个桌面端各自的当前登录 uid(未登录的档位为 null)。
273
+ * 两者是独立会话文件(workbuddy-desktop.info / workbuddy-desktop-ai.info),可同时各有一个 current;
274
+ * 会话归属按 provider 区分(workbuddy=国内 realm 签发 / workbuddy-intl=国际 realm)。
275
+ */
276
+ export async function currentWorkbuddyUids() {
277
+ const accounts = (await readWorkbuddySessions()).accounts;
278
+ return {
279
+ cn: accounts.find((a) => a.current && a.provider !== 'workbuddy-intl')?.uid || null,
280
+ intl: accounts.find((a) => a.current && a.provider === 'workbuddy-intl')?.uid || null,
281
+ };
282
+ }
283
+
284
+ /** 当前国内版 WorkBuddy 客户端登录的 uid(国际版用 currentWorkbuddyUids().intl)。异步:见 readWorkbuddySessions。 */
285
+ export async function currentWorkbuddyUid() {
286
+ return (await currentWorkbuddyUids()).cn;
287
+ }
288
+
289
+ // 客户端可执行文件候选(VS Code 系安装惯例:%LOCALAPPDATA%\Programs\<名>\<名>.exe)。
290
+ // 「已安装」只认 exe:凭据目录不能当依据——CreditDaddy 自己切换时 mkdir 也会把目录建出来
291
+ // (无客户端时静默切换留下的空壳目录),拿目录判断会把没装客户端的机器误报成已安装。
292
+ const CLIENT_CANDIDATES = process.platform === 'win32'
293
+ ? [
294
+ ['Programs', 'WorkBuddy', 'WorkBuddy.exe'],
295
+ ['Programs', 'WorkBuddyAI', 'WorkBuddyAI.exe'],
296
+ ['Programs', 'CodeBuddy CN', 'CodeBuddy CN.exe'],
297
+ ['Programs', 'CodeBuddy', 'CodeBuddy.exe'],
298
+ ['WorkBuddy', 'WorkBuddy.exe'],
299
+ ['WorkBuddyAI', 'WorkBuddyAI.exe'],
300
+ ['CodeBuddy CN', 'CodeBuddy CN.exe'],
301
+ ['CodeBuddy', 'CodeBuddy.exe'],
302
+ ]
303
+ : process.platform === 'darwin'
304
+ ? [
305
+ '/Applications/WorkBuddy.app',
306
+ '/Applications/WorkBuddy AI.app',
307
+ '/Applications/CodeBuddy CN.app',
308
+ '/Applications/CodeBuddy.app',
309
+ ]
310
+ : [];
311
+
312
+ // ── 自定义安装路径发现(issue #46) ──
313
+ // 客户端装在 D:/E: 盘或自定义目录时,CLIENT_CANDIDATES 的固定路径全部落空,面板误判「未安装」
314
+ // 并硬拦切换。这里按「注册表 Uninstall 键 → 进程路径」两路兜底。
315
+ //
316
+ // ⚠️ 性能铁律(1.6.6 白屏事故):detectWorkbuddy 是**同步函数**且被 /api/status 每轮调用,
317
+ // 绝不能在里面 spawn 子进程(spawnSync 起 PowerShell/reg 会卡住 Electron 主进程消息泵)。
318
+ // 因此这里只做**零子进程**的注册表文件级读取:直接解析 NTUSER.DAT / SOFTWARE hive 不可行,
319
+ // 所以改走「持久缓存 + 异步预热」——异步发现结果写进模块级缓存,detectWorkbuddy 只读缓存。
320
+ let discoveredClientPath = null; // 异步发现到的自定义安装路径(进程内缓存)
321
+ let discoverPromise = null; // 在途去重
322
+
323
+ /** 异步预热:注册表 / 进程探测(唯一允许起子进程的地方,且绝不阻塞调用方)。
324
+ * 契约:**永远返回 Promise**(已发现 / 非 win32 时 resolve 现状)——调用方都挂 .catch,
325
+ * 返回 null/undefined 会在 NAS 与已预热的 Windows 机器上直接 TypeError(1.7.0 审计发现)。 */
326
+ export function warmWorkbuddyClientPath() {
327
+ if (process.platform !== 'win32' || discoveredClientPath) return Promise.resolve(discoveredClientPath);
328
+ if (discoverPromise) return discoverPromise;
329
+ discoverPromise = (async () => {
330
+ try {
331
+ // ① 注册表 Uninstall 键:DisplayIcon / InstallLocation 指向真实安装目录
332
+ const out = await new Promise((resolve) => {
333
+ cp.execFile('reg', ['query', 'HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall', '/s', '/f', 'WorkBuddy', '/d'],
334
+ { encoding: 'utf8', windowsHide: true, timeout: 4000, maxBuffer: 2 * 1024 * 1024 },
335
+ (err, stdout) => resolve(err ? '' : String(stdout)));
336
+ });
337
+ let hits = String(out).match(/DisplayIcon\s+REG_SZ\s+([^\r\n]+)/gi) || [];
338
+ // CodeBuddy 是另一个产品名,再查一次
339
+ const out2 = await new Promise((resolve) => {
340
+ cp.execFile('reg', ['query', 'HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall', '/s', '/f', 'CodeBuddy', '/d'],
341
+ { encoding: 'utf8', windowsHide: true, timeout: 4000, maxBuffer: 2 * 1024 * 1024 },
342
+ (err, stdout) => resolve(err ? '' : String(stdout)));
343
+ });
344
+ hits = hits.concat(String(out2).match(/DisplayIcon\s+REG_SZ\s+([^\r\n]+)/gi) || []);
345
+ for (const line of hits) {
346
+ // DisplayIcon 常见值:D:\Apps\WorkBuddy\WorkBuddy.exe / "...\WorkBuddy.exe",0
347
+ const raw = line.replace(/^DisplayIcon\s+REG_SZ\s+/i, '').trim().replace(/^"(.*)"(?:,\d+)?$/, '$1').replace(/,\d+$/, '');
348
+ if (/\.exe$/i.test(raw) && fs.existsSync(raw)) { discoveredClientPath = raw; return; }
349
+ }
350
+ // ② 运行中的进程路径(客户端已启动但注册表没写 DisplayIcon 的情况)
351
+ const ps = await new Promise((resolve) => {
352
+ cp.execFile('powershell', ['-NoProfile', '-NonInteractive', '-Command',
353
+ "Get-Process -Name 'WorkBuddy','WorkBuddyAI','CodeBuddy*' -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Path -Unique"],
354
+ { encoding: 'utf8', windowsHide: true, timeout: 4000 },
355
+ (err, stdout) => resolve(err ? '' : String(stdout)));
356
+ });
357
+ for (const line of String(ps).split(/\r?\n/)) {
358
+ const p = line.trim();
359
+ if (/\.exe$/i.test(p) && fs.existsSync(p)) { discoveredClientPath = p; return; }
360
+ }
361
+ } catch { /* 探测失败只是保持「未发现」,不影响既有候选路径判定 */ }
362
+ })().finally(() => { discoverPromise = null; });
363
+ return discoverPromise;
364
+ }
365
+
366
+ /** 测试用:注入/清除自定义安装路径缓存 */
367
+ export function _setDiscoveredClientPathForTest(p) { discoveredClientPath = p || null; }
368
+
369
+ /**
370
+ * 本机 WorkBuddy / CodeBuddy 客户端探测(面板「客户端:未安装」提示与切换拦截用)。
371
+ * Linux / NAS 没有已知安装路径,退而用「凭据目录里有会话文件」判定——
372
+ * 会话文件只有客户端登录后才写,纯 Token 导入的机器不会产生。
373
+ * 同步、零子进程:自定义路径由 warmWorkbuddyClientPath() 异步预热进缓存(issue #46)。
374
+ */
375
+ export function detectWorkbuddy() {
376
+ const dir = workbuddyAuthDir();
377
+ let dirExists = false;
378
+ try { dirExists = fs.statSync(dir).isDirectory(); } catch { /* 未安装 / 从未登录 */ }
379
+ let clientPath = null;
380
+ for (const cand of CLIENT_CANDIDATES) {
381
+ const p = process.platform === 'win32' && Array.isArray(cand)
382
+ ? path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'), ...cand)
383
+ : cand;
384
+ try { if (fs.existsSync(p)) { clientPath = p; break; } } catch { /* 下一个候选 */ }
385
+ }
386
+ // 固定候选全落空时用异步发现的路径(自定义盘符 / 目录,issue #46)
387
+ if (!clientPath && discoveredClientPath) {
388
+ try { if (fs.existsSync(discoveredClientPath)) clientPath = discoveredClientPath; } catch { /* ignore */ }
389
+ }
390
+ // signedIn 只做轻量文件判定(当前会话文件存在且无 logged-out 标记):
391
+ // 绝不在此调 readWorkbuddySessions——那会对加密会话起子进程解密(异步),
392
+ // 而 detectWorkbuddy 是同步函数且被 /api/status 每轮调用,解密等待会拖慢状态轮
393
+ let signedIn = false;
394
+ if (dirExists) {
395
+ const curFile = path.join(dir, 'workbuddy-desktop.info');
396
+ try { signedIn = fs.existsSync(curFile) && !fs.existsSync(`${curFile}.logged-out`); } catch { /* 保持 false */ }
397
+ if (!signedIn) {
398
+ // 多认证 ID 形态(Tencent-Cloud.*.info 等非固定名):目录里任一无登出标记的 .info 即视为登录态
399
+ try {
400
+ for (const name of fs.readdirSync(dir)) {
401
+ if (!CURRENT_RE.test(name) || name === 'workbuddy-desktop.info') continue;
402
+ if (HISTORY_RE.test(name)) continue;
403
+ if (!fs.existsSync(path.join(dir, `${name}.logged-out`))) { signedIn = true; break; }
404
+ }
405
+ } catch { /* 保持 false */ }
406
+ }
407
+ }
408
+ return {
409
+ dir,
410
+ dirExists,
411
+ clientPath,
412
+ installed: Boolean(clientPath) || (CLIENT_CANDIDATES.length === 0 && signedIn),
413
+ signedIn,
414
+ };
415
+ }
416
+
417
+ /**
418
+ * 构造 WorkBuddy 会话对象(当账号缺少 native session 时动态合成完整会话)
419
+ */
420
+ export function buildWorkbuddySession(account) {
421
+ const isIntl = account.provider === 'workbuddy-intl';
422
+ const domain = account.meta?.domain || (isIntl ? 'www.codebuddy.ai' : 'www.codebuddy.cn');
423
+ const uid = String(account.uid || '');
424
+ const nickname = account.name || account.meta?.phone || 'User';
425
+ const phone = account.meta?.phone ? String(account.meta.phone) : '';
426
+ const phoneMasked = phone ? phone.slice(0, 3) + '****' + phone.slice(-4) : '';
427
+ const accessToken = String(account.token || '');
428
+ const refreshToken = String(account.refreshToken || '');
429
+ const expiresAt = account.expiresAt ? new Date(account.expiresAt).getTime() : Date.now() + 30 * 86400e3;
430
+ const now = Date.now();
431
+
432
+ const origAccount = account.meta?.session?.account || {};
433
+ const accountObj = {
434
+ uid,
435
+ nickname,
436
+ uin: origAccount.uin || '',
437
+ type: origAccount.type || 'personal',
438
+ lastLogin: true,
439
+ isCreator: false,
440
+ isAdmin: false,
441
+ pluginEnabled: true,
442
+ deployStatus: { statusCode: 0, statusMsg: '', detailMsg: '' },
443
+ accountType: '',
444
+ sso: { domain: '', domainModifiedTimes: 0 },
445
+ idp: '',
446
+ areaInfoComplete: false,
447
+ oneidAccountId: '',
448
+ isCurrentOneIdEnterprise: false,
449
+ isCurrentOneIdPersonal: true,
450
+ isFirstLogin: false,
451
+ phoneNumber: origAccount.phoneNumber || phoneMasked || phone,
452
+ wechatOpenId: origAccount.wechatOpenId || '',
453
+ mpOpenId: origAccount.mpOpenId || '',
454
+ logOutEnable: false,
455
+ };
456
+
457
+ const authObj = {
458
+ accessToken,
459
+ refreshToken,
460
+ tokenType: 'Bearer',
461
+ sessionState: account.meta?.session?.auth?.sessionState || '',
462
+ scope: 'acr offline_access profile basic roles email web-origins',
463
+ domain,
464
+ lastRefreshTime: now,
465
+ expiresAt,
466
+ expiresIn: Math.round((expiresAt - now) / 1000),
467
+ refreshExpiresIn: 5183999,
468
+ refreshExpiresAt: expiresAt + 30 * 86400e3,
469
+ };
470
+
471
+ return {
472
+ account: accountObj,
473
+ auth: authObj,
474
+ accounts: [accountObj],
475
+ allAccounts: [accountObj],
476
+ };
477
+ }
478
+
479
+ /**
480
+ * 把账号写成 WorkBuddy 当前会话(切换账号)。需要账号带有导入时保存的会话信息。
481
+ * 如果原模板是 $wbEncrypted 信封格式,写回时将自动封包为合法信封。
482
+ * 若无保存过的会话信息,则用账号凭据动态合成完整会话。
483
+ * 对国际版(workbuddy-intl)与国内版(workbuddy)自动分流并双写(workbuddy-desktop.info 与 workbuddy-desktop-ai.info),
484
+ * 确保 WorkBuddy(国内端)与 WorkBuddyAI(国际端)均能实时应用切换。
485
+ * @returns {{ file, previousUid }}
486
+ */
487
+ export async function writeWorkbuddySession(account, { clientPath } = {}) {
488
+ const s = account.meta?.session?.account ? account.meta.session : buildWorkbuddySession(account);
489
+ if (!s?.account) throw new Error('该账号缺少 WorkBuddy 会话信息,请从本机重新导入后再切换');
490
+ const dir = workbuddyAuthDir();
491
+ fs.mkdirSync(dir, { recursive: true });
492
+
493
+ const isIntlAccount = account.provider === 'workbuddy-intl' || s.auth?.domain?.includes('.ai');
494
+ const primaryFileName = isIntlAccount ? 'workbuddy-desktop-ai.info' : 'workbuddy-desktop.info';
495
+ const primaryFile = path.join(dir, primaryFileName);
496
+ let previousUid = null;
497
+ try { previousUid = JSON.parse(fs.readFileSync(primaryFile, 'utf8'))?.account?.uid || null; } catch {}
498
+
499
+ const ms = (iso) => (iso ? new Date(iso).getTime() : undefined);
500
+ const rawAuth = s.auth || {};
501
+
502
+ // 获取加密主密钥(若目标环境或模板需要加密)
503
+ let masterKey = await getWorkbuddyMasterKey(clientPath);
504
+
505
+ // 待写入的文件列表:国际版优先写 workbuddy-desktop-ai.info 并兼顾 workbuddy-desktop.info;国内版写 workbuddy-desktop.info
506
+ const targetFiles = isIntlAccount
507
+ ? ['workbuddy-desktop-ai.info', 'workbuddy-desktop.info']
508
+ : ['workbuddy-desktop.info'];
509
+
510
+ for (const fileName of targetFiles) {
511
+ const file = path.join(dir, fileName);
512
+ let isEncryptedTemplate = isWbEncrypted(rawAuth.accessToken) || isWbEncrypted(rawAuth.refreshToken);
513
+ let templateEnv = {};
514
+
515
+ // 检查目标文件现有模板是否加密
516
+ try {
517
+ const existing = JSON.parse(fs.readFileSync(file, 'utf8'));
518
+ if (isWbEncrypted(existing.auth?.accessToken)) {
519
+ isEncryptedTemplate = true;
520
+ templateEnv = JSON.parse(Buffer.from(existing.auth.accessToken.envelope, 'base64').toString('utf8'));
521
+ }
522
+ } catch {}
523
+
524
+ const keyId = templateEnv.keyId || (masterKey ? crypto.createHash('sha256').update(masterKey).digest('hex').slice(0, 16) : '9127dea1b44020a7');
525
+ const sealOpts = { suite: 1, keyId };
526
+
527
+ const accessPayload = isEncryptedTemplate && masterKey
528
+ ? sealEnvelope(account.token, masterKey, sealOpts)
529
+ : account.token;
530
+
531
+ const refreshVal = account.refreshToken || rawAuth.refreshToken;
532
+ const refreshPayload = isEncryptedTemplate && masterKey && refreshVal
533
+ ? sealEnvelope(refreshVal, masterKey, sealOpts)
534
+ : refreshVal;
535
+
536
+ // 国际端 workbuddy-desktop-ai.info 中的 nickname 也是加密字段,写入时需同步封包
537
+ const nickVal = account.name || s.account.nickname || 'User';
538
+ const nickPayload = fileName.includes('-ai') && masterKey
539
+ ? sealEnvelope(nickVal, masterKey, sealOpts)
540
+ : nickVal;
541
+
542
+ const session = {
543
+ account: {
544
+ ...s.account,
545
+ nickname: nickPayload,
546
+ },
547
+ auth: {
548
+ ...s.auth,
549
+ accessToken: accessPayload,
550
+ refreshToken: refreshPayload,
551
+ expiresAt: ms(account.expiresAt) ?? s.auth?.expiresAt,
552
+ lastRefreshTime: Date.now(),
553
+ },
554
+ accounts: s.accounts || [],
555
+ ...(Array.isArray(s.allAccounts) ? { allAccounts: s.allAccounts } : {}),
556
+ };
557
+
558
+ const tmp = `${file}.${process.pid}.${crypto.randomUUID()}.tmp`;
559
+ fs.writeFileSync(tmp, JSON.stringify(session, null, 2), { mode: 0o600 });
560
+ fs.renameSync(tmp, file);
561
+ try { fs.unlinkSync(`${file}.logged-out`); } catch {}
562
+ }
563
+
564
+ return { file: primaryFile, previousUid };
565
+ }