cursor-switch 1.0.7 → 1.0.8

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 (86) hide show
  1. package/README.md +76 -75
  2. package/SECURITY.md +22 -19
  3. package/bin/cswitch.js +31 -8
  4. package/dist/cli.d.ts +0 -4
  5. package/dist/cli.js +404 -241
  6. package/dist/core/account-store.d.ts +0 -7
  7. package/dist/core/account-store.js +22 -28
  8. package/dist/core/cdp-engine.d.ts +11 -49
  9. package/dist/core/cdp-engine.js +155 -110
  10. package/dist/core/config-store.d.ts +7 -6
  11. package/dist/core/config-store.js +33 -12
  12. package/dist/core/cursor-paths.d.ts +8 -18
  13. package/dist/core/cursor-paths.js +18 -37
  14. package/dist/core/dashboard-launcher.d.ts +0 -20
  15. package/dist/core/dashboard-launcher.js +3 -53
  16. package/dist/core/extract-client.d.ts +57 -0
  17. package/dist/core/extract-client.js +219 -0
  18. package/dist/core/extract-menu.d.ts +3 -0
  19. package/dist/core/extract-menu.js +360 -0
  20. package/dist/core/extract-service.d.ts +64 -0
  21. package/dist/core/extract-service.js +435 -0
  22. package/dist/core/fingerprint.d.ts +0 -4
  23. package/dist/core/fingerprint.js +0 -6
  24. package/dist/core/oauth-receiver.d.ts +1 -11
  25. package/dist/core/oauth-receiver.js +509 -527
  26. package/dist/core/official-api.d.ts +0 -17
  27. package/dist/core/official-api.js +4 -23
  28. package/dist/core/outlook-launcher.d.ts +0 -31
  29. package/dist/core/outlook-launcher.js +194 -248
  30. package/dist/core/process-manager.d.ts +0 -14
  31. package/dist/core/process-manager.js +7 -22
  32. package/dist/core/pure-login-service.d.ts +54 -38
  33. package/dist/core/pure-login-service.js +483 -395
  34. package/dist/core/refund-client.d.ts +0 -22
  35. package/dist/core/refund-client.js +7 -27
  36. package/dist/core/refund-service.d.ts +0 -16
  37. package/dist/core/refund-service.js +8 -34
  38. package/dist/core/safe-storage.d.ts +27 -0
  39. package/dist/core/safe-storage.js +284 -0
  40. package/dist/core/sqlite-bridge.d.ts +10 -11
  41. package/dist/core/sqlite-bridge.js +112 -47
  42. package/dist/core/storage-bridge.d.ts +14 -5
  43. package/dist/core/storage-bridge.js +84 -24
  44. package/dist/core/switch-orchestrator.d.ts +96 -0
  45. package/dist/core/switch-orchestrator.js +341 -0
  46. package/dist/core/token-exchange.d.ts +81 -0
  47. package/dist/core/token-exchange.js +275 -0
  48. package/dist/core/token-parser.d.ts +56 -20
  49. package/dist/core/token-parser.js +354 -43
  50. package/dist/core/update-checker.d.ts +1 -29
  51. package/dist/core/update-checker.js +28 -43
  52. package/dist/index.d.ts +1 -3
  53. package/dist/index.js +1 -3
  54. package/dist/menu.d.ts +0 -7
  55. package/dist/menu.js +445 -548
  56. package/dist/types.d.ts +12 -4
  57. package/dist/types.js +0 -4
  58. package/dist/utils/account-text-importer.d.ts +9 -0
  59. package/dist/utils/account-text-importer.js +96 -0
  60. package/dist/utils/browser-utils.d.ts +0 -24
  61. package/dist/utils/browser-utils.js +0 -57
  62. package/dist/utils/clipboard.d.ts +0 -4
  63. package/dist/utils/clipboard.js +0 -5
  64. package/dist/utils/credential-bundle-ui.d.ts +36 -0
  65. package/dist/utils/credential-bundle-ui.js +246 -0
  66. package/dist/utils/live-menu.d.ts +37 -9
  67. package/dist/utils/live-menu.js +510 -81
  68. package/dist/utils/plan-formatter.d.ts +0 -26
  69. package/dist/utils/plan-formatter.js +10 -44
  70. package/dist/utils/prompt-utils.d.ts +0 -18
  71. package/dist/utils/prompt-utils.js +0 -23
  72. package/dist/utils/proxy-bootstrap.d.ts +12 -0
  73. package/dist/utils/proxy-bootstrap.js +141 -0
  74. package/dist/utils/security.d.ts +2 -4
  75. package/dist/utils/security.js +36 -4
  76. package/dist/utils/table-renderer.d.ts +0 -4
  77. package/dist/utils/table-renderer.js +24 -8
  78. package/dist/utils/time-formatter.d.ts +0 -4
  79. package/dist/utils/time-formatter.js +0 -8
  80. package/dist/utils/token-preflight-ui.d.ts +28 -0
  81. package/dist/utils/token-preflight-ui.js +222 -0
  82. package/dist/utils/window-focus.d.ts +3 -0
  83. package/dist/utils/window-focus.js +106 -0
  84. package/package.json +12 -5
  85. package/dist/core/welcome-offer-service.d.ts +0 -52
  86. package/dist/core/welcome-offer-service.js +0 -369
