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.
Files changed (70) 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/bgdaemon.js +341 -341
  16. package/src/buildInfo.js +65 -65
  17. package/src/catpawClient.js +103 -103
  18. package/src/catpawLocal.js +236 -236
  19. package/src/checkin.js +7 -2
  20. package/src/codebuddyIdeLocal.js +381 -381
  21. package/src/constants.js +121 -117
  22. package/src/cookieSites.js +340 -301
  23. package/src/daemon.js +2682 -2443
  24. package/src/doubaoClient.js +167 -167
  25. package/src/dumateClient.js +517 -0
  26. package/src/dumateLocal.js +298 -0
  27. package/src/dumateQr.js +337 -0
  28. package/src/externalQuota.js +577 -574
  29. package/src/formatDuration.js +17 -17
  30. package/src/i18n/en.json +161 -7
  31. package/src/i18n/ja.json +161 -7
  32. package/src/i18n/ko.json +161 -7
  33. package/src/i18n/zh-TW.json +161 -7
  34. package/src/i18n.js +47 -47
  35. package/src/lingxiClient.js +373 -373
  36. package/src/localDetect.js +147 -147
  37. package/src/longcatClient.js +260 -260
  38. package/src/loomyAuth.js +230 -230
  39. package/src/loomyClient.js +366 -366
  40. package/src/loomyLocal.js +206 -206
  41. package/src/meooAuth.js +246 -0
  42. package/src/meooClient.js +250 -0
  43. package/src/minimaxGateway.js +520 -520
  44. package/src/minimaxLocal.js +344 -344
  45. package/src/mirasimClient.js +211 -211
  46. package/src/mirasimLocal.js +392 -392
  47. package/src/modelscopeClient.js +275 -275
  48. package/src/panel.html +374 -48
  49. package/src/prodIcons.json +7 -5
  50. package/src/providers.js +34 -0
  51. package/src/qoderApp.js +578 -578
  52. package/src/qoderClient.js +266 -266
  53. package/src/qoderUmid.js +199 -199
  54. package/src/quotaRefresh.js +119 -119
  55. package/src/refreshGuard.js +75 -75
  56. package/src/riverClient.js +372 -372
  57. package/src/store.js +2 -1
  58. package/src/tenrouterAccounts.js +237 -232
  59. package/src/traeAuth.js +601 -599
  60. package/src/traeClient.js +356 -360
  61. package/src/traeGateway.js +875 -875
  62. package/src/traeLocal.js +463 -371
  63. package/src/transfer.js +4 -0
  64. package/src/usageSync.js +535 -523
  65. package/src/winProc.js +134 -134
  66. package/src/xiaomiMimoClient.js +206 -206
  67. package/src/zcodeAuth.js +131 -131
  68. package/src/zcodeGateway.js +850 -850
  69. package/src/zcodeLocal.js +340 -340
  70. package/src/zcrypto.js +160 -160
