creditdaddy 1.8.0 → 1.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/store.js CHANGED
@@ -41,6 +41,42 @@ const ACCOUNTS_FILE = () => path.join(dataDir(), 'accounts.json');
41
41
  const STATE_FILE = () => path.join(dataDir(), 'state.json');
42
42
  const SETTINGS_FILE = () => path.join(dataDir(), 'settings.json');
43
43
 
44
+ // ─── 账号凭据静态加密(纵深防御,2026-11-19 用户立项)───
45
+ // 形态:桌面壳启动时生成/恢复 32B 随机密钥(safeStorage/DPAPI 加密存 userData/secret.key,
46
+ // 明文只活在内存),经 setAccountsCipher() 注入本模块——壳与同进程 daemon 共享同一份模块
47
+ // 实例,写入方与读取方天然一致。CLI / NAS 后台实例没有密钥来源:读到密文信封按损坏处理
48
+ // 并明示(不静默清空),写侧保持明文(现状零回归)。
49
+ // 文件形状:明文 = JSON 数组(历史兼容);密文 = { v:1, enc:'aes-256-gcm', rows:[{iv,tag,data}] }。
50
+ // 临时文件 .tmp 与 .bak 随主文件同形态——密钥丢失 = 数据不可恢复,所以密钥文件不清理、
51
+ // 注入失败宁可拒绝写也不回退明文(回退 = 用户以为还加密着)。
52
+ const ENC_FORMAT = 1;
53
+ let accountsCipher = null; // { encrypt(plain)→cipher, decrypt(cipher)→plain } | null
54
+ export function setAccountsCipher(c) { accountsCipher = (c && typeof c.keyBytes === 'function') ? c : null; }
55
+ export function hasAccountsCipher() { return accountsCipher !== null; }
56
+
57
+ function sealAccounts(list) {
58
+ if (!accountsCipher) return JSON.stringify(list, null, 2);
59
+ const iv = crypto.randomBytes(12);
60
+ const cipher = crypto.createCipheriv('aes-256-gcm', accountsCipher.keyBytes(), iv);
61
+ const data = Buffer.concat([cipher.update(Buffer.from(JSON.stringify(list), 'utf8')), cipher.final()]);
62
+ return JSON.stringify({ v: ENC_FORMAT, enc: 'aes-256-gcm', rows: [{ iv: iv.toString('base64'), tag: cipher.getAuthTag().toString('base64'), data: data.toString('base64') }] });
63
+ }
64
+
65
+ function unsealAccounts(raw) {
66
+ const parsed = JSON.parse(raw);
67
+ if (Array.isArray(parsed)) return parsed; // 历史明文:直接用
68
+ if (parsed && parsed.enc === 'aes-256-gcm' && Array.isArray(parsed.rows)) {
69
+ if (!accountsCipher) throw new Error('accounts.json 是加密形态但本进程没有解密密钥(桌面壳未注入)——请用桌面版启动,或先备份 accounts.json 后联系支持');
70
+ const row = parsed.rows[0];
71
+ const decipher = crypto.createDecipheriv('aes-256-gcm', accountsCipher.keyBytes(), Buffer.from(row.iv, 'base64'));
72
+ decipher.setAuthTag(Buffer.from(row.tag, 'base64'));
73
+ const plain = Buffer.concat([decipher.update(Buffer.from(row.data, 'base64')), decipher.final()]).toString('utf8');
74
+ const list = JSON.parse(plain);
75
+ return Array.isArray(list) ? list : [];
76
+ }
77
+ throw new Error('accounts.json 形态无法识别(既非明文数组也非加密信封)');
78
+ }
79
+
44
80
  async function ensureDir() {
45
81
  await fs.mkdir(dataDir(), { recursive: true, mode: 0o700 });
46
82
  }