@@ -1,30 +1,4 @@
1
- /**
2
- * 会员计划名称官方规范化映射工具
3
- * 输出 Cursor 官方英文标准等级名称 (Free / Pro / Pro+ / Ultra / Team / Enterprise / Expired 等)
4
- *
5
- * 官方全档位体系矩阵:
6
- * 👑 Ultra → Ultra
7
- * ⚡ Pro+ → Pro+
8
- * ⚡ Pro → Pro
9
- * 👥 Team → Team
10
- * 🏢 Enterprise → Enterprise
11
- * 🎓 Student → Student
12
- * 🎁 Trial → Trial
13
- * 🆓 Free → Free
14
- * ⚠️ Past Due → Past Due
15
- * ❌ Expired → Expired
16
- */
17
1
  export type PlanTier = 'ultra' | 'pro_plus' | 'pro' | 'team' | 'enterprise' | 'student' | 'trial' | 'free' | 'past_due' | 'token_expired';
18
- /**
19
- * 将原始计划字符串解析为规范的标准档位
20
- */
21
2
  export declare function parsePlanTier(rawPlan?: string | null): PlanTier;
22
- /**
23
- * 会员计划名称格式化工具
24
- * 输出 Cursor 官方英文规范等级名称 (Pro / Pro+ / Ultra / Team / Enterprise / Free 等)
25
- */
26
3
  export declare function formatPlanName(rawPlan?: string | null, trialDays?: number | null): string;
27
- /**
28
- * 具有专业色彩阶梯的终端高亮格式化
29
- */
30
4
  export declare function formatPlanBadge(rawPlan?: string | null, trialDays?: number | null): string;
@@ -1,23 +1,4 @@
1
- /**
2
- * 会员计划名称官方规范化映射工具
3
- * 输出 Cursor 官方英文标准等级名称 (Free / Pro / Pro+ / Ultra / Team / Enterprise / Expired 等)
4
- *
5
- * 官方全档位体系矩阵:
6
- * 👑 Ultra → Ultra
7
- * ⚡ Pro+ → Pro+
8
- * ⚡ Pro → Pro
9
- * 👥 Team → Team
10
- * 🏢 Enterprise → Enterprise
11
- * 🎓 Student → Student
12
- * 🎁 Trial → Trial
13
- * 🆓 Free → Free
14
- * ⚠️ Past Due → Past Due
15
- * ❌ Expired → Expired
16
- */
17
1
  import chalk from 'chalk';