package/src/qoderUmid.js CHANGED
@@ -1,199 +1,199 @@
1
- /**
2
- * Qoder 设备身份组件 —— 给没有 Qoder 客户端的 Linux(fnOS / NAS)提供国际版签到所需的风控身份。
3
- *
4
- * Qoder 国际版只向带 Cosy-MachineToken / Code / Type 的请求下发「每天领 100 Credits」,
5
- * 这三个值由 Qoder 的 UMID 程序(runtime-info)生成。桌面端客户端自带它;官方 CLI
6
- * @qoder-ai/qodercli 则把各平台的 UMID 二进制以 base64 内嵌在 bundle/qodercli.js 里,Linux x64 / arm64 都有。
7
- *
8
- * 这里在用户确认后从 npm 仓库下载官方 qodercli 包(校验 npm 的 sha512 integrity),
9
- * 按本机 CPU 架构取出对应的 ELF,试跑一次确认能产出身份,再存到 ~/.creditdaddy/qoder-umid/。
10
- * 不随 CreditDaddy 分发该二进制;调用方式与 qodercli 一致:runtime-info <env>,第一行输出 JSON。
11
- * env:国际版 4(SINGAPORE,qodercli 的全球区取值),国内版 0(ONLINE)。
12
- */
13
-
14
- import fs from 'node:fs';
15
- import path from 'node:path';
16
- import crypto from 'node:crypto';
17
- import zlib from 'node:zlib';
18
- import { execFile } from 'node:child_process';
19
- import { dataDir } from './store.js';
20
- import { logger } from './logger.js';
21
- import { t } from './i18n.js';
22
-
23
- const PKG = '@qoder-ai/qodercli';
24
- const REGISTRIES = ['https://registry.npmmirror.com', 'https://registry.npmjs.org'];
25
- const AUTH_REGISTRY = 'https://registry.npmjs.org'; // integrity 的权威来源(镜像只用于加速下载)
26
- const ELF_MACHINE = { x64: 62, arm64: 183 };
27
- const BUNDLE_ENTRY = 'package/bundle/qodercli.js';
28
- const FETCH_TIMEOUT_MS = 180_000;
29
- const META_TIMEOUT_MS = 15_000;
30
- export const CLI_RISK_ENV = { qoder: 4, 'qoder-cn': 0 };
31
-
32
- export function umidSupported(platform = process.platform, arch = process.arch) {
33
- return platform === 'linux' && Boolean(ELF_MACHINE[arch]);
34
- }
35
-
36
- const dir = () => path.join(dataDir(), 'qoder-umid');
37
- const binPath = () => path.join(dir(), 'runtime-info');
38
- const manifestPath = () => path.join(dir(), 'manifest.json');
39
-
40
- /** 已安装的组件:{ path, version, arch, sha256, installedAt, registry };未安装返回 null */
41
- export function installedUmid() {
42
- if (!umidSupported()) return null;
43
- try {
44
- const m = JSON.parse(fs.readFileSync(manifestPath(), 'utf8'));
45
- if (!fs.existsSync(binPath()) || m.arch !== process.arch) return null;
46
- return { ...m, path: binPath() };
47
- } catch { return null; }
48
- }
49
-
50
- // ── 纯函数(便于单测) ──
51
-
52
- /** 最小 tar 解析:按名字取一个普通文件的内容 */
53
- export function tarEntry(tar, wanted) {
54
- let off = 0;
55
- const cstr = (b, s, n) => { const x = b.subarray(s, s + n); const z = x.indexOf(0); return x.subarray(0, z < 0 ? n : z).toString('utf8'); };
56
- let longName = null;
57
- while (off + 512 <= tar.length) {
58
- const h = tar.subarray(off, off + 512);
59
- if (h.every((b) => b === 0)) break;
60
- const size = parseInt(cstr(h, 124, 12).trim() || '0', 8);
61
- const type = String.fromCharCode(h[156] || 48);
62
- const prefix = cstr(h, 345, 155);
63
- let name = longName || (prefix ? prefix + '/' : '') + cstr(h, 0, 100);
64
- longName = null;
65
- const body = tar.subarray(off + 512, off + 512 + size);
66
- off += 512 + Math.ceil(size / 512) * 512;
67
- if (type === 'L') { longName = body.toString('utf8').replace(/\0+$/, ''); continue; }
68
- if (type === 'x') { // pax 扩展头里的 path 覆盖下一个条目的名字
69
- const m = /\d+ path=([^\n]+)\n/.exec(body.toString('utf8'));
70
- if (m) longName = m[1];
71
- continue;
72
- }
73
- if ((type === '0' || type === '\0') && name === wanted) return body;
74
- }
75
- return null;
76
- }
77
-
78
- /** 在 qodercli bundle 文本里找内嵌的 ELF(base64 字面量),按 e_machine 挑出本机架构 */
79
- export function extractElf(jsText, machine) {
80
- const MARK = '"f0VMRgIB'; // "\x7fELF" + 64 位 + 小端 的 base64 开头
81
- let i = jsText.indexOf(MARK);
82
- while (i >= 0) {
83
- const start = i + 1;
84
- const end = jsText.indexOf('"', start);
85
- if (end < 0) break;
86
- const head = Buffer.from(jsText.slice(start, start + 28), 'base64');
87
- if (head.length >= 20 && head.readUInt16LE(18) === machine) {
88
- return Buffer.from(jsText.slice(start, end), 'base64');
89
- }
90
- i = jsText.indexOf(MARK, end);
91
- }
92
- return null;
93
- }
94
-
95
- /** npm integrity(sha512-<base64>)校验 */
96
- export function checkIntegrity(buf, integrity) {
97
- const m = /^sha512-(.+)$/.exec(String(integrity || '').split(/\s+/)[0]);
98
- if (!m) return false;
99
- return crypto.createHash('sha512').update(buf).digest('base64') === m[1];
100
- }
101
-
102
- // ── 安装 ──
103
-
104
- async function fetchBuf(url, timeoutMs = FETCH_TIMEOUT_MS) {
105
- const res = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
106
- if (!res.ok) throw new Error(`HTTP ${res.status}:${url}`);
107
- return Buffer.from(await res.arrayBuffer());
108
- }
109
-
110
- /**
111
- * 从 npmjs 拉权威 integrity。镜像(npmmirror)的元数据与 tarball 同源,
112
- * 镜像被污染时它自己的 integrity 校验形同虚设,所以校验值以 npmjs 为准;
113
- * npmjs 不可达时返回 null,退回镜像自身 integrity(与旧行为一致)。
114
- */
115
- async function authoritativeIntegrity() {
116
- try {
117
- const meta = JSON.parse((await fetchBuf(`${AUTH_REGISTRY}/${PKG.replace('/', '%2f')}/latest`, META_TIMEOUT_MS)).toString('utf8'));
118
- if (meta?.dist?.integrity && meta?.version) return { integrity: meta.dist.integrity, version: meta.version };
119
- } catch {}
120
- return null;
121
- }
122
-
123
- function testRun(file) {
124
- return new Promise((resolve, reject) => {
125
- execFile(file, [String(CLI_RISK_ENV.qoder)], { timeout: 30_000, maxBuffer: 1 << 20 }, (err, stdout) => {
126
- try {
127
- const j = JSON.parse(String(stdout).split('\n')[0]);
128
- if (typeof j.machineToken === 'string' && j.machineToken && j.machineCode && j.machineType) return resolve(j);
129
- } catch {}
130
- reject(new Error('组件试运行失败' + (err ? ':' + err.message : '(输出里没有设备身份)')));
131
- });
132
- });
133
- }
134
-
135
- let installing = null;
136
-
137
- /** 下载官方 qodercli 包并提取本机架构的 UMID;并发调用共用同一次安装 */
138
- export function installUmid() {
139
- if (!installing) installing = doInstall().finally(() => { installing = null; });
140
- return installing;
141
- }
142
- export const umidInstalling = () => Boolean(installing);
143
-
144
- async function doInstall() {
145
- if (!umidSupported()) throw new Error(`当前平台(${process.platform}/${process.arch})不需要或不支持该组件`);
146
- const authority = await authoritativeIntegrity();
147
- const errors = [];
148
- for (const registry of REGISTRIES) {
149
- try {
150
- const meta = JSON.parse((await fetchBuf(`${registry}/${PKG.replace('/', '%2f')}/latest`, META_TIMEOUT_MS)).toString('utf8'));
151
- const { tarball, integrity } = meta.dist || {};
152
- if (!tarball || !integrity) throw new Error('包元数据缺少 tarball / integrity');
153
- // 镜像版本与 npmjs 不一致时没有权威校验值可比,跳过镜像直接用官方源
154
- if (authority && registry !== AUTH_REGISTRY && meta.version !== authority.version) {
155
- throw new Error(`镜像版本(${meta.version})与 npmjs(${authority.version})不一致`);
156
- }
157
- const expected = authority && authority.version === meta.version ? authority.integrity : integrity;
158
- logger.info('UMID', '下载 {pkg}@{version}({registry})', { pkg: PKG, version: meta.version, registry });
159
- const tgz = await fetchBuf(tarball);
160
- if (!checkIntegrity(tgz, expected)) throw new Error('下载内容与 npm integrity 不一致');
161
- const bundle = tarEntry(zlib.gunzipSync(tgz), BUNDLE_ENTRY);
162
- if (!bundle) throw new Error(`包里没有 ${BUNDLE_ENTRY}(qodercli 结构可能变化)`);
163
- const elf = extractElf(bundle.toString('latin1'), ELF_MACHINE[process.arch]);
164
- if (!elf) throw new Error(`qodercli ${meta.version} 里没有 ${process.arch} 的 UMID 程序(结构可能变化)`);
165
-
166
- fs.mkdirSync(dir(), { recursive: true, mode: 0o700 });
167
- const tmp = binPath() + '.' + process.pid + '.tmp';
168
- fs.writeFileSync(tmp, elf, { mode: 0o755 });
169
- try { await testRun(tmp); } catch (e) { fs.rmSync(tmp, { force: true }); throw e; }
170
- fs.renameSync(tmp, binPath());
171
- const manifest = {
172
- version: meta.version, arch: process.arch, registry,
173
- sha256: crypto.createHash('sha256').update(elf).digest('hex'),
174
- installedAt: new Date().toISOString(),
175
- };
176
- fs.writeFileSync(manifestPath(), JSON.stringify(manifest, null, 2), { mode: 0o600 });
177
- logger.info('UMID', '设备身份组件已安装:qodercli {version} / {arch}', { version: meta.version, arch: process.arch });
178
- return { ...manifest, path: binPath() };
179
- } catch (e) {
180
- errors.push(`${registry}:${e.message}`);
181
- logger.warn('UMID', '从 {registry} 安装失败:{err}', { registry, err: e.message });
182
- }
183
- }
184
- throw new Error('设备身份组件安装失败 —— ' + errors.join(';'));
185
- }
186
-
187
- export function removeUmid() {
188
- fs.rmSync(dir(), { recursive: true, force: true });
189
- }
190
-
191
- /** 面板 / 状态接口用的摘要 */
192
- export function umidInfo() {
193
- const m = installedUmid();
194
- return {
195
- supported: umidSupported(),
196
- installing: umidInstalling(),
197
- installed: m ? { version: m.version, arch: m.arch, installedAt: m.installedAt } : null,
198
- };
199
- }
1
+ /**
2
+ * Qoder 设备身份组件 —— 给没有 Qoder 客户端的 Linux(fnOS / NAS)提供国际版签到所需的风控身份。
3
+ *
4
+ * Qoder 国际版只向带 Cosy-MachineToken / Code / Type 的请求下发「每天领 100 Credits」,
5
+ * 这三个值由 Qoder 的 UMID 程序(runtime-info)生成。桌面端客户端自带它;官方 CLI
6
+ * @qoder-ai/qodercli 则把各平台的 UMID 二进制以 base64 内嵌在 bundle/qodercli.js 里,Linux x64 / arm64 都有。
7
+ *
8
+ * 这里在用户确认后从 npm 仓库下载官方 qodercli 包(校验 npm 的 sha512 integrity),
9
+ * 按本机 CPU 架构取出对应的 ELF,试跑一次确认能产出身份,再存到 ~/.creditdaddy/qoder-umid/。
10
+ * 不随 CreditDaddy 分发该二进制;调用方式与 qodercli 一致:runtime-info <env>,第一行输出 JSON。
11
+ * env:国际版 4(SINGAPORE,qodercli 的全球区取值),国内版 0(ONLINE)。
12
+ */
13
+
14
+ import fs from 'node:fs';
15
+ import path from 'node:path';
16
+ import crypto from 'node:crypto';
17
+ import zlib from 'node:zlib';
18
+ import { execFile } from 'node:child_process';
19
+ import { dataDir } from './store.js';
20
+ import { logger } from './logger.js';
21
+ import { t } from './i18n.js';
22
+
23
+ const PKG = '@qoder-ai/qodercli';
24
+ const REGISTRIES = ['https://registry.npmmirror.com', 'https://registry.npmjs.org'];
25
+ const AUTH_REGISTRY = 'https://registry.npmjs.org'; // integrity 的权威来源(镜像只用于加速下载)
26
+ const ELF_MACHINE = { x64: 62, arm64: 183 };
27
+ const BUNDLE_ENTRY = 'package/bundle/qodercli.js';
28
+ const FETCH_TIMEOUT_MS = 180_000;
29
+ const META_TIMEOUT_MS = 15_000;
30
+ export const CLI_RISK_ENV = { qoder: 4, 'qoder-cn': 0 };
31
+
32
+ export function umidSupported(platform = process.platform, arch = process.arch) {
33
+ return platform === 'linux' && Boolean(ELF_MACHINE[arch]);
34
+ }
35
+
36
+ const dir = () => path.join(dataDir(), 'qoder-umid');
37
+ const binPath = () => path.join(dir(), 'runtime-info');
38
+ const manifestPath = () => path.join(dir(), 'manifest.json');
39
+
40
+ /** 已安装的组件:{ path, version, arch, sha256, installedAt, registry };未安装返回 null */
41
+ export function installedUmid() {
42
+ if (!umidSupported()) return null;
43
+ try {
44
+ const m = JSON.parse(fs.readFileSync(manifestPath(), 'utf8'));
45
+ if (!fs.existsSync(binPath()) || m.arch !== process.arch) return null;
46
+ return { ...m, path: binPath() };
47
+ } catch { return null; }
48
+ }
49
+
50
+ // ── 纯函数(便于单测) ──
51
+
52
+ /** 最小 tar 解析:按名字取一个普通文件的内容 */
53
+ export function tarEntry(tar, wanted) {
54
+ let off = 0;
55
+ const cstr = (b, s, n) => { const x = b.subarray(s, s + n); const z = x.indexOf(0); return x.subarray(0, z < 0 ? n : z).toString('utf8'); };
56
+ let longName = null;
57
+ while (off + 512 <= tar.length) {
58
+ const h = tar.subarray(off, off + 512);
59
+ if (h.every((b) => b === 0)) break;
60
+ const size = parseInt(cstr(h, 124, 12).trim() || '0', 8);
61
+ const type = String.fromCharCode(h[156] || 48);
62
+ const prefix = cstr(h, 345, 155);
63
+ let name = longName || (prefix ? prefix + '/' : '') + cstr(h, 0, 100);
64
+ longName = null;
65
+ const body = tar.subarray(off + 512, off + 512 + size);
66
+ off += 512 + Math.ceil(size / 512) * 512;
67
+ if (type === 'L') { longName = body.toString('utf8').replace(/\0+$/, ''); continue; }
68
+ if (type === 'x') { // pax 扩展头里的 path 覆盖下一个条目的名字
69
+ const m = /\d+ path=([^\n]+)\n/.exec(body.toString('utf8'));
70
+ if (m) longName = m[1];
71
+ continue;
72
+ }
73
+ if ((type === '0' || type === '\0') && name === wanted) return body;
74
+ }
75
+ return null;
76
+ }
77
+
78
+ /** 在 qodercli bundle 文本里找内嵌的 ELF(base64 字面量),按 e_machine 挑出本机架构 */
79
+ export function extractElf(jsText, machine) {
80
+ const MARK = '"f0VMRgIB'; // "\x7fELF" + 64 位 + 小端 的 base64 开头
81
+ let i = jsText.indexOf(MARK);
82
+ while (i >= 0) {
83
+ const start = i + 1;
84
+ const end = jsText.indexOf('"', start);
85
+ if (end < 0) break;
86
+ const head = Buffer.from(jsText.slice(start, start + 28), 'base64');
87
+ if (head.length >= 20 && head.readUInt16LE(18) === machine) {
88
+ return Buffer.from(jsText.slice(start, end), 'base64');
89
+ }
90
+ i = jsText.indexOf(MARK, end);
91
+ }
92
+ return null;
93
+ }
94
+
95
+ /** npm integrity(sha512-<base64>)校验 */
96
+ export function checkIntegrity(buf, integrity) {
97
+ const m = /^sha512-(.+)$/.exec(String(integrity || '').split(/\s+/)[0]);
98
+ if (!m) return false;
99
+ return crypto.createHash('sha512').update(buf).digest('base64') === m[1];
100
+ }
101
+
102
+ // ── 安装 ──
103
+
104
+ async function fetchBuf(url, timeoutMs = FETCH_TIMEOUT_MS) {
105
+ const res = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
106
+ if (!res.ok) throw new Error(`HTTP ${res.status}:${url}`);
107
+ return Buffer.from(await res.arrayBuffer());
108
+ }
109
+
110
+ /**
111
+ * 从 npmjs 拉权威 integrity。镜像(npmmirror)的元数据与 tarball 同源,
112
+ * 镜像被污染时它自己的 integrity 校验形同虚设,所以校验值以 npmjs 为准;
113
+ * npmjs 不可达时返回 null,退回镜像自身 integrity(与旧行为一致)。
114
+ */
115
+ async function authoritativeIntegrity() {
116
+ try {
117
+ const meta = JSON.parse((await fetchBuf(`${AUTH_REGISTRY}/${PKG.replace('/', '%2f')}/latest`, META_TIMEOUT_MS)).toString('utf8'));
118
+ if (meta?.dist?.integrity && meta?.version) return { integrity: meta.dist.integrity, version: meta.version };
119
+ } catch {}
120
+ return null;
121
+ }
122
+
123
+ function testRun(file) {
124
+ return new Promise((resolve, reject) => {
125
+ execFile(file, [String(CLI_RISK_ENV.qoder)], { timeout: 30_000, maxBuffer: 1 << 20 }, (err, stdout) => {
126
+ try {
127
+ const j = JSON.parse(String(stdout).split('\n')[0]);
128
+ if (typeof j.machineToken === 'string' && j.machineToken && j.machineCode && j.machineType) return resolve(j);
129
+ } catch {}
130
+ reject(new Error('组件试运行失败' + (err ? ':' + err.message : '(输出里没有设备身份)')));
131
+ });
132
+ });
133
+ }
134
+
135
+ let installing = null;
136
+
137
+ /** 下载官方 qodercli 包并提取本机架构的 UMID;并发调用共用同一次安装 */
138
+ export function installUmid() {
139
+ if (!installing) installing = doInstall().finally(() => { installing = null; });
140
+ return installing;
141
+ }
142
+ export const umidInstalling = () => Boolean(installing);
143
+
144
+ async function doInstall() {
145
+ if (!umidSupported()) throw new Error(`当前平台(${process.platform}/${process.arch})不需要或不支持该组件`);
146
+ const authority = await authoritativeIntegrity();
147
+ const errors = [];
148
+ for (const registry of REGISTRIES) {
149
+ try {
150
+ const meta = JSON.parse((await fetchBuf(`${registry}/${PKG.replace('/', '%2f')}/latest`, META_TIMEOUT_MS)).toString('utf8'));
151
+ const { tarball, integrity } = meta.dist || {};
152
+ if (!tarball || !integrity) throw new Error('包元数据缺少 tarball / integrity');
153
+ // 镜像版本与 npmjs 不一致时没有权威校验值可比,跳过镜像直接用官方源
154
+ if (authority && registry !== AUTH_REGISTRY && meta.version !== authority.version) {
155
+ throw new Error(`镜像版本(${meta.version})与 npmjs(${authority.version})不一致`);
156
+ }
157
+ const expected = authority && authority.version === meta.version ? authority.integrity : integrity;
158
+ logger.info('UMID', '下载 {pkg}@{version}({registry})', { pkg: PKG, version: meta.version, registry });
159
+ const tgz = await fetchBuf(tarball);
160
+ if (!checkIntegrity(tgz, expected)) throw new Error('下载内容与 npm integrity 不一致');
161
+ const bundle = tarEntry(zlib.gunzipSync(tgz), BUNDLE_ENTRY);
162
+ if (!bundle) throw new Error(`包里没有 ${BUNDLE_ENTRY}(qodercli 结构可能变化)`);
163
+ const elf = extractElf(bundle.toString('latin1'), ELF_MACHINE[process.arch]);
164
+ if (!elf) throw new Error(`qodercli ${meta.version} 里没有 ${process.arch} 的 UMID 程序(结构可能变化)`);
165
+
166
+ fs.mkdirSync(dir(), { recursive: true, mode: 0o700 });
167
+ const tmp = binPath() + '.' + process.pid + '.tmp';
168
+ fs.writeFileSync(tmp, elf, { mode: 0o755 });
169
+ try { await testRun(tmp); } catch (e) { fs.rmSync(tmp, { force: true }); throw e; }
170
+ fs.renameSync(tmp, binPath());
171
+ const manifest = {
172
+ version: meta.version, arch: process.arch, registry,
173
+ sha256: crypto.createHash('sha256').update(elf).digest('hex'),
174
+ installedAt: new Date().toISOString(),
175
+ };
176
+ fs.writeFileSync(manifestPath(), JSON.stringify(manifest, null, 2), { mode: 0o600 });
177
+ logger.info('UMID', '设备身份组件已安装:qodercli {version} / {arch}', { version: meta.version, arch: process.arch });
178
+ return { ...manifest, path: binPath() };
179
+ } catch (e) {
180
+ errors.push(`${registry}:${e.message}`);
181
+ logger.warn('UMID', '从 {registry} 安装失败:{err}', { registry, err: e.message });
182
+ }
183
+ }
184
+ throw new Error('设备身份组件安装失败 —— ' + errors.join(';'));
185
+ }
186
+
187
+ export function removeUmid() {
188
+ fs.rmSync(dir(), { recursive: true, force: true });
189
+ }
190
+
191
+ /** 面板 / 状态接口用的摘要 */
192
+ export function umidInfo() {
193
+ const m = installedUmid();
194
+ return {
195
+ supported: umidSupported(),
196
+ installing: umidInstalling(),
197
+ installed: m ? { version: m.version, arch: m.arch, installedAt: m.installedAt } : null,
198
+ };
199
+ }
@@ -1,119 +1,119 @@
1
- /**
2
- * 10Router 外配额卡「刷新配额」回调(CD 侧接口):
3
- * 10R 外配额卡的刷新按钮拿到载荷里的 refreshUrl → POST 回 CD → CD 现拉该 source 的
4
- * 最新余额并推卡(runQuotaPush 只推这一路)→ 10R 重读快照,卡片即显新数字。
5
- *
6
- * 安全模型(延续「推载荷只带标量、凭据材料禁止入载荷」):
7
- * - refreshUrl 里**没有裸令牌**——`sig = HMAC-SHA256(quotaRefreshToken, "v1\n<source>\n<exp>")`,
8
- * 密钥只存本机 settings.json(0600),永不出仓;载荷里只有 source / exp / sig 三个标量。
9
- * - 签名时效 8 天(> 10R 快照 TTL 7 天),每轮推送滚动换新;过期 = 卡片先旧后失效,重推即恢复。
10
- * - 触发接口本身只做「拉数字 → 推给**你自己配置的** 10Router」,响应不含任何账号数据。
11
- * - 限流 20 次/分/IP,防 LAN 熊孩子拿它当上游 API 打点器。
12
- */
13
-
14
- import crypto from 'node:crypto';
15
- import os from 'node:os';
16
- import { withSettings } from './store.js';
17
- import { readRuntime } from './bgdaemon.js';
18
- import { logger } from './logger.js';
19
-
20
- const SIGN_TTL_SEC = 8 * 24 * 3600; // 8 天(覆盖 10R 快照 7 天 TTL,推送节奏内滚动续签)
21
- const DEFAULT_PORT = 47860;
22
-
23
- /** 本机签名密钥:settings.quotaRefreshToken,缺失时随机生成并落盘(0600 数据目录) */
24
- export async function ensureQuotaRefreshToken() {
25
- return withSettings((s) => {
26
- if (!s.quotaRefreshToken || typeof s.quotaRefreshToken !== 'string' || s.quotaRefreshToken.length < 20) {
27
- s.quotaRefreshToken = crypto.randomBytes(24).toString('hex');
28
- }
29
- return s.quotaRefreshToken;
30
- });
31
- }
32
-
33
- /** 面板/回调可达基址:settings.quotaRefreshBase 可覆盖;默认按运行态 host:port 推导 */
34
- export function quotaRefreshBase() {
35
- const rec = readRuntime() || {};
36
- const port = Number(rec.port) || DEFAULT_PORT;
37
- let host = String(rec.host || '127.0.0.1');
38
- if (host === '0.0.0.0' || host === '::') {
39
- host = firstLanIPv4() || '127.0.0.1';
40
- }
41
- return { host, port, derived: `http://${host.includes(':') ? `[${host}]` : host}:${port}` };
42
- }
43
-
44
- function firstLanIPv4() {
45
- try {
46
- for (const list of Object.values(os.networkInterfaces())) {
47
- for (const it of list || []) {
48
- if (it && it.family === 'IPv4' && !it.internal && it.address) return it.address;
49
- }
50
- }
51
- } catch {}
52
- return null;
53
- }
54
-
55
- async function sign(source, expSec) {
56
- const token = await ensureQuotaRefreshToken();
57
- return crypto.createHmac('sha256', token).update(`v1\n${source}\n${expSec}`).digest('hex');
58
- }
59
-
60
- /**
61
- * 为某个 source 生成 refreshUrl(每轮推送调用,签名滚动续期)。
62
- * @param {string} source 外配额 source(xiaomi-mimo-… / river-… / modelscope-… / tokenharbor)
63
- * @param {{base?: string, nowMs?: number}} opts base 覆盖基址(测试注入)
64
- */
65
- export async function quotaRefreshUrl(source, { base, nowMs } = {}) {
66
- if (!source) return undefined;
67
- const b = base || (await loadBaseFromSettings());
68
- const expSec = Math.floor((nowMs ?? Date.now()) / 1000) + SIGN_TTL_SEC;
69
- const sig = await sign(source, expSec);
70
- return `${b}/api/quota-refresh?source=${encodeURIComponent(source)}&exp=${expSec}&sig=${sig}`;
71
- }
72
-
73
- async function loadBaseFromSettings() {
74
- // settings.quotaRefreshBase 优先(反代 / 多网卡场景手填),否则按运行态推导
75
- const { loadSettings } = await import('./store.js');
76
- const s = await loadSettings().catch(() => ({}));
77
- const custom = String(s.quotaRefreshBase || '').trim().replace(/\/+$/, '');
78
- return custom || quotaRefreshBase().derived;
79
- }
80
-
81
- /**
82
- * 校验签名(时序安全比较)。source/exp/sig 全部来自查询串,缺一即拒。
83
- * @returns {Promise<{ok: boolean, reason?: 'expired'|'bad-sig'|'bad-params'}>}
84
- */
85
- export async function verifyQuotaRefresh({ source, exp, sig }, { nowMs } = {}) {
86
- const src = String(source || '');
87
- const expSec = Number(exp);
88
- const given = String(sig || '');
89
- if (!src || !Number.isFinite(expSec) || !/^[0-9a-f]{32,128}$/i.test(given)) {
90
- return { ok: false, reason: 'bad-params' };
91
- }
92
- const nowSec = Math.floor((nowMs ?? Date.now()) / 1000);
93
- if (expSec < nowSec) return { ok: false, reason: 'expired' };
94
- // 给未来时间戳留 1 天容差(防时钟偏移),但不允许远期签名常驻
95
- if (expSec > nowSec + SIGN_TTL_SEC + 86_400) return { ok: false, reason: 'bad-params' };
96
- const expected = await sign(src, expSec);
97
- const a = Buffer.from(given.toLowerCase(), 'utf8');
98
- const b = Buffer.from(expected, 'utf8');
99
- return { ok: a.length === b.length && crypto.timingSafeEqual(a, b), reason: a.length === b.length ? undefined : 'bad-sig' };
100
- }
101
-
102
- /** 单 IP 滑动窗口限流(进程内,重启归零):默认 20 次/分钟 */
103
- const hits = new Map(); // ip → number[]
104
- export function refreshRateLimited(ip, { limit = 20, windowMs = 60_000, nowMs } = {}) {
105
- const now = nowMs ?? Date.now();
106
- // 顺手清掉整个窗口都没动静的来源:公网/网段扫描器每个 IP 都会占一条,永不回收
107
- for (const [k, v] of hits) {
108
- const last = v.length ? v[v.length - 1] : 0;
109
- if (now - last >= windowMs) hits.delete(k);
110
- }
111
- const arr = (hits.get(ip) || []).filter((t) => now - t < windowMs);
112
- arr.push(now);
113
- hits.set(ip, arr);
114
- return arr.length > limit;
115
- }
116
-
117
- export function logRefresh(source) {
118
- logger.info('10R', '外配额卡刷新回调触发({source})——现拉并推卡', { source });
119
- }
1
+ /**
2
+ * 10Router 外配额卡「刷新配额」回调(CD 侧接口):
3
+ * 10R 外配额卡的刷新按钮拿到载荷里的 refreshUrl → POST 回 CD → CD 现拉该 source 的
4
+ * 最新余额并推卡(runQuotaPush 只推这一路)→ 10R 重读快照,卡片即显新数字。
5
+ *
6
+ * 安全模型(延续「推载荷只带标量、凭据材料禁止入载荷」):
7
+ * - refreshUrl 里**没有裸令牌**——`sig = HMAC-SHA256(quotaRefreshToken, "v1\n<source>\n<exp>")`,
8
+ * 密钥只存本机 settings.json(0600),永不出仓;载荷里只有 source / exp / sig 三个标量。
9
+ * - 签名时效 8 天(> 10R 快照 TTL 7 天),每轮推送滚动换新;过期 = 卡片先旧后失效,重推即恢复。
10
+ * - 触发接口本身只做「拉数字 → 推给**你自己配置的** 10Router」,响应不含任何账号数据。
11
+ * - 限流 20 次/分/IP,防 LAN 熊孩子拿它当上游 API 打点器。
12
+ */
13
+
14
+ import crypto from 'node:crypto';
15
+ import os from 'node:os';
16
+ import { withSettings } from './store.js';
17
+ import { readRuntime } from './bgdaemon.js';
18
+ import { logger } from './logger.js';
19
+
20
+ const SIGN_TTL_SEC = 8 * 24 * 3600; // 8 天(覆盖 10R 快照 7 天 TTL,推送节奏内滚动续签)
21
+ const DEFAULT_PORT = 47860;
22
+
23
+ /** 本机签名密钥:settings.quotaRefreshToken,缺失时随机生成并落盘(0600 数据目录) */
24
+ export async function ensureQuotaRefreshToken() {
25
+ return withSettings((s) => {
26
+ if (!s.quotaRefreshToken || typeof s.quotaRefreshToken !== 'string' || s.quotaRefreshToken.length < 20) {
27
+ s.quotaRefreshToken = crypto.randomBytes(24).toString('hex');
28
+ }
29
+ return s.quotaRefreshToken;
30
+ });
31
+ }
32
+
33
+ /** 面板/回调可达基址:settings.quotaRefreshBase 可覆盖;默认按运行态 host:port 推导 */
34
+ export function quotaRefreshBase() {
35
+ const rec = readRuntime() || {};
36
+ const port = Number(rec.port) || DEFAULT_PORT;
37
+ let host = String(rec.host || '127.0.0.1');
38
+ if (host === '0.0.0.0' || host === '::') {
39
+ host = firstLanIPv4() || '127.0.0.1';
40
+ }
41
+ return { host, port, derived: `http://${host.includes(':') ? `[${host}]` : host}:${port}` };
42
+ }
43
+
44
+ function firstLanIPv4() {
45
+ try {
46
+ for (const list of Object.values(os.networkInterfaces())) {
47
+ for (const it of list || []) {
48
+ if (it && it.family === 'IPv4' && !it.internal && it.address) return it.address;
49
+ }
50
+ }
51
+ } catch {}
52
+ return null;
53
+ }
54
+
55
+ async function sign(source, expSec) {
56
+ const token = await ensureQuotaRefreshToken();
57
+ return crypto.createHmac('sha256', token).update(`v1\n${source}\n${expSec}`).digest('hex');
58
+ }
59
+
60
+ /**
61
+ * 为某个 source 生成 refreshUrl(每轮推送调用,签名滚动续期)。
62
+ * @param {string} source 外配额 source(xiaomi-mimo-… / river-… / modelscope-… / tokenharbor)
63
+ * @param {{base?: string, nowMs?: number}} opts base 覆盖基址(测试注入)
64
+ */
65
+ export async function quotaRefreshUrl(source, { base, nowMs } = {}) {
66
+ if (!source) return undefined;
67
+ const b = base || (await loadBaseFromSettings());
68
+ const expSec = Math.floor((nowMs ?? Date.now()) / 1000) + SIGN_TTL_SEC;
69
+ const sig = await sign(source, expSec);
70
+ return `${b}/api/quota-refresh?source=${encodeURIComponent(source)}&exp=${expSec}&sig=${sig}`;
71
+ }
72
+
73
+ async function loadBaseFromSettings() {
74
+ // settings.quotaRefreshBase 优先(反代 / 多网卡场景手填),否则按运行态推导
75
+ const { loadSettings } = await import('./store.js');
76
+ const s = await loadSettings().catch(() => ({}));
77
+ const custom = String(s.quotaRefreshBase || '').trim().replace(/\/+$/, '');
78
+ return custom || quotaRefreshBase().derived;
79
+ }
80
+
81
+ /**
82
+ * 校验签名(时序安全比较)。source/exp/sig 全部来自查询串,缺一即拒。
83
+ * @returns {Promise<{ok: boolean, reason?: 'expired'|'bad-sig'|'bad-params'}>}
84
+ */
85
+ export async function verifyQuotaRefresh({ source, exp, sig }, { nowMs } = {}) {
86
+ const src = String(source || '');
87
+ const expSec = Number(exp);
88
+ const given = String(sig || '');
89
+ if (!src || !Number.isFinite(expSec) || !/^[0-9a-f]{32,128}$/i.test(given)) {
90
+ return { ok: false, reason: 'bad-params' };
91
+ }
92
+ const nowSec = Math.floor((nowMs ?? Date.now()) / 1000);
93
+ if (expSec < nowSec) return { ok: false, reason: 'expired' };
94
+ // 给未来时间戳留 1 天容差(防时钟偏移),但不允许远期签名常驻
95
+ if (expSec > nowSec + SIGN_TTL_SEC + 86_400) return { ok: false, reason: 'bad-params' };
96
+ const expected = await sign(src, expSec);
97
+ const a = Buffer.from(given.toLowerCase(), 'utf8');
98
+ const b = Buffer.from(expected, 'utf8');
99
+ return { ok: a.length === b.length && crypto.timingSafeEqual(a, b), reason: a.length === b.length ? undefined : 'bad-sig' };
100
+ }
101
+
102
+ /** 单 IP 滑动窗口限流(进程内,重启归零):默认 20 次/分钟 */
103
+ const hits = new Map(); // ip → number[]
104
+ export function refreshRateLimited(ip, { limit = 20, windowMs = 60_000, nowMs } = {}) {
105
+ const now = nowMs ?? Date.now();
106
+ // 顺手清掉整个窗口都没动静的来源:公网/网段扫描器每个 IP 都会占一条,永不回收
107
+ for (const [k, v] of hits) {
108
+ const last = v.length ? v[v.length - 1] : 0;
109
+ if (now - last >= windowMs) hits.delete(k);
110
+ }
111
+ const arr = (hits.get(ip) || []).filter((t) => now - t < windowMs);
112
+ arr.push(now);
113
+ hits.set(ip, arr);
114
+ return arr.length > limit;
115
+ }
116
+
117
+ export function logRefresh(source) {
118
+ logger.info('10R', '外配额卡刷新回调触发({source})——现拉并推卡', { source });
119
+ }