creditdaddy 1.7.1 → 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.
Files changed (73) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +445 -440
  3. package/build.json +3 -3
  4. package/package.json +34 -34
  5. package/src/accounts.js +15 -0
  6. package/src/assets/donate-alipay.svg +1 -1
  7. package/src/assets/donate-ifdian.svg +1 -1
  8. package/src/assets/donate-wechat.svg +1 -1
  9. package/src/assets/providers/catpaw.png +0 -0
  10. package/src/assets/providers/codebuddy-ide.png +0 -0
  11. package/src/assets/providers/dumate.png +0 -0
  12. package/src/assets/providers/loomy.png +0 -0
  13. package/src/assets/providers/meoo.png +0 -0
  14. package/src/assets/providers/mirasim.png +0 -0
  15. package/src/authDevice.js +3 -1
  16. package/src/bgdaemon.js +341 -341
  17. package/src/buildInfo.js +65 -32
  18. package/src/catpawClient.js +103 -103
  19. package/src/catpawLocal.js +236 -236
  20. package/src/checkin.js +11 -2
  21. package/src/codebuddyIdeLocal.js +381 -381
  22. package/src/constants.js +121 -116
  23. package/src/cookieSites.js +340 -301
  24. package/src/daemon.js +2682 -2415
  25. package/src/doubaoClient.js +167 -167
  26. package/src/dumateClient.js +517 -0
  27. package/src/dumateLocal.js +298 -0
  28. package/src/dumateQr.js +337 -0
  29. package/src/externalQuota.js +577 -574
  30. package/src/formatDuration.js +17 -17
  31. package/src/i18n/en.json +2156 -1980
  32. package/src/i18n/ja.json +2156 -1980
  33. package/src/i18n/ko.json +2156 -1980
  34. package/src/i18n/zh-TW.json +2156 -1980
  35. package/src/i18n.js +47 -47
  36. package/src/lingxiClient.js +373 -332
  37. package/src/localDetect.js +147 -147
  38. package/src/longcatClient.js +260 -260
  39. package/src/loomyAuth.js +230 -230
  40. package/src/loomyClient.js +366 -366
  41. package/src/loomyLocal.js +206 -206
  42. package/src/meooAuth.js +246 -0
  43. package/src/meooClient.js +250 -0
  44. package/src/minimaxClient.js +86 -28
  45. package/src/minimaxGateway.js +520 -520
  46. package/src/minimaxLocal.js +344 -322
  47. package/src/mirasimClient.js +211 -211
  48. package/src/mirasimLocal.js +392 -392
  49. package/src/modelscopeClient.js +275 -275
  50. package/src/panel.html +5964 -5528
  51. package/src/prodIcons.json +7 -5
  52. package/src/providers.js +52 -4
  53. package/src/qoderApp.js +578 -578
  54. package/src/qoderClient.js +266 -266
  55. package/src/qoderUmid.js +199 -199
  56. package/src/quotaRefresh.js +119 -119
  57. package/src/refreshGuard.js +75 -75
  58. package/src/riverClient.js +372 -329
  59. package/src/store.js +3 -1
  60. package/src/tenrouterAccounts.js +18 -3
  61. package/src/traeAuth.js +601 -530
  62. package/src/traeClient.js +356 -337
  63. package/src/traeGateway.js +875 -812
  64. package/src/traeLocal.js +463 -371
  65. package/src/transfer.js +24 -1
  66. package/src/usageSync.js +535 -523
  67. package/src/winProc.js +134 -134
  68. package/src/workbuddyLocal.js +35 -4
  69. package/src/xiaomiMimoClient.js +206 -206
  70. package/src/zcodeAuth.js +131 -131
  71. package/src/zcodeGateway.js +850 -850
  72. package/src/zcodeLocal.js +340 -340
  73. package/src/zcrypto.js +160 -160
