creditdaddy 1.8.2 → 1.8.3

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.
@@ -0,0 +1,276 @@
1
+ /**
2
+ * Croli(croli.net,Clerk 账号体系)每日签到 + 积分余额抓取。
3
+ *
4
+ * 接口(2026-11-20 桌面客户端 app.asar bundle 与本机实测,协议沉淀见
5
+ * 记忆 croli-protocol-reverse.md):
6
+ * GET https://ds.croli.net/credits/v1/ops/home
7
+ * 任务中心全量 → { enabled, serverTime, programs: [{ id, key, name,
8
+ * status, tasks: [{ id, key, eventKey, periodUnit, periodKey, progress,
9
+ * target, status, claimMode, milestones: [{index,credits,status}],
10
+ * streak: {current,longest,nextBonusAt,nextBonusCredits} }] }] }
11
+ * POST https://ds.croli.net/credits/v1/ops/checkin { taskId }
12
+ * → { alreadyCheckedIn, creditsAwarded, streak, nextResetAt }
13
+ * GET https://ds.croli.net/credits/v1/account/balance
14
+ * → { balance, trial: { active, dailyLimitCredits, usedCredits,
15
+ * remainingCredits, remainingResets, nextResetAt, endsAt } }
16
+ * GET https://ds.croli.net/credits/v1/account/ledger?limit&before
17
+ * → 积分流水(reason: signup_bonus / daily_checkin / ops_task_reward /
18
+ * invite_reward / client_login_bonus …)
19
+ * POST https://ds.croli.net/credits/v1/invite/code { rotate:false }
20
+ * → { inviteCode, inviterRewardCredits, inviteeRewardCredits }
21
+ *
22
+ * 凭据 = Clerk access token(JWT,iss https://clerk.croli.net,24h 短命),
23
+ * 本机来源两选一:
24
+ * 1. 桌面客户端 %APPDATA%\Croli\auth.json(access_token/refresh_token/expires_at,
25
+ * sidecar croli-server.exe 用 refresh_token 自动轮换回写——token 随时新鲜,
26
+ * 本机导入即拿即用,与 DuMate 本地导入同思路)
27
+ * 2. CD 自造 OAuth PKCE 登录(croliAuth.js,协议同桌面端:
28
+ * clerk.croli.net/oauth/authorize + /oauth/token,loopback 回调)
29
+ *
30
+ * 会话失效统一 HTTP 401 {"code":"unauthenticated"};token 过期且无 refresh
31
+ * 凭据时按「凭据已失效,请重新登录/重新本机导入」处理,不重试、不猜。
32
+ *
33
+ * 首版边界:每日签到(ops/checkin,streak 信息带回)+ 余额展示(balance +
34
+ * trial 剩余);不推 10Router 外部配额卡(10R 无 croli 渠道口径)。
35
+ */
36
+
37
+ import { fetchJsonRace } from './zcodeClient.js';
38
+ import { FETCH_TIMEOUT_MS } from './constants.js';
39
+ import { t } from './i18n.js';
40
+
41
+ export const CROLI_CREDITS_BASE = 'https://ds.croli.net/credits';
42
+ export const CROLI_OPS_HOME_URL = `${CROLI_CREDITS_BASE}/v1/ops/home`;
43
+ export const CROLI_CHECKIN_URL = `${CROLI_CREDITS_BASE}/v1/ops/checkin`;
44
+ export const CROLI_BALANCE_URL = `${CROLI_CREDITS_BASE}/v1/account/balance`;
45
+ export const CROLI_INVITE_CODE_URL = `${CROLI_CREDITS_BASE}/v1/invite/code`;
46
+ export const CROLI_INVITE_REDEEM_URL = `${CROLI_CREDITS_BASE}/v1/invite/redeem`;
47
+
48
+ /** daily-checkin 任务的 key(taskId 服务端编号可能调整,按 key 找行再取 id) */
49
+ export const CROLI_CHECKIN_TASK_KEY = 'daily-checkin';
50
+
51
+ function croliHeaders(token, { json = false } = {}) {
52
+ const h = {
53
+ Authorization: `Bearer ${String(token || '').trim()}`,
54
+ Accept: 'application/json',
55
+ };
56
+ if (json) h['Content-Type'] = 'application/json';
57
+ return h;
58
+ }
59
+
60
+ function isAuthExpired(status, payload) {
61
+ if (status === 401 || status === 403) return true;
62
+ return payload?.code === 'unauthenticated';
63
+ }
64
+
65
+ /**
66
+ * 统一 GET/JSON。返回 { auth, ok, status, data, code }:
67
+ * auth=false = 凭据失效(401/403/unauthenticated),ok=false 其余失败。
68
+ */
69
+ async function croliRequest(url, token, { method = 'GET', body, fetchImpl } = {}) {
70
+ const doIt = fetchImpl || ((u, init) => fetchJsonRace(u, { ...init, timeoutMs: FETCH_TIMEOUT_MS }));
71
+ let res;
72
+ try {
73
+ res = await doIt(url, {
74
+ method,
75
+ headers: croliHeaders(token, { json: body !== undefined }),
76
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
77
+ });
78
+ } catch (e) {
79
+ return { auth: true, ok: false, status: 0, code: 'network', message: e?.message || String(e) };
80
+ }
81
+ const payload = await res.json().catch(() => null);
82
+ if (isAuthExpired(res.status, payload)) {
83
+ return { auth: false, ok: false, status: res.status, code: payload?.code || 'unauthenticated' };
84
+ }
85
+ if (res.status !== 200) {
86
+ return { auth: true, ok: false, status: res.status, code: payload?.code || `HTTP ${res.status}`, message: payload?.message };
87
+ }
88
+ return { auth: true, ok: true, status: 200, data: payload };
89
+ }
90
+
91
+ /** 任务中心全量(签到状态 / streak / 其它任务的 progress 都在这里) */
92
+ export async function fetchCroliOpsHome(token, { fetchImpl } = {}) {
93
+ return croliRequest(CROLI_OPS_HOME_URL, token, { fetchImpl });
94
+ }
95
+
96
+ /** 积分余额 + trial 免费额度 */
97
+ export async function fetchCroliBalance(token, { fetchImpl } = {}) {
98
+ return croliRequest(CROLI_BALANCE_URL, token, { fetchImpl });
99
+ }
100
+
101
+ /** 从 ops/home 里抽出 daily-checkin 任务行(找不到返回 null) */
102
+ export function croliCheckinTask(opsHome) {
103
+ for (const prog of opsHome?.programs || []) {
104
+ for (const task of prog.tasks || []) {
105
+ if (task.key === CROLI_CHECKIN_TASK_KEY || task.eventKey === CROLI_CHECKIN_TASK_KEY) return task;
106
+ }
107
+ }
108
+ return null;
109
+ }
110
+
111
+ /**
112
+ * 每日签到:先 ops/home 找 daily-checkin 任务(拿 taskId 与今日状态),
113
+ * 未完成才 POST ops/checkin。幂等:status=claimed 时直接 already。
114
+ */
115
+ export async function checkinCroli(account, ctx = {}) {
116
+ const token = account?.token;
117
+ if (!token) {
118
+ return { status: 'failed', authExpired: true, message: t('Croli 凭据缺失,请重新本机导入或浏览器登录') };
119
+ }
120
+ const fetchImpl = ctx?.fetchImpl;
121
+
122
+ const home = await fetchCroliOpsHome(token, { fetchImpl });
123
+ if (!home.auth) {
124
+ return { status: 'failed', authExpired: true, message: t('Croli 凭据已失效({code}),请重新本机导入或浏览器登录', { code: home.code || 'unauthenticated' }) };
125
+ }
126
+ if (!home.ok) {
127
+ return { status: 'failed', message: t('Croli 任务中心读取失败:{err}', { err: home.code || 'network' }) };
128
+ }
129
+ const task = croliCheckinTask(home.data);
130
+ if (!task) {
131
+ // 服务端没有 daily-checkin 任务(活动下线 / 结构变化)——如实报告,不猜 taskId
132
+ return { status: 'no-activity', message: t('任务中心无每日签到活动(可能已下线)') };
133
+ }
134
+
135
+ // 余额旁路(失败不影响领取结果)
136
+ let balanceAfter;
137
+ try {
138
+ const bal = await fetchCroliBalance(token, { fetchImpl });
139
+ if (bal.ok && Number.isFinite(bal.data?.balance)) balanceAfter = bal.data.balance;
140
+ } catch { /* 余额拿不到不阻断 */ }
141
+
142
+ if (task.status === 'claimed' || task.progress >= task.target) {
143
+ return { status: 'already', message: t('今日已签到'), ...(balanceAfter !== undefined ? { balanceAfter } : {}) };
144
+ }
145
+
146
+ try {
147
+ const r = await croliRequest(CROLI_CHECKIN_URL, token, { method: 'POST', body: { taskId: task.id }, fetchImpl });
148
+ if (!r.auth) {
149
+ return { status: 'failed', authExpired: true, message: t('Croli 凭据已失效({code}),请重新本机导入或浏览器登录', { code: r.code || 'unauthenticated' }) };
150
+ }
151
+ if (!r.ok) {
152
+ // 并发领取已被服务端记过 / 活动暂停:按服务端话术归类
153
+ const code = String(r.code || '');
154
+ if (/already|checked/i.test(code)) return { status: 'already', message: t('今日已签到') };
155
+ return { status: 'failed', message: t('Croli 签到失败:{err}', { err: code || 'network' }) };
156
+ }
157
+ const awarded = Number(r.data?.creditsAwarded) || 0;
158
+ const streak = r.data?.streak;
159
+ ctx?.log?.(t('Croli 签到成功'));
160
+ return {
161
+ status: 'checked-in',
162
+ message: awarded > 0 ? t('签到成功(+{n} 积分)', { n: awarded }) : t('签到成功'),
163
+ claimedAmount: awarded,
164
+ amount: awarded,
165
+ // streak.current 是**含本次**的连续天数(服务端口径,首次签到=1);CD 签到轮落库
166
+ // 时统一 +1(checkin.js 约定 productImpl 返回签到前口径)——这里回退 1 位对齐,
167
+ // 否则面板「连续 2 天」虚高(2026-11-20 用户实测首签即显示 2 天)
168
+ streakDays: Number.isFinite(Number(streak?.current)) ? Math.max(0, Number(streak.current) - 1) : undefined,
169
+ ...(balanceAfter !== undefined ? { balanceAfter } : {}),
170
+ };
171
+ } catch (e) {
172
+ return { status: 'failed', message: t('Croli 签到失败:{err}', { err: e?.message || 'network' }) };
173
+ }
174
+ }
175
+
176
+ /**
177
+ * 积分余额快照(额度卡口径):balance 为主,trial 每日免费额度并入提示行。
178
+ * parts:[积分余额] + [今日免费额度(剩余/上限)]。
179
+ */
180
+ export async function fetchCroliQuota(account, { fetchImpl } = {}) {
181
+ const token = account?.token;
182
+ if (!token) {
183
+ const err = new Error(t('Croli 凭据缺失,请重新本机导入或浏览器登录'));
184
+ err.auth = true;
185
+ throw err;
186
+ }
187
+ const bal = await fetchCroliBalance(token, { fetchImpl });
188
+ if (!bal.auth) {
189
+ const err = new Error(t('Croli 凭据已失效({code}),请重新本机导入或浏览器登录', { code: bal.code || 'unauthenticated' }));
190
+ err.auth = true;
191
+ throw err;
192
+ }
193
+ if (!bal.ok) {
194
+ throw new Error(t('Croli 余额读取失败:{err}', { err: bal.code || 'network' }));
195
+ }
196
+ const d = bal.data || {};
197
+ const balance = Number(d.balance) || 0;
198
+ const trial = d.trial || {};
199
+ const parts = [{ name: t('积分余额'), total: balance, used: 0, remaining: balance }];
200
+ if (trial.active && Number(trial.dailyLimitCredits) > 0) {
201
+ const limit = Number(trial.dailyLimitCredits);
202
+ const used = Number(trial.usedCredits) || 0;
203
+ parts.push({
204
+ name: t('今日免费额度'),
205
+ total: limit,
206
+ used,
207
+ remaining: Math.max(0, Number.isFinite(Number(trial.remainingCredits)) ? Number(trial.remainingCredits) : Math.max(0, limit - used)),
208
+ recurring: true,
209
+ expiresAt: trial.nextResetAt || undefined,
210
+ });
211
+ }
212
+ return {
213
+ unit: '积分',
214
+ total: parts.reduce((s, p) => s + p.total, 0),
215
+ used: parts.reduce((s, p) => s + p.used, 0),
216
+ remaining: parts.reduce((s, p) => s + p.remaining, 0),
217
+ parts,
218
+ exceeded: balance <= 0,
219
+ };
220
+ }
221
+
222
+ /** 身份验证(addAccount verify 调用):balance 200 即凭据有效;顺带带出 ops/home 里的账号线索 */
223
+ export async function verifyCroliAccount(account, { fetchImpl } = {}) {
224
+ const token = account?.token;
225
+ if (!token) return { auth: false, ok: false, error: t('缺少 Croli 凭据') };
226
+ const bal = await fetchCroliBalance(token, { fetchImpl });
227
+ if (!bal.auth) return { auth: false, ok: false, error: t('Croli 凭据已失效,请重新本机导入或浏览器登录') };
228
+ if (!bal.ok) return { auth: true, ok: false, error: bal.code || 'network' };
229
+ // uid:Clerk JWT 的 sub(user_…),归户稳定且不需要额外请求
230
+ let uid = null;
231
+ try {
232
+ const seg = String(token).split('.');
233
+ if (seg.length === 3) uid = JSON.parse(Buffer.from(seg[1], 'base64url').toString('utf8'))?.sub || null;
234
+ } catch { /* JWT 解析失败不阻断 */ }
235
+ return { auth: true, ok: true, uid, name: null };
236
+ }
237
+
238
+ /** uid 脱敏(user_3MMY… → use****5jz) */
239
+ export function maskCroliUserId(id) {
240
+ const s = String(id ?? '');
241
+ if (s.length >= 7) return s.slice(0, 3) + '****' + s.slice(-3);
242
+ if (s.length >= 4) return s.slice(0, 1) + '****' + s.slice(-1);
243
+ return '****';
244
+ }
245
+
246
+ /**
247
+ * 我的邀请码:POST /v1/invite/code {rotate:false}(实测 2026-11-20:
248
+ * → { inviteCode, inviterRewardCredits:2500, inviteeRewardCredits:3000 };
249
+ * rotate=true 会换新码(旧码作废),CD 一律 rotate:false 只读不轮换)
250
+ */
251
+ export async function fetchCroliMyInviteCode(token, { fetchImpl } = {}) {
252
+ if (!token) return { auth: true, ok: false, error: t('缺少 Croli 凭据') };
253
+ const r = await croliRequest(CROLI_INVITE_CODE_URL, token, { method: 'POST', body: { rotate: false }, fetchImpl });
254
+ if (!r.auth) return { auth: false, ok: false, error: t('Croli 凭据已失效,请重新本机导入或浏览器登录') };
255
+ if (!r.ok) return { auth: true, ok: false, error: r.code || 'network' };
256
+ return {
257
+ auth: true,
258
+ ok: true,
259
+ code: r.data?.inviteCode || null,
260
+ inviterRewardCredits: Number(r.data?.inviterRewardCredits) || null,
261
+ inviteeRewardCredits: Number(r.data?.inviteeRewardCredits) || null,
262
+ };
263
+ }
264
+
265
+ /** 兑换邀请码:POST /v1/invite/redeem {inviteCode, source}(好友安装并完成首个任务后双方得积分) */
266
+ export async function redeemCroliInviteCode(token, code, { fetchImpl } = {}) {
267
+ const clean = String(code || '').trim();
268
+ if (!clean) return { ok: false, error: t('邀请码不能为空') };
269
+ const r = await croliRequest(CROLI_INVITE_REDEEM_URL, token, { method: 'POST', body: { inviteCode: clean, source: 'task_center' }, fetchImpl });
270
+ if (!r.auth) return { ok: false, authExpired: true, error: t('Croli 凭据已失效,请重新本机导入或浏览器登录') };
271
+ if (!r.ok) {
272
+ // 服务端错误码(bundle 口径):已兑换过 / 码不存在 / 自己的码等——code 即话术
273
+ return { ok: false, error: r.code || 'network' };
274
+ }
275
+ return { ok: true, message: r.data?.message || '', result: r.data ?? null };
276
+ }
@@ -0,0 +1,249 @@
1
+ /**
2
+ * Croli 桌面客户端本机凭据读取与多账号切换。
3
+ *
4
+ * 凭据存储(Windows,2026-11-20 本机实测 v0.0.17):
5
+ * %APPDATA%\Croli\auth.json
6
+ * { access_token: <Clerk JWT>, refresh_token, expires_at: <epoch 秒> }
7
+ * ——明文 JSON,无加密壳(与 DuMate 的 AES-GCM 密钥罐不同),读即用。
8
+ * JWT claims:iss=https://clerk.croli.net,client_id=znV4SkcUsY1AektQ,
9
+ * scope=profile email offline_access,寿命 24h。
10
+ *
11
+ * 刷新:sidecar croli-server.exe 持有 refresh_token 自动轮换回写 auth.json
12
+ * (Clerk refresh token 是轮换制——每次刷新旧 rt 即作废)。所以:
13
+ * - 读:随时读都是 sidecar 刚回写的新鲜 token,本机导入零续期负担;
14
+ * - 切:必须沿用 Loomy/DuMate 硬切纪律——切前把 live 快照回写账号库(防丢号,
15
+ * daemon switch 路由已做),杀 Croli.exe + croli-server.exe → 原子写目标
16
+ * auth.json → 延时复核(防退出清理回写)→ 面板重开客户端。
17
+ * 注意:账号库存的 rt 是捕获时刻的快照,若客户端在库外又刷过,rt 可能已被
18
+ * 轮换作废——切换写入后复核 access_token 是否落地即可,凭据失效时提示用户
19
+ * 在客户端重新登录该账号后再次导入(与 Loomy 口径一致)。
20
+ *
21
+ * 安全纪律:token 只在本机进程内流转,不落日志、不出本机。
22
+ */
23
+
24
+ import fs from 'node:fs';
25
+ import os from 'node:os';
26
+ import path from 'node:path';
27
+ import crypto from 'node:crypto';
28
+ import { execFileSync } from 'node:child_process';
29
+ import { t } from './i18n.js';
30
+
31
+ const EXE_NAMES = ['Croli.exe', 'croli-server.exe', 'croli-cli.exe'];
32
+
33
+ /** %APPDATA%\Croli(客户端 userData 根,auth.json 所在) */
34
+ export function croliDataDir() {
35
+ if (process.env.CROLI_DATA_DIR) return process.env.CROLI_DATA_DIR;
36
+ if (process.platform !== 'win32') {
37
+ const cfg = process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config');
38
+ return path.join(cfg, 'Croli');
39
+ }
40
+ const appdata = process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming');
41
+ return path.join(appdata, 'Croli');
42
+ }
43
+
44
+ export function authFile() {
45
+ return path.join(croliDataDir(), 'auth.json');
46
+ }
47
+
48
+ function readJson(file) {
49
+ try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; }
50
+ }
51
+
52
+ /**
53
+ * 读取本机当前登录凭据 → { accessToken, refreshToken, expiresAt(ms), expired }
54
+ * 未登录 / 文件缺失返回 null。expires_at 是秒级 epoch。
55
+ */
56
+ export function readCroliCredential() {
57
+ const j = readJson(authFile());
58
+ if (!j?.access_token) return null;
59
+ const expSec = Number(j.expires_at) || 0;
60
+ return {
61
+ accessToken: String(j.access_token),
62
+ refreshToken: j.refresh_token ? String(j.refresh_token) : null,
63
+ expiresAt: expSec > 0 ? expSec * 1000 : null,
64
+ expired: expSec > 0 && expSec * 1000 < Date.now(),
65
+ };
66
+ }
67
+
68
+ /** Clerk JWT 的 sub(user_…)——归户 uid;解析失败返回 null */
69
+ export function croliSubOf(jwt) {
70
+ try {
71
+ const seg = String(jwt || '').split('.');
72
+ if (seg.length !== 3) return null;
73
+ return JSON.parse(Buffer.from(seg[1], 'base64url').toString('utf8'))?.sub || null;
74
+ } catch { return null; }
75
+ }
76
+
77
+ /**
78
+ * Clerk userinfo 拉取(/oauth/userinfo,Bearer JWT):
79
+ * → { sub, email, name, given_name, family_name, picture }
80
+ * 失败返回 null(调用方回退 uid 掩码命名,不阻断导入)。
81
+ */
82
+ export async function fetchCroliProfile(accessToken, { fetchImpl } = {}) {
83
+ const doIt = fetchImpl || fetch;
84
+ try {
85
+ const res = await doIt('https://clerk.croli.net/oauth/userinfo', {
86
+ headers: { Authorization: `Bearer ${String(accessToken || '')}`, Accept: 'application/json' },
87
+ signal: AbortSignal.timeout(12_000),
88
+ });
89
+ if (!res.ok) return null;
90
+ const j = await res.json().catch(() => null);
91
+ if (!j?.sub) return null;
92
+ return j;
93
+ } catch { return null; }
94
+ }
95
+
96
+ function procRunningCached(exeNames) {
97
+ // 轻量判定:tasklist 查主壳即可(croli-server 随壳起)
98
+ try {
99
+ const out = execFileSync('tasklist.exe', ['/FI', `IMAGENAME eq ${exeNames[0]}`, '/NH'],
100
+ { windowsHide: true, encoding: 'utf8', timeout: 8000 });
101
+ return out.toLowerCase().includes(exeNames[0].toLowerCase()) && !/no tasks|没有找到|没有任务/i.test(out);
102
+ } catch { return false; }
103
+ }
104
+
105
+ /** 客户端可执行文件候选路径(与 desktop/main.js open-croli-client 同口径) */
106
+ export function candidateClientPath() {
107
+ if (process.env.CROLI_CLIENT_PATH) return process.env.CROLI_CLIENT_PATH;
108
+ if (process.platform !== 'win32') return null;
109
+ const local = process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local');
110
+ const cands = [
111
+ path.join(local, 'Programs', 'Croli', 'Croli.exe'),
112
+ 'C:\\Program Files\\Croli\\Croli.exe',
113
+ 'C:\\Program Files (x86)\\Croli\\Croli.exe',
114
+ ];
115
+ for (const c of cands) {
116
+ try { if (fs.existsSync(c)) return c; } catch { /* 忽略不可读候选 */ }
117
+ }
118
+ return null;
119
+ }
120
+
121
+ /** 本机安装/登录态盘点(detect* 家族口径):installed / signedIn / running / expired */
122
+ export function detectCroli() {
123
+ const clientPath = candidateClientPath();
124
+ const cred = readCroliCredential();
125
+ return {
126
+ installed: Boolean(clientPath),
127
+ clientPath,
128
+ signedIn: Boolean(cred),
129
+ running: process.platform === 'win32' ? procRunningCached(EXE_NAMES) : false,
130
+ expired: cred ? cred.expired : false,
131
+ };
132
+ }
133
+
134
+ /** 本机当前登录 → CD 账号记录(本机导入线 liveToAccount 同构)。
135
+ * 命名:Clerk userinfo 的 name/email 优先(「Croli (师洋 余)」可辨识多号),
136
+ * userinfo 失败回退 sub 前 5 位掩码;归户恒用 sub。 */
137
+ export async function liveToAccount() {
138
+ const cred = readCroliCredential();
139
+ if (!cred) return null;
140
+ const uid = croliSubOf(cred.accessToken);
141
+ const profile = await fetchCroliProfile(cred.accessToken).catch(() => null);
142
+ const display = (profile?.name || profile?.email || '').trim() || null;
143
+ const masked = uid ? `${uid.slice(0, 5)}…` : null;
144
+ const name = display ? `Croli (${display})` : uid ? `Croli (${masked})` : 'Croli (本机)';
145
+ return {
146
+ provider: 'croli',
147
+ token: cred.accessToken,
148
+ refreshToken: cred.refreshToken,
149
+ uid,
150
+ name,
151
+ email: profile?.email || null,
152
+ expiresAt: cred.expiresAt ? new Date(cred.expiresAt).toISOString() : null,
153
+ source: 'local-app',
154
+ meta: {
155
+ croliAuthFile: authFile(),
156
+ displayName: display,
157
+ avatarUrl: profile?.picture || null,
158
+ capturedAt: new Date().toISOString(),
159
+ },
160
+ };
161
+ }
162
+
163
+ /* ───────────────────── 账号切换(写客户端凭据,Loomy/DuMate hardSwitch 同构) ─────────────────────
164
+ *
165
+ * Croli 启动路径:Electron 壳拉起 croli-server.exe(sidecar),sidecar 读
166
+ * %APPDATA%\Croli\auth.json 恢复登录并持有 refresh_token 自动轮换。CD 冷状态
167
+ * 重写 auth.json 即完成切换:杀壳与 sidecar → 原子写文件 → 延时复核(防退出
168
+ * 清理回写)→ 面板重开客户端。refresh_token 轮换制意味着写入的 rt 快照可能是
169
+ * 已轮换的旧值——sidecar 刷新失败时会退回登录态,凭据失效按客户端内重登处理。
170
+ */
171
+
172
+ const nap = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
173
+ const napAsync = (ms) => new Promise((r) => setTimeout(r, ms));
174
+
175
+ /** 杀客户端壳 + sidecar + CLI(切换期间它们缓存旧账号身份、可能回写凭据) */
176
+ export function terminateCroli({ timeoutMs = 8000 } = {}) {
177
+ if (process.platform !== 'win32') return { closed: false, supported: false };
178
+ const anyRunning = () => EXE_NAMES.some((exe) => {
179
+ try {
180
+ const out = execFileSync('tasklist.exe', ['/FI', `IMAGENAME eq ${exe}`, '/NH'],
181
+ { windowsHide: true, encoding: 'utf8', timeout: 8000 });
182
+ return out.toLowerCase().includes(exe.toLowerCase()) && !/no tasks|没有找到|没有任务/i.test(out);
183
+ } catch { return false; }
184
+ });
185
+ if (!anyRunning()) return { closed: false, running: false };
186
+ for (const exe of EXE_NAMES) {
187
+ try { execFileSync('taskkill.exe', ['/IM', exe, '/T', '/F'], { windowsHide: true, stdio: 'ignore', timeout: 15_000 }); } catch {}
188
+ }
189
+ let deadline = Date.now() + timeoutMs;
190
+ while (Date.now() < deadline && anyRunning()) nap(250);
191
+ return { closed: !anyRunning(), running: anyRunning() };
192
+ }
193
+
194
+ function writeAuthJson(next) {
195
+ const tmp = `${authFile()}.tmp-${crypto.randomUUID()}`;
196
+ fs.writeFileSync(tmp, JSON.stringify(next, null, 2) + '\n', 'utf8');
197
+ fs.renameSync(tmp, authFile());
198
+ }
199
+
200
+ /** 按 CD 账号匹配目标凭据:优先 meta.croliRefreshToken 全等,回落 uid(JWT sub)全等 */
201
+ function matchesTarget(account, cred) {
202
+ if (account?.meta?.croliRefreshToken && cred.refreshToken
203
+ && account.meta.croliRefreshToken === cred.refreshToken) return true;
204
+ const wantUid = account?.uid || croliSubOf(account?.token);
205
+ if (!wantUid) return false;
206
+ return croliSubOf(cred.accessToken) === wantUid;
207
+ }
208
+
209
+ /**
210
+ * 硬切换:杀客户端 + sidecar → 重写 auth.json → 延时复核。
211
+ * requireClient=false 仅供测试注入(非 Windows 验证写入/复核逻辑)。
212
+ */
213
+ export async function hardSwitchCroli(account, { requireClient = true } = {}) {
214
+ if (!account?.token) throw new Error(t('目标账号缺少 Croli 凭据'));
215
+ const current = readCroliCredential();
216
+ if (!current) {
217
+ const err = new Error(t('未读到 Croli 客户端凭据库(%APPDATA%\\Croli\\auth.json)——请先安装客户端并登录任一账号'));
218
+ err.croliNotInstalled = true;
219
+ throw err;
220
+ }
221
+ if (matchesTarget(account, current)) {
222
+ return { switched: false, alreadyActive: true, closedClient: false, verified: true };
223
+ }
224
+ if (requireClient && process.platform !== 'win32') {
225
+ const err = new Error(t('Croli 客户端仅支持 Windows,本平台无法切换'));
226
+ err.croliNotInstalled = true;
227
+ throw err;
228
+ }
229
+
230
+ const wasRunning = procRunningCached(EXE_NAMES);
231
+ const term = terminateCroli();
232
+ const closedClient = wasRunning && term.running === false;
233
+
234
+ // 客户端凭据形状就是 auth.json 三键——目标账号存的捕获快照原样写回
235
+ const next = {
236
+ access_token: account.token,
237
+ ...(account.refreshToken ? { refresh_token: account.refreshToken } : {}),
238
+ ...(account.expiresAt ? { expires_at: Math.floor(new Date(account.expiresAt).getTime() / 1000) } : {}),
239
+ };
240
+ writeAuthJson(next);
241
+ await napAsync(1200);
242
+ let verified = matchesTarget(account, readCroliCredential());
243
+ if (!verified) {
244
+ writeAuthJson(next);
245
+ await napAsync(1200);
246
+ verified = matchesTarget(account, readCroliCredential());
247
+ }
248
+ return { switched: true, alreadyActive: false, closedClient, verified };
249
+ }