@@ -110,8 +146,25 @@ async function readJson(file, fallback) {
110
146
  // ─── 账号 ───
111
147
 
112
148
  export async function loadAccounts() {
113
- const list = await readJson(ACCOUNTS_FILE(), []);
114
- return Array.isArray(list) ? list : [];
149
+ // 密文信封不能走 readJson(会 JSON.parse 两次语义混淆):直接读原文,空/缺失回落 []
150
+ let raw = null;
151
+ try { raw = await fs.readFile(ACCOUNTS_FILE(), 'utf8'); } catch (e) {
152
+ if (e.code !== 'ENOENT') throw new Error(`读取 accounts.json 失败: ${e.message}`);
153
+ return [];
154
+ }
155
+ if (!raw || !raw.trim()) return [];
156
+ try {
157
+ const list = unsealAccounts(raw);
158
+ return Array.isArray(list) ? list : [];
159
+ } catch (e) {
160
+ // 主文件损坏/解密失败 → 试 .bak(同形态),都失败才抛
161
+ try {
162
+ const bakText = await fs.readFile(ACCOUNTS_FILE() + '.bak', 'utf8');
163
+ const list = unsealAccounts(bakText);
164
+ console.error('loadAccounts: 主文件损坏/解密失败,已用备份恢复 ' + ACCOUNTS_FILE() + '.bak');
165
+ return Array.isArray(list) ? list : [];
166
+ } catch { throw new Error(`读取 accounts.json 失败: ${e.message}`); }
167
+ }
115
168
  }
116
169
 
117
170
  export async function saveAccounts(accounts) {
@@ -119,13 +172,14 @@ export async function saveAccounts(accounts) {
119
172
  const file = ACCOUNTS_FILE();
120
173
  const bak = file + '.bak';
121
174
  try {
122
- // 只有当已有账号文件存在且非空时才建立/更新 .bak 备份
175
+ // 只有当已有账号文件存在且非空时才建立/更新 .bak 备份(形态随主文件——密文环境里
176
+ // 备份同样是密文,不因备份产生第二份明文)
123
177
  const existing = await fs.readFile(file, 'utf8').catch(() => null);
124
178
  if (existing && existing.trim().length > 2) {
125
179
  await atomicWrite(bak, existing);
126
180
  }
127
181
  } catch {}
128
- await atomicWrite(file, JSON.stringify(accounts, null, 2));
182
+ await atomicWrite(file, sealAccounts(accounts));
129
183
  }
130
184
 
131
185
  // 进程内串行队列:所有「读-改-写」都经由 withAccounts,避免并发请求互相覆盖
@@ -0,0 +1,199 @@
1
+ /**
2
+ * 开机自启(托盘菜单项)— 移植自 10Router cli/src/cli/tray/autostart.js(AGPL-3.0 同族)。
3
+ * Windows=启动目录 VBS(隐藏窗口直启 node);macOS=LaunchAgent plist;Linux=XDG autostart .desktop。
4
+ * 不依赖 npm bin -g(npm 9 已移除),cli.js 路径按 __dirname 反推。
5
+ */
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import os from 'node:os';
9
+ import { execSync } from 'node:child_process';
10
+
11
+ const APP_NAME = 'creditdaddy';
12
+ const APP_LABEL = 'com.creditdaddy.autostart';
13
+
14
+ /** 解析本包 cli.js 绝对路径:显式参数 → process.argv[1] → __dirname 反推(全局装布局无关) */
15
+ function getCliJsPath(cliPath) {
16
+ if (cliPath) {
17
+ const resolved = path.resolve(cliPath);
18
+ if (fs.existsSync(resolved)) return resolved;
19
+ }
20
+ if (process.argv[1]) {
21
+ const resolved = path.resolve(process.argv[1]);
22
+ if (path.basename(resolved) === 'creditdaddy.js' && fs.existsSync(resolved)) {
23
+ return resolved;
24
+ }
25
+ }
26
+ // autostart.js 在 <pkg>/src/tray/ 下,cli.js 在 <pkg>/bin/ 下
27
+ const computed = path.resolve(__dirname, '..', '..', 'bin', 'creditdaddy.js');
28
+ if (fs.existsSync(computed)) return computed;
29
+ return null;
30
+ }
31
+
32
+ function enableAutoStart(cliPath) {
33
+ const platform = process.platform;
34
+ if (!['darwin', 'win32', 'linux'].includes(platform)) return false;
35
+ if (platform === 'linux' && !process.env.DISPLAY) return false;
36
+ try {
37
+ if (platform === 'darwin') return enableMacOS(cliPath);
38
+ if (platform === 'win32') return enableWindows(cliPath);
39
+ if (platform === 'linux') return enableLinux(cliPath);
40
+ } catch (err) { /* 自启是可选能力,静默失败 */ }
41
+ return false;
42
+ }
43
+
44
+ function disableAutoStart() {
45
+ const platform = process.platform;
46
+ try {
47
+ if (platform === 'darwin') return disableMacOS();
48
+ if (platform === 'win32') return disableWindows();
49
+ if (platform === 'linux') return disableLinux();
50
+ } catch (e) {}
51
+ return false;
52
+ }
53
+
54
+ /** macOS 需 plist 文件 + launchd 注册同时在才如实报告(launchd 处于失败态时不撒谎) */
55
+ function isAutoStartEnabled() {
56
+ const platform = process.platform;
57
+ try {
58
+ if (platform === 'darwin') {
59
+ const plistPath = path.join(os.homedir(), 'Library', 'LaunchAgents', `${APP_LABEL}.plist`);
60
+ if (!fs.existsSync(plistPath)) return false;
61
+ try {
62
+ execSync(`launchctl list ${APP_LABEL}`, { stdio: ['ignore', 'ignore', 'ignore'], timeout: 3000 });
63
+ return true;
64
+ } catch (e) {
65
+ return false;
66
+ }
67
+ } else if (platform === 'win32') {
68
+ const startupPath = path.join(process.env.APPDATA || '', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup', `${APP_NAME}.vbs`);
69
+ return fs.existsSync(startupPath);
70
+ } else if (platform === 'linux') {
71
+ const desktopPath = path.join(os.homedir(), '.config', 'autostart', `${APP_NAME}.desktop`);
72
+ return fs.existsSync(desktopPath);
73
+ }
74
+ } catch (e) {}
75
+ return false;
76
+ }
77
+
78
+ /**
79
+ * 当前 Node 进程是否就是 launchd 管理的那个 agent 实例——
80
+ * `launchctl unload` 对 Aqua 域 agent 发 SIGTERM,若托盘点击者自己就是被管理的进程,
81
+ * unload 会杀掉执行点击的进程(图标消失而非菜单翻转)。enable/disable 侧避开。
82
+ */
83
+ function isAgentSelfMacOS() {
84
+ try {
85
+ const output = execSync(`launchctl list ${APP_LABEL}`, {
86
+ encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 3000,
87
+ });
88
+ const match = output.match(/"PID"\s*=\s*(\d+)/);
89
+ return !!(match && parseInt(match[1], 10) === process.pid);
90
+ } catch (e) {
91
+ return false;
92
+ }
93
+ }
94
+
95
+ function enableMacOS(cliPath) {
96
+ const launchAgentsDir = path.join(os.homedir(), 'Library', 'LaunchAgents');
97
+ const plistPath = path.join(launchAgentsDir, `${APP_LABEL}.plist`);
98
+ if (!fs.existsSync(launchAgentsDir)) {
99
+ fs.mkdirSync(launchAgentsDir, { recursive: true });
100
+ }
101
+ const nodePath = process.execPath;
102
+ const script = getCliJsPath(cliPath);
103
+ if (!script) return false;
104
+ // node + cli.js 直启(绝对路径、无 shell wrapper)——zsh -l 依赖用户 rc 文件,脆弱
105
+ const launchPath = `${path.dirname(nodePath)}:/usr/local/bin:/usr/bin:/bin`;
106
+ const plistContent = `<?xml version="1.0" encoding="UTF-8"?>
107
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
108
+ <plist version="1.0">
109
+ <dict>
110
+ <key>Label</key>
111
+ <string>${APP_LABEL}</string>
112
+ <key>ProgramArguments</key>
113
+ <array>
114
+ <string>${nodePath}</string>
115
+ <string>${script}</string>
116
+ <string>daemon</string>
117
+ <string>--tray</string>
118
+ </array>
119
+ <key>EnvironmentVariables</key>
120
+ <dict>
121
+ <key>PATH</key>
122
+ <string>${launchPath}</string>
123
+ </dict>
124
+ <key>RunAtLoad</key>
125
+ <true/>
126
+ <key>KeepAlive</key>
127
+ <false/>
128
+ <key>StandardOutPath</key>
129
+ <string>/tmp/creditdaddy.log</string>
130
+ <key>StandardErrorPath</key>
131
+ <string>/tmp/creditdaddy.error.log</string>
132
+ </dict>
133
+ </plist>`;
134
+ fs.writeFileSync(plistPath, plistContent);
135
+ if (isAgentSelfMacOS()) return true; // 不杀自己:plist 已更新,下次登录生效
136
+ try { execSync(`launchctl unload "${plistPath}"`, { stdio: 'ignore' }); } catch (e) {}
137
+ try { execSync(`launchctl load -w "${plistPath}"`, { stdio: 'ignore' }); } catch (e) {}
138
+ return true;
139
+ }
140
+
141
+ function disableMacOS() {
142
+ const plistPath = path.join(os.homedir(), 'Library', 'LaunchAgents', `${APP_LABEL}.plist`);
143
+ if (!isAgentSelfMacOS()) {
144
+ try { execSync(`launchctl unload "${plistPath}"`, { stdio: 'ignore' }); } catch (e) {}
145
+ }
146
+ if (fs.existsSync(plistPath)) fs.unlinkSync(plistPath);
147
+ return true;
148
+ }
149
+
150
+ function enableWindows(cliPath) {
151
+ const startupDir = path.join(process.env.APPDATA || '', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup');
152
+ const vbsPath = path.join(startupDir, `${APP_NAME}.vbs`);
153
+ if (!fs.existsSync(startupDir)) return false;
154
+ const nodePath = process.execPath;
155
+ const script = getCliJsPath(cliPath);
156
+ if (!script) return false;
157
+ // node + cli.js 直启、隐藏窗口(不绕 .cmd 查找——npm prefix 路径不可靠)
158
+ const vbsContent = `Set WshShell = CreateObject("WScript.Shell")
159
+ WshShell.Run """${nodePath}"" ""${script}"" daemon --tray", 0, False
160
+ `;
161
+ fs.writeFileSync(vbsPath, vbsContent);
162
+ return true;
163
+ }
164
+
165
+ function disableWindows() {
166
+ const vbsPath = path.join(process.env.APPDATA || '', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup', `${APP_NAME}.vbs`);
167
+ if (fs.existsSync(vbsPath)) fs.unlinkSync(vbsPath);
168
+ return true;
169
+ }
170
+
171
+ function enableLinux(cliPath) {
172
+ const autostartDir = path.join(os.homedir(), '.config', 'autostart');
173
+ const desktopPath = path.join(autostartDir, `${APP_NAME}.desktop`);
174
+ if (!fs.existsSync(autostartDir)) {
175
+ try { fs.mkdirSync(autostartDir, { recursive: true }); } catch (e) { return false; }
176
+ }
177
+ const nodePath = process.execPath;
178
+ const script = getCliJsPath(cliPath);
179
+ if (!script) return false;
180
+ const desktopContent = `[Desktop Entry]
181
+ Type=Application
182
+ Name=CreditDaddy
183
+ Comment=CreditDaddy daemon
184
+ Exec=${nodePath} ${script} daemon --tray
185
+ Hidden=false
186
+ NoDisplay=false
187
+ X-GNOME-Autostart-enabled=true
188
+ `;
189
+ fs.writeFileSync(desktopPath, desktopContent);
190
+ return true;
191
+ }
192
+
193
+ function disableLinux() {
194
+ const desktopPath = path.join(os.homedir(), '.config', 'autostart', `${APP_NAME}.desktop`);
195
+ if (fs.existsSync(desktopPath)) fs.unlinkSync(desktopPath);
196
+ return true;
197
+ }
198
+
199
+ export { enableAutoStart, disableAutoStart, isAutoStartEnabled };
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
@@ -0,0 +1,249 @@
1
+ /**
2
+ * CLI 托盘 — 移植自 10Router cli/src/cli/tray/tray.js(AGPL-3.0 同族,双向移植免许可记账)。
3
+ *
4
+ * Windows:PowerShell NotifyIcon(零二进制、杀软友好);macOS/Linux:懒装 systray2
5
+ * (装进用户数据目录 runtime/node_modules,npm 包本体不携带签名二进制——杀软误报防线,
6
+ * 见 trayRuntime.js)。菜单:打开面板 / 立即领取 / 开机自启开关 / 退出。
7
+ *
8
+ * CD 适配差异(对照 10R 原版):
9
+ * - 「立即领取」替代 10R 无此项:托盘直达 checkin-all(CD 的核心动作)
10
+ * - i18n 走 src/i18n.js 的 t()(面板四语词典同一出处),不单独建 tray.json
11
+ * - 面板地址 = daemon 实际绑定端口(daemon 起来后回填,端口冲突自动 +1 的口径一致)
12
+ */
13
+ import { exec } from 'node:child_process';
14
+ import { createRequire } from 'node:module';
15
+ const nodeRequire = createRequire(import.meta.url);
16
+ import fs from 'node:fs';
17
+ import path from 'node:path';
18
+
19
+ let trayInstance = null;
20
+ let isWinTray = false;
21
+
22
+ /** 托盘图标:单色模板图(macOS 菜单栏随明暗着色)→ 品牌 PNG 回落 */
23
+ function getIconBase64() {
24
+ const platform = process.platform;
25
+ const iconFile = platform === 'darwin' ? 'icon-template.png' : 'icon-brand.png';
26
+ try {
27
+ const iconPath = path.join(__dirname, iconFile);
28
+ if (fs.existsSync(iconPath)) {
29
+ return fs.readFileSync(iconPath).toString('base64');
30
+ }
31
+ } catch (e) {}
32
+ // 回落:1×1 透明 PNG(systray 无图不注册)
33
+ return 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAALEwAACxMBAJqcGAAAAHpJREFUOE9jYBgFgwEwMjIy/Gdg+P8fyP4PxP8ZGBgEcBnGyMjIsICBgSEAhyH/gfgBUNN8XJoZsdkCVL8Ah+b/QPwbqvkBMvk/AwMDAzYX/GdgYAhAN+A/SICRWAMYGfFEJSMjzriEiwDR/xmIa2RkZCSqnZERb3QCAAo3KxzxbKe1AAAAAElFTkSuQmCC';
34
+ }
35
+
36
+ function isTraySupported() {
37
+ const platform = process.platform;
38
+ if (!['darwin', 'win32', 'linux'].includes(platform)) return false;
39
+ if (platform === 'linux' && !process.env.DISPLAY) return false;
40
+ return true;
41
+ }
42
+
43
+ /**
44
+ * 初始化托盘。options: { port, onQuit, onOpenPanel, onClaimAll }
45
+ * daemon 未就绪时仍可先挂图标(端口回填靠 setTooltip/updateItem)。
46
+ */
47
+ function initTray(options) {
48
+ if (!isTraySupported()) return null;
49
+ if (process.platform === 'win32') return initWindowsTray(options);
50
+ return initUnixTray(options);
51
+ }
52
+
53
+ async function buildMenuItems(port, autostartEnabled) {
54
+ // i18n 延迟取——词典可能随面板切换语言,菜单项构建时取当前值
55
+ const { t } = await import('../i18n.js');
56
+ return [
57
+ { title: t('托盘:CreditDaddy(端口 {port})', { port: port || '…' }), tooltip: t('服务运行中'), enabled: false },
58
+ { title: t('打开面板'), tooltip: t('在浏览器中打开'), enabled: true },
59
+ { title: t('立即领取全部'), tooltip: t('对所有账号跑一轮签到与活动领取'), enabled: true },
60
+ { title: autostartEnabled ? t('✓ 已开启开机自启') : t('开启开机自启'), tooltip: t('系统启动时自动运行'), enabled: true },
61
+ { title: t('退出'), tooltip: t('停止守护进程并退出'), enabled: true },
62
+ ];
63
+ }
64
+
65
+ const MENU_INDEX = { STATUS: 0, PANEL: 1, CLAIM: 2, AUTOSTART: 3, QUIT: 4 };
66
+
67
+ async function getAutostartEnabled() {
68
+ try {
69
+ const { isAutoStartEnabled } = await import('./autostart.js');
70
+ return isAutoStartEnabled();
71
+ } catch (e) {
72
+ return false;
73
+ }
74
+ }
75
+
76
+ async function handleClick(index, options, onAutostartToggle) {
77
+ const { onQuit, onOpenPanel, onClaimAll, port } = options;
78
+ const { t } = await import('../i18n.js');
79
+ if (index === MENU_INDEX.PANEL) {
80
+ if (onOpenPanel) onOpenPanel();
81
+ else openBrowser(`http://127.0.0.1:${port || 47860}`);
82
+ } else if (index === MENU_INDEX.CLAIM) {
83
+ if (onClaimAll) onClaimAll();
84
+ } else if (index === MENU_INDEX.AUTOSTART) {
85
+ const enabled = getAutostartEnabled();
86
+ try {
87
+ const { enableAutoStart, disableAutoStart } = await import('./autostart.js');
88
+ if (enabled) disableAutoStart();
89
+ else enableAutoStart();
90
+ onAutostartToggle(!enabled);
91
+ } catch (e) {}
92
+ } else if (index === MENU_INDEX.QUIT) {
93
+ console.log(t('\n正在停止 CreditDaddy…'));
94
+ if (onQuit) onQuit();
95
+ killTray();
96
+ setTimeout(() => process.exit(0), 500);
97
+ }
98
+ }
99
+
100
+ async function initWindowsTray(options) {
101
+ try {
102
+ const { initWinTray, winTrayIconPath } = await import('./trayWin.js');
103
+ const { t } = await import('../i18n.js');
104
+ const iconPath = winTrayIconPath();
105
+ const autostartEnabled = await getAutostartEnabled();
106
+ const items = await buildMenuItems(options.port, autostartEnabled);
107
+ trayInstance = initWinTray({
108
+ iconPath,
109
+ tooltip: t('CreditDaddy - 端口 {port}', { port: options.port || '…' }),
110
+ items,
111
+ onClick: (index) => {
112
+ handleClick(index, options, async (newEnabled) => {
113
+ const { t: tt } = await import('../i18n.js');
114
+ trayInstance.updateItem(MENU_INDEX.AUTOSTART, newEnabled ? tt('✓ 已开启开机自启') : tt('开启开机自启'), true);
115
+ });
116
+ },
117
+ });
118
+ isWinTray = true;
119
+ return trayInstance;
120
+ } catch (err) {
121
+ return null;
122
+ }
123
+ }
124
+
125
+ /** macOS/Linux:懒装 systray2(trayRuntime 负责),装不上时托盘静默降级(无图标但 daemon 照常) */
126
+ async function resolveSystray() {
127
+ let runtimeDir = null;
128
+ try {
129
+ const { getRuntimeNodeModules } = await import('./trayRuntime.js');
130
+ runtimeDir = getRuntimeNodeModules();
131
+ } catch (e) {}
132
+ const candidates = [];
133
+ if (runtimeDir) {
134
+ candidates.push(path.join(runtimeDir, 'systray2'), path.join(runtimeDir, 'systray'));
135
+ }
136
+ candidates.push('systray2', 'systray');
137
+ for (const spec of candidates) {
138
+ try {
139
+ const mod = nodeRequire(spec);
140
+ if (mod && (mod.default || mod)) return { mod: mod.default || mod, isV2: String(spec).endsWith('systray2') };
141
+ } catch (e) {}
142
+ }
143
+ return null;
144
+ }
145
+
146
+ async function chmodTrayBin(pkgName) {
147
+ // systray2 的 Go 二进制偶发落盘没带 +x(macOS 实测),spawn 时 EACCES 静默失败难排查
148
+ try {
149
+ const { getRuntimeNodeModules } = await import('./trayRuntime.js');
150
+ const binName = process.platform === 'darwin' ? 'tray_darwin_release' : 'tray_linux_release';
151
+ const candidates = [
152
+ path.join(getRuntimeNodeModules(), pkgName, 'traybin', binName),
153
+ ];
154
+ for (const p of candidates) {
155
+ if (fs.existsSync(p)) fs.chmodSync(p, 0o755);
156
+ }
157
+ } catch (e) {}
158
+ }
159
+
160
+ async function initUnixTray(options) {
161
+ try {
162
+ const resolved = await resolveSystray();
163
+ if (!resolved) return null;
164
+ const { mod: SysTray, isV2 } = resolved;
165
+ const { t } = await import('../i18n.js');
166
+ await chmodTrayBin(isV2 ? 'systray2' : 'systray');
167
+
168
+ const autostartEnabled = await getAutostartEnabled();
169
+ const items = await buildMenuItems(options.port, autostartEnabled);
170
+ const menu = {
171
+ icon: getIconBase64(),
172
+ // macOS:模板模式——icon-template.png 的 alpha 通道即图形,菜单栏随明暗着色;
173
+ // 彩色品牌图的 alpha 是实心方块不能做模板。Linux 面板无模板惯例 → 用彩色图。
174
+ isTemplateIcon: process.platform === 'darwin',
175
+ title: '',
176
+ tooltip: t('CreditDaddy - 端口 {port}', { port: options.port || '…' }),
177
+ items,
178
+ };
179
+ trayInstance = new SysTray({ menu, debug: false, copyDir: true });
180
+ isWinTray = false;
181
+ trayInstance.onClick((action) => {
182
+ handleClick(action.seq_id, options, (newEnabled) => {
183
+ trayInstance.sendAction({
184
+ type: 'update-item',
185
+ item: { title: newEnabled ? t('✓ 已开启开机自启') : t('开启开机自启'), tooltip: t('系统启动时自动运行'), enabled: true },
186
+ seq_id: MENU_INDEX.AUTOSTART,
187
+ });
188
+ });
189
+ });
190
+ if (isV2 && typeof trayInstance.ready === 'function') {
191
+ trayInstance.ready().catch(() => {});
192
+ }
193
+ return trayInstance;
194
+ } catch (err) {
195
+ return null;
196
+ }
197
+ }
198
+
199
+ /** 停托盘,等子进程完全退出(macOS 不释放 NSStatusItem 会留幽灵图标、重挂注册不上) */
200
+ function killTray() {
201
+ const instance = trayInstance;
202
+ const wasWin = isWinTray;
203
+ trayInstance = null;
204
+ if (!instance) return Promise.resolve();
205
+
206
+ if (wasWin) {
207
+ try { instance.kill(); } catch (e) {}
208
+ return Promise.resolve();
209
+ }
210
+
211
+ let proc = null;
212
+ try {
213
+ proc = instance._process || (typeof instance.process === 'function' ? instance.process() : null);
214
+ } catch (e) {}
215
+
216
+ const gracefulQuit = () => { try { instance.kill(true); } catch (e) {} };
217
+ const closeIpc = () => { try { instance.kill(false); } catch (e) {} };
218
+
219
+ if (!proc || !proc.pid) {
220
+ gracefulQuit();
221
+ closeIpc();
222
+ return Promise.resolve();
223
+ }
224
+
225
+ return new Promise((resolve) => {
226
+ let done = false;
227
+ const finish = () => { if (done) return; done = true; closeIpc(); resolve(); };
228
+ proc.once('exit', finish);
229
+ gracefulQuit();
230
+ setTimeout(() => { try { process.kill(proc.pid, 0); proc.kill('SIGTERM'); } catch (e) {} }, 800);
231
+ setTimeout(() => { try { process.kill(proc.pid, 0); proc.kill('SIGKILL'); } catch (e) {} }, 1600);
232
+ const deadline = Date.now() + 3000;
233
+ const poll = setInterval(() => {
234
+ try { process.kill(proc.pid, 0); } catch { clearInterval(poll); finish(); return; }
235
+ if (Date.now() > deadline) { clearInterval(poll); finish(); }
236
+ }, 50);
237
+ });
238
+ }
239
+
240
+ function openBrowser(url) {
241
+ const platform = process.platform;
242
+ let cmd;
243
+ if (platform === 'darwin') cmd = `open "${url}"`;
244
+ else if (platform === 'win32') cmd = `start "" "${url}"`;
245
+ else cmd = `xdg-open "${url}"`;
246
+ exec(cmd);
247
+ }
248
+
249
+ export { initTray, killTray, isTraySupported, MENU_INDEX };
@@ -0,0 +1,130 @@
1
+ # 10Router tray icon for Windows using NotifyIcon
2
+ # IPC: stdin JSON commands, stdout JSON events
3
+ param([string]$IconPath, [string]$Tooltip)
4
+
5
+ $ErrorActionPreference = "Stop"
6
+
7
+ Add-Type @"
8
+ using System;
9
+ using System.Runtime.InteropServices;
10
+
11
+ public static class WinDpiAwareness {
12
+ public static IntPtr PerMonitorAwareV2 { get { return new IntPtr(-4); } }
13
+ public static IntPtr PerMonitorAware { get { return new IntPtr(-3); } }
14
+
15
+ [DllImport("user32.dll")]
16
+ public static extern bool SetProcessDpiAwarenessContext(IntPtr value);
17
+
18
+ [DllImport("user32.dll")]
19
+ public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr value);
20
+
21
+ [DllImport("shcore.dll")]
22
+ public static extern int SetProcessDpiAwareness(int value);
23
+
24
+ [DllImport("user32.dll")]
25
+ public static extern bool SetProcessDPIAware();
26
+ }
27
+ "@
28
+
29
+ function Enable-HighDpiAwareness {
30
+ $contexts = @(
31
+ [WinDpiAwareness]::PerMonitorAwareV2,
32
+ [WinDpiAwareness]::PerMonitorAware
33
+ )
34
+
35
+ foreach ($context in $contexts) {
36
+ try {
37
+ if ([WinDpiAwareness]::SetProcessDpiAwarenessContext($context)) { break }
38
+ } catch {}
39
+ }
40
+
41
+ try { [WinDpiAwareness]::SetProcessDpiAwareness(2) | Out-Null } catch {}
42
+ try { [WinDpiAwareness]::SetProcessDPIAware() | Out-Null } catch {}
43
+
44
+ foreach ($context in $contexts) {
45
+ try {
46
+ $previous = [WinDpiAwareness]::SetThreadDpiAwarenessContext($context)
47
+ if ($previous -ne [IntPtr]::Zero) { break }
48
+ } catch {}
49
+ }
50
+ }
51
+
52
+ Enable-HighDpiAwareness
53
+
54
+ Add-Type -AssemblyName System.Windows.Forms
55
+ Add-Type -AssemblyName System.Drawing
56
+
57
+ [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
58
+ [Console]::InputEncoding = [System.Text.Encoding]::UTF8
59
+ $OutputEncoding = [System.Text.Encoding]::UTF8
60
+
61
+ [System.Windows.Forms.Application]::EnableVisualStyles()
62
+ [System.Windows.Forms.Application]::SetCompatibleTextRenderingDefault($false)
63
+
64
+ $script:notifyIcon = New-Object System.Windows.Forms.NotifyIcon
65
+ $script:notifyIcon.Icon = New-Object System.Drawing.Icon($IconPath)
66
+ $script:notifyIcon.Text = $Tooltip
67
+ $script:notifyIcon.Visible = $true
68
+
69
+ $script:menu = New-Object System.Windows.Forms.ContextMenuStrip
70
+ $script:notifyIcon.ContextMenuStrip = $script:menu
71
+ $script:items = @()
72
+
73
+ function Write-Event($obj) {
74
+ $json = $obj | ConvertTo-Json -Compress
75
+ [Console]::Out.WriteLine($json)
76
+ [Console]::Out.Flush()
77
+ }
78
+
79
+ function Add-MenuItem($index, $title, $enabled) {
80
+ $item = New-Object System.Windows.Forms.ToolStripMenuItem
81
+ $item.Text = $title
82
+ $item.Enabled = $enabled
83
+ $idx = $index
84
+ $item.Add_Click({ Write-Event @{ type = "click"; index = $idx } }.GetNewClosure())
85
+ $script:menu.Items.Add($item) | Out-Null
86
+ $script:items += $item
87
+ }
88
+
89
+ function Update-MenuItem($index, $title, $enabled) {
90
+ if ($index -lt $script:items.Count) {
91
+ $script:items[$index].Text = $title
92
+ $script:items[$index].Enabled = $enabled
93
+ }
94
+ }
95
+
96
+ function Set-Tooltip($text) {
97
+ # NotifyIcon.Text max 63 chars
98
+ if ($text.Length -gt 63) { $text = $text.Substring(0, 63) }
99
+ $script:notifyIcon.Text = $text
100
+ }
101
+
102
+ # Background reader thread polls stdin via timer on UI thread
103
+ $script:timer = New-Object System.Windows.Forms.Timer
104
+ $script:timer.Interval = 100
105
+ $script:timer.Add_Tick({
106
+ try {
107
+ while ([Console]::In.Peek() -ne -1) {
108
+ $line = [Console]::In.ReadLine()
109
+ if ([string]::IsNullOrWhiteSpace($line)) { continue }
110
+ $cmd = $line | ConvertFrom-Json
111
+ switch ($cmd.action) {
112
+ "add-item" { Add-MenuItem $cmd.index $cmd.title $cmd.enabled }
113
+ "update-item" { Update-MenuItem $cmd.index $cmd.title $cmd.enabled }
114
+ "set-tooltip" { Set-Tooltip $cmd.text }
115
+ "ready" { Write-Event @{ type = "ready" } }
116
+ "kill" {
117
+ $script:notifyIcon.Visible = $false
118
+ $script:notifyIcon.Dispose()
119
+ [System.Windows.Forms.Application]::Exit()
120
+ }
121
+ }
122
+ }
123
+ } catch {
124
+ Write-Event @{ type = "error"; message = $_.Exception.Message }
125
+ }
126
+ })
127
+ $script:timer.Start()
128
+
129
+ Write-Event @{ type = "started" }
130
+ [System.Windows.Forms.Application]::Run()