package/src/qoderApp.js CHANGED
@@ -1,578 +1,578 @@
1
- /**
2
- * 本机 Qoder 客户端(Qoder App,Electron)集成 — 全部在本机完成,不依赖第三方包。
3
- *
4
- * 1. 安装探测:国际版 Qoder / 国内版 Qoder CN 的程序目录、数据目录、版本号
5
- * 2. 设备风控身份:调用客户端自带的 umid/runtime-info 生成
6
- * Cosy-MachineToken / Cosy-MachineCode / Cosy-MachineType。
7
- * 国际版服务端只对带风控身份的请求下发「每天领 100 Credits」活动(实测)。
8
- * 3. 登录凭据读取:解密客户端数据目录下的 auth.v1.dat(Electron safeStorage)
9
- * Windows: "v10" + nonce(12) + AES-256-GCM(密文+tag),密钥 = DPAPI 解开 Local State 的 os_crypt.encrypted_key
10
- * macOS: "v10" + AES-128-CBC,密钥 = PBKDF2(钥匙串 "<App> Safe Storage", 'saltysalt', 1003)
11
- * Linux: "v10" + AES-128-CBC,密钥 = PBKDF2('peanuts', 'saltysalt', 1)(v11 需系统密钥环,不支持)
12
- *
13
- * 协议细节来自本机 Qoder App 0.2.x 的客户端代码(campaignMainService / nativeRiskIdentityMainService)。
14
- */
15
-
16
- import fs from 'node:fs';
17
- import os from 'node:os';
18
- import path from 'node:path';
19
- import crypto from 'node:crypto';
20
- import { spawn, execFile, execFileSync } from 'node:child_process';
21
- import { dataDir } from './store.js';
22
- import { anyProcRunning, procRunningCached } from './winProc.js';
23
- import { installedUmid, CLI_RISK_ENV } from './qoderUmid.js';
24
-
25
- const RISK_TTL_MS = 50 * 60 * 1000; // 客户端每 60±5 分钟刷新一次,这里保守取 50 分钟
26
- const RISK_TIMEOUT_MS = 25_000; // 与客户端一致
27
- const DEFAULT_CLIENT_VERSION = '0.2.5';
28
-
29
- const VARIANTS = [
30
- { provider: 'qoder', label: 'Qoder 国际版', installName: 'Qoder', appId: 'com.qoder.app', riskEnv: 3 },
31
- { provider: 'qoder-cn', label: 'Qoder 国内版', installName: 'Qoder CN', appId: 'com.qodercn.app', riskEnv: 0 },
32
- ];
33
-
34
- const exists = (p) => { try { return fs.existsSync(p); } catch { return false; } };
35
-
36
- const versionParts = (s) => s.split('.').map((n) => Number(n) || 0);
37
- function compareVersionDesc(a, b) {
38
- const x = versionParts(a), y = versionParts(b);
39
- for (let i = 0; i < Math.max(x.length, y.length); i++) {
40
- if ((x[i] || 0) !== (y[i] || 0)) return (y[i] || 0) - (x[i] || 0);
41
- }
42
- return 0;
43
- }
44
-
45
- /**
46
- * 一个安装目录下的 resources 候选:0.3+ 的启动器把实际运行的版本放在
47
- * .qoder-versions\<ver>\resources(按版本从新到旧),顶层 resources 可能只是首装时的旧版残留。
48
- */
49
- function resourceDirsIn(installDir) {
50
- const root = path.join(installDir, '.qoder-versions');
51
- let versions = [];
52
- try {
53
- versions = fs.readdirSync(root, { withFileTypes: true })
54
- .filter((e) => e.isDirectory() && /^\d+(\.\d+)*$/.test(e.name))
55
- .map((e) => e.name)
56
- .sort(compareVersionDesc);
57
- } catch {}
58
- return [...versions.map((ver) => path.join(root, ver, 'resources')), path.join(installDir, 'resources')];
59
- }
60
-
61
- /**
62
- * 卸载注册表里登记的安装目录(自定义安装路径)。DisplayName 形如「Qoder 0.4.1」/「Qoder CN 0.4.1」,
63
- * 不匹配「Qoder IDE」(IDE 不带 runtime-info)。走 PowerShell 以正确读出中文路径;结果缓存 5 分钟。
64
- */
65
- let registryCache = { at: 0, entries: null };
66
- function registryInstallDirs(v) {
67
- if (process.platform !== 'win32') return [];
68
- if (!registryCache.entries || Date.now() - registryCache.at > 5 * 60_000) {
69
- let entries = [];
70
- try {
71
- const script = "$ProgressPreference='SilentlyContinue';[Console]::OutputEncoding=[Text.Encoding]::UTF8;"
72
- + "Get-ItemProperty 'HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKLM:\\Software\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*' -ErrorAction SilentlyContinue"
73
- + " | Where-Object { $_.DisplayName -like 'Qoder*' }"
74
- + ' | Select-Object DisplayName,InstallLocation,UninstallString,DisplayIcon | ConvertTo-Json -Compress';
75
- const out = execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')],
76
- { encoding: 'utf8', windowsHide: true, timeout: 10_000, stdio: ['ignore', 'pipe', 'ignore'] }).trim();
77
- if (out) entries = [].concat(JSON.parse(out));
78
- } catch {}
79
- registryCache = { at: Date.now(), entries };
80
- }
81
- const nameRe = new RegExp(`^${v.installName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(\\s+v?\\d[\\d.]*)?$`, 'i');
82
- const exeDir = (s) => {
83
- const m = String(s || '').match(/^\s*"([^"]+)"|^\s*([^,]+?\.exe)/i);
84
- return m ? path.dirname(m[1] || m[2]) : null;
85
- };
86
- const dirs = [];
87
- for (const e of registryCache.entries) {
88
- if (!nameRe.test(String(e?.DisplayName || '').trim())) continue;
89
- const dir = (e.InstallLocation && String(e.InstallLocation).trim()) || exeDir(e.UninstallString) || exeDir(e.DisplayIcon);
90
- if (dir) dirs.push(dir.replace(/[\\/]+$/, ''));
91
- }
92
- return dirs;
93
- }
94
-
95
- function candidateResourceDirs(v, { registry = false } = {}) {
96
- const home = os.homedir();
97
- if (process.platform === 'win32') {
98
- const local = process.env.LOCALAPPDATA || path.join(home, 'AppData', 'Local');
99
- const installDirs = [
100
- path.join(local, 'Programs', v.installName),
101
- path.join(process.env.ProgramFiles || 'C:\\Program Files', v.installName),
102
- path.join(process.env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)', v.installName),
103
- ...(registry ? registryInstallDirs(v) : []),
104
- ];
105
- const seen = new Set();
106
- const unique = installDirs.filter((d) => {
107
- const k = path.resolve(d).toLowerCase();
108
- if (seen.has(k)) return false;
109
- seen.add(k);
110
- return true;
111
- });
112
- return [
113
- ...unique.flatMap(resourceDirsIn),
114
- // AppX 风格(微软商店版 / MSIX):Qoder_*.msix 通常在 Start Menu 快捷方式指向的位置
115
- path.join(local, 'Microsoft', 'WindowsApps', v.installName),
116
- // Squirrel 更新目录:Electron 应用的临时升级包
117
- path.join(local, 'electron', 'updates', v.installName),
118
- ];
119
- }
120
- if (process.platform === 'darwin') {
121
- return [
122
- `/Applications/${v.installName}.app/Contents/Resources`,
123
- path.join(home, 'Applications', `${v.installName}.app`, 'Contents', 'Resources'),
124
- // 可能是 qodercn.app 或 qoder.app
125
- `/Applications/Qoder.app/Contents/Resources`,
126
- `/Applications/Qoder\\ CN.app/Contents/Resources`,
127
- ];
128
- }
129
- const slug = v.installName.toLowerCase().replace(/\s+/g, '-');
130
- return [`/opt/${v.installName}/resources`, `/opt/${slug}/resources`, `/usr/lib/${slug}/resources`, '/snap/qoder/current/resources'];
131
- }
132
-
133
- function userDataDir(v) {
134
- const home = os.homedir();
135
- const name = `${v.appId}.stable`;
136
- if (process.platform === 'win32') {
137
- return path.join(process.env.APPDATA || path.join(home, 'AppData', 'Roaming'), name);
138
- }
139
- if (process.platform === 'darwin') return path.join(home, 'Library', 'Application Support', name);
140
- return path.join(process.env.XDG_CONFIG_HOME || path.join(home, '.config'), name);
141
- }
142
-
143
- function readVersion(resourcesDir) {
144
- try {
145
- const m = JSON.parse(fs.readFileSync(path.join(resourcesDir, 'build-manifest.json'), 'utf8'));
146
- if (typeof m.productVersion === 'string') return m.productVersion;
147
- } catch {}
148
- return null;
149
- }
150
-
151
- const RUNTIME_INFO_EXE = process.platform === 'win32' ? 'runtime-info.exe' : 'runtime-info';
152
- const runtimeInfoIn = (resources) => (exists(path.join(resources, 'umid', RUNTIME_INFO_EXE)) ? path.join(resources, 'umid', RUNTIME_INFO_EXE) : null);
153
- const isDir = (p) => { try { return fs.statSync(p).isDirectory(); } catch { return false; } };
154
-
155
- /** 在候选里选 resources:优先带 runtime-info 的(风控身份靠它),否则第一个存在的 */
156
- function pickResources(dirs) {
157
- const existing = dirs.filter(isDir);
158
- return existing.find((d) => runtimeInfoIn(d)) || existing[0] || null;
159
- }
160
-
161
- /** 探测本机已安装的 Qoder 客户端(国际版 / 国内版) */
162
- export function detectQoderApps() {
163
- return VARIANTS.map((v) => {
164
- let resources = pickResources(candidateResourceDirs(v));
165
- // 默认位置没找到可用的 runtime-info → 再查卸载注册表里的实际安装目录(自定义路径)
166
- if (process.platform === 'win32' && !(resources && runtimeInfoIn(resources))) {
167
- resources = pickResources(candidateResourceDirs(v, { registry: true })) || resources;
168
- }
169
- const runtimeInfo = resources ? runtimeInfoIn(resources) : null;
170
- const data = userDataDir(v);
171
- return {
172
- provider: v.provider,
173
- label: v.label,
174
- installed: Boolean(resources),
175
- resourcesDir: resources,
176
- version: resources ? readVersion(resources) : null,
177
- runtimeInfo,
178
- dataDir: data,
179
- dataExists: exists(data),
180
- signedIn: exists(path.join(data, 'auth.v1.dat')),
181
- };
182
- });
183
- }
184
-
185
- // ─── 设备风控身份 ───
186
-
187
- /** 与客户端一致的 Cosy-MachineOS 格式:x86_64_win32 / aarch64_darwin … */
188
- export function machineOs() {
189
- const a = process.arch === 'arm64' ? 'aarch64' : process.arch === 'x64' ? 'x86_64' : process.arch;
190
- return `${a}_${process.platform}`;
191
- }
192
-
193
- /** 与客户端一致的主机名清洗:可打印 ASCII,超长截断并附短哈希 */
194
- export function machineHostname(raw = os.hostname()) {
195
- const e = String(raw || '').trim();
196
- if (!e) return undefined;
197
- const clip = (t) => {
198
- if (t.length <= 96) return t;
199
- const h = crypto.createHash('sha256').update(t, 'utf8').digest('hex').slice(0, 8);
200
- const head = t.slice(0, 96 - 8 - 1).replace(/[-\s]+$/u, '');
201
- return head ? `${head}-${h}` : `unknown-${h}`;
202
- };
203
- if (/^[\x21-\x7e](?:[\x20-\x7e]*[\x21-\x7e])?$/u.test(e)) return clip(e);
204
- const h = crypto.createHash('sha256').update(e, 'utf8').digest('hex').slice(0, 8);
205
- const n = e.replace(/[^\x21-\x7e]+/gu, '-').replace(/-{2,}/gu, '-').replace(/^-+|-+$/gu, '');
206
- return clip(n ? `${n}-${h}` : `unknown-${h}`);
207
- }
208
-
209
- const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
210
-
211
- /** 机器 ID:优先复用客户端的 auth.machine-id,否则在 CreditDaddy 数据目录持久化一个 */
212
- export function machineId(provider) {
213
- const v = VARIANTS.find((x) => x.provider === provider) || VARIANTS[0];
214
- for (const file of [path.join(userDataDir(v), 'auth.machine-id'), path.join(dataDir(), 'machine-id')]) {
215
- try {
216
- const id = fs.readFileSync(file, 'utf8').trim();
217
- if (UUID_RE.test(id)) return id;
218
- } catch {}
219
- }
220
- const id = crypto.randomUUID();
221
- try {
222
- fs.mkdirSync(dataDir(), { recursive: true, mode: 0o700 });
223
- fs.writeFileSync(path.join(dataDir(), 'machine-id'), id, { mode: 0o600 });
224
- } catch {}
225
- return id;
226
- }
227
-
228
- /** 客户端版本号(用于 Cosy-Version) */
229
- export function clientVersion(provider) {
230
- const apps = detectQoderApps();
231
- const app = apps.find((a) => a.provider === provider && a.version) || apps.find((a) => a.version);
232
- return app?.version || DEFAULT_CLIENT_VERSION;
233
- }
234
-
235
- function runRuntimeInfo(exe, env, account) {
236
- return new Promise((resolve, reject) => {
237
- const withStdin = process.platform === 'darwin' || process.platform === 'win32';
238
- const child = spawn(exe, withStdin ? [String(env), '--account-stdin'] : [String(env)], {
239
- stdio: [withStdin ? 'pipe' : 'ignore', 'pipe', 'pipe'],
240
- windowsHide: true,
241
- });
242
- let out = '';
243
- let settled = false;
244
- const done = (err, val) => {
245
- if (settled) return;
246
- settled = true;
247
- clearTimeout(timer);
248
- if (child.exitCode === null) child.kill();
249
- err ? reject(err) : resolve(val);
250
- };
251
- const timer = setTimeout(() => done(new Error('runtime-info 超时')), RISK_TIMEOUT_MS);
252
- const tryParse = () => {
253
- const nl = out.indexOf('\n');
254
- if (nl < 0) return false;
255
- try {
256
- const j = JSON.parse(out.slice(0, nl));
257
- const pick = (k) => {
258
- const s = typeof j[k] === 'string' ? j[k].trim() : '';
259
- if (!s || s.length > 4096) throw new Error(`runtime-info 输出缺少 ${k}`);
260
- return s;
261
- };
262
- done(null, { machineToken: pick('machineToken'), machineCode: pick('machineCode'), machineType: pick('machineType') });
263
- } catch (e) { done(e); }
264
- return true;
265
- };
266
- child.stdout.on('data', (d) => {
267
- out += d.toString('utf8');
268
- if (out.length > 1024 * 1024) return done(new Error('runtime-info 输出过大'));
269
- tryParse();
270
- });
271
- child.stderr.on('data', () => {});
272
- child.once('error', (e) => done(new Error(`runtime-info 启动失败:${e.message}`)));
273
- child.once('close', (code) => {
274
- if (!tryParse()) done(new Error(`runtime-info 退出码 ${code}`));
275
- });
276
- if (withStdin) {
277
- child.stdin.on('error', () => {});
278
- child.stdin.end(JSON.stringify({ account }) + '\n');
279
- }
280
- });
281
- }
282
-
283
- const riskCache = new Map(); // `${provider}:${uid}` → { value, at } | { promise }
284
-
285
- /**
286
- * 风控身份来源:优先本机 Qoder 客户端自带的 runtime-info(国际版 env=3 / 国内版 env=0,缺失时用另一版本的),
287
- * 其次是从官方 qodercli 提取的设备身份组件(Linux / fnOS,见 qoderUmid.js,env 与 qodercli 一致)。
288
- */
289
- function riskRunner(provider) {
290
- const apps = detectQoderApps().filter((a) => a.runtimeInfo);
291
- const app = apps.find((a) => a.provider === provider) || apps[0];
292
- if (app) return { exe: app.runtimeInfo, env: (VARIANTS.find((v) => v.provider === provider) || VARIANTS[0]).riskEnv, source: 'app' };
293
- const cli = installedUmid() || bundledCliUmid(provider);
294
- if (cli) return { exe: cli.path, env: CLI_RISK_ENV[provider] ?? CLI_RISK_ENV.qoder, source: 'cli' };
295
- const localBin = qodercliRuntimeInfo(provider);
296
- if (localBin) return { exe: localBin, env: CLI_RISK_ENV[provider] ?? CLI_RISK_ENV.qoder, source: 'cli' };
297
- return null;
298
- }
299
-
300
- /** Windows:客户端自带的 qodercli 会把设备身份组件解压到 ~\.qoder\.bin\umid-win32-<arch>-*\(国内版 ~\.qoder-cn) */
301
- function bundledCliUmid(provider) {
302
- if (process.platform !== 'win32') return null;
303
- const homes = provider === 'qoder-cn' ? ['.qoder-cn', '.qoder'] : ['.qoder', '.qoder-cn'];
304
- for (const h of homes) {
305
- const bin = path.join(os.homedir(), h, '.bin');
306
- let dirs = [];
307
- try { dirs = fs.readdirSync(bin).filter((n) => n.startsWith('umid-win32-')); } catch {}
308
- for (const d of dirs) {
309
- const exe = path.join(bin, d, RUNTIME_INFO_EXE);
310
- if (exists(exe)) return { path: exe };
311
- }
312
- }
313
- return null;
314
- }
315
-
316
- /** macOS:官方 qodercli(@qoder-ai/qodercli)把 runtime-info 设备身份组件解压到 ~\.qoder\.bin\runtime-info-darwin-<arch>-*(国内版 ~\.qoder-cn) */
317
- function qodercliRuntimeInfo(provider) {
318
- if (process.platform !== 'darwin') return null;
319
- const homes = provider === 'qoder-cn' ? ['.qoder-cn', '.qoder'] : ['.qoder', '.qoder-cn'];
320
- for (const h of homes) {
321
- const bin = path.join(os.homedir(), h, '.bin');
322
- let entries = [];
323
- try { entries = fs.readdirSync(bin, { withFileTypes: true }).filter((n) => n.name.startsWith(`runtime-info-darwin-${process.arch}`)); } catch {}
324
- if (!entries.length) continue;
325
- // 版本排序(1.2.10 > 1.2.9,字典序会反);目录形态时拼组件名,文件形态直接用;
326
- // 必须 exists 校验——升级残留的旧条目/坏条目不能静默选中
327
- const ver = (name) => name.split('-').slice(-1)[0].split('.').map((x) => Number(x) || 0);
328
- const cmp = (a, b) => { const va = ver(a), vb = ver(b); for (let i = 0; i < Math.max(va.length, vb.length); i++) { if ((va[i] || 0) !== (vb[i] || 0)) return (va[i] || 0) - (vb[i] || 0); } return 0; };
329
- for (const e of entries.sort((a, b) => cmp(b.name, a.name))) {
330
- const p = e.isDirectory() ? path.join(bin, e.name, RUNTIME_INFO_EXE) : path.join(bin, e.name);
331
- try { if (fs.statSync(p).isFile()) return p; } catch { /* 坏条目跳过,试下一个 */ }
332
- }
333
- }
334
- return null;
335
- }
336
-
337
- /** 获取某账号的设备风控身份;本机既没有 Qoder 客户端也没装设备身份组件时返回 null。 */
338
- export async function getRiskIdentity(provider, uid) {
339
- if (!uid) return null;
340
- const key = `${provider}:${uid}`;
341
- const hit = riskCache.get(key);
342
- if (hit?.value && Date.now() - hit.at < RISK_TTL_MS) return hit.value;
343
- if (hit?.promise) return hit.promise;
344
-
345
- const runner = riskRunner(provider);
346
- if (!runner) return null;
347
-
348
- const promise = runRuntimeInfo(runner.exe, runner.env, uid)
349
- .then((value) => { riskCache.set(key, { value, at: Date.now() }); return value; })
350
- .catch((e) => { riskCache.delete(key); throw e; });
351
- riskCache.set(key, { promise });
352
- return promise;
353
- }
354
-
355
- export function riskIdentityAvailable() {
356
- return Boolean(riskRunner('qoder'));
357
- }
358
-
359
- /** 风控身份来源:'app'(Qoder 客户端)/ 'cli'(qodercli 设备身份组件)/ null */
360
- export function riskIdentitySource() {
361
- return riskRunner('qoder')?.source || null;
362
- }
363
-
364
- // ─── Electron safeStorage 解密 ───
365
-
366
- function dpapiUnprotect(buf) {
367
- const script = 'Add-Type -AssemblyName System.Security;'
368
- + '$b=[Convert]::FromBase64String([Console]::In.ReadToEnd());'
369
- + "[Convert]::ToBase64String([System.Security.Cryptography.ProtectedData]::Unprotect($b,$null,'CurrentUser'))";
370
- // 使用 -EncodedCommand 传入 UTF-16LE Base64,避免命令行参数中包含敏感 API 关键字被杀毒软件误报
371
- const encoded = Buffer.from(script, 'utf16le').toString('base64');
372
- return new Promise((resolve, reject) => {
373
- const child = execFile('powershell.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded],
374
- { windowsHide: true, timeout: 20_000 }, (err, stdout) => {
375
- if (err) return reject(new Error('DPAPI 解密失败:' + err.message));
376
- resolve(Buffer.from(String(stdout).trim(), 'base64'));
377
- });
378
- child.stdin.end(buf.toString('base64'));
379
- });
380
- }
381
-
382
- function macKeychainPassword(service) {
383
- return new Promise((resolve) => {
384
- execFile('security', ['find-generic-password', '-w', '-s', service], { timeout: 20_000 },
385
- (err, stdout) => resolve(err ? null : String(stdout).trim()));
386
- });
387
- }
388
-
389
- const keyCache = new Map();
390
- let codecOverride = null; // 测试注入:替代 safeStorageCodec(DPAPI 依赖真实用户上下文,测试绕开)
391
- /** 测试钩子:注入编解码器(切换写入路径用),传 null 恢复真实实现。 */
392
- export function _setCodecForTests(codec) { codecOverride = codec; }
393
-
394
- /**
395
- * 某个 Electron userData 目录对应的 safeStorage 编解码器。
396
- * encrypt 用于把账号库里的登录快照写回客户端(切换账号),与 decrypt 同密钥同格式:
397
- * Windows = 'v10' + nonce(12) + AES-256-GCM 密文 + tag(16);mac/linux = 'v10' + AES-128-CBC。
398
- */
399
- export async function safeStorageCodec(userData, appNames) {
400
- if (keyCache.has(userData)) return keyCache.get(userData);
401
- let decrypt, encrypt;
402
- if (process.platform === 'win32') {
403
- const ls = JSON.parse(fs.readFileSync(path.join(userData, 'Local State'), 'utf8'));
404
- const enc = Buffer.from(ls?.os_crypt?.encrypted_key || '', 'base64');
405
- if (enc.subarray(0, 5).toString() !== 'DPAPI') throw new Error('Local State 中没有 DPAPI 密钥');
406
- const key = await dpapiUnprotect(enc.subarray(5));
407
- decrypt = (data) => {
408
- if (data.subarray(0, 3).toString() !== 'v10') throw new Error('未知的加密格式');
409
- const nonce = data.subarray(3, 15);
410
- const tag = data.subarray(data.length - 16);
411
- const d = crypto.createDecipheriv('aes-256-gcm', key, nonce);
412
- d.setAuthTag(tag);
413
- return Buffer.concat([d.update(data.subarray(15, data.length - 16)), d.final()]).toString('utf8');
414
- };
415
- encrypt = (text) => {
416
- const nonce = crypto.randomBytes(12);
417
- const c = crypto.createCipheriv('aes-256-gcm', key, nonce);
418
- const ct = Buffer.concat([c.update(text, 'utf8'), c.final()]);
419
- return Buffer.concat([Buffer.from('v10'), nonce, ct, c.getAuthTag()]);
420
- };
421
- } else {
422
- let password = 'peanuts', iterations = 1;
423
- if (process.platform === 'darwin') {
424
- for (const n of appNames) {
425
- password = await macKeychainPassword(`${n} Safe Storage`);
426
- if (password) break;
427
- }
428
- if (!password) throw new Error('无法从钥匙串读取 Qoder 的 Safe Storage 密钥');
429
- iterations = 1003;
430
- }
431
- const key = crypto.pbkdf2Sync(password, 'saltysalt', iterations, 16, 'sha1');
432
- const iv = Buffer.alloc(16, ' ');
433
- decrypt = (data) => {
434
- const ver = data.subarray(0, 3).toString();
435
- if (ver !== 'v10') throw new Error(ver === 'v11' ? '需要系统密钥环(v11),暂不支持' : '未知的加密格式');
436
- const d = crypto.createDecipheriv('aes-128-cbc', key, iv);
437
- return Buffer.concat([d.update(data.subarray(3)), d.final()]).toString('utf8');
438
- };
439
- encrypt = (text) => {
440
- const c = crypto.createCipheriv('aes-128-cbc', key, iv);
441
- return Buffer.concat([Buffer.from('v10'), c.update(text, 'utf8'), c.final()]);
442
- };
443
- }
444
- const codec = { decrypt, encrypt };
445
- keyCache.set(userData, codec);
446
- return codec;
447
- }
448
-
449
- /**
450
- * 读取本机 Qoder 客户端当前登录的账号(解密 auth.v1.dat)。
451
- * @returns {Promise<{accounts: Array, errors: Array}>} 每个账号含 provider/token/refreshToken/expiresAt/user
452
- */
453
- export async function readQoderAppAccounts() {
454
- const accounts = [];
455
- const errors = [];
456
- for (const app of detectQoderApps()) {
457
- const file = path.join(app.dataDir, 'auth.v1.dat');
458
- if (!exists(file)) continue;
459
- try {
460
- const { decrypt } = await safeStorageCodec(app.dataDir, ['Qoder App', app.label.includes('国内') ? 'Qoder CN' : 'Qoder']);
461
- const obj = JSON.parse(decrypt(fs.readFileSync(file)));
462
- if (typeof obj?.token !== 'string' || !obj.token) throw new Error('auth.v1.dat 中没有 token');
463
- accounts.push({
464
- provider: app.provider,
465
- source: `${app.label} 客户端`,
466
- file,
467
- authJson: obj,
468
- token: obj.token,
469
- refreshToken: typeof obj.refreshToken === 'string' ? obj.refreshToken : null,
470
- expiresAt: typeof obj.expiresAt === 'string' ? obj.expiresAt : null,
471
- user: {
472
- id: obj.user?.id || null,
473
- name: obj.user?.name || null,
474
- email: obj.user?.email || null,
475
- },
476
- });
477
- } catch (e) {
478
- errors.push({ provider: app.provider, file, error: e.message });
479
- }
480
- }
481
- return { accounts, errors };
482
- }
483
-
484
- // ─── 切换本机 Qoder 登录账号 ───
485
-
486
- const QODER_EXES = ['Qoder.exe', 'Qoder CN.exe'];
487
-
488
- /** Qoder IDE(国际版 / 国内版)是否在运行 */
489
- export function qoderRunning() {
490
- // 走 winProc:这里曾经用 latin1 解 tasklist,中文 Windows 上恒为 true
491
- return anyProcRunning(QODER_EXES);
492
- }
493
-
494
- /** 轮询口径(/api/status 用):读 winProc 全量快照,不 spawn;switchTo/terminate 仍走 qoderRunning()。 */
495
- export function qoderRunningCached() {
496
- return procRunningCached(QODER_EXES);
497
- }
498
-
499
- const nap = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
500
-
501
- /** 结束 Qoder 进程:先普通终止(给客户端落盘的机会),超时后 /F */
502
- export function terminateQoder({ timeoutMs = 8000 } = {}) {
503
- if (process.platform !== 'win32') return { closed: false, supported: false };
504
- if (!qoderRunning()) return { closed: false, running: false };
505
- for (const exe of QODER_EXES) {
506
- try { execFileSync('taskkill.exe', ['/IM', exe, '/T'], { windowsHide: true, stdio: 'ignore' }); } catch {}
507
- }
508
- let deadline = Date.now() + timeoutMs;
509
- while (Date.now() < deadline && qoderRunning()) nap(250);
510
- if (qoderRunning()) {
511
- for (const exe of QODER_EXES) {
512
- try { execFileSync('taskkill.exe', ['/IM', exe, '/T', '/F'], { windowsHide: true, stdio: 'ignore' }); } catch {}
513
- }
514
- deadline = Date.now() + 3000;
515
- while (Date.now() < deadline && qoderRunning()) nap(250);
516
- }
517
- return { closed: !qoderRunning(), running: qoderRunning() };
518
- }
519
-
520
- /**
521
- * 把本机 Qoder 客户端的登录换成目标账号(写回 auth.v1.dat)。
522
- * force:由调用方先 terminateQoder 再进来(运行中的 Qoder 退出时会把内存里的旧登录覆盖回文件)。
523
- *
524
- * ## ★ 过期快照必须拒绝写入(2026-11-07 用户实测)
525
- *
526
- * Qoder 设备流登录的 token 约 30 天且**没有续期通道**(上游对无签名的刷新调用一律
527
- * 403 "Request discarded",10router 同款结论),快照里的 expiresAt 一旦过了,客户端
528
- * 读到就是死凭据:启动时判定无效 → 删掉 auth.v1.dat → 登录页。此前把过期快照照写
529
- * 不误,用户看到的是「切换成功 → 重开客户端 → 被登出」的哑谜,还得手动重登。现在
530
- * 写入前拦下,把真实原因说清楚;临期(<24h)照常切换但带 warn 让面板提示。
531
- */
532
- export async function switchTo(account, { force = false } = {}) {
533
- const auth = account.meta?.qoderAuth;
534
- const file = account.meta?.qoderAuthFile;
535
- if (!auth || !file) {
536
- throw new Error(`账号「${account.name || account.id}」没有本机登录快照,无法切换:请在 Qoder 里登录该账号后到「添加账号 → 本机导入」导入一次`);
537
- }
538
- if (!fs.existsSync(file)) {
539
- // 本机当初导入时文件是在的,现在没了:绝大多数情况是客户端退出登录(登出/换号后它会删掉
540
- // auth.v1.dat),只有少数是卸载或换了数据目录。按发生率给指引,别让人以为软件坏了。
541
- const app = detectQoderApps().find((a) => a.provider === account.provider);
542
- const label = app?.label || (account.provider === 'qoder-cn' ? 'Qoder 国内版' : 'Qoder 国际版');
543
- const hint = app?.installed
544
- ? `请打开「${label}」客户端确认已登录该账号,然后到「添加账号 → 本机导入」重新导入一次`
545
- : `没检测到「${label}」客户端,请先安装并登录,然后到「添加账号 → 本机导入」导入`;
546
- throw new Error(`账号「${account.name || account.id}」的切换凭据已失效:${label}的登录文件不在了(${file})。${hint}`);
547
- }
548
- const expiresAtMs = Date.parse(auth.expiresAt || '');
549
- let nearExpiryWarn = null;
550
- if (Number.isFinite(expiresAtMs)) {
551
- if (expiresAtMs <= Date.now()) {
552
- const e = new Error(`账号「${account.name || account.id}」的登录快照已于 ${new Date(expiresAtMs).toLocaleString()} 过期,写进去只会让客户端被登出。Qoder 的设备登录 token 约 30 天且到期不可续期——请在 Qoder 客户端登录该账号后到「本机导入」重新导入,再切换。`);
553
- e.staleAuth = true;
554
- throw e;
555
- }
556
- if (expiresAtMs - Date.now() < 24 * 3600_000) {
557
- nearExpiryWarn = `该账号的登录快照将于 ${new Date(expiresAtMs).toLocaleString()} 过期,届时需重新登录导入`;
558
- }
559
- }
560
- if (!force && qoderRunning()) {
561
- const e = new Error('Qoder 正在运行。切换会改写 Qoder 的登录文件,运行中的 Qoder 退出时会把旧登录写回去——退出后重试,或选择「关闭并强制切换」。');
562
- e.qoderRunning = true;
563
- throw e;
564
- }
565
- const { encrypt, decrypt } = codecOverride || await safeStorageCodec(path.dirname(file), ['Qoder App', account.provider === 'qoder-cn' ? 'Qoder CN' : 'Qoder']);
566
- try {
567
- if (JSON.parse(decrypt(fs.readFileSync(file))).token === auth.token) {
568
- return { switched: false, alreadyActive: true };
569
- }
570
- } catch { /* 当前文件解不开就当作不同账号,继续写入 */ }
571
- const buf = encrypt(JSON.stringify(auth));
572
- const bak = file + '.creditdaddy.bak';
573
- try { fs.copyFileSync(file, bak); } catch { /* 备份失败不阻断,下面原子写仍会成功 */ }
574
- const tmp = file + '.tmp';
575
- fs.writeFileSync(tmp, buf, { mode: 0o600 });
576
- fs.renameSync(tmp, file);
577
- return { switched: true, alreadyActive: false, warn: nearExpiryWarn };
578
- }
1
+ /**
2
+ * 本机 Qoder 客户端(Qoder App,Electron)集成 — 全部在本机完成,不依赖第三方包。
3
+ *
4
+ * 1. 安装探测:国际版 Qoder / 国内版 Qoder CN 的程序目录、数据目录、版本号
5
+ * 2. 设备风控身份:调用客户端自带的 umid/runtime-info 生成
6
+ * Cosy-MachineToken / Cosy-MachineCode / Cosy-MachineType。
7
+ * 国际版服务端只对带风控身份的请求下发「每天领 100 Credits」活动(实测)。
8
+ * 3. 登录凭据读取:解密客户端数据目录下的 auth.v1.dat(Electron safeStorage)
9
+ * Windows: "v10" + nonce(12) + AES-256-GCM(密文+tag),密钥 = DPAPI 解开 Local State 的 os_crypt.encrypted_key
10
+ * macOS: "v10" + AES-128-CBC,密钥 = PBKDF2(钥匙串 "<App> Safe Storage", 'saltysalt', 1003)
11
+ * Linux: "v10" + AES-128-CBC,密钥 = PBKDF2('peanuts', 'saltysalt', 1)(v11 需系统密钥环,不支持)
12
+ *
13
+ * 协议细节来自本机 Qoder App 0.2.x 的客户端代码(campaignMainService / nativeRiskIdentityMainService)。
14
+ */
15
+
16
+ import fs from 'node:fs';
17
+ import os from 'node:os';
18
+ import path from 'node:path';
19
+ import crypto from 'node:crypto';
20
+ import { spawn, execFile, execFileSync } from 'node:child_process';
21
+ import { dataDir } from './store.js';
22
+ import { anyProcRunning, procRunningCached } from './winProc.js';
23
+ import { installedUmid, CLI_RISK_ENV } from './qoderUmid.js';
24
+
25
+ const RISK_TTL_MS = 50 * 60 * 1000; // 客户端每 60±5 分钟刷新一次,这里保守取 50 分钟
26
+ const RISK_TIMEOUT_MS = 25_000; // 与客户端一致
27
+ const DEFAULT_CLIENT_VERSION = '0.2.5';
28
+
29
+ const VARIANTS = [
30
+ { provider: 'qoder', label: 'Qoder 国际版', installName: 'Qoder', appId: 'com.qoder.app', riskEnv: 3 },
31
+ { provider: 'qoder-cn', label: 'Qoder 国内版', installName: 'Qoder CN', appId: 'com.qodercn.app', riskEnv: 0 },
32
+ ];
33
+
34
+ const exists = (p) => { try { return fs.existsSync(p); } catch { return false; } };
35
+
36
+ const versionParts = (s) => s.split('.').map((n) => Number(n) || 0);
37
+ function compareVersionDesc(a, b) {
38
+ const x = versionParts(a), y = versionParts(b);
39
+ for (let i = 0; i < Math.max(x.length, y.length); i++) {
40
+ if ((x[i] || 0) !== (y[i] || 0)) return (y[i] || 0) - (x[i] || 0);
41
+ }
42
+ return 0;
43
+ }
44
+
45
+ /**
46
+ * 一个安装目录下的 resources 候选:0.3+ 的启动器把实际运行的版本放在
47
+ * .qoder-versions\<ver>\resources(按版本从新到旧),顶层 resources 可能只是首装时的旧版残留。
48
+ */
49
+ function resourceDirsIn(installDir) {
50
+ const root = path.join(installDir, '.qoder-versions');
51
+ let versions = [];
52
+ try {
53
+ versions = fs.readdirSync(root, { withFileTypes: true })
54
+ .filter((e) => e.isDirectory() && /^\d+(\.\d+)*$/.test(e.name))
55
+ .map((e) => e.name)
56
+ .sort(compareVersionDesc);
57
+ } catch {}
58
+ return [...versions.map((ver) => path.join(root, ver, 'resources')), path.join(installDir, 'resources')];
59
+ }
60
+
61
+ /**
62
+ * 卸载注册表里登记的安装目录(自定义安装路径)。DisplayName 形如「Qoder 0.4.1」/「Qoder CN 0.4.1」,
63
+ * 不匹配「Qoder IDE」(IDE 不带 runtime-info)。走 PowerShell 以正确读出中文路径;结果缓存 5 分钟。
64
+ */
65
+ let registryCache = { at: 0, entries: null };
66
+ function registryInstallDirs(v) {
67
+ if (process.platform !== 'win32') return [];
68
+ if (!registryCache.entries || Date.now() - registryCache.at > 5 * 60_000) {
69
+ let entries = [];
70
+ try {
71
+ const script = "$ProgressPreference='SilentlyContinue';[Console]::OutputEncoding=[Text.Encoding]::UTF8;"
72
+ + "Get-ItemProperty 'HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKLM:\\Software\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*' -ErrorAction SilentlyContinue"
73
+ + " | Where-Object { $_.DisplayName -like 'Qoder*' }"
74
+ + ' | Select-Object DisplayName,InstallLocation,UninstallString,DisplayIcon | ConvertTo-Json -Compress';
75
+ const out = execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')],
76
+ { encoding: 'utf8', windowsHide: true, timeout: 10_000, stdio: ['ignore', 'pipe', 'ignore'] }).trim();
77
+ if (out) entries = [].concat(JSON.parse(out));
78
+ } catch {}
79
+ registryCache = { at: Date.now(), entries };
80
+ }
81
+ const nameRe = new RegExp(`^${v.installName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(\\s+v?\\d[\\d.]*)?$`, 'i');
82
+ const exeDir = (s) => {
83
+ const m = String(s || '').match(/^\s*"([^"]+)"|^\s*([^,]+?\.exe)/i);
84
+ return m ? path.dirname(m[1] || m[2]) : null;
85
+ };
86
+ const dirs = [];
87
+ for (const e of registryCache.entries) {
88
+ if (!nameRe.test(String(e?.DisplayName || '').trim())) continue;
89
+ const dir = (e.InstallLocation && String(e.InstallLocation).trim()) || exeDir(e.UninstallString) || exeDir(e.DisplayIcon);
90
+ if (dir) dirs.push(dir.replace(/[\\/]+$/, ''));
91
+ }
92
+ return dirs;
93
+ }
94
+
95
+ function candidateResourceDirs(v, { registry = false } = {}) {
96
+ const home = os.homedir();
97
+ if (process.platform === 'win32') {
98
+ const local = process.env.LOCALAPPDATA || path.join(home, 'AppData', 'Local');
99
+ const installDirs = [
100
+ path.join(local, 'Programs', v.installName),
101
+ path.join(process.env.ProgramFiles || 'C:\\Program Files', v.installName),
102
+ path.join(process.env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)', v.installName),
103
+ ...(registry ? registryInstallDirs(v) : []),
104
+ ];
105
+ const seen = new Set();
106
+ const unique = installDirs.filter((d) => {
107
+ const k = path.resolve(d).toLowerCase();
108
+ if (seen.has(k)) return false;
109
+ seen.add(k);
110
+ return true;
111
+ });
112
+ return [
113
+ ...unique.flatMap(resourceDirsIn),
114
+ // AppX 风格(微软商店版 / MSIX):Qoder_*.msix 通常在 Start Menu 快捷方式指向的位置
115
+ path.join(local, 'Microsoft', 'WindowsApps', v.installName),
116
+ // Squirrel 更新目录:Electron 应用的临时升级包
117
+ path.join(local, 'electron', 'updates', v.installName),
118
+ ];
119
+ }
120
+ if (process.platform === 'darwin') {
121
+ return [
122
+ `/Applications/${v.installName}.app/Contents/Resources`,
123
+ path.join(home, 'Applications', `${v.installName}.app`, 'Contents', 'Resources'),
124
+ // 可能是 qodercn.app 或 qoder.app
125
+ `/Applications/Qoder.app/Contents/Resources`,
126
+ `/Applications/Qoder\\ CN.app/Contents/Resources`,
127
+ ];
128
+ }
129
+ const slug = v.installName.toLowerCase().replace(/\s+/g, '-');
130
+ return [`/opt/${v.installName}/resources`, `/opt/${slug}/resources`, `/usr/lib/${slug}/resources`, '/snap/qoder/current/resources'];
131
+ }
132
+
133
+ function userDataDir(v) {
134
+ const home = os.homedir();
135
+ const name = `${v.appId}.stable`;
136
+ if (process.platform === 'win32') {
137
+ return path.join(process.env.APPDATA || path.join(home, 'AppData', 'Roaming'), name);
138
+ }
139
+ if (process.platform === 'darwin') return path.join(home, 'Library', 'Application Support', name);
140
+ return path.join(process.env.XDG_CONFIG_HOME || path.join(home, '.config'), name);
141
+ }
142
+
143
+ function readVersion(resourcesDir) {
144
+ try {
145
+ const m = JSON.parse(fs.readFileSync(path.join(resourcesDir, 'build-manifest.json'), 'utf8'));
146
+ if (typeof m.productVersion === 'string') return m.productVersion;
147
+ } catch {}
148
+ return null;
149
+ }
150
+
151
+ const RUNTIME_INFO_EXE = process.platform === 'win32' ? 'runtime-info.exe' : 'runtime-info';
152
+ const runtimeInfoIn = (resources) => (exists(path.join(resources, 'umid', RUNTIME_INFO_EXE)) ? path.join(resources, 'umid', RUNTIME_INFO_EXE) : null);
153
+ const isDir = (p) => { try { return fs.statSync(p).isDirectory(); } catch { return false; } };
154
+
155
+ /** 在候选里选 resources:优先带 runtime-info 的(风控身份靠它),否则第一个存在的 */
156
+ function pickResources(dirs) {
157
+ const existing = dirs.filter(isDir);
158
+ return existing.find((d) => runtimeInfoIn(d)) || existing[0] || null;
159
+ }
160
+
161
+ /** 探测本机已安装的 Qoder 客户端(国际版 / 国内版) */
162
+ export function detectQoderApps() {
163
+ return VARIANTS.map((v) => {
164
+ let resources = pickResources(candidateResourceDirs(v));
165
+ // 默认位置没找到可用的 runtime-info → 再查卸载注册表里的实际安装目录(自定义路径)
166
+ if (process.platform === 'win32' && !(resources && runtimeInfoIn(resources))) {
167
+ resources = pickResources(candidateResourceDirs(v, { registry: true })) || resources;
168
+ }
169
+ const runtimeInfo = resources ? runtimeInfoIn(resources) : null;
170
+ const data = userDataDir(v);
171
+ return {
172
+ provider: v.provider,
173
+ label: v.label,
174
+ installed: Boolean(resources),
175
+ resourcesDir: resources,
176
+ version: resources ? readVersion(resources) : null,
177
+ runtimeInfo,
178
+ dataDir: data,
179
+ dataExists: exists(data),
180
+ signedIn: exists(path.join(data, 'auth.v1.dat')),
181
+ };
182
+ });
183
+ }
184
+
185
+ // ─── 设备风控身份 ───
186
+
187
+ /** 与客户端一致的 Cosy-MachineOS 格式:x86_64_win32 / aarch64_darwin … */
188
+ export function machineOs() {
189
+ const a = process.arch === 'arm64' ? 'aarch64' : process.arch === 'x64' ? 'x86_64' : process.arch;
190
+ return `${a}_${process.platform}`;
191
+ }
192
+
193
+ /** 与客户端一致的主机名清洗:可打印 ASCII,超长截断并附短哈希 */
194
+ export function machineHostname(raw = os.hostname()) {
195
+ const e = String(raw || '').trim();
196
+ if (!e) return undefined;
197
+ const clip = (t) => {
198
+ if (t.length <= 96) return t;
199
+ const h = crypto.createHash('sha256').update(t, 'utf8').digest('hex').slice(0, 8);
200
+ const head = t.slice(0, 96 - 8 - 1).replace(/[-\s]+$/u, '');
201
+ return head ? `${head}-${h}` : `unknown-${h}`;
202
+ };
203
+ if (/^[\x21-\x7e](?:[\x20-\x7e]*[\x21-\x7e])?$/u.test(e)) return clip(e);
204
+ const h = crypto.createHash('sha256').update(e, 'utf8').digest('hex').slice(0, 8);
205
+ const n = e.replace(/[^\x21-\x7e]+/gu, '-').replace(/-{2,}/gu, '-').replace(/^-+|-+$/gu, '');
206
+ return clip(n ? `${n}-${h}` : `unknown-${h}`);
207
+ }
208
+
209
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
210
+
211
+ /** 机器 ID:优先复用客户端的 auth.machine-id,否则在 CreditDaddy 数据目录持久化一个 */
212
+ export function machineId(provider) {
213
+ const v = VARIANTS.find((x) => x.provider === provider) || VARIANTS[0];
214
+ for (const file of [path.join(userDataDir(v), 'auth.machine-id'), path.join(dataDir(), 'machine-id')]) {
215
+ try {
216
+ const id = fs.readFileSync(file, 'utf8').trim();
217
+ if (UUID_RE.test(id)) return id;
218
+ } catch {}
219
+ }
220
+ const id = crypto.randomUUID();
221
+ try {
222
+ fs.mkdirSync(dataDir(), { recursive: true, mode: 0o700 });
223
+ fs.writeFileSync(path.join(dataDir(), 'machine-id'), id, { mode: 0o600 });
224
+ } catch {}
225
+ return id;
226
+ }
227
+
228
+ /** 客户端版本号(用于 Cosy-Version) */
229
+ export function clientVersion(provider) {
230
+ const apps = detectQoderApps();
231
+ const app = apps.find((a) => a.provider === provider && a.version) || apps.find((a) => a.version);
232
+ return app?.version || DEFAULT_CLIENT_VERSION;
233
+ }
234
+
235
+ function runRuntimeInfo(exe, env, account) {
236
+ return new Promise((resolve, reject) => {
237
+ const withStdin = process.platform === 'darwin' || process.platform === 'win32';
238
+ const child = spawn(exe, withStdin ? [String(env), '--account-stdin'] : [String(env)], {
239
+ stdio: [withStdin ? 'pipe' : 'ignore', 'pipe', 'pipe'],
240
+ windowsHide: true,
241
+ });
242
+ let out = '';
243
+ let settled = false;
244
+ const done = (err, val) => {
245
+ if (settled) return;
246
+ settled = true;
247
+ clearTimeout(timer);
248
+ if (child.exitCode === null) child.kill();
249
+ err ? reject(err) : resolve(val);
250
+ };
251
+ const timer = setTimeout(() => done(new Error('runtime-info 超时')), RISK_TIMEOUT_MS);
252
+ const tryParse = () => {
253
+ const nl = out.indexOf('\n');
254
+ if (nl < 0) return false;
255
+ try {
256
+ const j = JSON.parse(out.slice(0, nl));
257
+ const pick = (k) => {
258
+ const s = typeof j[k] === 'string' ? j[k].trim() : '';
259
+ if (!s || s.length > 4096) throw new Error(`runtime-info 输出缺少 ${k}`);
260
+ return s;
261
+ };
262
+ done(null, { machineToken: pick('machineToken'), machineCode: pick('machineCode'), machineType: pick('machineType') });
263
+ } catch (e) { done(e); }
264
+ return true;
265
+ };
266
+ child.stdout.on('data', (d) => {
267
+ out += d.toString('utf8');
268
+ if (out.length > 1024 * 1024) return done(new Error('runtime-info 输出过大'));
269
+ tryParse();
270
+ });
271
+ child.stderr.on('data', () => {});
272
+ child.once('error', (e) => done(new Error(`runtime-info 启动失败:${e.message}`)));
273
+ child.once('close', (code) => {
274
+ if (!tryParse()) done(new Error(`runtime-info 退出码 ${code}`));
275
+ });
276
+ if (withStdin) {
277
+ child.stdin.on('error', () => {});
278
+ child.stdin.end(JSON.stringify({ account }) + '\n');
279
+ }
280
+ });
281
+ }
282
+
283
+ const riskCache = new Map(); // `${provider}:${uid}` → { value, at } | { promise }
284
+
285
+ /**
286
+ * 风控身份来源:优先本机 Qoder 客户端自带的 runtime-info(国际版 env=3 / 国内版 env=0,缺失时用另一版本的),
287
+ * 其次是从官方 qodercli 提取的设备身份组件(Linux / fnOS,见 qoderUmid.js,env 与 qodercli 一致)。
288
+ */
289
+ function riskRunner(provider) {
290
+ const apps = detectQoderApps().filter((a) => a.runtimeInfo);
291
+ const app = apps.find((a) => a.provider === provider) || apps[0];
292
+ if (app) return { exe: app.runtimeInfo, env: (VARIANTS.find((v) => v.provider === provider) || VARIANTS[0]).riskEnv, source: 'app' };
293
+ const cli = installedUmid() || bundledCliUmid(provider);
294
+ if (cli) return { exe: cli.path, env: CLI_RISK_ENV[provider] ?? CLI_RISK_ENV.qoder, source: 'cli' };
295
+ const localBin = qodercliRuntimeInfo(provider);
296
+ if (localBin) return { exe: localBin, env: CLI_RISK_ENV[provider] ?? CLI_RISK_ENV.qoder, source: 'cli' };
297
+ return null;
298
+ }
299
+
300
+ /** Windows:客户端自带的 qodercli 会把设备身份组件解压到 ~\.qoder\.bin\umid-win32-<arch>-*\(国内版 ~\.qoder-cn) */
301
+ function bundledCliUmid(provider) {
302
+ if (process.platform !== 'win32') return null;
303
+ const homes = provider === 'qoder-cn' ? ['.qoder-cn', '.qoder'] : ['.qoder', '.qoder-cn'];
304
+ for (const h of homes) {
305
+ const bin = path.join(os.homedir(), h, '.bin');
306
+ let dirs = [];
307
+ try { dirs = fs.readdirSync(bin).filter((n) => n.startsWith('umid-win32-')); } catch {}
308
+ for (const d of dirs) {
309
+ const exe = path.join(bin, d, RUNTIME_INFO_EXE);
310
+ if (exists(exe)) return { path: exe };
311
+ }
312
+ }
313
+ return null;
314
+ }
315
+
316
+ /** macOS:官方 qodercli(@qoder-ai/qodercli)把 runtime-info 设备身份组件解压到 ~\.qoder\.bin\runtime-info-darwin-<arch>-*(国内版 ~\.qoder-cn) */
317
+ function qodercliRuntimeInfo(provider) {
318
+ if (process.platform !== 'darwin') return null;
319
+ const homes = provider === 'qoder-cn' ? ['.qoder-cn', '.qoder'] : ['.qoder', '.qoder-cn'];
320
+ for (const h of homes) {
321
+ const bin = path.join(os.homedir(), h, '.bin');
322
+ let entries = [];
323
+ try { entries = fs.readdirSync(bin, { withFileTypes: true }).filter((n) => n.name.startsWith(`runtime-info-darwin-${process.arch}`)); } catch {}
324
+ if (!entries.length) continue;
325
+ // 版本排序(1.2.10 > 1.2.9,字典序会反);目录形态时拼组件名,文件形态直接用;
326
+ // 必须 exists 校验——升级残留的旧条目/坏条目不能静默选中
327
+ const ver = (name) => name.split('-').slice(-1)[0].split('.').map((x) => Number(x) || 0);
328
+ const cmp = (a, b) => { const va = ver(a), vb = ver(b); for (let i = 0; i < Math.max(va.length, vb.length); i++) { if ((va[i] || 0) !== (vb[i] || 0)) return (va[i] || 0) - (vb[i] || 0); } return 0; };
329
+ for (const e of entries.sort((a, b) => cmp(b.name, a.name))) {
330
+ const p = e.isDirectory() ? path.join(bin, e.name, RUNTIME_INFO_EXE) : path.join(bin, e.name);
331
+ try { if (fs.statSync(p).isFile()) return p; } catch { /* 坏条目跳过,试下一个 */ }
332
+ }
333
+ }
334
+ return null;
335
+ }
336
+
337
+ /** 获取某账号的设备风控身份;本机既没有 Qoder 客户端也没装设备身份组件时返回 null。 */
338
+ export async function getRiskIdentity(provider, uid) {
339
+ if (!uid) return null;
340
+ const key = `${provider}:${uid}`;
341
+ const hit = riskCache.get(key);
342
+ if (hit?.value && Date.now() - hit.at < RISK_TTL_MS) return hit.value;
343
+ if (hit?.promise) return hit.promise;
344
+
345
+ const runner = riskRunner(provider);
346
+ if (!runner) return null;
347
+
348
+ const promise = runRuntimeInfo(runner.exe, runner.env, uid)
349
+ .then((value) => { riskCache.set(key, { value, at: Date.now() }); return value; })
350
+ .catch((e) => { riskCache.delete(key); throw e; });
351
+ riskCache.set(key, { promise });
352
+ return promise;
353
+ }
354
+
355
+ export function riskIdentityAvailable() {
356
+ return Boolean(riskRunner('qoder'));
357
+ }
358
+
359
+ /** 风控身份来源:'app'(Qoder 客户端)/ 'cli'(qodercli 设备身份组件)/ null */
360
+ export function riskIdentitySource() {
361
+ return riskRunner('qoder')?.source || null;
362
+ }
363
+
364
+ // ─── Electron safeStorage 解密 ───
365
+
366
+ function dpapiUnprotect(buf) {
367
+ const script = 'Add-Type -AssemblyName System.Security;'
368
+ + '$b=[Convert]::FromBase64String([Console]::In.ReadToEnd());'
369
+ + "[Convert]::ToBase64String([System.Security.Cryptography.ProtectedData]::Unprotect($b,$null,'CurrentUser'))";
370
+ // 使用 -EncodedCommand 传入 UTF-16LE Base64,避免命令行参数中包含敏感 API 关键字被杀毒软件误报
371
+ const encoded = Buffer.from(script, 'utf16le').toString('base64');
372
+ return new Promise((resolve, reject) => {
373
+ const child = execFile('powershell.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded],
374
+ { windowsHide: true, timeout: 20_000 }, (err, stdout) => {
375
+ if (err) return reject(new Error('DPAPI 解密失败:' + err.message));
376
+ resolve(Buffer.from(String(stdout).trim(), 'base64'));
377
+ });
378
+ child.stdin.end(buf.toString('base64'));
379
+ });
380
+ }
381
+
382
+ function macKeychainPassword(service) {
383
+ return new Promise((resolve) => {
384
+ execFile('security', ['find-generic-password', '-w', '-s', service], { timeout: 20_000 },
385
+ (err, stdout) => resolve(err ? null : String(stdout).trim()));
386
+ });
387
+ }
388
+
389
+ const keyCache = new Map();
390
+ let codecOverride = null; // 测试注入:替代 safeStorageCodec(DPAPI 依赖真实用户上下文,测试绕开)
391
+ /** 测试钩子:注入编解码器(切换写入路径用),传 null 恢复真实实现。 */
392
+ export function _setCodecForTests(codec) { codecOverride = codec; }
393
+
394
+ /**
395
+ * 某个 Electron userData 目录对应的 safeStorage 编解码器。
396
+ * encrypt 用于把账号库里的登录快照写回客户端(切换账号),与 decrypt 同密钥同格式:
397
+ * Windows = 'v10' + nonce(12) + AES-256-GCM 密文 + tag(16);mac/linux = 'v10' + AES-128-CBC。
398
+ */
399
+ export async function safeStorageCodec(userData, appNames) {
400
+ if (keyCache.has(userData)) return keyCache.get(userData);
401
+ let decrypt, encrypt;
402
+ if (process.platform === 'win32') {
403
+ const ls = JSON.parse(fs.readFileSync(path.join(userData, 'Local State'), 'utf8'));
404
+ const enc = Buffer.from(ls?.os_crypt?.encrypted_key || '', 'base64');
405
+ if (enc.subarray(0, 5).toString() !== 'DPAPI') throw new Error('Local State 中没有 DPAPI 密钥');
406
+ const key = await dpapiUnprotect(enc.subarray(5));
407
+ decrypt = (data) => {
408
+ if (data.subarray(0, 3).toString() !== 'v10') throw new Error('未知的加密格式');
409
+ const nonce = data.subarray(3, 15);
410
+ const tag = data.subarray(data.length - 16);
411
+ const d = crypto.createDecipheriv('aes-256-gcm', key, nonce);
412
+ d.setAuthTag(tag);
413
+ return Buffer.concat([d.update(data.subarray(15, data.length - 16)), d.final()]).toString('utf8');
414
+ };
415
+ encrypt = (text) => {
416
+ const nonce = crypto.randomBytes(12);
417
+ const c = crypto.createCipheriv('aes-256-gcm', key, nonce);
418
+ const ct = Buffer.concat([c.update(text, 'utf8'), c.final()]);
419
+ return Buffer.concat([Buffer.from('v10'), nonce, ct, c.getAuthTag()]);
420
+ };
421
+ } else {
422
+ let password = 'peanuts', iterations = 1;
423
+ if (process.platform === 'darwin') {
424
+ for (const n of appNames) {
425
+ password = await macKeychainPassword(`${n} Safe Storage`);
426
+ if (password) break;
427
+ }
428
+ if (!password) throw new Error('无法从钥匙串读取 Qoder 的 Safe Storage 密钥');
429
+ iterations = 1003;
430
+ }
431
+ const key = crypto.pbkdf2Sync(password, 'saltysalt', iterations, 16, 'sha1');
432
+ const iv = Buffer.alloc(16, ' ');
433
+ decrypt = (data) => {
434
+ const ver = data.subarray(0, 3).toString();
435
+ if (ver !== 'v10') throw new Error(ver === 'v11' ? '需要系统密钥环(v11),暂不支持' : '未知的加密格式');
436
+ const d = crypto.createDecipheriv('aes-128-cbc', key, iv);
437
+ return Buffer.concat([d.update(data.subarray(3)), d.final()]).toString('utf8');
438
+ };
439
+ encrypt = (text) => {
440
+ const c = crypto.createCipheriv('aes-128-cbc', key, iv);
441
+ return Buffer.concat([Buffer.from('v10'), c.update(text, 'utf8'), c.final()]);
442
+ };
443
+ }
444
+ const codec = { decrypt, encrypt };
445
+ keyCache.set(userData, codec);
446
+ return codec;
447
+ }
448
+
449
+ /**
450
+ * 读取本机 Qoder 客户端当前登录的账号(解密 auth.v1.dat)。
451
+ * @returns {Promise<{accounts: Array, errors: Array}>} 每个账号含 provider/token/refreshToken/expiresAt/user
452
+ */
453
+ export async function readQoderAppAccounts() {
454
+ const accounts = [];
455
+ const errors = [];
456
+ for (const app of detectQoderApps()) {
457
+ const file = path.join(app.dataDir, 'auth.v1.dat');
458
+ if (!exists(file)) continue;
459
+ try {
460
+ const { decrypt } = await safeStorageCodec(app.dataDir, ['Qoder App', app.label.includes('国内') ? 'Qoder CN' : 'Qoder']);
461
+ const obj = JSON.parse(decrypt(fs.readFileSync(file)));
462
+ if (typeof obj?.token !== 'string' || !obj.token) throw new Error('auth.v1.dat 中没有 token');
463
+ accounts.push({
464
+ provider: app.provider,
465
+ source: `${app.label} 客户端`,
466
+ file,
467
+ authJson: obj,
468
+ token: obj.token,
469
+ refreshToken: typeof obj.refreshToken === 'string' ? obj.refreshToken : null,
470
+ expiresAt: typeof obj.expiresAt === 'string' ? obj.expiresAt : null,
471
+ user: {
472
+ id: obj.user?.id || null,
473
+ name: obj.user?.name || null,
474
+ email: obj.user?.email || null,
475
+ },
476
+ });
477
+ } catch (e) {
478
+ errors.push({ provider: app.provider, file, error: e.message });
479
+ }
480
+ }
481
+ return { accounts, errors };
482
+ }
483
+
484
+ // ─── 切换本机 Qoder 登录账号 ───
485
+
486
+ const QODER_EXES = ['Qoder.exe', 'Qoder CN.exe'];
487
+
488
+ /** Qoder IDE(国际版 / 国内版)是否在运行 */
489
+ export function qoderRunning() {
490
+ // 走 winProc:这里曾经用 latin1 解 tasklist,中文 Windows 上恒为 true
491
+ return anyProcRunning(QODER_EXES);
492
+ }
493
+
494
+ /** 轮询口径(/api/status 用):读 winProc 全量快照,不 spawn;switchTo/terminate 仍走 qoderRunning()。 */
495
+ export function qoderRunningCached() {
496
+ return procRunningCached(QODER_EXES);
497
+ }
498
+
499
+ const nap = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
500
+
501
+ /** 结束 Qoder 进程:先普通终止(给客户端落盘的机会),超时后 /F */
502
+ export function terminateQoder({ timeoutMs = 8000 } = {}) {
503
+ if (process.platform !== 'win32') return { closed: false, supported: false };
504
+ if (!qoderRunning()) return { closed: false, running: false };
505
+ for (const exe of QODER_EXES) {
506
+ try { execFileSync('taskkill.exe', ['/IM', exe, '/T'], { windowsHide: true, stdio: 'ignore' }); } catch {}
507
+ }
508
+ let deadline = Date.now() + timeoutMs;
509
+ while (Date.now() < deadline && qoderRunning()) nap(250);
510
+ if (qoderRunning()) {
511
+ for (const exe of QODER_EXES) {
512
+ try { execFileSync('taskkill.exe', ['/IM', exe, '/T', '/F'], { windowsHide: true, stdio: 'ignore' }); } catch {}
513
+ }
514
+ deadline = Date.now() + 3000;
515
+ while (Date.now() < deadline && qoderRunning()) nap(250);
516
+ }
517
+ return { closed: !qoderRunning(), running: qoderRunning() };
518
+ }
519
+
520
+ /**
521
+ * 把本机 Qoder 客户端的登录换成目标账号(写回 auth.v1.dat)。
522
+ * force:由调用方先 terminateQoder 再进来(运行中的 Qoder 退出时会把内存里的旧登录覆盖回文件)。
523
+ *
524
+ * ## ★ 过期快照必须拒绝写入(2026-11-07 用户实测)
525
+ *
526
+ * Qoder 设备流登录的 token 约 30 天且**没有续期通道**(上游对无签名的刷新调用一律
527
+ * 403 "Request discarded",10router 同款结论),快照里的 expiresAt 一旦过了,客户端
528
+ * 读到就是死凭据:启动时判定无效 → 删掉 auth.v1.dat → 登录页。此前把过期快照照写
529
+ * 不误,用户看到的是「切换成功 → 重开客户端 → 被登出」的哑谜,还得手动重登。现在
530
+ * 写入前拦下,把真实原因说清楚;临期(<24h)照常切换但带 warn 让面板提示。
531
+ */
532
+ export async function switchTo(account, { force = false } = {}) {
533
+ const auth = account.meta?.qoderAuth;
534
+ const file = account.meta?.qoderAuthFile;
535
+ if (!auth || !file) {
536
+ throw new Error(`账号「${account.name || account.id}」没有本机登录快照,无法切换:请在 Qoder 里登录该账号后到「添加账号 → 本机导入」导入一次`);
537
+ }
538
+ if (!fs.existsSync(file)) {
539
+ // 本机当初导入时文件是在的,现在没了:绝大多数情况是客户端退出登录(登出/换号后它会删掉
540
+ // auth.v1.dat),只有少数是卸载或换了数据目录。按发生率给指引,别让人以为软件坏了。
541
+ const app = detectQoderApps().find((a) => a.provider === account.provider);
542
+ const label = app?.label || (account.provider === 'qoder-cn' ? 'Qoder 国内版' : 'Qoder 国际版');
543
+ const hint = app?.installed
544
+ ? `请打开「${label}」客户端确认已登录该账号,然后到「添加账号 → 本机导入」重新导入一次`
545
+ : `没检测到「${label}」客户端,请先安装并登录,然后到「添加账号 → 本机导入」导入`;
546
+ throw new Error(`账号「${account.name || account.id}」的切换凭据已失效:${label}的登录文件不在了(${file})。${hint}`);
547
+ }
548
+ const expiresAtMs = Date.parse(auth.expiresAt || '');
549
+ let nearExpiryWarn = null;
550
+ if (Number.isFinite(expiresAtMs)) {
551
+ if (expiresAtMs <= Date.now()) {
552
+ const e = new Error(`账号「${account.name || account.id}」的登录快照已于 ${new Date(expiresAtMs).toLocaleString()} 过期,写进去只会让客户端被登出。Qoder 的设备登录 token 约 30 天且到期不可续期——请在 Qoder 客户端登录该账号后到「本机导入」重新导入,再切换。`);
553
+ e.staleAuth = true;
554
+ throw e;
555
+ }
556
+ if (expiresAtMs - Date.now() < 24 * 3600_000) {
557
+ nearExpiryWarn = `该账号的登录快照将于 ${new Date(expiresAtMs).toLocaleString()} 过期,届时需重新登录导入`;
558
+ }
559
+ }
560
+ if (!force && qoderRunning()) {
561
+ const e = new Error('Qoder 正在运行。切换会改写 Qoder 的登录文件,运行中的 Qoder 退出时会把旧登录写回去——退出后重试,或选择「关闭并强制切换」。');
562
+ e.qoderRunning = true;
563
+ throw e;
564
+ }
565
+ const { encrypt, decrypt } = codecOverride || await safeStorageCodec(path.dirname(file), ['Qoder App', account.provider === 'qoder-cn' ? 'Qoder CN' : 'Qoder']);
566
+ try {
567
+ if (JSON.parse(decrypt(fs.readFileSync(file))).token === auth.token) {
568
+ return { switched: false, alreadyActive: true };
569
+ }
570
+ } catch { /* 当前文件解不开就当作不同账号,继续写入 */ }
571
+ const buf = encrypt(JSON.stringify(auth));
572
+ const bak = file + '.creditdaddy.bak';
573
+ try { fs.copyFileSync(file, bak); } catch { /* 备份失败不阻断,下面原子写仍会成功 */ }
574
+ const tmp = file + '.tmp';
575
+ fs.writeFileSync(tmp, buf, { mode: 0o600 });
576
+ fs.renameSync(tmp, file);
577
+ return { switched: true, alreadyActive: false, warn: nearExpiryWarn };
578
+ }