18
- /**
19
- * 将原始计划字符串解析为规范的标准档位
20
- */
21
2
  export function parsePlanTier(rawPlan) {
22
3
  if (!rawPlan)
23
4
  return 'free';
@@ -29,11 +10,9 @@ export function parsePlanTier(rawPlan) {
29
10
  if (clean.includes('past_due') || clean.includes('unpaid')) {
30
11
  return 'past_due';
31
12
  }
32
- // Ultra 档位(最高个人档)
33
13
  if (compact.includes('ultra')) {
34
14
  return 'ultra';
35
15
  }
36
- // ⚠️ 极其关键:必须在 includes('pro') 之前判断 pro+ / pro_plus,否则会被抢先匹配为 Pro
37
16
  if (compact.includes('proplus') ||
38
17
  compact.includes('pro+') ||
39
18
  compact === 'pro+' ||
@@ -41,36 +20,26 @@ export function parsePlanTier(rawPlan) {
41
20
  clean.includes('pro-plus')) {
42
21
  return 'pro_plus';
43
22
  }
44
- // 团队 / 商业档位
45
23
  if (compact.startsWith('team') || clean.includes('team') || clean.includes('business')) {
46
24
  return 'team';
47
25
  }
48
- // 企业定制档位
49
26
  if (clean.includes('enterprise')) {
50
27
  return 'enterprise';
51
28
  }
52
- // 学生 / 教师教育档位
53
29
  if (clean.includes('student') || clean.includes('edu')) {
54
30
  return 'student';
55
31
  }
56
- // 试用档位
57
32
  if (clean.includes('trial')) {
58
33
  return 'trial';
59
34
  }
60
- // 标准 Pro 档位
61
35
  if (compact.includes('pro') || compact === 'individualpro') {
62
36
  return 'pro';
63
37
  }
64
- // 免费档位
65
38
  if (clean.includes('free')) {
66
39
  return 'free';
67
40
  }
68
41
  return 'free';
69
42
  }
70
- /**
71
- * 会员计划名称格式化工具
72
- * 输出 Cursor 官方英文规范等级名称 (Pro / Pro+ / Ultra / Team / Enterprise / Free 等)
73
- */
74
43
  export function formatPlanName(rawPlan, trialDays) {
75
44
  if (!rawPlan)
76
45
  return 'Free';
@@ -121,33 +90,30 @@ export function formatPlanName(rawPlan, trialDays) {
121
90
  }
122
91
  return name;
123
92
  }
124
- /**
125
- * 具有专业色彩阶梯的终端高亮格式化
126
- */
127
93
  export function formatPlanBadge(rawPlan, trialDays) {
128
94
  const tier = parsePlanTier(rawPlan);
129
95
  const name = formatPlanName(rawPlan, trialDays);
130
96
  switch (tier) {
131
97
  case 'ultra':
132
- return chalk.hex('#F59E0B').bold(name); // 金黄色尊享
98
+ return chalk.hex('#F59E0B').bold(name);
133
99
  case 'pro_plus':
134
- return chalk.hex('#A855F7').bold(name); // 高贵紫进阶
100
+ return chalk.hex('#A855F7').bold(name);
135
101
  case 'pro':
136
- return chalk.hex('#3B82F6').bold(name); // 经典蓝专业
102
+ return chalk.hex('#3B82F6').bold(name);
137
103
  case 'team':
138
- return chalk.hex('#10B981').bold(name); // 翡翠绿团队
104
+ return chalk.hex('#10B981').bold(name);
139
105
  case 'enterprise':
140
- return chalk.hex('#EC4899').bold(name); // 玫瑰红企业
106
+ return chalk.hex('#EC4899').bold(name);
141
107
  case 'student':
142
- return chalk.hex('#06B6D4').bold(name); // 青蓝教育
108
+ return chalk.hex('#06B6D4').bold(name);
143
109
  case 'trial':
144
- return chalk.hex('#818CF8')(name); // 试用靛蓝
110
+ return chalk.hex('#818CF8')(name);
145
111
  case 'past_due':
146
- return chalk.hex('#F97316')(name); // 警示橙
112
+ return chalk.hex('#F97316')(name);
147
113
  case 'token_expired':
148
- return chalk.hex('#EF4444')(name); // 告警红
114
+ return chalk.hex('#EF4444')(name);
149
115
  case 'free':
150
116
  default:
151
- return chalk.dim(name); // 极简灰
117
+ return chalk.dim(name);
152
118
  }
153
119
  }
@@ -1,29 +1,14 @@
1
- /**
2
- * 终端交互安全输入工具 (Safe Input Prompts)
3
- * 统一提供 0、q、Esc 与直接回车一键返回能力,杜绝用户在任何输入框被卡死
4
- */
5
1
  export interface SafeInputOptions {
6
2
  message: string;
7
3
  default?: string;
8
4
  canCancel?: boolean;
9
5
  cancelHint?: string;
10
6
  }
11
- /**
12
- * 安全文本输入:统一支持输入 0、q 或直接按回车取消并返回
13
- * 若用户按 Ctrl+C,安全退出整个进程,绝不吞掉退出信号导致终端卡死
14
- * 返回用户输入的有效字符串;用户取消时返回 null
15
- */
16
7
  export declare function safeInput(options: SafeInputOptions): Promise<string | null>;
17
- /**
18
- * 安全布尔确认输入:用户按 Ctrl+C 时确保立即退出并还原光标
19
- */
20
8
  export declare function safeConfirm(options: {
21
9
  message: string;
22
10
  default?: boolean;
23
11
  }): Promise<boolean>;
24
- /**
25
- * 安全多选复选框输入:用户按 Ctrl+C 时确保立即退出并还原光标
26
- */
27
12
  export declare function safeCheckbox<T>(options: {
28
13
  message: string;
29
14
  choices: Array<{
@@ -34,7 +19,4 @@ export declare function safeCheckbox<T>(options: {
34
19
  }>;
35
20
  pageSize?: number;
36
21
  }): Promise<T[]>;
37
- /**
38
- * 原生安全单键等待:按任意键或回车立即返回,自动擦除提示行,绝不污染终端历史
39
- */
40
22
  export declare function safePressAnyKey(message?: string): Promise<void>;
@@ -1,15 +1,6 @@
1
- /**
2
- * 终端交互安全输入工具 (Safe Input Prompts)
3
- * 统一提供 0、q、Esc 与直接回车一键返回能力,杜绝用户在任何输入框被卡死
4
- */
5
1
  import { input, confirm, checkbox } from '@inquirer/prompts';
6
2
  import { createPrompt, useState, useKeypress } from '@inquirer/core';
7
3
  import chalk from 'chalk';
8
- /**
9
- * 安全文本输入:统一支持输入 0、q 或直接按回车取消并返回
10
- * 若用户按 Ctrl+C,安全退出整个进程,绝不吞掉退出信号导致终端卡死
11
- * 返回用户输入的有效字符串;用户取消时返回 null
12
- */
13
4
  export async function safeInput(options) {
14
5
  const { message, default: defaultVal, canCancel = true, cancelHint } = options;
15
6
  const tip = canCancel ? chalk.dim(` (${cancelHint || '输入 0、q 或直接回车返回'})`) : '';
@@ -33,9 +24,6 @@ export async function safeInput(options) {
33
24
  throw err;
34
25
  }
35
26
  }
36
- /**
37
- * 安全布尔确认输入:用户按 Ctrl+C 时确保立即退出并还原光标
38
- */
39
27
  export async function safeConfirm(options) {
40
28
  try {
41
29
  return await confirm(options);
@@ -48,9 +36,6 @@ export async function safeConfirm(options) {
48
36
  throw err;
49
37
  }
50
38
  }
51
- /**
52
- * 安全多选复选框输入:用户按 Ctrl+C 时确保立即退出并还原光标
53
- */
54
39
  export async function safeCheckbox(options) {
55
40
  try {
56
41
  return await checkbox(options);
@@ -63,17 +48,12 @@ export async function safeCheckbox(options) {
63
48
  throw err;
64
49
  }
65
50
  }
66
- /**
67
- * 内部基于 Inquirer 核心生命周期的按键监听器
68
- * 绝不手动调用 process.stdin.setRawMode / data 事件,彻底终结 Windows 控制台 TTY 失活假死
69
- */
70
51
  const pressKeyPrompt = createPrompt((config, done) => {
71
52
  const { message = '按回车或 Esc 键返回...' } = config;
72
53
  const [status, setStatus] = useState('idle');
73
54
  useKeypress((key) => {
74
55
  if (status !== 'idle')
75
56
  return;
76
- // 无论何时敲击 Ctrl+C,瞬间恢复光标秒退进程
77
57
  if (key.ctrl && key.name === 'c') {
78
58
  process.stdout.write('\x1b[?25h\n');
79
59
  process.exit(0);
@@ -86,9 +66,6 @@ const pressKeyPrompt = createPrompt((config, done) => {
86
66
  }
87
67
  return `\n ${chalk.dim(message)}\x1b[?25l`;
88
68
  });
89
- /**
90
- * 原生安全单键等待:按任意键或回车立即返回,自动擦除提示行,绝不污染终端历史
91
- */
92
69
  export async function safePressAnyKey(message = '按回车或 Esc 键返回...') {
93
70
  if (!process.stdin.isTTY) {
94
71
  return;
@@ -0,0 +1,12 @@
1
+ declare let activeSummary: {
2
+ httpProxy?: string;
3
+ httpsProxy?: string;
4
+ source: 'env' | 'wininet' | 'none';
5
+ };
6
+ export declare function parseWindowsProxyServer(raw: string): {
7
+ httpProxy?: string;
8
+ httpsProxy?: string;
9
+ };
10
+ export declare function ensureGlobalProxy(): typeof activeSummary;
11
+ export declare function formatNetworkError(err: any): string;
12
+ export {};
@@ -0,0 +1,141 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { EnvHttpProxyAgent, setGlobalDispatcher } from 'undici';
3
+ let initialized = false;
4
+ let activeSummary = {
5
+ source: 'none',
6
+ };
7
+ function normalizeHttpProxyUrl(raw) {
8
+ const val = (raw || '').trim().replace(/^["']|["']$/g, '');
9
+ if (!val)
10
+ return undefined;
11
+ if (/^https?:\/\//i.test(val))
12
+ return val;
13
+ if (/^[a-z0-9+.-]+:\/\//i.test(val))
14
+ return undefined;
15
+ return `http://${val}`;
16
+ }
17
+ export function parseWindowsProxyServer(raw) {
18
+ const trimmed = (raw || '').trim();
19
+ if (!trimmed)
20
+ return {};
21
+ if (!trimmed.includes('=')) {
22
+ const single = normalizeHttpProxyUrl(trimmed);
23
+ return single ? { httpProxy: single, httpsProxy: single } : {};
24
+ }
25
+ const result = {};
26
+ for (const entry of trimmed.split(';')) {
27
+ const idx = entry.indexOf('=');
28
+ if (idx <= 0)
29
+ continue;
30
+ const proto = entry.slice(0, idx).trim().toLowerCase();
31
+ const addr = normalizeHttpProxyUrl(entry.slice(idx + 1));
32
+ if (!addr)
33
+ continue;
34
+ if (proto === 'http')
35
+ result.httpProxy = addr;
36
+ else if (proto === 'https')
37
+ result.httpsProxy = addr;
38
+ }
39
+ if (!result.httpsProxy && result.httpProxy)
40
+ result.httpsProxy = result.httpProxy;
41
+ if (!result.httpProxy && result.httpsProxy)
42
+ result.httpProxy = result.httpsProxy;
43
+ return result;
44
+ }
45
+ function queryWinRegValue(key, valueName) {
46
+ try {
47
+ const out = execFileSync('reg.exe', ['query', key, '/v', valueName], {
48
+ encoding: 'utf8',
49
+ timeout: 1500,
50
+ windowsHide: true,
51
+ stdio: ['ignore', 'pipe', 'ignore'],
52
+ });
53
+ const m = out.match(new RegExp(`${valueName}\\s+REG_\\w+\\s+(.+)`, 'i'));
54
+ return m ? m[1].trim() : '';
55
+ }
56
+ catch {
57
+ return '';
58
+ }
59
+ }
60
+ function readWindowsSystemProxy() {
61
+ if (process.platform !== 'win32')
62
+ return {};
63
+ const key = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings';
64
+ const enabledRaw = queryWinRegValue(key, 'ProxyEnable').toLowerCase();
65
+ if (enabledRaw !== '0x1' && enabledRaw !== '1')
66
+ return {};
67
+ const serverRaw = queryWinRegValue(key, 'ProxyServer');
68
+ const parsed = parseWindowsProxyServer(serverRaw);
69
+ const overrideRaw = queryWinRegValue(key, 'ProxyOverride');
70
+ const noProxy = overrideRaw
71
+ ? overrideRaw
72
+ .split(';')
73
+ .map((s) => s.trim())
74
+ .filter((s) => s && s !== '<local>')
75
+ .join(',')
76
+ : '';
77
+ return { ...parsed, noProxy };
78
+ }
79
+ function mergeNoProxy(...parts) {
80
+ const seen = new Set(['localhost', '127.0.0.1', '::1']);
81
+ for (const part of parts) {
82
+ if (!part)
83
+ continue;
84
+ for (const item of part.split(',')) {
85
+ const cleaned = item.trim();
86
+ if (cleaned)
87
+ seen.add(cleaned);
88
+ }
89
+ }
90
+ return Array.from(seen).join(',');
91
+ }
92
+ export function ensureGlobalProxy() {
93
+ if (initialized)
94
+ return activeSummary;
95
+ initialized = true;
96
+ const envHttps = normalizeHttpProxyUrl(process.env.HTTPS_PROXY || process.env.https_proxy || '');
97
+ const envHttp = normalizeHttpProxyUrl(process.env.HTTP_PROXY || process.env.http_proxy || '');
98
+ const envAll = normalizeHttpProxyUrl(process.env.ALL_PROXY || process.env.all_proxy || '');
99
+ const envNoProxy = process.env.NO_PROXY || process.env.no_proxy || '';
100
+ let httpProxy = envHttp || envAll;
101
+ let httpsProxy = envHttps || envAll || envHttp;
102
+ let winNoProxy = '';
103
+ let source = httpProxy || httpsProxy ? 'env' : 'none';
104
+ if (!httpProxy && !httpsProxy && process.platform === 'win32') {
105
+ const win = readWindowsSystemProxy();
106
+ if (win.httpProxy || win.httpsProxy) {
107
+ httpProxy = win.httpProxy;
108
+ httpsProxy = win.httpsProxy;
109
+ winNoProxy = win.noProxy || '';
110
+ source = 'wininet';
111
+ }
112
+ }
113
+ if (httpProxy || httpsProxy) {
114
+ try {
115
+ const noProxy = mergeNoProxy(envNoProxy, winNoProxy);
116
+ setGlobalDispatcher(new EnvHttpProxyAgent({
117
+ httpProxy,
118
+ httpsProxy,
119
+ noProxy,
120
+ proxyTunnel: false,
121
+ }));
122
+ activeSummary = { httpProxy, httpsProxy, source };
123
+ }
124
+ catch {
125
+ activeSummary = { source: 'none' };
126
+ }
127
+ }
128
+ return activeSummary;
129
+ }
130
+ export function formatNetworkError(err) {
131
+ const msg = String(err?.message || err || '未知网络错误').trim();
132
+ const causeCode = err?.cause?.code ? String(err.cause.code) : '';
133
+ const causeMsg = err?.cause?.message ? String(err.cause.message) : '';
134
+ if (causeCode && !msg.includes(causeCode)) {
135
+ return `${msg} (${causeCode})`;
136
+ }
137
+ if (causeMsg && !msg.includes(causeMsg)) {
138
+ return `${msg} (${causeMsg})`;
139
+ }
140
+ return msg;
141
+ }
@@ -1,6 +1,4 @@
1
- /**
2
- * 敏感信息脱敏与安全工具
3
- * 终端打印 Token 时自动打码,防止录屏与截屏泄露隐私
4
- */
1
+ export declare function ensureSecureDirSync(dirPath: string): void;
2
+ export declare function writeSecureFileSync(filePath: string, content: string): void;
5
3
  export declare function maskToken(token: string | null | undefined): string;
6
4
  export declare function maskEmail(email: string | null | undefined): string;
@@ -1,7 +1,39 @@
1
- /**
2
- * 敏感信息脱敏与安全工具
3
- * 终端打印 Token 时自动打码,防止录屏与截屏泄露隐私
4
- */
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ export function ensureSecureDirSync(dirPath) {
4
+ if (!fs.existsSync(dirPath)) {
5
+ fs.mkdirSync(dirPath, { recursive: true, mode: 0o700 });
6
+ }
7
+ if (process.platform !== 'win32') {
8
+ try {
9
+ fs.chmodSync(dirPath, 0o700);
10
+ }
11
+ catch { }
12
+ }
13
+ }
14
+ export function writeSecureFileSync(filePath, content) {
15
+ const dir = path.dirname(filePath);
16
+ ensureSecureDirSync(dir);
17
+ const tmpPath = `${filePath}.tmp_${process.pid}_${Date.now()}`;
18
+ try {
19
+ fs.writeFileSync(tmpPath, content, { encoding: 'utf8', mode: 0o600 });
20
+ fs.renameSync(tmpPath, filePath);
21
+ }
22
+ catch (err) {
23
+ try {
24
+ if (fs.existsSync(tmpPath))
25
+ fs.unlinkSync(tmpPath);
26
+ }
27
+ catch { }
28
+ fs.writeFileSync(filePath, content, { encoding: 'utf8', mode: 0o600 });
29
+ }
30
+ if (process.platform !== 'win32') {
31
+ try {
32
+ fs.chmodSync(filePath, 0o600);
33
+ }
34
+ catch { }
35
+ }
36
+ }
5
37
  export function maskToken(token) {
6
38
  if (!token)
7
39
  return '--';
@@ -1,7 +1,3 @@
1
- /**
2
- * 终端高颜值 ASCII 看板渲染器 (cli-table3 + chalk)
3
- * 支持毫秒级解析、状态着色、进度条与 1 小时重订保护期醒目标注
4
- */
5
1
  import type { AccountInfo } from '../types.js';
6
2
  export declare function renderProgressBar(usedPercent?: number, width?: number): string;
7
3
  export declare function renderAccountTable(accounts: AccountInfo[]): string;
@@ -1,12 +1,23 @@
1
- /**
2
- * 终端高颜值 ASCII 看板渲染器 (cli-table3 + chalk)
3
- * 支持毫秒级解析、状态着色、进度条与 1 小时重订保护期醒目标注
4
- */
5
1
  import Table from 'cli-table3';
6
2
  import chalk from 'chalk';
7
3
  import { getExpiryStatus } from './time-formatter.js';
8
4
  import { formatMachineIdSummary } from '../core/fingerprint.js';
5
+ import { TokenParser } from '../core/token-parser.js';
9
6
  import { formatPlanBadge } from './plan-formatter.js';
7
+ function formatCredentialCell(acc) {
8
+ const cls = TokenParser.classifyAccount(acc);
9
+ const label = TokenParser.formatCredentialBadge(cls);
10
+ switch (cls.credentialState) {
11
+ case 'client_with_rt':
12
+ return { cell: chalk.green(label), isWebOnly: false };
13
+ case 'client_no_rt':
14
+ return { cell: chalk.cyan(label), isWebOnly: false };
15
+ case 'web_only':
16
+ return { cell: chalk.yellow(label), isWebOnly: true };
17
+ case 'expired':
18
+ return { cell: chalk.red(label), isWebOnly: false };
19
+ }
20
+ }
10
21
  export function renderProgressBar(usedPercent = 0, width = 10) {
11
22
  const safePercent = Math.max(0, Math.min(100, usedPercent));
12
23
  const filled = Math.round((safePercent / 100) * width);
@@ -27,6 +38,7 @@ export function renderAccountTable(accounts) {
27
38
  chalk.grey('序号'),
28
39
  chalk.grey('状态'),
29
40
  chalk.grey('账号邮箱'),
41
+ chalk.grey('凭据'),
30
42
  chalk.grey('会员级别'),
31
43
  chalk.grey('请求余量'),
32
44
  chalk.grey('到期时间'),
@@ -39,24 +51,24 @@ export function renderAccountTable(accounts) {
39
51
  },
40
52
  });
41
53
  let hasGoldenWindow = false;
54
+ let hasWebOnly = false;
42
55
  accounts.forEach((acc, index) => {
43
56
  const isCurrent = !!acc.is_current;
44
57
  const statusText = isCurrent ? chalk.green('● 在用') : chalk.grey('○ 空闲');
45
- // 邮箱与别名
58
+ const cred = formatCredentialCell(acc);
59
+ if (cred.isWebOnly)
60
+ hasWebOnly = true;
46
61
  let emailDisplay = isCurrent ? chalk.bold.white(acc.email) : chalk.white(acc.email);
47
62
  if (acc.username) {
48
63
  emailDisplay += chalk.grey(` (${acc.username})`);
49
64
  }
50
- // 会员级别 (全档位专业色彩阶梯)
51
65
  const planBadge = formatPlanBadge(acc.subscription_type);
52
- // 用量
53
66
  const usageObj = acc.current_period_usage?.planUsage;
54
67
  const totalPercent = usageObj?.totalPercentUsed ?? 0;
55
68
  const bar = renderProgressBar(totalPercent, 8);
56
69
  const limit = usageObj?.limit ?? 500;
57
70
  const remain = usageObj?.remaining ?? Math.round(limit * (1 - totalPercent / 100));
58
71
  const usageDisplay = `${bar} ${remain}/${limit}`;
59
- // 到期时间与状态
60
72
  const cycleEnd = acc.current_period_usage?.billingCycleEnd;
61
73
  const expiry = getExpiryStatus(cycleEnd);
62
74
  let countdownDisplay = chalk.blue(expiry.countdownText);
@@ -72,6 +84,7 @@ export function renderAccountTable(accounts) {
72
84
  chalk.grey(String(index + 1)),
73
85
  statusText,
74
86
  emailDisplay,
87
+ cred.cell,
75
88
  planBadge,
76
89
  usageDisplay,
77
90
  chalk.grey(expiry.formattedDate),
@@ -84,5 +97,8 @@ export function renderAccountTable(accounts) {
84
97
  output += chalk.bgYellow.black.bold(' 提示 ') + chalk.yellow(' 发现账号正处于「1小时黄金重订保护期」,请及时续订以保留权益\n\n');
85
98
  }
86
99
  output += table.toString() + '\n';
100
+ if (hasWebOnly) {
101
+ output += chalk.dim(' 提示: 「仅Web」账号可用于官网控制台 (dash) 与用量查询;切入桌面 IDE 前请先通过 oauth 或 pure 获取客户端双票。\n');
102
+ }
87
103
  return output;
88
104
  }
@@ -1,7 +1,3 @@
1
- /**
2
- * 时间与倒计时工具
3
- * 精确到秒,支持 Cursor 订阅到期「1小时重订黄金窗口期」智能判定
4
- */
5
1
  export interface ExpiryStatus {
6
2
  formattedDate: string;
7
3
  countdownText: string;
@@ -1,14 +1,9 @@
1
- /**
2
- * 时间与倒计时工具
3
- * 精确到秒,支持 Cursor 订阅到期「1小时重订黄金窗口期」智能判定
4
- */
5
1
  export function formatTimestamp(ts) {
6
2
  if (!ts)
7
3
  return '--';
8
4
  const num = typeof ts === 'string' ? Number(ts) : ts;
9
5
  if (isNaN(num) || num <= 0)
10
6
  return '--';
11
- // 处理秒级和毫秒级时间戳
12
7
  const date = new Date(num < 1e11 ? num * 1000 : num);
13
8
  if (isNaN(date.getTime()))
14
9
  return '--';
@@ -36,7 +31,6 @@ export function getExpiryStatus(cycleEnd) {
36
31
  const nowMs = Date.now();
37
32
  const diffMs = targetMs - nowMs;
38
33
  const ONE_HOUR_MS = 60 * 60 * 1000;
39
- // 1. 尚未到期
40
34
  if (diffMs > 0) {
41
35
  const totalSeconds = Math.floor(diffMs / 1000);
42
36
  const days = Math.floor(totalSeconds / 86400);
@@ -56,7 +50,6 @@ export function getExpiryStatus(cycleEnd) {
56
50
  statusBadge: '● 正常',
57
51
  };
58
52
  }
59
- // 2. 处于到期后 1 小时内(黄金重订窗口期)
60
53
  if (diffMs <= 0 && diffMs >= -ONE_HOUR_MS) {
61
54
  const passedSeconds = Math.abs(Math.floor(diffMs / 1000));
62
55
  const passedMin = Math.floor(passedSeconds / 60);
@@ -71,7 +64,6 @@ export function getExpiryStatus(cycleEnd) {
71
64
  statusBadge: '● 保护期',
72
65
  };
73
66
  }
74
- // 3. 超过 1 小时已完全失效
75
67
  const passedDays = Math.floor(Math.abs(diffMs) / (86400 * 1000));
76
68
  return {
77
69
  formattedDate,
@@ -0,0 +1,28 @@
1
+ import type { AccountInfo } from '../types.js';
2
+ import type { AccountStore } from '../core/account-store.js';
3
+ import type { StorageBridge } from '../core/storage-bridge.js';
4
+ import type { SqliteBridge } from '../core/sqlite-bridge.js';
5
+ import type { StaleTokenResolution } from '../core/switch-orchestrator.js';
6
+ import { type TokenClassification } from '../core/token-parser.js';
7
+ import { type IngestUpgradeResult, type SwitchPreflightIssue } from '../core/token-exchange.js';
8
+ import { type QuickMenuChoice } from './live-menu.js';
9
+ export declare function printFactualTokenStatus(rawOrCleanToken: string, existingRefreshToken?: string | null, workosSessionToken?: string | null): TokenClassification;
10
+ export declare function printIngestUpgradeResult(res: IngestUpgradeResult): void;
11
+ export declare function renderPreflightBlockBox(issue: SwitchPreflightIssue, email?: string): void;
12
+ export declare function promptStaleSwitchConfirmation(issue: SwitchPreflightIssue, email?: string, opts?: {
13
+ force?: boolean;
14
+ interactive?: boolean;
15
+ confirmFn?: (message: string) => Promise<boolean>;
16
+ }): Promise<boolean>;
17
+ export interface StaleSwitchHealerContext {
18
+ store: AccountStore;
19
+ storage: StorageBridge;
20
+ sqlite: SqliteBridge;
21
+ executablePath?: string;
22
+ force?: boolean;
23
+ interactive?: boolean;
24
+ runBrowserOAuthFn?: () => Promise<AccountInfo | null>;
25
+ runPureReloginFn?: (account: AccountInfo) => Promise<AccountInfo | null>;
26
+ selectActionFn?: (choices: QuickMenuChoice[], message: string) => Promise<string>;
27
+ }
28
+ export declare function resolveStaleSwitchWithHealing(issue: SwitchPreflightIssue, account: AccountInfo, ctx: StaleSwitchHealerContext): Promise<StaleTokenResolution>;