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,7 +1,3 @@
1
- /**
2
- * 奥仔席位退款/自动退款云端 API 交互客户端
3
- * 原生对接 getdoubao.com / getaozai.com 后端接口
4
- */
5
1
  export interface CardAuthInfo {
6
2
  token: string;
7
3
  tokenType: string;
@@ -58,41 +54,23 @@ export declare class RefundClient {
58
54
  private apiBase;
59
55
  constructor(apiBase?: string);
60
56
  getApiBase(): string;
61
- /**
62
- * 使用卡密换取 Bearer 访问令牌
63
- */
64
57
  login(cardCode: string): Promise<{
65
58
  success: boolean;
66
59
  data?: CardAuthInfo;
67
60
  error?: string;
68
61
  }>;
69
- /**
70
- * 查询当前卡密余额与最新资费令牌
71
- */
72
62
  getBalance(authToken: string): Promise<{
73
63
  success: boolean;
74
64
  data?: CardBalanceInfo;
75
65
  error?: string;
76
66
  }>;
77
- /**
78
- * 确认并开通资费扣点权限 (首次使用白名单确认)
79
- */
80
67
  acceptTerms(authToken: string): Promise<{
81
68
  success: boolean;
82
69
  pricingToken?: string;
83
70
  error?: string;
84
71
  }>;
85
- /**
86
- * 提交一次席位退款/刷新请求
87
- */
88
72
  submitProcess(authToken: string, sessionToken: string, pricingToken?: string): Promise<ProcessSubmitResult>;
89
- /**
90
- * 长轮询跟踪任务状态直至完成或失败
91
- */
92
73
  pollOperation(authToken: string, operationId: string, onTick?: (res: OperationStatusResult) => void, maxWaitDurationMs?: number): Promise<OperationStatusResult>;
93
- /**
94
- * 拉取该卡密的使用明细与退款流水
95
- */
96
74
  getUsageHistory(authToken: string): Promise<{
97
75
  success: boolean;
98
76
  total?: number;
@@ -1,18 +1,13 @@
1
- /**
2
- * 奥仔席位退款/自动退款云端 API 交互客户端
3
- * 原生对接 getdoubao.com / getaozai.com 后端接口
4
- */
1
+ import { ensureGlobalProxy, formatNetworkError } from '../utils/proxy-bootstrap.js';
5
2
  export class RefundClient {
6
3
  apiBase;
7
4
  constructor(apiBase = 'https://getdoubao.com') {
5
+ ensureGlobalProxy();
8
6
  this.apiBase = apiBase.replace(/\/+$/, '');
9
7
  }
10
8
  getApiBase() {
11
9
  return this.apiBase;
12
10
  }
13
- /**
14
- * 使用卡密换取 Bearer 访问令牌
15
- */
16
11
  async login(cardCode) {
17
12
  const code = cardCode.trim();
18
13
  if (!code) {
@@ -46,12 +41,9 @@ export class RefundClient {
46
41
  };
47
42
  }
48
43
  catch (err) {
49
- return { success: false, error: err.message || '网络连接超时,请检查网络或代理' };
44
+ return { success: false, error: formatNetworkError(err) || '网络连接超时,请检查网络或代理' };
50
45
  }
51
46
  }
52
- /**
53
- * 查询当前卡密余额与最新资费令牌
54
- */
55
47
  async getBalance(authToken) {
56
48
  try {
57
49
  const res = await fetch(`${this.apiBase}/api/v1/card`, {
@@ -77,12 +69,9 @@ export class RefundClient {
77
69
  };
78
70
  }
79
71
  catch (err) {
80
- return { success: false, error: err.message || '网络连接异常' };
72
+ return { success: false, error: formatNetworkError(err) || '网络连接异常' };
81
73
  }
82
74
  }
83
- /**
84
- * 确认并开通资费扣点权限 (首次使用白名单确认)
85
- */
86
75
  async acceptTerms(authToken) {
87
76
  try {
88
77
  const res = await fetch(`${this.apiBase}/api/v1/auth/accept-api-terms`, {
@@ -104,12 +93,9 @@ export class RefundClient {
104
93
  };
105
94
  }
106
95
  catch (err) {
107
- return { success: false, error: err.message || '网络连接异常' };
96
+ return { success: false, error: formatNetworkError(err) || '网络连接异常' };
108
97
  }
109
98
  }
110
- /**
111
- * 提交一次席位退款/刷新请求
112
- */
113
99
  async submitProcess(authToken, sessionToken, pricingToken) {
114
100
  try {
115
101
  const bodyPayload = {
@@ -151,12 +137,9 @@ export class RefundClient {
151
137
  };
152
138
  }
153
139
  catch (err) {
154
- return { success: false, message: err.message || '网络超时,无法连接至退款服务网关' };
140
+ return { success: false, message: formatNetworkError(err) || '网络超时,无法连接至退款服务网关' };
155
141
  }
156
142
  }
157
- /**
158
- * 长轮询跟踪任务状态直至完成或失败
159
- */
160
143
  async pollOperation(authToken, operationId, onTick, maxWaitDurationMs = 180000) {
161
144
  const startTime = Date.now();
162
145
  while (Date.now() - startTime < maxWaitDurationMs) {
@@ -195,9 +178,6 @@ export class RefundClient {
195
178
  error: '处理耗时较长,后台仍在排队推进中,稍后可刷新余额确认',
196
179
  };
197
180
  }
198
- /**
199
- * 拉取该卡密的使用明细与退款流水
200
- */
201
181
  async getUsageHistory(authToken) {
202
182
  try {
203
183
  const res = await fetch(`${this.apiBase}/api/v1/card/usage`, {
@@ -215,7 +195,7 @@ export class RefundClient {
215
195
  };
216
196
  }
217
197
  catch (err) {
218
- return { success: false, error: err.message || '网络连接异常' };
198
+ return { success: false, error: formatNetworkError(err) || '网络连接异常' };
219
199
  }
220
200
  }
221
201
  }
@@ -1,7 +1,3 @@
1
- /**
2
- * 奥仔席位退款业务编排器 (RefundService)
3
- * 整合卡密管理、Session Token 提取、云端执行、配额自动同步与进程唤醒
4
- */
5
1
  import { ConfigStore } from './config-store.js';
6
2
  import { RefundClient, type CardAuthInfo } from './refund-client.js';
7
3
  import type { AccountInfo } from '../types.js';
@@ -12,28 +8,16 @@ export declare class RefundService {
12
8
  constructor(customApiBase?: string);
13
9
  getConfigStore(): ConfigStore;
14
10
  getClient(): RefundClient;
15
- /**
16
- * 登录并获取有效的卡密信息与令牌 (优雅卡片交互)
17
- */
18
11
  ensureCardAuth(providedCardCode?: string, promptIfMissing?: boolean): Promise<{
19
12
  auth: CardAuthInfo;
20
13
  cardCode: string;
21
14
  } | null>;
22
- /**
23
- * 确保卡密已同意资费协议 (未同意则引导同意)
24
- */
25
15
  ensureApiTerms(auth: CardAuthInfo, autoYes?: boolean): Promise<string>;
26
- /**
27
- * 核心席位退款执行引擎
28
- */
29
16
  runRefundForAccount(params: {
30
17
  account?: AccountInfo;
31
18
  sessionToken?: string;
32
19
  cardCode?: string;
33
20
  autoYes?: boolean;
34
21
  }): Promise<boolean>;
35
- /**
36
- * 打印卡密流水明细表格 (优雅表格卡片)
37
- */
38
22
  printUsageHistory(cardCode?: string): Promise<void>;
39
23
  }
@@ -1,7 +1,3 @@
1
- /**
2
- * 奥仔席位退款业务编排器 (RefundService)
3
- * 整合卡密管理、Session Token 提取、云端执行、配额自动同步与进程唤醒
4
- */
5
1
  import chalk from 'chalk';
6
2
  import Table from 'cli-table3';
7
3
  import boxen from 'boxen';
@@ -11,6 +7,7 @@ import { RefundClient } from './refund-client.js';
11
7
  import { OfficialApiClient } from './official-api.js';
12
8
  import { ProcessManager } from './process-manager.js';
13
9
  import { resolveCursorPaths } from './cursor-paths.js';
10
+ import { TokenParser } from './token-parser.js';
14
11
  import { maskToken } from '../utils/security.js';
15
12
  import { safeInput, safeConfirm, safePressAnyKey } from '../utils/prompt-utils.js';
16
13
  export class RefundService {
@@ -29,17 +26,14 @@ export class RefundService {
29
26
  getClient() {
30
27
  return this.client;
31
28
  }
32
- /**
33
- * 登录并获取有效的卡密信息与令牌 (优雅卡片交互)
34
- */
35
29
  async ensureCardAuth(providedCardCode, promptIfMissing = true) {
36
30
  let code = providedCardCode || this.configStore.getSeatCardCode();
37
31
  if (!code && promptIfMissing) {
38
32
  console.clear();
39
33
  console.log(boxen([
40
- chalk.bold.cyan('● 绑定奥仔席位卡密'),
34
+ chalk.bold.cyan('● 绑定 Cursor 退款服务卡密'),
41
35
  chalk.dim('────────────────────────────────────────────────'),
42
- '执行席位退款需要绑定卡密,请输入您的席位卡密。',
36
+ '执行 Cursor 退款服务需要绑定卡密,请输入您的退款卡密。',
43
37
  chalk.dim('• 格式示例 : ABCD-EFGH-1234'),
44
38
  chalk.dim('• 本地安全 : 仅保存于本地 ~/.cursor-switch/config.json'),
45
39
  chalk.dim('• 取消方式 : 输入 0、q 或直接按回车可取消返回'),
@@ -48,7 +42,7 @@ export class RefundService {
48
42
  borderColor: 'cyan',
49
43
  borderStyle: 'round',
50
44
  }));
51
- const answer = await safeInput({ message: '席位卡密' });
45
+ const answer = await safeInput({ message: '退款卡密' });
52
46
  if (!answer) {
53
47
  return null;
54
48
  }
@@ -57,7 +51,7 @@ export class RefundService {
57
51
  if (!code || code === '0' || code.toLowerCase() === 'q') {
58
52
  return null;
59
53
  }
60
- process.stdout.write(chalk.cyan('\n正在连接奥仔席位网关验证卡密有效性... '));
54
+ process.stdout.write(chalk.cyan('\n正在连接 Cursor 退款服务网关验证卡密有效性... '));
61
55
  const res = await this.client.login(code);
62
56
  if (!res.success || !res.data) {
63
57
  console.log(chalk.red('✖ 失败'));
@@ -75,13 +69,9 @@ export class RefundService {
75
69
  return null;
76
70
  }
77
71
  console.log(chalk.green('✔ 验证通过'));
78
- // 成功则自动保存到本地配置
79
72
  this.configStore.setSeatCardCode(code);
80
73
  return { auth: res.data, cardCode: code };
81
74
  }
82
- /**
83
- * 确保卡密已同意资费协议 (未同意则引导同意)
84
- */
85
75
  async ensureApiTerms(auth, autoYes = false) {
86
76
  const balRes = await this.client.getBalance(auth.token);
87
77
  const balance = balRes.data || {
@@ -97,7 +87,6 @@ export class RefundService {
97
87
  if (balance.apiAllowed && balance.pricingToken) {
98
88
  return balance.pricingToken;
99
89
  }
100
- // 需要开通知情确认
101
90
  console.log(boxen([
102
91
  chalk.bold.yellow('● 首次使用资费确认'),
103
92
  chalk.dim('────────────────────────────────────────────────'),
@@ -126,14 +115,9 @@ export class RefundService {
126
115
  console.log(chalk.green('✔ 资费规则确认成功,已为您开通退款权限!\n'));
127
116
  return acceptRes.pricingToken || '';
128
117
  }
129
- /**
130
- * 核心席位退款执行引擎
131
- */
132
118
  async runRefundForAccount(params) {
133
119
  const { account, cardCode, autoYes } = params;
134
- // 1. 提取 Session Token
135
- let rawToken = params.sessionToken || account?.workos_cursor_session_token || account?.token || '';
136
- rawToken = rawToken.trim();
120
+ let rawToken = TokenParser.extractWebSessionToken(params.sessionToken || account?.workos_cursor_session_token || account?.token || '');
137
121
  if (!rawToken) {
138
122
  console.log(boxen([
139
123
  chalk.bold.red('✖ 缺少 Cursor 会话凭据'),
@@ -148,7 +132,6 @@ export class RefundService {
148
132
  await safePressAnyKey();
149
133
  return false;
150
134
  }
151
- // 2. 鉴权卡密 (若未绑定自动以优雅卡片引导,取消则秒退)
152
135
  const cardRes = await this.ensureCardAuth(cardCode, true);
153
136
  if (!cardRes) {
154
137
  return false;
@@ -160,7 +143,7 @@ export class RefundService {
160
143
  chalk.dim('────────────────────────────────────────────────'),
161
144
  `• 当前卡密 : ${chalk.white(maskToken(actualCard))}`,
162
145
  `• 剩余点数 : ${chalk.red(auth.remaining)} 点`,
163
- '• 请联系充值或在退款菜单选择 [5. 绑定/更换席位卡密]。',
146
+ '• 请联系充值或在退款菜单选择 [3. 更换退款卡密]。',
164
147
  ].join('\n'), {
165
148
  padding: { top: 0, bottom: 0, left: 1, right: 1 },
166
149
  borderColor: 'red',
@@ -169,7 +152,6 @@ export class RefundService {
169
152
  await safePressAnyKey();
170
153
  return false;
171
154
  }
172
- // 3. 校验并开通资费
173
155
  let pricingToken = '';
174
156
  try {
175
157
  pricingToken = await this.ensureApiTerms(auth, autoYes);
@@ -182,7 +164,6 @@ export class RefundService {
182
164
  console.log(chalk.grey('\n已取消操作。\n'));
183
165
  return false;
184
166
  }
185
- // 4. 前置确认卡 (Pre-flight Summary Confirmation)
186
167
  if (!autoYes) {
187
168
  console.clear();
188
169
  const targetLabel = account?.email || '手动提取的 Session 账号';
@@ -206,7 +187,6 @@ export class RefundService {
206
187
  return false;
207
188
  }
208
189
  }
209
- // 5. 提交任务
210
190
  console.log(chalk.cyan('\n[1/3] ● 正在向官方席位团队通道提交任务...'));
211
191
  const submitRes = await this.client.submitProcess(auth.token, rawToken, pricingToken);
212
192
  if (!submitRes.success || !submitRes.operationId) {
@@ -221,7 +201,6 @@ export class RefundService {
221
201
  }
222
202
  const opId = submitRes.operationId;
223
203
  console.log(chalk.grey(` ✔ 任务单号: ${opId.slice(0, 10)}... (已预扣 ${submitRes.deductedPoints || auth.pointsPerOp} 点)`));
224
- // 6. 长轮询等待结果 (展示平滑进度指示)
225
204
  console.log(chalk.cyan('[2/3] ● 正在执行席位退款处理 (耗时约 5~8 秒)...'));
226
205
  const finalStatus = await this.client.pollOperation(auth.token, opId, (tick) => {
227
206
  if (tick.status === 'processing') {
@@ -247,7 +226,6 @@ export class RefundService {
247
226
  borderColor: 'green',
248
227
  borderStyle: 'round',
249
228
  }));
250
- // 7. 自动联动:向 Cursor 官方接口拉取最新用量配额
251
229
  if (account && account.token) {
252
230
  process.stdout.write(chalk.dim('\n正在向 Cursor 官方接口同步最新配额状态... '));
253
231
  try {
@@ -266,8 +244,7 @@ export class RefundService {
266
244
  console.log(chalk.dim('○ 稍后生效'));
267
245
  }
268
246
  }
269
- // 8. 检查当前 Cursor 是否正在运行,并提示重启生效
270
- if (account?.is_current && ProcessManager.isCursorRunning()) {
247
+ if (account?.is_current && ProcessManager.isCursorRunning(true)) {
271
248
  const paths = resolveCursorPaths();
272
249
  if (paths.executablePath) {
273
250
  const restart = autoYes || (await safeConfirm({
@@ -304,9 +281,6 @@ export class RefundService {
304
281
  return false;
305
282
  }
306
283
  }
307
- /**
308
- * 打印卡密流水明细表格 (优雅表格卡片)
309
- */
310
284
  async printUsageHistory(cardCode) {
311
285
  const cardRes = await this.ensureCardAuth(cardCode, true);
312
286
  if (!cardRes)
@@ -0,0 +1,27 @@
1
+ export declare const SAFE_STORAGE_PREFIX = "cursor-safe-storage:v1:";
2
+ export declare const SCOPED_TOKEN_PREFIX = "scoped:v1:";
3
+ export declare const CURSOR_STALE_AUTH_KEYS: readonly ["cursorAuth/accessToken", "cursorAuth/refreshToken", "cursorAuth/cachedEmail", "cursorAuth/cachedSignUpType", "cursorAuth/stripeMembershipType", "cursorAuth/stripeMembershipAuthId", "cursorAuth/stripeSubscriptionStatus", "cursorAuth/stripeCustomerId", "cursorAuth/cachedScopedProfile", "cursorAuth/cachedTeam", "cursorAuth/teamId", "cursorAuth/authId", "cursorAuth/userId", "cursorAuth/cachedUserId", "cursorAuth/openIdUserId", "cursorAuth/user", "cursorAuth/email", "cursorAuth/workosCursorSessionToken", "cursorAuth/cachedWorkosSessionToken", "cursorAuth/isAuthenticated", "cursorAuth/isAuthorized", "cursorAuth/isLoggedIn", "cursor.email", "cursor.accessToken", "glass.lastSignedInAuthId", "adminSettings.cachedAuthId", "autorun.cachedAdminSettings", "cursorai/serverConfig"];
4
+ export interface SafeStorageDecodeOptions {
5
+ localStatePath?: string;
6
+ dbOrStoragePath?: string;
7
+ platform?: NodeJS.Platform;
8
+ dpapiUnprotect?: (protectedBytes: Buffer) => Buffer;
9
+ keychainLookup?: () => string[];
10
+ }
11
+ export interface SafeStorageDecodeResult {
12
+ token: string | null;
13
+ isEncrypted: boolean;
14
+ decrypted: boolean;
15
+ format: 'plain' | 'scoped' | 'safe-storage' | 'empty';
16
+ error?: string;
17
+ }
18
+ export declare function clearSafeStorageKeyCache(): void;
19
+ export declare function stripJsonStringQuotes(raw: string): string;
20
+ export declare function stripScopedPrefix(raw: string): {
21
+ value: string;
22
+ wasScoped: boolean;
23
+ };
24
+ export declare function isSafeStorageValue(raw: string | null | undefined): boolean;
25
+ export declare function decryptWindowsChromiumBlob(blob: Buffer, encryptedMasterKeyB64: string, dpapiUnprotect?: (buf: Buffer) => Buffer, cacheKey?: string): string | null;
26
+ export declare function decryptMacChromiumBlob(blob: Buffer, passwords: string[]): string | null;
27
+ export declare function decodeStoredToken(raw: string | null | undefined, opts?: SafeStorageDecodeOptions): SafeStorageDecodeResult;
@@ -0,0 +1,284 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import { execFileSync } from 'node:child_process';
4
+ import { resolveSidecarPaths } from './cursor-paths.js';
5
+ export const SAFE_STORAGE_PREFIX = 'cursor-safe-storage:v1:';
6
+ export const SCOPED_TOKEN_PREFIX = 'scoped:v1:';
7
+ export const CURSOR_STALE_AUTH_KEYS = [
8
+ 'cursorAuth/accessToken',
9
+ 'cursorAuth/refreshToken',
10
+ 'cursorAuth/cachedEmail',
11
+ 'cursorAuth/cachedSignUpType',
12
+ 'cursorAuth/stripeMembershipType',
13
+ 'cursorAuth/stripeMembershipAuthId',
14
+ 'cursorAuth/stripeSubscriptionStatus',
15
+ 'cursorAuth/stripeCustomerId',
16
+ 'cursorAuth/cachedScopedProfile',
17
+ 'cursorAuth/cachedTeam',
18
+ 'cursorAuth/teamId',
19
+ 'cursorAuth/authId',
20
+ 'cursorAuth/userId',
21
+ 'cursorAuth/cachedUserId',
22
+ 'cursorAuth/openIdUserId',
23
+ 'cursorAuth/user',
24
+ 'cursorAuth/email',
25
+ 'cursorAuth/workosCursorSessionToken',
26
+ 'cursorAuth/cachedWorkosSessionToken',
27
+ 'cursorAuth/isAuthenticated',
28
+ 'cursorAuth/isAuthorized',
29
+ 'cursorAuth/isLoggedIn',
30
+ 'cursor.email',
31
+ 'cursor.accessToken',
32
+ 'glass.lastSignedInAuthId',
33
+ 'adminSettings.cachedAuthId',
34
+ 'autorun.cachedAdminSettings',
35
+ 'cursorai/serverConfig',
36
+ ];
37
+ const windowsMasterKeyCache = new Map();
38
+ export function clearSafeStorageKeyCache() {
39
+ windowsMasterKeyCache.clear();
40
+ }
41
+ export function stripJsonStringQuotes(raw) {
42
+ const trimmed = raw.trim();
43
+ if (trimmed.length >= 2 && trimmed.startsWith('"') && trimmed.endsWith('"')) {
44
+ try {
45
+ const parsed = JSON.parse(trimmed);
46
+ if (typeof parsed === 'string') {
47
+ return parsed.trim();
48
+ }
49
+ }
50
+ catch { }
51
+ }
52
+ return trimmed;
53
+ }
54
+ export function stripScopedPrefix(raw) {
55
+ if (!raw.startsWith(SCOPED_TOKEN_PREFIX)) {
56
+ return { value: raw, wasScoped: false };
57
+ }
58
+ const rest = raw.slice(SCOPED_TOKEN_PREFIX.length);
59
+ const sep = rest.indexOf(':');
60
+ if (sep < 0) {
61
+ return { value: raw, wasScoped: false };
62
+ }
63
+ return { value: rest.slice(sep + 1).trim(), wasScoped: true };
64
+ }
65
+ export function isSafeStorageValue(raw) {
66
+ if (typeof raw !== 'string')
67
+ return false;
68
+ const unquoted = stripJsonStringQuotes(raw);
69
+ return unquoted.startsWith(SAFE_STORAGE_PREFIX);
70
+ }
71
+ function isUsablePlaintextToken(value) {
72
+ if (!value)
73
+ return false;
74
+ for (let i = 0; i < value.length; i++) {
75
+ const code = value.charCodeAt(i);
76
+ if (code < 0x21 || code > 0x7e) {
77
+ return false;
78
+ }
79
+ }
80
+ return true;
81
+ }
82
+ function defaultWindowsDpapiUnprotect(protectedBytes) {
83
+ const b64 = protectedBytes.toString('base64');
84
+ const script = `Add-Type -AssemblyName System.Security; ` +
85
+ `$bytes = [Convert]::FromBase64String('${b64}'); ` +
86
+ `$plain = [System.Security.Cryptography.ProtectedData]::Unprotect($bytes, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser); ` +
87
+ `[Convert]::ToBase64String($plain)`;
88
+ const out = execFileSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', script], {
89
+ encoding: 'utf8',
90
+ stdio: ['ignore', 'pipe', 'pipe'],
91
+ windowsHide: true,
92
+ timeout: 8000,
93
+ }).trim();
94
+ if (!out) {
95
+ throw new Error('DPAPI unprotect returned empty output');
96
+ }
97
+ return Buffer.from(out, 'base64');
98
+ }
99
+ function defaultMacKeychainLookup() {
100
+ const passwords = [];
101
+ for (const account of ['Cursor Key', 'Cursor']) {
102
+ try {
103
+ const pw = execFileSync('security', ['find-generic-password', '-w', '-s', 'Cursor Safe Storage', '-a', account], {
104
+ encoding: 'utf8',
105
+ stdio: ['ignore', 'pipe', 'ignore'],
106
+ timeout: 5000,
107
+ }).trim();
108
+ if (pw)
109
+ passwords.push(pw);
110
+ }
111
+ catch { }
112
+ }
113
+ return passwords;
114
+ }
115
+ function readWindowsEncryptedKeyB64(localStatePath) {
116
+ if (!localStatePath || !fs.existsSync(localStatePath)) {
117
+ return null;
118
+ }
119
+ const parsed = JSON.parse(fs.readFileSync(localStatePath, 'utf8'));
120
+ const key = parsed?.os_crypt?.encrypted_key;
121
+ return typeof key === 'string' && key.trim() ? key.trim() : null;
122
+ }
123
+ export function decryptWindowsChromiumBlob(blob, encryptedMasterKeyB64, dpapiUnprotect = defaultWindowsDpapiUnprotect, cacheKey) {
124
+ const versionTag = blob.subarray(0, 3).toString('ascii');
125
+ if ((versionTag !== 'v10' && versionTag !== 'v11') || blob.length <= 3 + 12 + 16) {
126
+ return null;
127
+ }
128
+ let masterKey = cacheKey ? windowsMasterKeyCache.get(cacheKey) : undefined;
129
+ if (!masterKey) {
130
+ const rawKey = Buffer.from(encryptedMasterKeyB64, 'base64');
131
+ if (rawKey.length <= 5 || rawKey.subarray(0, 5).toString('ascii') !== 'DPAPI') {
132
+ return null;
133
+ }
134
+ masterKey = dpapiUnprotect(rawKey.subarray(5));
135
+ if (masterKey.length !== 32) {
136
+ return null;
137
+ }
138
+ if (cacheKey) {
139
+ windowsMasterKeyCache.set(cacheKey, masterKey);
140
+ }
141
+ }
142
+ const nonce = blob.subarray(3, 15);
143
+ const tag = blob.subarray(blob.length - 16);
144
+ const ciphertext = blob.subarray(15, blob.length - 16);
145
+ const decipher = crypto.createDecipheriv('aes-256-gcm', masterKey, nonce);
146
+ decipher.setAuthTag(tag);
147
+ const plainBuf = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
148
+ const token = plainBuf.toString('utf8').trim();
149
+ return isUsablePlaintextToken(token) ? token : null;
150
+ }
151
+ export function decryptMacChromiumBlob(blob, passwords) {
152
+ if (blob.subarray(0, 3).toString('ascii') !== 'v10' || blob.length <= 3) {
153
+ return null;
154
+ }
155
+ const ciphertext = blob.subarray(3);
156
+ if (ciphertext.length === 0 || ciphertext.length % 16 !== 0) {
157
+ return null;
158
+ }
159
+ const salt = Buffer.from('saltysalt', 'utf8');
160
+ const iv = Buffer.alloc(16, 0x20);
161
+ for (const pw of passwords) {
162
+ try {
163
+ const key = crypto.pbkdf2Sync(Buffer.from(pw, 'utf8'), salt, 1003, 16, 'sha1');
164
+ const decipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
165
+ const plainBuf = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
166
+ const token = plainBuf.toString('utf8').trim();
167
+ if (isUsablePlaintextToken(token)) {
168
+ return token;
169
+ }
170
+ }
171
+ catch { }
172
+ }
173
+ return null;
174
+ }
175
+ export function decodeStoredToken(raw, opts = {}) {
176
+ if (typeof raw !== 'string' || !raw.trim()) {
177
+ return { token: null, isEncrypted: false, decrypted: false, format: 'empty' };
178
+ }
179
+ const unquoted = stripJsonStringQuotes(raw);
180
+ if (!unquoted) {
181
+ return { token: null, isEncrypted: false, decrypted: false, format: 'empty' };
182
+ }
183
+ if (unquoted.startsWith(SAFE_STORAGE_PREFIX)) {
184
+ const encoded = unquoted.slice(SAFE_STORAGE_PREFIX.length).trim();
185
+ let blob;
186
+ try {
187
+ blob = Buffer.from(encoded, 'base64');
188
+ }
189
+ catch (err) {
190
+ return {
191
+ token: null,
192
+ isEncrypted: true,
193
+ decrypted: false,
194
+ format: 'safe-storage',
195
+ error: `safe-storage Base64 解码失败: ${err?.message || err}`,
196
+ };
197
+ }
198
+ const platform = opts.platform ?? process.platform;
199
+ try {
200
+ if (platform === 'win32') {
201
+ const localStatePath = opts.localStatePath ||
202
+ (opts.dbOrStoragePath ? resolveSidecarPaths(opts.dbOrStoragePath).localStateFile : '');
203
+ if (!localStatePath) {
204
+ return {
205
+ token: null,
206
+ isEncrypted: true,
207
+ decrypted: false,
208
+ format: 'safe-storage',
209
+ error: '检测到 cursor-safe-storage:v1 加密凭据,但缺少 Local State 路径',
210
+ };
211
+ }
212
+ const encKeyB64 = readWindowsEncryptedKeyB64(localStatePath);
213
+ if (!encKeyB64) {
214
+ return {
215
+ token: null,
216
+ isEncrypted: true,
217
+ decrypted: false,
218
+ format: 'safe-storage',
219
+ error: `未在 ${localStatePath} 中找到 os_crypt.encrypted_key`,
220
+ };
221
+ }
222
+ const cacheKey = `${localStatePath}:${encKeyB64.slice(0, 24)}`;
223
+ const decrypted = decryptWindowsChromiumBlob(blob, encKeyB64, opts.dpapiUnprotect, cacheKey);
224
+ if (decrypted) {
225
+ return {
226
+ token: decrypted,
227
+ isEncrypted: true,
228
+ decrypted: true,
229
+ format: 'safe-storage',
230
+ };
231
+ }
232
+ return {
233
+ token: null,
234
+ isEncrypted: true,
235
+ decrypted: false,
236
+ format: 'safe-storage',
237
+ error: 'Windows DPAPI / AES-256-GCM 解密 cursor-safe-storage:v1 失败',
238
+ };
239
+ }
240
+ if (platform === 'darwin') {
241
+ const passwords = (opts.keychainLookup || defaultMacKeychainLookup)();
242
+ const decrypted = decryptMacChromiumBlob(blob, passwords);
243
+ if (decrypted) {
244
+ return {
245
+ token: decrypted,
246
+ isEncrypted: true,
247
+ decrypted: true,
248
+ format: 'safe-storage',
249
+ };
250
+ }
251
+ return {
252
+ token: null,
253
+ isEncrypted: true,
254
+ decrypted: false,
255
+ format: 'safe-storage',
256
+ error: 'macOS Keychain (Cursor Safe Storage) 解密失败',
257
+ };
258
+ }
259
+ return {
260
+ token: null,
261
+ isEncrypted: true,
262
+ decrypted: false,
263
+ format: 'safe-storage',
264
+ error: `当前平台 (${platform}) 暂不支持解密 cursor-safe-storage:v1 凭据`,
265
+ };
266
+ }
267
+ catch (err) {
268
+ return {
269
+ token: null,
270
+ isEncrypted: true,
271
+ decrypted: false,
272
+ format: 'safe-storage',
273
+ error: err?.message || String(err),
274
+ };
275
+ }
276
+ }
277
+ const { value, wasScoped } = stripScopedPrefix(unquoted);
278
+ return {
279
+ token: value || null,
280
+ isEncrypted: false,
281
+ decrypted: false,
282
+ format: wasScoped ? 'scoped' : 'plain',
283
+ };
284
+ }