creditdaddy 1.7.2 → 1.8.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.
- package/LICENSE +21 -21
- package/README.md +445 -440
- package/build.json +3 -3
- package/package.json +34 -34
- package/src/accounts.js +15 -0
- package/src/assets/donate-alipay.svg +1 -1
- package/src/assets/donate-ifdian.svg +1 -1
- package/src/assets/donate-wechat.svg +1 -1
- package/src/assets/providers/catpaw.png +0 -0
- package/src/assets/providers/codebuddy-ide.png +0 -0
- package/src/assets/providers/dumate.png +0 -0
- package/src/assets/providers/loomy.png +0 -0
- package/src/assets/providers/meoo.png +0 -0
- package/src/assets/providers/mirasim.png +0 -0
- package/src/bgdaemon.js +341 -341
- package/src/buildInfo.js +65 -65
- package/src/catpawClient.js +103 -103
- package/src/catpawLocal.js +236 -236
- package/src/checkin.js +7 -2
- package/src/codebuddyIdeLocal.js +381 -381
- package/src/constants.js +121 -117
- package/src/cookieSites.js +340 -301
- package/src/daemon.js +2682 -2443
- package/src/doubaoClient.js +167 -167
- package/src/dumateClient.js +517 -0
- package/src/dumateLocal.js +298 -0
- package/src/dumateQr.js +337 -0
- package/src/externalQuota.js +577 -574
- package/src/formatDuration.js +17 -17
- package/src/i18n/en.json +161 -7
- package/src/i18n/ja.json +161 -7
- package/src/i18n/ko.json +161 -7
- package/src/i18n/zh-TW.json +161 -7
- package/src/i18n.js +47 -47
- package/src/lingxiClient.js +373 -373
- package/src/localDetect.js +147 -147
- package/src/longcatClient.js +260 -260
- package/src/loomyAuth.js +230 -230
- package/src/loomyClient.js +366 -366
- package/src/loomyLocal.js +206 -206
- package/src/meooAuth.js +246 -0
- package/src/meooClient.js +250 -0
- package/src/minimaxGateway.js +520 -520
- package/src/minimaxLocal.js +344 -344
- package/src/mirasimClient.js +211 -211
- package/src/mirasimLocal.js +392 -392
- package/src/modelscopeClient.js +275 -275
- package/src/panel.html +374 -48
- package/src/prodIcons.json +7 -5
- package/src/providers.js +34 -0
- package/src/qoderApp.js +578 -578
- package/src/qoderClient.js +266 -266
- package/src/qoderUmid.js +199 -199
- package/src/quotaRefresh.js +119 -119
- package/src/refreshGuard.js +75 -75
- package/src/riverClient.js +372 -372
- package/src/store.js +2 -1
- package/src/tenrouterAccounts.js +237 -232
- package/src/traeAuth.js +601 -599
- package/src/traeClient.js +356 -360
- package/src/traeGateway.js +875 -875
- package/src/traeLocal.js +463 -371
- package/src/transfer.js +4 -0
- package/src/usageSync.js +535 -523
- package/src/winProc.js +134 -134
- package/src/xiaomiMimoClient.js +206 -206
- package/src/zcodeAuth.js +131 -131
- package/src/zcodeGateway.js +850 -850
- package/src/zcodeLocal.js +340 -340
- package/src/zcrypto.js +160 -160
package/src/codebuddyIdeLocal.js
CHANGED
|
@@ -1,381 +1,381 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* CodeBuddy IDE(桌面客户端)账号读取与切换 —— issue #51。
|
|
3
|
-
*
|
|
4
|
-
* 与 WorkBuddy 的关系:**账号体系同源**(token 都由 `www.codebuddy.cn` / `codebuddy.ai`
|
|
5
|
-
* 的同一个 realm 签发,`inspectToken` 识别为 workbuddy / workbuddy-intl),
|
|
6
|
-
* 所以额度查询、签到、10Router 推送全部复用既有链路,本模块只负责「读写 IDE 自己的存储」。
|
|
7
|
-
*
|
|
8
|
-
* 但**存储位置完全不同**:
|
|
9
|
-
* WorkBuddy:%LOCALAPPDATA%\CodeBuddyExtension\Data\Public\auth\*.info(明文/信封 JSON)
|
|
10
|
-
* CodeBuddy IDE:%APPDATA%\CodeBuddy CN\User\globalStorage\state.vscdb(SQLite)
|
|
11
|
-
* ItemTable 的 key = secret://{"extensionId":"tencent-cloud.coding-copilot","key":"<secretKey>"}
|
|
12
|
-
* value = JSON { type:"Buffer", data:[...] } —— Chromium Safe Storage 加密的密文
|
|
13
|
-
*
|
|
14
|
-
* 加解密(Windows):
|
|
15
|
-
* Local State 的 os_crypt.encrypted_key(base64,前缀 "DPAPI")
|
|
16
|
-
* → 去前缀 → DPAPI 解密 → 32 字节 AES-256 密钥
|
|
17
|
-
* → 密文格式 v10 | 12B nonce | ciphertext | 16B GCM tag
|
|
18
|
-
*
|
|
19
|
-
* 国内版 / 国际版:目录 CodeBuddy CN / CodeBuddy,secretKey ...accessTokencn / ...accessToken。
|
|
20
|
-
*
|
|
21
|
-
* ⚠️ 性能铁律(1.6.6 白屏事故):DPAPI 要走 PowerShell 子进程。
|
|
22
|
-
* 本模块**所有导出都是 async**,只允许在用户显式操作(本机导入 / 切换账号)时调用,
|
|
23
|
-
* 绝不能挂进 /api/status 状态轮询(那会把子进程塞进 Electron 主进程热路径)。
|
|
24
|
-
*/
|
|
25
|
-
|
|
26
|
-
import fs from 'node:fs';
|
|
27
|
-
import os from 'node:os';
|
|
28
|
-
import path from 'node:path';
|
|
29
|
-
import crypto from 'node:crypto';
|
|
30
|
-
import { execFile } from 'node:child_process';
|
|
31
|
-
|
|
32
|
-
const SECRET_EXTENSION_ID = 'tencent-cloud.coding-copilot';
|
|
33
|
-
const SECRET_KEY_CN = 'planning-genie.new.accessTokencn';
|
|
34
|
-
const SECRET_KEY_INTL = 'planning-genie.new.accessToken';
|
|
35
|
-
|
|
36
|
-
/** 两个档位:国内 CN / 国际版 */
|
|
37
|
-
export const CODEBUDDY_IDE_FLAVORS = {
|
|
38
|
-
cn: { dataDirName: 'CodeBuddy CN', secretKey: SECRET_KEY_CN, provider: 'workbuddy', label: 'CodeBuddy CN' },
|
|
39
|
-
intl: { dataDirName: 'CodeBuddy', secretKey: SECRET_KEY_INTL, provider: 'workbuddy-intl', label: 'CodeBuddy' },
|
|
40
|
-
};
|
|
41
|
-
|
|
42
|
-
/** Electron/VS Code 系客户端的数据根目录(Windows 是 %APPDATA%,不是 %LOCALAPPDATA%) */
|
|
43
|
-
function appDataRoot() {
|
|
44
|
-
if (process.platform === 'win32') return process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming');
|
|
45
|
-
if (process.platform === 'darwin') return path.join(os.homedir(), 'Library', 'Application Support');
|
|
46
|
-
return process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config');
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/** 某档位的数据根目录(Custom 目录可经 env 覆盖,供测试注入) */
|
|
50
|
-
export function codebuddyIdeDataDir(flavor = 'cn') {
|
|
51
|
-
const f = CODEBUDDY_IDE_FLAVORS[flavor];
|
|
52
|
-
if (!f) throw new Error(`未知的 CodeBuddy IDE 档位:${flavor}`);
|
|
53
|
-
const override = flavor === 'cn' ? process.env.CODEBUDDY_IDE_DIR_CN : process.env.CODEBUDDY_IDE_DIR_INTL;
|
|
54
|
-
return override || path.join(appDataRoot(), f.dataDirName);
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
/** state.vscdb 路径(只读探测用:不做 create 副作用,见参考实现 issue #91 的教训) */
|
|
58
|
-
export function codebuddyIdeStateDbPath(flavor = 'cn') {
|
|
59
|
-
const root = codebuddyIdeDataDir(flavor);
|
|
60
|
-
const candidates = [
|
|
61
|
-
path.join(root, 'User', 'globalStorage', 'state.vscdb'),
|
|
62
|
-
path.join(root, 'globalStorage', 'state.vscdb'),
|
|
63
|
-
path.join(root, 'state.vscdb'),
|
|
64
|
-
];
|
|
65
|
-
return candidates.find((p) => { try { return fs.existsSync(p); } catch { return false; } }) || candidates[0];
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/** 同步探测「有没有装」——只做文件存在性判断,不起子进程,可安全用于状态展示 */
|
|
69
|
-
export function detectCodeBuddyIde(flavor = 'cn') {
|
|
70
|
-
const dbPath = codebuddyIdeStateDbPath(flavor);
|
|
71
|
-
let exists = false;
|
|
72
|
-
try { exists = fs.existsSync(dbPath); } catch { /* ignore */ }
|
|
73
|
-
return { flavor, dataDir: codebuddyIdeDataDir(flavor), dbPath, installed: exists };
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
let cachedActiveUid = null;
|
|
77
|
-
let cachedActiveMtime = 0;
|
|
78
|
-
|
|
79
|
-
/**
|
|
80
|
-
* 快速读取当前 CodeBuddy IDE 激活的账号 UID(纯本地文件 mtime 缓存,零子进程开销)
|
|
81
|
-
*/
|
|
82
|
-
export async function getActiveCodeBuddyIdeUid(flavor = 'cn') {
|
|
83
|
-
const det = detectCodeBuddyIde(flavor);
|
|
84
|
-
if (!det.installed) return null;
|
|
85
|
-
try {
|
|
86
|
-
const stat = fs.statSync(det.dbPath);
|
|
87
|
-
if (cachedActiveUid !== null && stat.mtimeMs === cachedActiveMtime) {
|
|
88
|
-
return cachedActiveUid;
|
|
89
|
-
}
|
|
90
|
-
const s = await readCodeBuddyIdeSession(flavor);
|
|
91
|
-
cachedActiveMtime = stat.mtimeMs;
|
|
92
|
-
cachedActiveUid = s?.account?.uid || null;
|
|
93
|
-
return cachedActiveUid;
|
|
94
|
-
} catch {
|
|
95
|
-
return null;
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
/** 同时探测两个档位(面板展示用,纯同步) */
|
|
100
|
-
export function detectCodeBuddyIdeAll() {
|
|
101
|
-
return { cn: detectCodeBuddyIde('cn'), intl: detectCodeBuddyIde('intl') };
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
// ── SQLite 读取(node:sqlite,Node 22.5+ 内置;Electron 37 自带 Node 22) ──
|
|
105
|
-
// 没装 sqlite 的环境(如 Node 20 的 CLI)给出明确错误,而不是抛一个看不懂的 MODULE_NOT_FOUND
|
|
106
|
-
async function openDb(dbPath, { readOnly }) {
|
|
107
|
-
let DatabaseSync;
|
|
108
|
-
try {
|
|
109
|
-
({ DatabaseSync } = await import('node:sqlite'));
|
|
110
|
-
} catch {
|
|
111
|
-
throw new Error('当前运行环境不支持 node:sqlite(需要 Node 22.5+ 或桌面版),无法读写 CodeBuddy IDE 存储');
|
|
112
|
-
}
|
|
113
|
-
return new DatabaseSync(dbPath, { readOnly });
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
// ── Windows 密钥:Local State → DPAPI → 32B AES key ──
|
|
117
|
-
function dpapiUnprotect(cipherB64) {
|
|
118
|
-
return new Promise((resolve, reject) => {
|
|
119
|
-
// PowerShell 5 的 System.Security.Cryptography.ProtectedData 就是 DPAPI(CurrentUser 范围)
|
|
120
|
-
const script =
|
|
121
|
-
'Add-Type -AssemblyName System.Security; ' +
|
|
122
|
-
`$b=[Convert]::FromBase64String('${cipherB64}'); ` +
|
|
123
|
-
"$d=[System.Security.Cryptography.ProtectedData]::Unprotect($b,$null,'CurrentUser'); " +
|
|
124
|
-
'[Convert]::ToBase64String($d)';
|
|
125
|
-
execFile('powershell', ['-NoProfile', '-NonInteractive', '-Command', script],
|
|
126
|
-
{ encoding: 'utf8', windowsHide: true, timeout: 15000 },
|
|
127
|
-
(err, stdout) => {
|
|
128
|
-
if (err) return reject(new Error('DPAPI 解密失败:' + (err.message || err)));
|
|
129
|
-
const out = String(stdout || '').trim();
|
|
130
|
-
if (!out) return reject(new Error('DPAPI 返回空结果'));
|
|
131
|
-
try { resolve(Buffer.from(out, 'base64')); } catch (e) { reject(e); }
|
|
132
|
-
});
|
|
133
|
-
});
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
/** macOS Keychain 里该应用的 Safe Storage 密码(PBKDF2-SHA1 派生 AES-128 密钥用) */
|
|
137
|
-
function macSafeStoragePassword(flavor) {
|
|
138
|
-
const service = flavor === 'cn' ? 'CodeBuddy CN Safe Storage' : 'CodeBuddy Safe Storage';
|
|
139
|
-
return new Promise((resolve, reject) => {
|
|
140
|
-
execFile('security', ['find-generic-password', '-w', '-s', service],
|
|
141
|
-
{ encoding: 'utf8', timeout: 10000 }, (err, stdout) => {
|
|
142
|
-
if (err) return reject(new Error(`无法从 Keychain 读取「${service}」密码(请先打开该应用并登录一次)`));
|
|
143
|
-
const v = String(stdout || '').trim();
|
|
144
|
-
if (!v) return reject(new Error(`Keychain 中「${service}」为空`));
|
|
145
|
-
resolve(v);
|
|
146
|
-
});
|
|
147
|
-
});
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
/**
|
|
151
|
-
* 取本档位的解密密钥。Windows 返回 32 字节 AES-256;macOS 返回 PBKDF2 派生的 16 字节 AES-128。
|
|
152
|
-
* @returns {Promise<{alg:'aes-256-gcm'|'aes-128-cbc', key: Buffer}>}
|
|
153
|
-
*/
|
|
154
|
-
async function loadCryptoKey(flavor) {
|
|
155
|
-
if (process.platform === 'win32') {
|
|
156
|
-
const localStatePath = path.join(codebuddyIdeDataDir(flavor), 'Local State');
|
|
157
|
-
let json;
|
|
158
|
-
try { json = JSON.parse(fs.readFileSync(localStatePath, 'utf8')); }
|
|
159
|
-
catch { throw new Error(`读取 Local State 失败(${localStatePath})——请先打开 CodeBuddy 客户端并登录一次`); }
|
|
160
|
-
const b64 = json?.os_crypt?.encrypted_key;
|
|
161
|
-
if (!b64) throw new Error('Local State 缺少 os_crypt.encrypted_key');
|
|
162
|
-
const raw = Buffer.from(b64, 'base64');
|
|
163
|
-
if (raw.subarray(0, 5).toString('latin1') !== 'DPAPI') throw new Error('encrypted_key 前缀不是 DPAPI');
|
|
164
|
-
const key = await dpapiUnprotect(raw.subarray(5).toString('base64'));
|
|
165
|
-
if (key.length !== 32) throw new Error(`DPAPI 解出的密钥长度是 ${key.length},期望 32(AES-256)`);
|
|
166
|
-
return { alg: 'aes-256-gcm', key };
|
|
167
|
-
}
|
|
168
|
-
if (process.platform === 'darwin') {
|
|
169
|
-
const pw = await macSafeStoragePassword(flavor);
|
|
170
|
-
const key = crypto.pbkdf2Sync(pw, Buffer.from('saltysalt'), 1003, 16, 'sha1');
|
|
171
|
-
return { alg: 'aes-128-cbc', key };
|
|
172
|
-
}
|
|
173
|
-
throw new Error('CodeBuddy IDE 凭据读取目前只支持 Windows / macOS');
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
/** 解密 v10 密文 → 明文 */
|
|
177
|
-
function decryptSecretPayload(buf, { alg, key }) {
|
|
178
|
-
const prefix = buf.subarray(0, 3).toString('latin1');
|
|
179
|
-
if (prefix !== 'v10') throw new Error(`密文前缀不是 v10(实际 "${prefix}")`);
|
|
180
|
-
if (alg === 'aes-256-gcm') {
|
|
181
|
-
const d = crypto.createDecipheriv('aes-256-gcm', key, buf.subarray(3, 15));
|
|
182
|
-
d.setAuthTag(buf.subarray(buf.length - 16));
|
|
183
|
-
return Buffer.concat([d.update(buf.subarray(15, buf.length - 16)), d.final()]);
|
|
184
|
-
}
|
|
185
|
-
const d = crypto.createDecipheriv('aes-128-cbc', key, Buffer.alloc(16, 0x20)); // CBC IV 为 16 个空格
|
|
186
|
-
return Buffer.concat([d.update(buf.subarray(3)), d.final()]);
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
/** 明文 → v10 密文(每次随机 nonce,与 Chromium 行为一致) */
|
|
190
|
-
function encryptSecretPayload(plain, { alg, key }) {
|
|
191
|
-
if (alg === 'aes-256-gcm') {
|
|
192
|
-
const iv = crypto.randomBytes(12);
|
|
193
|
-
const c = crypto.createCipheriv('aes-256-gcm', key, iv);
|
|
194
|
-
const ct = Buffer.concat([c.update(plain), c.final()]);
|
|
195
|
-
return Buffer.concat([Buffer.from('v10'), iv, ct, c.getAuthTag()]);
|
|
196
|
-
}
|
|
197
|
-
const c = crypto.createCipheriv('aes-128-cbc', key, Buffer.alloc(16, 0x20));
|
|
198
|
-
return Buffer.concat([Buffer.from('v10'), c.update(plain), c.final()]);
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
function secretRowKey(flavor) {
|
|
202
|
-
return `secret://{"extensionId":"${SECRET_EXTENSION_ID}","key":"${CODEBUDDY_IDE_FLAVORS[flavor].secretKey}"}`;
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
/** 把 ItemTable 的 value(string 或 Buffer)解析成密文字节 */
|
|
206
|
-
function parseBufferValue(value) {
|
|
207
|
-
const text = typeof value === 'string' ? value : Buffer.from(value).toString('utf8');
|
|
208
|
-
const parsed = JSON.parse(text);
|
|
209
|
-
if (parsed?.type !== 'Buffer' || !Array.isArray(parsed.data)) throw new Error('secret 值不是 Buffer 结构');
|
|
210
|
-
return { bytes: Buffer.from(parsed.data), raw: parsed };
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
/**
|
|
214
|
-
* 读取 CodeBuddy IDE 当前登录的会话(解密后的完整 JSON)。
|
|
215
|
-
* @returns {Promise<null | { flavor, session, accessToken, refreshToken, account, auth }>}
|
|
216
|
-
*/
|
|
217
|
-
export async function readCodeBuddyIdeSession(flavor = 'cn') {
|
|
218
|
-
const det = detectCodeBuddyIde(flavor);
|
|
219
|
-
if (!det.installed) return null;
|
|
220
|
-
const keyInfo = await loadCryptoKey(flavor);
|
|
221
|
-
const db = await openDb(det.dbPath, { readOnly: true });
|
|
222
|
-
let row;
|
|
223
|
-
try {
|
|
224
|
-
row = db.prepare('SELECT value FROM ItemTable WHERE key = ?').get(secretRowKey(flavor));
|
|
225
|
-
} finally {
|
|
226
|
-
try { db.close(); } catch { /* ignore */ }
|
|
227
|
-
}
|
|
228
|
-
if (!row) return null;
|
|
229
|
-
const { bytes } = parseBufferValue(row.value);
|
|
230
|
-
const plain = decryptSecretPayload(bytes, keyInfo).toString('utf8');
|
|
231
|
-
let session;
|
|
232
|
-
try { session = JSON.parse(plain); } catch { throw new Error('解密成功但内容不是 JSON(存储格式可能已变)'); }
|
|
233
|
-
const auth = session.auth || {};
|
|
234
|
-
const account = session.account || {};
|
|
235
|
-
return {
|
|
236
|
-
flavor,
|
|
237
|
-
session,
|
|
238
|
-
accessToken: auth.accessToken || session.token || null,
|
|
239
|
-
refreshToken: auth.refreshToken || session.refreshToken || null,
|
|
240
|
-
account,
|
|
241
|
-
auth,
|
|
242
|
-
};
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
/**
|
|
246
|
-
* 把一份会话写回 CodeBuddy IDE(切换账号)。
|
|
247
|
-
* 写前强制备份 state.vscdb → state.vscdb.bak-<时间戳>。
|
|
248
|
-
* @returns {Promise<{ dbPath, backup, uid }>}
|
|
249
|
-
*/
|
|
250
|
-
export async function writeCodeBuddyIdeSession(flavor, session) {
|
|
251
|
-
if (!session || typeof session !== 'object') throw new Error('会话内容为空');
|
|
252
|
-
const det = detectCodeBuddyIde(flavor);
|
|
253
|
-
if (!det.installed) throw new Error(`未找到 ${CODEBUDDY_IDE_FLAVORS[flavor].label} 的存储(${det.dbPath})`);
|
|
254
|
-
const keyInfo = await loadCryptoKey(flavor);
|
|
255
|
-
const plain = Buffer.from(JSON.stringify(session), 'utf8');
|
|
256
|
-
const cipher = encryptSecretPayload(plain, keyInfo);
|
|
257
|
-
|
|
258
|
-
// 备份:写坏了能立刻还原,这是改用户主工作环境的最低保障
|
|
259
|
-
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
260
|
-
const backup = `${det.dbPath}.bak-${stamp}`;
|
|
261
|
-
fs.copyFileSync(det.dbPath, backup);
|
|
262
|
-
|
|
263
|
-
const db = await openDb(det.dbPath, { readOnly: false });
|
|
264
|
-
try {
|
|
265
|
-
// upsert 而非裸 UPDATE:IDE 装了但从没登录时 secret 行不存在,裸 UPDATE 影响 0 行
|
|
266
|
-
// 却不报错 → 切号返回 ok 但用户重启 IDE 后什么都没变(「硬写后假成功」同款问题)
|
|
267
|
-
const changes = db.prepare(
|
|
268
|
-
`INSERT INTO ItemTable (key, value) VALUES (?, ?)
|
|
269
|
-
ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
|
|
270
|
-
).run(secretRowKey(flavor), JSON.stringify({ type: 'Buffer', data: Array.from(cipher) }));
|
|
271
|
-
if (!Number(changes.changes)) throw new Error('写入 CodeBuddy IDE 存储失败(0 行受影响)');
|
|
272
|
-
} finally {
|
|
273
|
-
try { db.close(); } catch { /* ignore */ }
|
|
274
|
-
}
|
|
275
|
-
return { dbPath: det.dbPath, backup, uid: session.account?.uid || null };
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
/**
|
|
279
|
-
* 构造注入到 CodeBuddy IDE 的会话 JSON(与 workbuddy-switch 的 build_session_json 规范一致)。
|
|
280
|
-
* 任何 WorkBuddy 系账号(只要有 token、refreshToken 或会话数据)都可以合成为合法的 IDE 会话。
|
|
281
|
-
*/
|
|
282
|
-
export function buildCodeBuddyIdeSession(account, flavor = 'cn') {
|
|
283
|
-
const isIntl = account.provider === 'workbuddy-intl' || flavor === 'intl';
|
|
284
|
-
const domain = account.meta?.domain || (isIntl ? 'www.codebuddy.ai' : 'www.codebuddy.cn');
|
|
285
|
-
const id = isIntl ? 'Tencent-Cloud.genie-ide' : 'Tencent-Cloud.genie-ide-cn';
|
|
286
|
-
const uid = String(account.uid || '');
|
|
287
|
-
const nickname = account.name || account.meta?.phone || 'User';
|
|
288
|
-
const phone = account.meta?.phone ? String(account.meta.phone) : '';
|
|
289
|
-
const phoneMasked = phone ? phone.slice(0, 3) + '****' + phone.slice(-4) : '';
|
|
290
|
-
const accessToken = String(account.token || '');
|
|
291
|
-
const refreshToken = String(account.refreshToken || '');
|
|
292
|
-
const expiresAt = account.expiresAt ? new Date(account.expiresAt).getTime() : Date.now() + 30 * 86400e3;
|
|
293
|
-
const now = Date.now();
|
|
294
|
-
|
|
295
|
-
const origAccount = account.meta?.session?.account || {};
|
|
296
|
-
const accountObj = {
|
|
297
|
-
uid,
|
|
298
|
-
nickname,
|
|
299
|
-
uin: origAccount.uin || '',
|
|
300
|
-
type: origAccount.type || 'personal',
|
|
301
|
-
lastLogin: true,
|
|
302
|
-
isCreator: false,
|
|
303
|
-
isAdmin: false,
|
|
304
|
-
pluginEnabled: true,
|
|
305
|
-
deployStatus: { statusCode: 0, statusMsg: '', detailMsg: '' },
|
|
306
|
-
accountType: '',
|
|
307
|
-
sso: { domain: '', domainModifiedTimes: 0 },
|
|
308
|
-
idp: '',
|
|
309
|
-
areaInfoComplete: false,
|
|
310
|
-
oneidAccountId: '',
|
|
311
|
-
isCurrentOneIdEnterprise: false,
|
|
312
|
-
isCurrentOneIdPersonal: false,
|
|
313
|
-
isFirstLogin: false,
|
|
314
|
-
phoneNumber: origAccount.phoneNumber || phoneMasked,
|
|
315
|
-
wechatOpenId: origAccount.wechatOpenId || '',
|
|
316
|
-
mpOpenId: origAccount.mpOpenId || '',
|
|
317
|
-
logOutEnable: false,
|
|
318
|
-
id: uid,
|
|
319
|
-
label: nickname,
|
|
320
|
-
};
|
|
321
|
-
|
|
322
|
-
const authObj = {
|
|
323
|
-
accessToken,
|
|
324
|
-
refreshToken,
|
|
325
|
-
tokenType: 'Bearer',
|
|
326
|
-
sessionState: account.meta?.session?.auth?.sessionState || '',
|
|
327
|
-
scope: 'acr offline_access profile basic roles email web-origins',
|
|
328
|
-
domain,
|
|
329
|
-
lastRefreshTime: now,
|
|
330
|
-
expiresAt,
|
|
331
|
-
expiresIn: Math.round((expiresAt - now) / 1000),
|
|
332
|
-
refreshExpiresIn: 5183999,
|
|
333
|
-
refreshExpiresAt: expiresAt + 30 * 86400e3,
|
|
334
|
-
};
|
|
335
|
-
|
|
336
|
-
return {
|
|
337
|
-
id,
|
|
338
|
-
token: accessToken,
|
|
339
|
-
refreshToken,
|
|
340
|
-
expiresAt,
|
|
341
|
-
domain,
|
|
342
|
-
accessToken: `${uid}+${accessToken}`,
|
|
343
|
-
converted: true,
|
|
344
|
-
account: accountObj,
|
|
345
|
-
auth: authObj,
|
|
346
|
-
accounts: [accountObj],
|
|
347
|
-
};
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
/**
|
|
351
|
-
* 读到的会话 → CreditDaddy 账号记录(不直接落库,交给调用方的 addRecord)。
|
|
352
|
-
* provider 由 token 的 iss 决定(workbuddy / workbuddy-intl),与 WorkBuddy 完全同源。
|
|
353
|
-
*/
|
|
354
|
-
export function codebuddySessionToAccount(flavor, read, inspectToken) {
|
|
355
|
-
const info = inspectToken(read.accessToken || '');
|
|
356
|
-
if (!info.provider) return null;
|
|
357
|
-
const acc = read.account || {};
|
|
358
|
-
const auth = read.auth || {};
|
|
359
|
-
const iso = (ms) => (Number.isFinite(ms) ? new Date(ms).toISOString() : null);
|
|
360
|
-
const rawPhone = typeof acc.phoneNumber === 'string' ? acc.phoneNumber.trim() : '';
|
|
361
|
-
const phone = (!rawPhone || rawPhone.includes('*')) ? (info.phone || rawPhone || null) : rawPhone;
|
|
362
|
-
return {
|
|
363
|
-
provider: info.provider,
|
|
364
|
-
token: read.accessToken,
|
|
365
|
-
refreshToken: read.refreshToken || null,
|
|
366
|
-
expiresAt: iso(auth.expiresAt) || info.expiresAt,
|
|
367
|
-
uid: acc.uid || info.uid,
|
|
368
|
-
name: acc.nickname || acc.name || acc.label || info.name || null,
|
|
369
|
-
email: acc.email || info.email || null,
|
|
370
|
-
source: 'codebuddy-ide',
|
|
371
|
-
meta: {
|
|
372
|
-
domain: auth.domain || info.host,
|
|
373
|
-
phone,
|
|
374
|
-
refreshExpiresAt: iso(auth.refreshExpiresAt),
|
|
375
|
-
// 记录来源档位,切换时据此写回正确的库
|
|
376
|
-
codebuddyIdeFlavor: flavor,
|
|
377
|
-
// 整份会话留着,切换时原样(重新加密)写回
|
|
378
|
-
cbIdeSession: read.session,
|
|
379
|
-
},
|
|
380
|
-
};
|
|
381
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* CodeBuddy IDE(桌面客户端)账号读取与切换 —— issue #51。
|
|
3
|
+
*
|
|
4
|
+
* 与 WorkBuddy 的关系:**账号体系同源**(token 都由 `www.codebuddy.cn` / `codebuddy.ai`
|
|
5
|
+
* 的同一个 realm 签发,`inspectToken` 识别为 workbuddy / workbuddy-intl),
|
|
6
|
+
* 所以额度查询、签到、10Router 推送全部复用既有链路,本模块只负责「读写 IDE 自己的存储」。
|
|
7
|
+
*
|
|
8
|
+
* 但**存储位置完全不同**:
|
|
9
|
+
* WorkBuddy:%LOCALAPPDATA%\CodeBuddyExtension\Data\Public\auth\*.info(明文/信封 JSON)
|
|
10
|
+
* CodeBuddy IDE:%APPDATA%\CodeBuddy CN\User\globalStorage\state.vscdb(SQLite)
|
|
11
|
+
* ItemTable 的 key = secret://{"extensionId":"tencent-cloud.coding-copilot","key":"<secretKey>"}
|
|
12
|
+
* value = JSON { type:"Buffer", data:[...] } —— Chromium Safe Storage 加密的密文
|
|
13
|
+
*
|
|
14
|
+
* 加解密(Windows):
|
|
15
|
+
* Local State 的 os_crypt.encrypted_key(base64,前缀 "DPAPI")
|
|
16
|
+
* → 去前缀 → DPAPI 解密 → 32 字节 AES-256 密钥
|
|
17
|
+
* → 密文格式 v10 | 12B nonce | ciphertext | 16B GCM tag
|
|
18
|
+
*
|
|
19
|
+
* 国内版 / 国际版:目录 CodeBuddy CN / CodeBuddy,secretKey ...accessTokencn / ...accessToken。
|
|
20
|
+
*
|
|
21
|
+
* ⚠️ 性能铁律(1.6.6 白屏事故):DPAPI 要走 PowerShell 子进程。
|
|
22
|
+
* 本模块**所有导出都是 async**,只允许在用户显式操作(本机导入 / 切换账号)时调用,
|
|
23
|
+
* 绝不能挂进 /api/status 状态轮询(那会把子进程塞进 Electron 主进程热路径)。
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import fs from 'node:fs';
|
|
27
|
+
import os from 'node:os';
|
|
28
|
+
import path from 'node:path';
|
|
29
|
+
import crypto from 'node:crypto';
|
|
30
|
+
import { execFile } from 'node:child_process';
|
|
31
|
+
|
|
32
|
+
const SECRET_EXTENSION_ID = 'tencent-cloud.coding-copilot';
|
|
33
|
+
const SECRET_KEY_CN = 'planning-genie.new.accessTokencn';
|
|
34
|
+
const SECRET_KEY_INTL = 'planning-genie.new.accessToken';
|
|
35
|
+
|
|
36
|
+
/** 两个档位:国内 CN / 国际版 */
|
|
37
|
+
export const CODEBUDDY_IDE_FLAVORS = {
|
|
38
|
+
cn: { dataDirName: 'CodeBuddy CN', secretKey: SECRET_KEY_CN, provider: 'workbuddy', label: 'CodeBuddy CN' },
|
|
39
|
+
intl: { dataDirName: 'CodeBuddy', secretKey: SECRET_KEY_INTL, provider: 'workbuddy-intl', label: 'CodeBuddy' },
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
/** Electron/VS Code 系客户端的数据根目录(Windows 是 %APPDATA%,不是 %LOCALAPPDATA%) */
|
|
43
|
+
function appDataRoot() {
|
|
44
|
+
if (process.platform === 'win32') return process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming');
|
|
45
|
+
if (process.platform === 'darwin') return path.join(os.homedir(), 'Library', 'Application Support');
|
|
46
|
+
return process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config');
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** 某档位的数据根目录(Custom 目录可经 env 覆盖,供测试注入) */
|
|
50
|
+
export function codebuddyIdeDataDir(flavor = 'cn') {
|
|
51
|
+
const f = CODEBUDDY_IDE_FLAVORS[flavor];
|
|
52
|
+
if (!f) throw new Error(`未知的 CodeBuddy IDE 档位:${flavor}`);
|
|
53
|
+
const override = flavor === 'cn' ? process.env.CODEBUDDY_IDE_DIR_CN : process.env.CODEBUDDY_IDE_DIR_INTL;
|
|
54
|
+
return override || path.join(appDataRoot(), f.dataDirName);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** state.vscdb 路径(只读探测用:不做 create 副作用,见参考实现 issue #91 的教训) */
|
|
58
|
+
export function codebuddyIdeStateDbPath(flavor = 'cn') {
|
|
59
|
+
const root = codebuddyIdeDataDir(flavor);
|
|
60
|
+
const candidates = [
|
|
61
|
+
path.join(root, 'User', 'globalStorage', 'state.vscdb'),
|
|
62
|
+
path.join(root, 'globalStorage', 'state.vscdb'),
|
|
63
|
+
path.join(root, 'state.vscdb'),
|
|
64
|
+
];
|
|
65
|
+
return candidates.find((p) => { try { return fs.existsSync(p); } catch { return false; } }) || candidates[0];
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** 同步探测「有没有装」——只做文件存在性判断,不起子进程,可安全用于状态展示 */
|
|
69
|
+
export function detectCodeBuddyIde(flavor = 'cn') {
|
|
70
|
+
const dbPath = codebuddyIdeStateDbPath(flavor);
|
|
71
|
+
let exists = false;
|
|
72
|
+
try { exists = fs.existsSync(dbPath); } catch { /* ignore */ }
|
|
73
|
+
return { flavor, dataDir: codebuddyIdeDataDir(flavor), dbPath, installed: exists };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
let cachedActiveUid = null;
|
|
77
|
+
let cachedActiveMtime = 0;
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* 快速读取当前 CodeBuddy IDE 激活的账号 UID(纯本地文件 mtime 缓存,零子进程开销)
|
|
81
|
+
*/
|
|
82
|
+
export async function getActiveCodeBuddyIdeUid(flavor = 'cn') {
|
|
83
|
+
const det = detectCodeBuddyIde(flavor);
|
|
84
|
+
if (!det.installed) return null;
|
|
85
|
+
try {
|
|
86
|
+
const stat = fs.statSync(det.dbPath);
|
|
87
|
+
if (cachedActiveUid !== null && stat.mtimeMs === cachedActiveMtime) {
|
|
88
|
+
return cachedActiveUid;
|
|
89
|
+
}
|
|
90
|
+
const s = await readCodeBuddyIdeSession(flavor);
|
|
91
|
+
cachedActiveMtime = stat.mtimeMs;
|
|
92
|
+
cachedActiveUid = s?.account?.uid || null;
|
|
93
|
+
return cachedActiveUid;
|
|
94
|
+
} catch {
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** 同时探测两个档位(面板展示用,纯同步) */
|
|
100
|
+
export function detectCodeBuddyIdeAll() {
|
|
101
|
+
return { cn: detectCodeBuddyIde('cn'), intl: detectCodeBuddyIde('intl') };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// ── SQLite 读取(node:sqlite,Node 22.5+ 内置;Electron 37 自带 Node 22) ──
|
|
105
|
+
// 没装 sqlite 的环境(如 Node 20 的 CLI)给出明确错误,而不是抛一个看不懂的 MODULE_NOT_FOUND
|
|
106
|
+
async function openDb(dbPath, { readOnly }) {
|
|
107
|
+
let DatabaseSync;
|
|
108
|
+
try {
|
|
109
|
+
({ DatabaseSync } = await import('node:sqlite'));
|
|
110
|
+
} catch {
|
|
111
|
+
throw new Error('当前运行环境不支持 node:sqlite(需要 Node 22.5+ 或桌面版),无法读写 CodeBuddy IDE 存储');
|
|
112
|
+
}
|
|
113
|
+
return new DatabaseSync(dbPath, { readOnly });
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// ── Windows 密钥:Local State → DPAPI → 32B AES key ──
|
|
117
|
+
function dpapiUnprotect(cipherB64) {
|
|
118
|
+
return new Promise((resolve, reject) => {
|
|
119
|
+
// PowerShell 5 的 System.Security.Cryptography.ProtectedData 就是 DPAPI(CurrentUser 范围)
|
|
120
|
+
const script =
|
|
121
|
+
'Add-Type -AssemblyName System.Security; ' +
|
|
122
|
+
`$b=[Convert]::FromBase64String('${cipherB64}'); ` +
|
|
123
|
+
"$d=[System.Security.Cryptography.ProtectedData]::Unprotect($b,$null,'CurrentUser'); " +
|
|
124
|
+
'[Convert]::ToBase64String($d)';
|
|
125
|
+
execFile('powershell', ['-NoProfile', '-NonInteractive', '-Command', script],
|
|
126
|
+
{ encoding: 'utf8', windowsHide: true, timeout: 15000 },
|
|
127
|
+
(err, stdout) => {
|
|
128
|
+
if (err) return reject(new Error('DPAPI 解密失败:' + (err.message || err)));
|
|
129
|
+
const out = String(stdout || '').trim();
|
|
130
|
+
if (!out) return reject(new Error('DPAPI 返回空结果'));
|
|
131
|
+
try { resolve(Buffer.from(out, 'base64')); } catch (e) { reject(e); }
|
|
132
|
+
});
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** macOS Keychain 里该应用的 Safe Storage 密码(PBKDF2-SHA1 派生 AES-128 密钥用) */
|
|
137
|
+
function macSafeStoragePassword(flavor) {
|
|
138
|
+
const service = flavor === 'cn' ? 'CodeBuddy CN Safe Storage' : 'CodeBuddy Safe Storage';
|
|
139
|
+
return new Promise((resolve, reject) => {
|
|
140
|
+
execFile('security', ['find-generic-password', '-w', '-s', service],
|
|
141
|
+
{ encoding: 'utf8', timeout: 10000 }, (err, stdout) => {
|
|
142
|
+
if (err) return reject(new Error(`无法从 Keychain 读取「${service}」密码(请先打开该应用并登录一次)`));
|
|
143
|
+
const v = String(stdout || '').trim();
|
|
144
|
+
if (!v) return reject(new Error(`Keychain 中「${service}」为空`));
|
|
145
|
+
resolve(v);
|
|
146
|
+
});
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* 取本档位的解密密钥。Windows 返回 32 字节 AES-256;macOS 返回 PBKDF2 派生的 16 字节 AES-128。
|
|
152
|
+
* @returns {Promise<{alg:'aes-256-gcm'|'aes-128-cbc', key: Buffer}>}
|
|
153
|
+
*/
|
|
154
|
+
async function loadCryptoKey(flavor) {
|
|
155
|
+
if (process.platform === 'win32') {
|
|
156
|
+
const localStatePath = path.join(codebuddyIdeDataDir(flavor), 'Local State');
|
|
157
|
+
let json;
|
|
158
|
+
try { json = JSON.parse(fs.readFileSync(localStatePath, 'utf8')); }
|
|
159
|
+
catch { throw new Error(`读取 Local State 失败(${localStatePath})——请先打开 CodeBuddy 客户端并登录一次`); }
|
|
160
|
+
const b64 = json?.os_crypt?.encrypted_key;
|
|
161
|
+
if (!b64) throw new Error('Local State 缺少 os_crypt.encrypted_key');
|
|
162
|
+
const raw = Buffer.from(b64, 'base64');
|
|
163
|
+
if (raw.subarray(0, 5).toString('latin1') !== 'DPAPI') throw new Error('encrypted_key 前缀不是 DPAPI');
|
|
164
|
+
const key = await dpapiUnprotect(raw.subarray(5).toString('base64'));
|
|
165
|
+
if (key.length !== 32) throw new Error(`DPAPI 解出的密钥长度是 ${key.length},期望 32(AES-256)`);
|
|
166
|
+
return { alg: 'aes-256-gcm', key };
|
|
167
|
+
}
|
|
168
|
+
if (process.platform === 'darwin') {
|
|
169
|
+
const pw = await macSafeStoragePassword(flavor);
|
|
170
|
+
const key = crypto.pbkdf2Sync(pw, Buffer.from('saltysalt'), 1003, 16, 'sha1');
|
|
171
|
+
return { alg: 'aes-128-cbc', key };
|
|
172
|
+
}
|
|
173
|
+
throw new Error('CodeBuddy IDE 凭据读取目前只支持 Windows / macOS');
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** 解密 v10 密文 → 明文 */
|
|
177
|
+
function decryptSecretPayload(buf, { alg, key }) {
|
|
178
|
+
const prefix = buf.subarray(0, 3).toString('latin1');
|
|
179
|
+
if (prefix !== 'v10') throw new Error(`密文前缀不是 v10(实际 "${prefix}")`);
|
|
180
|
+
if (alg === 'aes-256-gcm') {
|
|
181
|
+
const d = crypto.createDecipheriv('aes-256-gcm', key, buf.subarray(3, 15));
|
|
182
|
+
d.setAuthTag(buf.subarray(buf.length - 16));
|
|
183
|
+
return Buffer.concat([d.update(buf.subarray(15, buf.length - 16)), d.final()]);
|
|
184
|
+
}
|
|
185
|
+
const d = crypto.createDecipheriv('aes-128-cbc', key, Buffer.alloc(16, 0x20)); // CBC IV 为 16 个空格
|
|
186
|
+
return Buffer.concat([d.update(buf.subarray(3)), d.final()]);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** 明文 → v10 密文(每次随机 nonce,与 Chromium 行为一致) */
|
|
190
|
+
function encryptSecretPayload(plain, { alg, key }) {
|
|
191
|
+
if (alg === 'aes-256-gcm') {
|
|
192
|
+
const iv = crypto.randomBytes(12);
|
|
193
|
+
const c = crypto.createCipheriv('aes-256-gcm', key, iv);
|
|
194
|
+
const ct = Buffer.concat([c.update(plain), c.final()]);
|
|
195
|
+
return Buffer.concat([Buffer.from('v10'), iv, ct, c.getAuthTag()]);
|
|
196
|
+
}
|
|
197
|
+
const c = crypto.createCipheriv('aes-128-cbc', key, Buffer.alloc(16, 0x20));
|
|
198
|
+
return Buffer.concat([Buffer.from('v10'), c.update(plain), c.final()]);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function secretRowKey(flavor) {
|
|
202
|
+
return `secret://{"extensionId":"${SECRET_EXTENSION_ID}","key":"${CODEBUDDY_IDE_FLAVORS[flavor].secretKey}"}`;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** 把 ItemTable 的 value(string 或 Buffer)解析成密文字节 */
|
|
206
|
+
function parseBufferValue(value) {
|
|
207
|
+
const text = typeof value === 'string' ? value : Buffer.from(value).toString('utf8');
|
|
208
|
+
const parsed = JSON.parse(text);
|
|
209
|
+
if (parsed?.type !== 'Buffer' || !Array.isArray(parsed.data)) throw new Error('secret 值不是 Buffer 结构');
|
|
210
|
+
return { bytes: Buffer.from(parsed.data), raw: parsed };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* 读取 CodeBuddy IDE 当前登录的会话(解密后的完整 JSON)。
|
|
215
|
+
* @returns {Promise<null | { flavor, session, accessToken, refreshToken, account, auth }>}
|
|
216
|
+
*/
|
|
217
|
+
export async function readCodeBuddyIdeSession(flavor = 'cn') {
|
|
218
|
+
const det = detectCodeBuddyIde(flavor);
|
|
219
|
+
if (!det.installed) return null;
|
|
220
|
+
const keyInfo = await loadCryptoKey(flavor);
|
|
221
|
+
const db = await openDb(det.dbPath, { readOnly: true });
|
|
222
|
+
let row;
|
|
223
|
+
try {
|
|
224
|
+
row = db.prepare('SELECT value FROM ItemTable WHERE key = ?').get(secretRowKey(flavor));
|
|
225
|
+
} finally {
|
|
226
|
+
try { db.close(); } catch { /* ignore */ }
|
|
227
|
+
}
|
|
228
|
+
if (!row) return null;
|
|
229
|
+
const { bytes } = parseBufferValue(row.value);
|
|
230
|
+
const plain = decryptSecretPayload(bytes, keyInfo).toString('utf8');
|
|
231
|
+
let session;
|
|
232
|
+
try { session = JSON.parse(plain); } catch { throw new Error('解密成功但内容不是 JSON(存储格式可能已变)'); }
|
|
233
|
+
const auth = session.auth || {};
|
|
234
|
+
const account = session.account || {};
|
|
235
|
+
return {
|
|
236
|
+
flavor,
|
|
237
|
+
session,
|
|
238
|
+
accessToken: auth.accessToken || session.token || null,
|
|
239
|
+
refreshToken: auth.refreshToken || session.refreshToken || null,
|
|
240
|
+
account,
|
|
241
|
+
auth,
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* 把一份会话写回 CodeBuddy IDE(切换账号)。
|
|
247
|
+
* 写前强制备份 state.vscdb → state.vscdb.bak-<时间戳>。
|
|
248
|
+
* @returns {Promise<{ dbPath, backup, uid }>}
|
|
249
|
+
*/
|
|
250
|
+
export async function writeCodeBuddyIdeSession(flavor, session) {
|
|
251
|
+
if (!session || typeof session !== 'object') throw new Error('会话内容为空');
|
|
252
|
+
const det = detectCodeBuddyIde(flavor);
|
|
253
|
+
if (!det.installed) throw new Error(`未找到 ${CODEBUDDY_IDE_FLAVORS[flavor].label} 的存储(${det.dbPath})`);
|
|
254
|
+
const keyInfo = await loadCryptoKey(flavor);
|
|
255
|
+
const plain = Buffer.from(JSON.stringify(session), 'utf8');
|
|
256
|
+
const cipher = encryptSecretPayload(plain, keyInfo);
|
|
257
|
+
|
|
258
|
+
// 备份:写坏了能立刻还原,这是改用户主工作环境的最低保障
|
|
259
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
260
|
+
const backup = `${det.dbPath}.bak-${stamp}`;
|
|
261
|
+
fs.copyFileSync(det.dbPath, backup);
|
|
262
|
+
|
|
263
|
+
const db = await openDb(det.dbPath, { readOnly: false });
|
|
264
|
+
try {
|
|
265
|
+
// upsert 而非裸 UPDATE:IDE 装了但从没登录时 secret 行不存在,裸 UPDATE 影响 0 行
|
|
266
|
+
// 却不报错 → 切号返回 ok 但用户重启 IDE 后什么都没变(「硬写后假成功」同款问题)
|
|
267
|
+
const changes = db.prepare(
|
|
268
|
+
`INSERT INTO ItemTable (key, value) VALUES (?, ?)
|
|
269
|
+
ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
|
|
270
|
+
).run(secretRowKey(flavor), JSON.stringify({ type: 'Buffer', data: Array.from(cipher) }));
|
|
271
|
+
if (!Number(changes.changes)) throw new Error('写入 CodeBuddy IDE 存储失败(0 行受影响)');
|
|
272
|
+
} finally {
|
|
273
|
+
try { db.close(); } catch { /* ignore */ }
|
|
274
|
+
}
|
|
275
|
+
return { dbPath: det.dbPath, backup, uid: session.account?.uid || null };
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* 构造注入到 CodeBuddy IDE 的会话 JSON(与 workbuddy-switch 的 build_session_json 规范一致)。
|
|
280
|
+
* 任何 WorkBuddy 系账号(只要有 token、refreshToken 或会话数据)都可以合成为合法的 IDE 会话。
|
|
281
|
+
*/
|
|
282
|
+
export function buildCodeBuddyIdeSession(account, flavor = 'cn') {
|
|
283
|
+
const isIntl = account.provider === 'workbuddy-intl' || flavor === 'intl';
|
|
284
|
+
const domain = account.meta?.domain || (isIntl ? 'www.codebuddy.ai' : 'www.codebuddy.cn');
|
|
285
|
+
const id = isIntl ? 'Tencent-Cloud.genie-ide' : 'Tencent-Cloud.genie-ide-cn';
|
|
286
|
+
const uid = String(account.uid || '');
|
|
287
|
+
const nickname = account.name || account.meta?.phone || 'User';
|
|
288
|
+
const phone = account.meta?.phone ? String(account.meta.phone) : '';
|
|
289
|
+
const phoneMasked = phone ? phone.slice(0, 3) + '****' + phone.slice(-4) : '';
|
|
290
|
+
const accessToken = String(account.token || '');
|
|
291
|
+
const refreshToken = String(account.refreshToken || '');
|
|
292
|
+
const expiresAt = account.expiresAt ? new Date(account.expiresAt).getTime() : Date.now() + 30 * 86400e3;
|
|
293
|
+
const now = Date.now();
|
|
294
|
+
|
|
295
|
+
const origAccount = account.meta?.session?.account || {};
|
|
296
|
+
const accountObj = {
|
|
297
|
+
uid,
|
|
298
|
+
nickname,
|
|
299
|
+
uin: origAccount.uin || '',
|
|
300
|
+
type: origAccount.type || 'personal',
|
|
301
|
+
lastLogin: true,
|
|
302
|
+
isCreator: false,
|
|
303
|
+
isAdmin: false,
|
|
304
|
+
pluginEnabled: true,
|
|
305
|
+
deployStatus: { statusCode: 0, statusMsg: '', detailMsg: '' },
|
|
306
|
+
accountType: '',
|
|
307
|
+
sso: { domain: '', domainModifiedTimes: 0 },
|
|
308
|
+
idp: '',
|
|
309
|
+
areaInfoComplete: false,
|
|
310
|
+
oneidAccountId: '',
|
|
311
|
+
isCurrentOneIdEnterprise: false,
|
|
312
|
+
isCurrentOneIdPersonal: false,
|
|
313
|
+
isFirstLogin: false,
|
|
314
|
+
phoneNumber: origAccount.phoneNumber || phoneMasked,
|
|
315
|
+
wechatOpenId: origAccount.wechatOpenId || '',
|
|
316
|
+
mpOpenId: origAccount.mpOpenId || '',
|
|
317
|
+
logOutEnable: false,
|
|
318
|
+
id: uid,
|
|
319
|
+
label: nickname,
|
|
320
|
+
};
|
|
321
|
+
|
|
322
|
+
const authObj = {
|
|
323
|
+
accessToken,
|
|
324
|
+
refreshToken,
|
|
325
|
+
tokenType: 'Bearer',
|
|
326
|
+
sessionState: account.meta?.session?.auth?.sessionState || '',
|
|
327
|
+
scope: 'acr offline_access profile basic roles email web-origins',
|
|
328
|
+
domain,
|
|
329
|
+
lastRefreshTime: now,
|
|
330
|
+
expiresAt,
|
|
331
|
+
expiresIn: Math.round((expiresAt - now) / 1000),
|
|
332
|
+
refreshExpiresIn: 5183999,
|
|
333
|
+
refreshExpiresAt: expiresAt + 30 * 86400e3,
|
|
334
|
+
};
|
|
335
|
+
|
|
336
|
+
return {
|
|
337
|
+
id,
|
|
338
|
+
token: accessToken,
|
|
339
|
+
refreshToken,
|
|
340
|
+
expiresAt,
|
|
341
|
+
domain,
|
|
342
|
+
accessToken: `${uid}+${accessToken}`,
|
|
343
|
+
converted: true,
|
|
344
|
+
account: accountObj,
|
|
345
|
+
auth: authObj,
|
|
346
|
+
accounts: [accountObj],
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* 读到的会话 → CreditDaddy 账号记录(不直接落库,交给调用方的 addRecord)。
|
|
352
|
+
* provider 由 token 的 iss 决定(workbuddy / workbuddy-intl),与 WorkBuddy 完全同源。
|
|
353
|
+
*/
|
|
354
|
+
export function codebuddySessionToAccount(flavor, read, inspectToken) {
|
|
355
|
+
const info = inspectToken(read.accessToken || '');
|
|
356
|
+
if (!info.provider) return null;
|
|
357
|
+
const acc = read.account || {};
|
|
358
|
+
const auth = read.auth || {};
|
|
359
|
+
const iso = (ms) => (Number.isFinite(ms) ? new Date(ms).toISOString() : null);
|
|
360
|
+
const rawPhone = typeof acc.phoneNumber === 'string' ? acc.phoneNumber.trim() : '';
|
|
361
|
+
const phone = (!rawPhone || rawPhone.includes('*')) ? (info.phone || rawPhone || null) : rawPhone;
|
|
362
|
+
return {
|
|
363
|
+
provider: info.provider,
|
|
364
|
+
token: read.accessToken,
|
|
365
|
+
refreshToken: read.refreshToken || null,
|
|
366
|
+
expiresAt: iso(auth.expiresAt) || info.expiresAt,
|
|
367
|
+
uid: acc.uid || info.uid,
|
|
368
|
+
name: acc.nickname || acc.name || acc.label || info.name || null,
|
|
369
|
+
email: acc.email || info.email || null,
|
|
370
|
+
source: 'codebuddy-ide',
|
|
371
|
+
meta: {
|
|
372
|
+
domain: auth.domain || info.host,
|
|
373
|
+
phone,
|
|
374
|
+
refreshExpiresAt: iso(auth.refreshExpiresAt),
|
|
375
|
+
// 记录来源档位,切换时据此写回正确的库
|
|
376
|
+
codebuddyIdeFlavor: flavor,
|
|
377
|
+
// 整份会话留着,切换时原样(重新加密)写回
|
|
378
|
+
cbIdeSession: read.session,
|
|
379
|
+
},
|
|
380
|
+
};
|
|
381
|
+
}
|