-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathbackground.js
More file actions
1111 lines (974 loc) · 36.7 KB
/
background.js
File metadata and controls
1111 lines (974 loc) · 36.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 原生消息主机配置
const NATIVE_HOST_NAME = 'com.cursor.client.manage';
// JWT解码工具函数
const JWTDecoder = {
/**
* 解码JWT token的payload部分
* @param {string} token - JWT token
* @returns {object|null} 解码后的payload对象,失败返回null
*/
decodePayload(token) {
try {
if (!token || typeof token !== 'string') {
console.error('❌ JWT解码失败: token无效');
return null;
}
// JWT由三部分组成: header.payload.signature
const parts = token.split('.');
if (parts.length !== 3) {
console.error('❌ JWT解码失败: token格式错误,应该有3个部分');
return null;
}
// 解码payload部分(第二部分)
const payload = this.decodeBase64Part(parts[1]);
console.log('✅ JWT payload解码成功:', payload);
return payload;
} catch (error) {
console.error('❌ JWT解码过程出错:', error);
return null;
}
},
/**
* 解码JWT的base64部分
* @param {string} part - base64编码的部分
* @returns {object} 解码后的对象
*/
decodeBase64Part(part) {
// 添加必要的padding
let paddedPart = part;
const missingPadding = paddedPart.length % 4;
if (missingPadding) {
paddedPart += '='.repeat(4 - missingPadding);
}
// Base64解码
const decodedBytes = atob(paddedPart.replace(/-/g, '+').replace(/_/g, '/'));
return JSON.parse(decodedBytes);
},
/**
* 从JWT token中提取用户ID
* @param {string} token - JWT token
* @returns {string|null} 用户ID,失败返回null
*/
extractUserId(token) {
const payload = this.decodePayload(token);
if (!payload || !payload.sub) {
console.error('❌ 无法从JWT中提取用户ID: sub字段不存在');
return null;
}
const sub = payload.sub;
console.log('🔍 JWT sub字段:', sub);
// 如果sub包含|分隔符,提取后半部分作为用户ID
if (sub.includes('|')) {
const userId = sub.split('|')[1];
console.log('✅ 从JWT提取的用户ID:', userId);
return userId;
} else {
// 直接使用sub作为用户ID
console.log('✅ 直接使用sub作为用户ID:', sub);
return sub;
}
},
/**
* 从JWT token中提取过期时间
* @param {string} token - JWT token
* @returns {object|null} 包含过期时间信息的对象,失败返回null
*/
extractExpirationInfo(token) {
const payload = this.decodePayload(token);
if (!payload || !payload.exp) {
console.error('❌ 无法从JWT中提取过期时间: exp字段不存在');
return null;
}
const expTimestamp = payload.exp;
const expDate = new Date(expTimestamp * 1000); // exp是秒级时间戳,需要转换为毫秒
const currentDate = new Date();
const isExpired = expDate <= currentDate;
// 计算剩余天数
const remainingMs = expDate.getTime() - currentDate.getTime();
const remainingDays = Math.max(0, Math.ceil(remainingMs / (1000 * 60 * 60 * 24)));
const expirationInfo = {
expTimestamp: expTimestamp,
expDate: expDate.toISOString(),
isExpired: isExpired,
remainingDays: remainingDays
};
console.log('✅ JWT过期时间信息:', expirationInfo);
return expirationInfo;
},
/**
* 完整解析JWT token,提取所有关键信息
* @param {string} token - JWT token
* @returns {object|null} 包含用户ID和过期信息的对象,失败返回null
*/
parseToken(token) {
try {
const payload = this.decodePayload(token);
if (!payload) {
return null;
}
const userId = this.extractUserId(token);
const expirationInfo = this.extractExpirationInfo(token);
if (!userId || !expirationInfo) {
console.error('❌ JWT解析失败: 无法提取必要信息');
return null;
}
const result = {
userId: userId,
sub: payload.sub,
exp: payload.exp,
expirationInfo: expirationInfo,
fullPayload: payload
};
console.log('✅ JWT完整解析结果:', result);
return result;
} catch (error) {
console.error('❌ JWT完整解析失败:', error);
return null;
}
}
};
// 安装时的初始化
chrome.runtime.onInstalled.addListener(() => {
console.log('Cursor Client2Login 插件已安装');
});
// 消息处理器映射
const messageHandlers = {
'getCursorData': getCursorAuthData,
'autoReadCursorData': autoReadCursorData,
'saveToLocalStorage': (data) => saveToLocalStorage(data),
'setCookie': (data) => setCursorCookie(data),
'clearCookie': clearCursorCookie,
'openDashboard': openCursorDashboard,
'getCurrentCookieStatus': getCurrentCookieStatus,
'validateCurrentAccountStatus': validateCurrentAccountStatus,
'getDeepToken': (data) => getDeepToken(data),
'pollDeepToken': (data) => pollDeepToken(data),
'getAccountList': () => chrome.storage.local.get(['accountList']).then(result => ({ accountList: result.accountList || [] })),
'getCurrentAccount': () => chrome.storage.local.get(['currentAccount']).then(result => ({ currentAccount: result.currentAccount || null })),
'switchAccount': (data) => switchAccount(data),
'parseFileContent': (data) => parseFileContent(data.content, data.fileType)
};
// 统一的消息处理器
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
const handler = messageHandlers[request.action];
if (handler) {
// 根据不同的action类型,选择正确的数据字段
let handlerData;
if (request.action === 'switchAccount') {
// switchAccount使用accountData字段
handlerData = request.accountData;
console.log('🔄 处理switchAccount消息:', {
hasAccountData: !!handlerData,
accountEmail: handlerData?.email,
accountUserid: handlerData?.userid
});
} else {
// 其他action使用data字段
handlerData = request.data;
}
const result = handler(handlerData);
// 如果返回Promise,等待结果
if (result && typeof result.then === 'function') {
result.then(sendResponse).catch(error => {
console.error(`处理${request.action}时发生错误:`, error);
sendResponse({ success: false, error: error.message });
});
return true; // 保持消息通道开启
} else {
// 同步结果直接返回
sendResponse(result);
}
} else {
console.warn('未知的消息类型:', request.action);
sendResponse({ success: false, error: '未知的消息类型' });
}
});
// 自动读取Cursor认证数据
async function autoReadCursorData() {
try {
console.log('开始尝试自动读取Cursor数据...');
// 方法1: 尝试使用原生消息传递
try {
console.log('尝试连接原生主机:', NATIVE_HOST_NAME);
const nativeResult = await sendNativeMessage({ action: 'getClientCurrentData' });
console.log('原生主机响应:', nativeResult);
if (nativeResult && !nativeResult.error) {
console.log('原生主机读取成功');
return {
success: true,
data: nativeResult,
method: 'native'
};
} else {
console.log('原生主机返回错误:', nativeResult?.error);
return {
success: false,
error: `原生主机错误: ${nativeResult?.error || '未知错误'}`,
needFileSelection: true
};
}
} catch (nativeError) {
console.error('原生消息传递失败:', nativeError);
// 提取详细错误信息
let errorMessage = '原生主机连接失败';
let errorDetails = '';
let troubleshooting = [];
try {
// 尝试解析JSON格式的错误信息
const errorInfo = JSON.parse(nativeError.message);
errorMessage = errorInfo.message || errorMessage;
errorDetails = errorInfo.originalError || '';
troubleshooting = errorInfo.troubleshooting || [];
} catch (parseError) {
// 如果不是JSON格式,直接使用错误消息
if (nativeError.message) {
errorDetails = nativeError.message;
} else if (typeof nativeError === 'object') {
errorDetails = JSON.stringify(nativeError);
} else {
errorDetails = String(nativeError);
}
// 检查常见错误类型
if (errorDetails.includes('not found') || errorDetails.includes('access denied')) {
errorMessage = '原生主机未正确安装或权限不足';
} else if (errorDetails.includes('Specified native messaging host not found')) {
errorMessage = '找不到原生主机程序,请检查安装是否正确';
} else if (errorDetails.includes('disconnected') || errorDetails.includes('connection')) {
errorMessage = '原生主机连接中断,请重启Chrome浏览器';
}
}
console.log('错误详情:', errorDetails);
console.log('故障排除建议:', troubleshooting);
return {
success: false,
error: errorMessage,
details: errorDetails,
troubleshooting: troubleshooting,
needFileSelection: true
};
}
} catch (error) {
console.error('autoReadCursorData error:', error);
return {
success: false,
error: `自动读取失败: ${error.message}`,
needFileSelection: true
};
}
}
// 发送原生消息
function sendNativeMessage(message) {
return new Promise((resolve, reject) => {
console.log('发送原生消息:', message);
// 检查原生消息传递权限
if (!chrome.runtime.sendNativeMessage) {
reject(new Error('原生消息传递API不可用,请检查插件权限'));
return;
}
try {
chrome.runtime.sendNativeMessage(NATIVE_HOST_NAME, message, (response) => {
const lastError = chrome.runtime.lastError;
if (lastError) {
console.error('原生消息错误对象:', lastError);
console.error('错误消息:', lastError.message);
// 创建详细的错误信息
let errorMessage = lastError.message || '未知错误';
// 检查常见错误类型并提供更好的错误信息
if (errorMessage.includes('Specified native messaging host not found')) {
errorMessage = `原生主机未找到 (${NATIVE_HOST_NAME})。请确保已正确安装原生主机程序。`;
} else if (errorMessage.includes('Access denied')) {
errorMessage = '访问被拒绝。请检查原生主机程序的权限设置。';
} else if (errorMessage.includes('Invalid native messaging host name')) {
errorMessage = `无效的原生主机名称: ${NATIVE_HOST_NAME}`;
}
const errorInfo = {
message: errorMessage,
originalError: lastError.message,
hostName: NATIVE_HOST_NAME,
timestamp: new Date().toISOString(),
troubleshooting: [
'1. 确保已运行 python3 install_native_host.py',
'2. 重启 Chrome 浏览器',
'3. 检查原生主机配置文件是否存在',
'4. 尝试使用具体扩展ID更新配置'
]
};
reject(new Error(JSON.stringify(errorInfo, null, 2)));
} else {
console.log('原生消息响应:', response);
resolve(response);
}
});
} catch (syncError) {
console.error('同步错误:', syncError);
reject(new Error(`同步调用失败: ${syncError.message}`));
}
});
}
// 处理文件内容解析
async function parseFileContent(fileContent, fileType) {
try {
if (fileType === 'database') {
// 这里应该解析SQLite数据库,但浏览器环境限制较大
// 我们提供一个替代方案:让用户导出数据
return {
success: false,
error: '浏览器无法直接解析SQLite数据库,请使用原生主机或手动导入'
};
} else if (fileType === 'json') {
// 解析scope_v3.json
const content = fileContent.replace(/%$/, '').trim();
const data = JSON.parse(content);
const userInfo = data.scope?.user || {};
const email = userInfo.email;
const userIdFull = userInfo.id;
if (email && userIdFull && userIdFull.includes('|')) {
const userid = userIdFull.split('|')[1];
return {
success: true,
data: { email, userid }
};
} else {
return {
success: false,
error: '无法从JSON文件中提取有效的email或userid'
};
}
}
} catch (error) {
return {
success: false,
error: `文件解析失败: ${error.message}`
};
}
}
// 获取Cursor认证数据
async function getCursorAuthData() {
try {
// 首先尝试从localStorage中获取已保存的数据
const savedData = await chrome.storage.local.get(['cursorAuthData']);
if (savedData.cursorAuthData) {
return { success: true, data: savedData.cursorAuthData };
}
// 如果没有保存的数据,需要用户手动提供
return {
success: false,
error: '需要用户手动导入Cursor认证数据',
needManualImport: true
};
} catch (error) {
return { success: false, error: error.message };
}
}
// 保存到localStorage
async function saveToLocalStorage(data) {
try {
console.log('💾 开始保存账户数据到Storage并更新Cookie...', {
email: data.email,
userid: data.userid,
tokenType: data.tokenType || 'client',
accessTokenLength: data.accessToken ? data.accessToken.length : 0
});
// 获取现有的账户列表
const result = await chrome.storage.local.get(['accountList']);
let accountList = result.accountList || [];
// 检查是否已存在相同email的账户
const existingIndex = accountList.findIndex(account => account.email === data.email);
if (existingIndex >= 0) {
// 更新现有账户
console.log('🔄 更新现有账户:', data.email);
accountList[existingIndex] = data;
} else {
// 添加新账户
console.log('➕ 添加新账户:', data.email);
accountList.push(data);
}
// 保存到chrome.storage
await chrome.storage.local.set({
accountList: accountList,
currentAccount: data
});
console.log('✅ 账户数据已保存到Storage');
// 统一在这里设置Cookie,确保Storage和Cookie同步
console.log('🍪 开始统一设置Cookie...');
const cookieResult = await setCursorCookie({
userid: data.userid,
accessToken: data.accessToken
});
if (!cookieResult.success) {
console.warn('⚠️ Cookie设置失败,但Storage已保存:', cookieResult.error);
return {
success: true,
message: '账户信息已保存到本地存储,但Cookie设置失败',
cookieError: cookieResult.error
};
}
console.log('✅ 账户数据和Cookie已同步更新');
return {
success: true,
message: '账户信息已保存到本地存储并更新Cookie',
cookieSet: true
};
} catch (error) {
console.error('❌ 保存账户数据失败:', error);
return { success: false, error: error.message };
}
}
// 设置Cookie
async function setCursorCookie(data) {
try {
const { userid, accessToken } = data;
const cookieValue = `${userid}%3A%3A${accessToken}`;
console.log('🍪 开始设置Cursor Cookie...', {
userid: userid,
accessTokenLength: accessToken ? accessToken.length : 0,
cookieValueLength: cookieValue.length
});
// 先尝试删除现有的Cookie,确保强制覆盖
try {
await chrome.cookies.remove({
url: 'https://www.cursor.com',
name: 'WorkosCursorSessionToken'
});
console.log('🗑️ 已删除现有Cookie,准备设置新Cookie');
} catch (removeError) {
console.log('⚠️ 删除现有Cookie时出错(可能不存在):', removeError.message);
}
// 等待一下确保删除操作完成
await new Promise(resolve => setTimeout(resolve, 200));
// 设置新的Cookie
const cookieParams = {
url: 'https://www.cursor.com',
name: 'WorkosCursorSessionToken',
value: cookieValue,
domain: '.cursor.com',
path: '/',
httpOnly: false,
secure: true,
sameSite: 'lax'
};
console.log('🍪 设置Cookie参数:', {
name: cookieParams.name,
domain: cookieParams.domain,
path: cookieParams.path,
valueLength: cookieParams.value.length,
secure: cookieParams.secure,
sameSite: cookieParams.sameSite
});
await chrome.cookies.set(cookieParams);
console.log('✅ Cookie设置操作完成');
// 验证Cookie是否设置成功
const verificationCookies = await chrome.cookies.getAll({
url: 'https://www.cursor.com',
name: 'WorkosCursorSessionToken'
});
if (verificationCookies.length > 0) {
const verifiedCookie = verificationCookies[0];
console.log('✅ Cookie设置验证成功:', {
name: verifiedCookie.name,
domain: verifiedCookie.domain,
valueLength: verifiedCookie.value ? verifiedCookie.value.length : 0,
secure: verifiedCookie.secure
});
// 检查Cookie值是否正确
if (verifiedCookie.value === cookieValue) {
console.log('✅ Cookie值完全匹配');
return { success: true, message: 'Cookie已设置成功并验证' };
} else {
console.warn('⚠️ Cookie值不匹配', {
expected: cookieValue.substring(0, 50) + '...',
actual: verifiedCookie.value ? verifiedCookie.value.substring(0, 50) + '...' : 'null'
});
return { success: true, message: 'Cookie已设置但值可能不匹配' };
}
} else {
console.warn('⚠️ Cookie设置后验证失败:未找到Cookie');
return { success: false, error: 'Cookie设置后验证失败' };
}
} catch (error) {
console.error('❌ 设置Cookie时发生错误:', error);
return { success: false, error: error.message };
}
}
// 清除Cookie
async function clearCursorCookie() {
try {
console.log('🍪 开始彻底清除Cursor认证Cookie...');
// 多种方式清除特定的Cookie,确保彻底删除
const removeTargets = [
{ url: 'https://www.cursor.com', name: 'WorkosCursorSessionToken' },
{ url: 'https://cursor.com', name: 'WorkosCursorSessionToken' },
{ url: 'http://www.cursor.com', name: 'WorkosCursorSessionToken' },
{ url: 'http://cursor.com', name: 'WorkosCursorSessionToken' }
];
for (const target of removeTargets) {
try {
await chrome.cookies.remove(target);
console.log(`🗑️ 尝试清除Cookie: ${target.url} - ${target.name}`);
} catch (err) {
console.log(`⚠️ 清除Cookie失败 (${target.url}):`, err.message);
}
}
// 查找并清除所有可能的cursor相关cookie
const allDomains = ['.cursor.com', 'cursor.com', 'www.cursor.com'];
for (const domain of allDomains) {
try {
const allCookies = await chrome.cookies.getAll({ domain });
console.log(`🔍 在域名 ${domain} 找到的Cookies:`, allCookies.length);
for (const cookie of allCookies) {
if (cookie.name.toLowerCase().includes('session') ||
cookie.name.toLowerCase().includes('auth') ||
cookie.name.toLowerCase().includes('token') ||
cookie.name === 'WorkosCursorSessionToken') {
try {
// 尝试多种URL格式来删除Cookie
const urlsToTry = [
`https://${cookie.domain.startsWith('.') ? cookie.domain.substring(1) : cookie.domain}`,
`https://${cookie.domain}`,
`http://${cookie.domain.startsWith('.') ? cookie.domain.substring(1) : cookie.domain}`,
`http://${cookie.domain}`
];
for (const url of urlsToTry) {
try {
await chrome.cookies.remove({
url: url,
name: cookie.name
});
console.log(`✅ 成功清除Cookie: ${cookie.name} (${url})`);
break; // 如果成功了就跳出循环
} catch (removeErr) {
console.log(`⚠️ 尝试删除失败 ${cookie.name} (${url}):`, removeErr.message);
}
}
} catch (err) {
console.warn(`⚠️ 清除Cookie失败: ${cookie.name}`, err);
}
}
}
} catch (domainErr) {
console.log(`⚠️ 查询域名 ${domain} 的Cookie失败:`, domainErr.message);
}
}
// 等待一下确保删除操作完成
await new Promise(resolve => setTimeout(resolve, 500));
// 验证清除结果
const remainingCookies = await chrome.cookies.getAll({
name: 'WorkosCursorSessionToken'
});
if (remainingCookies.length === 0) {
console.log('✅ 所有WorkosCursorSessionToken Cookie已彻底清除');
return { success: true, message: 'Cursor认证Cookie已彻底清除' };
} else {
console.warn('⚠️ 仍有Cookie未清除:', remainingCookies.map(c => ({ name: c.name, domain: c.domain })));
return { success: true, message: `Cursor认证Cookie已部分清除,仍有${remainingCookies.length}个Cookie残留` };
}
} catch (error) {
console.error('❌ 清除Cookie时发生错误:', error);
return { success: false, error: error.message };
}
}
// 打开Cursor Dashboard
async function openCursorDashboard() {
try {
await chrome.tabs.create({
url: 'https://www.cursor.com/cn/dashboard',
active: true
});
return { success: true, message: 'Dashboard页面已打开' };
} catch (error) {
return { success: false, error: error.message };
}
}
// 注意:消息处理已在上面的统一处理器中合并,此处删除重复代码
// 切换账户
async function switchAccount(accountData) {
try {
console.log('🔄 开始切换账户...', {
accountData: accountData ? {
email: accountData.email,
userid: accountData.userid,
hasAccessToken: !!accountData.accessToken,
hasWorkosToken: !!accountData.WorkosCursorSessionToken
} : 'undefined'
});
// 检查accountData是否存在
if (!accountData) {
throw new Error('账户数据为空,无法切换账户');
}
// 提取accessToken,支持两种格式
let accessToken;
if (accountData.accessToken) {
accessToken = accountData.accessToken;
console.log('✅ 使用直接的accessToken');
} else if (accountData.WorkosCursorSessionToken && accountData.WorkosCursorSessionToken.includes('%3A%3A')) {
accessToken = accountData.WorkosCursorSessionToken.split('%3A%3A')[1];
console.log('✅ 从WorkosCursorSessionToken中提取accessToken');
} else {
console.error('❌ 无法找到有效的accessToken:', {
hasAccessToken: !!accountData.accessToken,
hasWorkosToken: !!accountData.WorkosCursorSessionToken,
workosTokenFormat: accountData.WorkosCursorSessionToken ?
(accountData.WorkosCursorSessionToken.includes('%3A%3A') ? '包含分隔符' : '不包含分隔符') :
'不存在'
});
throw new Error('无法找到有效的accessToken');
}
await setCursorCookie({
userid: accountData.userid,
accessToken: accessToken
});
await chrome.storage.local.set({ currentAccount: accountData });
return { success: true, message: '账户切换成功' };
} catch (error) {
return { success: false, error: error.message };
}
}
// 获取当前Cookie状态
async function getCurrentCookieStatus() {
try {
console.log('🍪 开始检查当前Cookie状态...');
// 方法1: 使用URL查询
let cookies = await chrome.cookies.getAll({
url: 'https://www.cursor.com',
name: 'WorkosCursorSessionToken'
});
console.log('🔍 方法1 - URL查询结果:', cookies.length);
// 方法2: 如果没找到,尝试仅使用name查询
if (cookies.length === 0) {
console.log('🔍 尝试方法2 - 仅使用name查询...');
cookies = await chrome.cookies.getAll({
name: 'WorkosCursorSessionToken'
});
console.log('🔍 方法2查询结果:', cookies.length);
}
// 方法3: 如果还没找到,查询所有cursor.com域名的Cookie
if (cookies.length === 0) {
console.log('🔍 尝试方法3 - 查询所有cursor域名Cookie...');
const allCursorCookies = await chrome.cookies.getAll({
domain: '.cursor.com'
});
console.log('🔍 所有cursor Cookie:', allCursorCookies.map(c => c.name));
cookies = allCursorCookies.filter(cookie =>
cookie.name === 'WorkosCursorSessionToken'
);
console.log('🔍 方法3过滤结果:', cookies.length);
}
// 方法4: 尝试不同的域名格式
if (cookies.length === 0) {
console.log('🔍 尝试方法4 - 使用cursor.com域名查询...');
const cursorCookies = await chrome.cookies.getAll({
domain: 'cursor.com'
});
console.log('🔍 cursor.com域名Cookie:', cursorCookies.map(c => c.name));
cookies = cursorCookies.filter(cookie =>
cookie.name === 'WorkosCursorSessionToken'
);
console.log('🔍 方法4过滤结果:', cookies.length);
}
console.log('🔍 最终查找Cookie结果:', {
找到的Cookie数量: cookies.length,
cookies: cookies.map(c => ({
name: c.name,
domain: c.domain,
path: c.path,
valueLength: c.value ? c.value.length : 0
}))
});
if (cookies.length === 0) {
console.log('❌ 未找到WorkosCursorSessionToken Cookie');
// 获取所有可能相关的Cookie用于调试
const allCookies = await chrome.cookies.getAll({});
const relevantCookies = allCookies.filter(cookie =>
cookie.domain.includes('cursor') ||
cookie.name.toLowerCase().includes('session') ||
cookie.name.toLowerCase().includes('token')
);
return {
success: true,
hasCookie: false,
message: '当前无认证Cookie',
debugInfo: {
查询方法: '尝试了4种不同的查询方式',
相关Cookie: relevantCookies.map(c => ({
name: c.name,
domain: c.domain,
path: c.path
}))
}
};
}
const cookie = cookies[0];
console.log('🍪 找到Cookie详情:', {
name: cookie.name,
value: cookie.value ? cookie.value.substring(0, 50) + '...' : 'null',
valueLength: cookie.value ? cookie.value.length : 0,
domain: cookie.domain,
path: cookie.path,
expirationDate: cookie.expirationDate,
secure: cookie.secure,
httpOnly: cookie.httpOnly
});
// 解析Cookie值
if (!cookie.value) {
return {
success: true,
hasCookie: true,
cookieData: null,
message: 'Cookie值为空',
debugInfo: {
cookie: cookie
}
};
}
// 格式检查:userid%3A%3AaccessToken
if (cookie.value.includes('%3A%3A')) {
const parts = cookie.value.split('%3A%3A');
console.log('🔍 Cookie分割结果:', {
原始值长度: cookie.value.length,
分割后部分数量: parts.length,
第一部分长度: parts[0] ? parts[0].length : 0,
第二部分长度: parts[1] ? parts[1].length : 0
});
if (parts.length === 2 && parts[0] && parts[1]) {
const userid = parts[0];
const accessToken = parts[1];
// 使用JWT解码获取用户ID和过期时间
console.log('🔍 开始使用JWT解码分析Token...');
const jwtInfo = JWTDecoder.parseToken(accessToken);
let finalUserId = userid;
let tokenExpirationInfo = null;
let isTokenExpired = false;
if (jwtInfo) {
// 使用JWT解码的用户ID(如果可用)
if (jwtInfo.userId) {
finalUserId = jwtInfo.userId;
console.log('✅ 使用JWT解码的用户ID:', finalUserId);
}
// 使用JWT解码的过期时间
if (jwtInfo.expirationInfo) {
tokenExpirationInfo = jwtInfo.expirationInfo;
isTokenExpired = jwtInfo.expirationInfo.isExpired;
console.log('✅ 使用JWT解码的过期时间:', {
expDate: jwtInfo.expirationInfo.expDate,
isExpired: isTokenExpired,
remainingDays: jwtInfo.expirationInfo.remainingDays
});
}
} else {
console.warn('⚠️ JWT解码失败,使用Cookie原始信息');
// 如果JWT解码失败,回退到Cookie的过期时间
isTokenExpired = cookie.expirationDate && cookie.expirationDate * 1000 < Date.now();
}
console.log('✅ Cookie解析成功:', {
originalUserId: userid,
finalUserId: finalUserId,
accessTokenLength: accessToken.length,
isTokenExpired: isTokenExpired,
hasJWTInfo: !!jwtInfo,
cookieExpirationDate: cookie.expirationDate ? new Date(cookie.expirationDate * 1000).toISOString() : 'undefined',
jwtExpirationDate: tokenExpirationInfo ? tokenExpirationInfo.expDate : 'undefined'
});
return {
success: true,
hasCookie: true,
cookieData: {
userid: finalUserId,
originalUserId: userid, // 保留原始用户ID用于调试
accessToken: accessToken,
expirationDate: cookie.expirationDate,
isExpired: isTokenExpired,
domain: cookie.domain,
path: cookie.path,
jwtInfo: jwtInfo, // 包含完整的JWT解码信息
tokenExpirationInfo: tokenExpirationInfo // JWT解码的过期信息
},
message: isTokenExpired ? 'Token已过期' : 'Token有效',
debugInfo: {
原始Cookie值: cookie.value,
解析结果: {
originalUserId: userid,
finalUserId: finalUserId,
accessTokenLength: accessToken.length,
jwtDecoded: !!jwtInfo
}
}
};
}
}
console.log('⚠️ Cookie格式无法解析:', {
value: cookie.value,
包含分隔符: cookie.value.includes('%3A%3A'),
valueType: typeof cookie.value
});
return {
success: true,
hasCookie: true,
cookieData: null,
message: 'Cookie格式无法解析',
debugInfo: {
原始Cookie值: cookie.value,
格式检查: {
包含分隔符: cookie.value.includes('%3A%3A'),
值类型: typeof cookie.value,
值内容: cookie.value
}
}
};
} catch (error) {
console.error('❌ 检查Cookie状态时发生错误:', error);
return {
success: false,
error: error.message,
debugInfo: {
错误类型: error.name,
错误消息: error.message,
错误堆栈: error.stack
}
};
}
}
// 获取深度Token
async function getDeepToken(params = {}) {
try {
console.log('开始获取深度Token...', params);
/*
========================================
无头模式逻辑 - 暂时注释掉
========================================
原因:原生主机的无头模式实现存在问题,需要完善后再启用
恢复方法:取消下面的注释,并确保 native_host.py 中的相关方法正常工作
注意:目前只支持浏览器模式(deep_browser),无头模式(deep_headless)暂时禁用
========================================
*/
// 检查模式,暂时只支持浏览器模式
const mode = params.mode || 'deep_browser';
if (mode === 'deep_headless') {
console.warn('⚠️ 无头模式暂时禁用,自动切换到浏览器模式');
params.mode = 'deep_browser';
}
const message = {
action: 'getClientCurrentData',
params: {
mode: params.mode || 'deep_browser' // 默认使用浏览器模式
}
};
const nativeResult = await sendNativeMessage(message);
console.log('深度Token原生主机响应:', nativeResult);
if (nativeResult && !nativeResult.error) {
console.log('深度Token获取成功');
return {
success: true,
data: nativeResult,
method: 'native'
};
} else {
console.log('深度Token原生主机返回错误:', nativeResult?.error);
return {
success: false,
error: `深度Token获取失败: ${nativeResult?.error || '未知错误'}`,
needFileSelection: true
};
}
} catch (error) {
console.error('getDeepToken error:', error);
return {
success: false,
error: `深度Token获取失败: ${error.message}`,
needFileSelection: true
};
}
}
// 验证当前账户状态(对比storage和cookie)
async function validateCurrentAccountStatus() {