-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbackground.js
More file actions
1244 lines (1100 loc) · 44.1 KB
/
background.js
File metadata and controls
1244 lines (1100 loc) · 44.1 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
// Background script for Cursor Account Manager extension
// Import services
importScripts("services/account.js");
importScripts("services/payment.js");
importScripts("services/account-deletion.js");
importScripts("services/generator.js");
// Initialize generator service
const generatorService = new GeneratorService();
// Stripe API monitoring for automatic card switching
const STRIPE_API_URL = "https://api.stripe.com/v1/payment_methods";
// Check if webRequest API is available before using it
if (
chrome.webRequest &&
chrome.webRequest.onCompleted &&
chrome.webRequest.onErrorOccurred
) {
console.log("✅ WebRequest API available, setting up Stripe monitoring...");
try {
// Monitor Stripe API responses for pro trial activation
chrome.webRequest.onCompleted.addListener(
(details) => {
console.log("Stripe API Response:", {
url: details.url,
statusCode: details.statusCode,
method: details.method,
});
if (typeof details.tabId === "number" && details.tabId >= 0) {
try {
chrome.tabs.sendMessage(details.tabId, {
type: "stripe-response",
statusCode: details.statusCode,
url: details.url,
});
} catch (error) {
console.log("Failed to send stripe response to tab:", error);
}
}
},
{ urls: [STRIPE_API_URL] }
);
chrome.webRequest.onErrorOccurred.addListener(
(details) => {
console.log("Stripe API Error:", {
url: details.url,
error: details.error,
method: details.method,
});
if (typeof details.tabId === "number" && details.tabId >= 0) {
try {
chrome.tabs.sendMessage(details.tabId, {
type: "stripe-response",
statusCode: 0,
error: details.error,
url: details.url,
});
} catch (error) {
console.log("Failed to send stripe error to tab:", error);
}
}
},
{ urls: [STRIPE_API_URL] }
);
console.log("✅ Stripe API monitoring setup completed");
} catch (error) {
console.error("❌ Failed to setup WebRequest listeners:", error);
}
} else {
console.warn("⚠️ WebRequest API not available - Stripe monitoring disabled");
}
// Initialize on install
chrome.runtime.onInstalled.addListener(async () => {
console.log("Cursor Account Manager extension installed");
try {
// Enable side panel for all tabs (if supported)
if (chrome.sidePanel) {
console.log("Side Panel API available");
await chrome.sidePanel.setPanelBehavior({
openPanelOnActionClick: true, // Always open sidebar on click
});
} else {
console.log("Side Panel API not available - requires Chrome 114+");
}
// Check if there's an active session
const cookies = await accountService.getCurrentCookies();
console.log("Found cookies:", cookies.length);
if (cookies.length > 0) {
const username = await accountService.autoDetectAccount();
console.log("Auto-detected username:", username);
if (username) {
await accountService.updateBadge(username);
}
}
} catch (error) {
console.error("Error during initialization:", error);
}
});
// Sync accounts when cookies change
chrome.cookies.onChanged.addListener(async (changeInfo) => {
if (changeInfo.cookie.domain.includes("cursor.com")) {
// If cookie was added and we don't have an active account, auto-detect
if (!changeInfo.removed) {
const activeAccount = await accountService.getActiveAccount();
if (!activeAccount) {
await accountService.autoDetectAccount();
}
}
}
});
// Handle messages from popup and content scripts
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
(async () => {
try {
console.log("Received message:", request.type);
switch (request.type) {
case "ping":
sendResponse({ success: true });
break;
case "getAccounts":
const accounts = await accountService.getAll();
sendResponse({ success: true, data: accounts });
break;
case "switchAccount":
await accountService.switchTo(request.account);
sendResponse({ success: true });
break;
case "removeAccount":
await accountService.remove(
request.account,
request.deleteFile || false
);
sendResponse({ success: true });
break;
case "addCurrentAccount":
const username = await accountService.autoDetectAccount();
sendResponse({ success: true, data: username });
break;
case "getActiveAccount":
const active = await accountService.getActiveAccount();
sendResponse({ success: true, data: active });
break;
case "importAccount":
await accountService.upsert(
request.account.name,
request.account.cookies
);
sendResponse({ success: true });
break;
case "checkSwitchSuccess":
// Verify if the account switch was successful
const currentActive = await accountService.getActiveAccount();
const expectedAccount = request.expectedAccount;
sendResponse({
success: true,
switchSuccessful: currentActive === expectedAccount,
currentActive: currentActive,
});
break;
case "scanDownloadsFolder":
// Scan Downloads folder for account files
const downloadFiles = await accountService.scanDownloadsForAccounts();
sendResponse({ success: true, data: downloadFiles });
break;
case "importAccountJSON":
console.log("📥 Received importAccountJSON request");
try {
// ULTRA SAFE VALIDATION
if (!request) {
throw new Error("No request data provided");
}
if (!request.jsonText || typeof request.jsonText !== "string") {
console.error(
"❌ Invalid JSON data type:",
typeof request.jsonText
);
throw new Error("Invalid JSON data provided");
}
// VERY CONSERVATIVE size limit - 512KB
if (request.jsonText.length > 512 * 1024) {
console.error(
"❌ JSON too large:",
request.jsonText.length,
"bytes"
);
throw new Error(
`JSON file too large (${Math.round(
request.jsonText.length / 1024
)}KB > 512KB limit)`
);
}
console.log(
"✅ JSON size validation passed:",
request.jsonText.length,
"bytes"
);
// Parse and validate JSON before processing
let jsonData;
try {
jsonData = JSON.parse(request.jsonText);
console.log("✅ JSON parsing successful");
} catch (parseError) {
console.error("❌ JSON parse error:", parseError);
throw new Error(`Invalid JSON format: ${parseError.message}`);
}
// Validate JSON structure
if (!jsonData || typeof jsonData !== "object") {
throw new Error("Invalid JSON structure - not an object");
}
console.log("📤 Calling accountService.importAccountFromJSON");
const accountName = await accountService.importAccountFromJSON(
request.jsonText,
request.customName,
request.overrideExisting || false
);
console.log("🎉 Import successful:", accountName);
sendResponse({ success: true, data: accountName });
} catch (error) {
console.error("💥 Import error:", error);
// Safe error response
const errorResponse = {
success: false,
error: error.message || "Unknown import error",
isDuplicate: error.isDuplicate || false,
existingAccount: error.existingAccount || null,
};
console.log("📤 Sending error response:", errorResponse);
sendResponse(errorResponse);
}
break;
case "exportAccount":
await accountService.exportAccountToFile(request.account);
sendResponse({ success: true });
break;
case "revealAccountFile":
const revealResult = await accountService.revealAccountFile(
request.account
);
if (typeof revealResult === "boolean") {
// Legacy support
sendResponse({ success: revealResult });
} else {
// New detailed response
sendResponse(revealResult);
}
break;
case "clearAllData":
const cleared = await accountService.clearAllData();
sendResponse({ success: cleared });
break;
case "getAllStoredData":
const allData = await accountService.getAllStoredData();
sendResponse({ success: true, data: allData });
break;
case "checkDuplicateAccount":
const duplicate = await accountService.findDuplicateAccount(
request.cookies
);
sendResponse({ success: true, duplicate: duplicate });
break;
case "consolidateDuplicates":
const consolidationResult =
await accountService.consolidateDuplicates();
sendResponse(consolidationResult);
break;
case "updateAccountInfo":
await accountService.saveAccountInfo(
request.account,
request.email,
request.status
);
sendResponse({ success: true });
break;
case "getAccountInfo":
// Extract info from current page
const [tab] = await chrome.tabs.query({
active: true,
currentWindow: true,
});
// Only process if we're on any cursor.com page (broaden scope)
if (tab && tab.url && tab.url.includes("cursor.com")) {
const result = await chrome.scripting.executeScript({
target: { tabId: tab.id },
func: () => {
// This runs in the page context
const extractInfo = () => {
let email = null;
let username = null;
let status = "unknown";
// Find username first (names without @)
const nameSelectors = [
'p[class*="truncate"][class*="text-sm"][class*="font-medium"]',
"p.truncate.text-sm.font-medium",
'[class*="font-medium"][class*="truncate"]',
'p[class*="truncate"]', // More flexible selector
'div[title*="@"] p', // Target p inside div with email title
];
for (const selector of nameSelectors) {
const nameEls = document.querySelectorAll(selector);
for (const el of nameEls) {
const text = el.textContent.trim();
// Look for username (non-email text)
if (text && !text.includes("@") && text.length > 1) {
username = text;
break;
}
}
if (username) break;
}
// Step 1: Try to find email from title attributes first (most reliable)
const divsWithEmailTitle =
document.querySelectorAll('div[title*="@"]');
for (const div of divsWithEmailTitle) {
const title = div.getAttribute("title");
if (title && title.includes("@")) {
const emailMatch = title.match(
/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/
);
if (emailMatch) {
email = emailMatch[1];
break;
}
}
}
// Step 2: If no email from title, try text content from p tags
if (!email) {
const allPTags = document.querySelectorAll("p");
for (const p of allPTags) {
const text = p.textContent?.trim();
if (text && text.includes("@")) {
const emailMatch = text.match(
/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/
);
if (emailMatch) {
email = emailMatch[1];
break;
}
}
}
// Fallback: Try other elements containing @
if (!email) {
const allElements = document.querySelectorAll("*");
for (const el of allElements) {
const text = el.textContent?.trim();
if (text && text.includes("@") && text.length < 100) {
const emailMatch = text.match(
/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/
);
if (emailMatch) {
email = emailMatch[1];
break;
}
}
}
}
}
// Last-resort fallback: scan entire document text for first email-like string
if (!email) {
try {
const walker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_TEXT
);
let node;
const emailRegex =
/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/;
while ((node = walker.nextNode())) {
const m =
node.textContent &&
node.textContent.match(emailRegex);
if (m) {
email = m[0];
break;
}
}
} catch (e) {
// ignore
}
}
console.log("Looking for account status on page...");
// Find status - UPDATED WITH SPECIFIC SELECTORS FROM USER
const statusSelectors = [
// HIGHEST PRIORITY: User-provided specific selectors
'div[class*="flex min-w-0 items-center gap-1"][title*="Pro Trial"]',
'div[class*="flex min-w-0 items-center gap-1"][title*="Free"]',
'div[class*="flex min-w-0 items-center gap-1"][title*="Pro Plan"]',
'div[class*="flex min-w-0 items-center gap-1"][title*="Business"]',
// Specific p tag from user example
'p[class*="flex-shrink-0"][class*="text-sm"][class*="text-brand-gray-300"]',
// More flexible versions of the above
'div.flex.min-w-0.items-center.gap-1[title*="Trial"]',
'div.flex.min-w-0.items-center.gap-1[title*="Free"]',
'div.flex.min-w-0.items-center.gap-1[title*="Pro"]',
'div.flex.min-w-0.items-center.gap-1[title*="Business"]',
// Exact class selectors
"p.flex-shrink-0.text-sm.text-brand-gray-300",
// FALLBACK: Previous selectors
'div[title="Pro Trial"] p',
'div[title*="Trial"] p',
'div[title*="Free"] p',
'div[title*="Pro"] p',
'div[title*="Business"] p',
'div[title="Pro Trial"]',
'div[title="Free Plan"]',
'div[title="Pro Plan"]',
'div[title="Business Plan"]',
'[class*="text-brand-gray-300"]',
'div[title*="Plan"] p',
'div[title*="plan"] p',
"div.flex.min-w-0.items-center.gap-1 p",
// Manual :contains() implementation
'p:contains("Trial")',
'p:contains("Free")',
'p:contains("Pro")',
'span[class*="text-brand-gray-300"]',
'[class*="text-sm"]:contains("Trial")',
'[class*="text-sm"]:contains("Free")',
'[class*="text-sm"]:contains("Pro")',
];
for (const selector of statusSelectors) {
let statusEls;
// Handle :contains() pseudo-selector manually since it's not supported in all browsers
if (selector.includes(":contains(")) {
const baseSelector = selector.split(":contains(")[0];
const searchText = selector
.split(":contains(")[1]
.replace(")", "")
.replace(/"/g, "");
statusEls = Array.from(
document.querySelectorAll(baseSelector)
).filter((el) =>
el.textContent
.toLowerCase()
.includes(searchText.toLowerCase())
);
} else {
statusEls = document.querySelectorAll(selector);
}
for (const el of statusEls) {
const text = el.textContent.trim().toLowerCase();
const title = el.getAttribute("title") || "";
const titleLower = title.toLowerCase();
if (text || title) {
console.log(
`Found status element with text: "${text}", title: "${title}"`
);
// Check title attribute first (more reliable)
if (
titleLower.includes("pro trial") ||
titleLower === "pro trial"
) {
status = "pro trial";
break;
} else if (titleLower.includes("free")) {
status = "free";
break;
} else if (
titleLower.includes("pro plan") ||
titleLower === "pro plan"
) {
status = "pro plan";
break;
} else if (titleLower.includes("business")) {
status = "business";
break;
}
// Then check text content
else if (text.includes("free")) {
status = "free";
break;
} else if (
text.includes("pro trial") ||
text.includes("trial")
) {
status = "pro trial";
break;
} else if (text.includes("pro")) {
status = "pro plan";
break;
} else if (text.includes("business")) {
status = "business";
break;
}
}
}
if (status !== "unknown") break;
}
// Fallback: check title attributes and aria-labels
if (status === "unknown") {
const titleEls = document.querySelectorAll(
'[title*="Plan"], [title*="plan"], [title*="Trial"], [title*="trial"]'
);
for (const el of titleEls) {
const title = el.getAttribute("title").toLowerCase();
if (title.includes("free")) {
status = "free";
break;
} else if (
title.includes("pro trial") ||
title.includes("trial")
) {
status = "pro trial";
break;
} else if (title.includes("pro")) {
status = "pro plan";
break;
} else if (title.includes("business")) {
status = "business";
break;
}
}
}
// Additional fallback: search all text containing status keywords
if (status === "unknown") {
const allTextElements =
document.querySelectorAll("p, span, div");
for (const el of allTextElements) {
const text = el.textContent.trim().toLowerCase();
if (
text === "pro trial" ||
text === "free plan" ||
text === "pro plan" ||
text === "business plan"
) {
console.log(`Found status in fallback: "${text}"`);
if (text.includes("free")) {
status = "free";
break;
} else if (
text.includes("pro trial") ||
text === "pro trial"
) {
status = "pro trial";
break;
} else if (text.includes("pro")) {
status = "pro plan";
break;
} else if (text.includes("business")) {
status = "business";
break;
}
}
}
}
// Debug logging (can be removed in production)
console.log("Extracted account info:", {
username,
email,
status,
});
// Fallback logic for username and email
if (!email && username) {
email = username;
}
// Extract username from email if no separate username found
if (email && !username) {
const emailParts = email.split("@");
if (emailParts.length > 1 && emailParts[0].length > 2) {
username = emailParts[0]; // e.g., "vogogek963" from "vogogek963@namestal.com"
} else {
username = email; // Fallback to full email
}
}
// Final fallback: if still no username, use email
if (!username && email) {
username = email;
}
return { username, email, status };
};
return extractInfo();
},
});
if (result && result[0] && result[0].result) {
sendResponse({ success: true, data: result[0].result });
} else {
sendResponse({ success: false, error: "Could not extract info" });
}
} else {
sendResponse({ success: false, error: "Not on cursor.com" });
}
break;
// Payment service handlers
case "importPaymentCards":
const importedCount = await paymentService.importCards(
request.cardData,
request.replace || false
);
sendResponse({ success: true, data: importedCount });
break;
case "exportPaymentCards":
const exportData = await paymentService.exportCards();
sendResponse({ success: true, data: exportData });
break;
case "getPaymentCards":
const cards = await paymentService.getCards();
sendResponse({ success: true, data: cards });
break;
case "removePaymentCard":
await paymentService.removeCard(request.cardId);
sendResponse({ success: true });
break;
case "clearPaymentCards":
await paymentService.clearAllCards();
sendResponse({ success: true });
break;
case "autoFillPayment":
// Get card data first
const cardData = await paymentService.getCard(request.cardId);
if (!cardData) {
sendResponse({ success: false, error: "Card not found" });
break;
}
// Execute auto-fill in the current tab
const [currentTab] = await chrome.tabs.query({
active: true,
currentWindow: true,
});
if (!currentTab) {
sendResponse({ success: false, error: "No active tab found" });
break;
}
try {
const result = await chrome.scripting.executeScript({
target: { tabId: currentTab.id },
func: (card) => {
// Auto-fill payment fields with improved Stripe support
const fillInput = (element, value) => {
if (!element || !value) return false;
// Focus the element first
element.focus();
// Clear existing value
element.value = "";
// Simulate typing for React/Stripe forms
for (let i = 0; i < value.length; i++) {
const char = value[i];
// KeyDown event
const keyDownEvent = new KeyboardEvent("keydown", {
key: char,
keyCode: char.charCodeAt(0),
which: char.charCodeAt(0),
bubbles: true,
cancelable: true,
});
element.dispatchEvent(keyDownEvent);
// Update value progressively
element.value = value.substring(0, i + 1);
// Input event after each character
const inputEvent = new Event("input", { bubbles: true });
element.dispatchEvent(inputEvent);
// KeyUp event
const keyUpEvent = new KeyboardEvent("keyup", {
key: char,
keyCode: char.charCodeAt(0),
which: char.charCodeAt(0),
bubbles: true,
cancelable: true,
});
element.dispatchEvent(keyUpEvent);
}
// Final events
const events = ["change", "blur"];
events.forEach((eventType) => {
const event = new Event(eventType, { bubbles: true });
element.dispatchEvent(event);
});
return true;
};
let filledCount = 0;
// Stripe-specific selectors first, then generic
const cardNumberSelectors = [
"#cardNumber",
'input[name="cardNumber"]',
'input[autocomplete="cc-number"]',
'input[aria-label*="Card number"]',
'input.CheckoutInput[autocomplete="cc-number"]',
];
const expirySelectors = [
"#cardExpiry",
'input[name="cardExpiry"]',
'input[autocomplete="cc-exp"]',
'input[aria-label*="Expiration"]',
'input.CheckoutInput[autocomplete="cc-exp"]',
];
const cvcSelectors = [
"#cardCvc",
'input[name="cardCvc"]',
'input[autocomplete="cc-csc"]',
'input[aria-label*="CVC"]',
'input.CheckoutInput[autocomplete="cc-csc"]',
];
// Fill card number
for (const selector of cardNumberSelectors) {
const element = document.querySelector(selector);
if (element && element.offsetParent !== null) {
if (fillInput(element, card.number)) filledCount++;
break;
}
}
// Fill expiry
for (const selector of expirySelectors) {
const element = document.querySelector(selector);
if (element && element.offsetParent !== null) {
if (fillInput(element, card.expiry)) filledCount++;
break;
}
}
// Fill CVC
for (const selector of cvcSelectors) {
const element = document.querySelector(selector);
if (element && element.offsetParent !== null) {
if (fillInput(element, card.cvc)) filledCount++;
break;
}
}
return { filled: filledCount, cardType: card.type };
},
args: [cardData],
});
if (result && result[0] && result[0].result.filled > 0) {
sendResponse({
success: true,
data: {
filled: result[0].result.filled,
cardType: result[0].result.cardType,
},
});
} else {
sendResponse({
success: false,
error: "No payment fields found or filled",
});
}
} catch (error) {
sendResponse({ success: false, error: error.message });
}
break;
case "findPaymentFields":
// Find payment fields in current tab
const [activeTab] = await chrome.tabs.query({
active: true,
currentWindow: true,
});
if (!activeTab) {
sendResponse({ success: false, error: "No active tab found" });
break;
}
try {
const result = await chrome.scripting.executeScript({
target: { tabId: activeTab.id },
func: () => {
// Find payment form fields
const fields = {
cardNumber: null,
expiry: null,
cvc: null,
name: null,
};
const cardNumberSelectors = [
'input[name*="card"]',
'input[name*="number"]',
'input[placeholder*="card"]',
'input[autocomplete="cc-number"]',
"#card-number",
];
for (const selector of cardNumberSelectors) {
const element = document.querySelector(selector);
if (element && element.offsetParent !== null) {
fields.cardNumber = true;
break;
}
}
// Similar logic for other fields...
const expirySelectors = [
'input[name*="expir"]',
'input[placeholder*="MM/YY"]',
];
for (const selector of expirySelectors) {
const element = document.querySelector(selector);
if (element && element.offsetParent !== null) {
fields.expiry = true;
break;
}
}
const cvcSelectors = [
'input[name*="cvc"]',
'input[name*="cvv"]',
];
for (const selector of cvcSelectors) {
const element = document.querySelector(selector);
if (element && element.offsetParent !== null) {
fields.cvc = true;
break;
}
}
return {
found: Object.values(fields).filter(Boolean).length,
fields: fields,
};
},
});
sendResponse({ success: true, data: result[0].result });
} catch (error) {
sendResponse({ success: false, error: error.message });
}
break;
case "deleteFreeAccount":
try {
const result = await accountDeletionService.deleteFreeAccount();
sendResponse(result);
} catch (error) {
sendResponse({ success: false, error: error.message });
}
break;
case "deleteProTrialAccount":
try {
const result = await accountDeletionService.deleteProTrialAccount();
sendResponse(result);
} catch (error) {
sendResponse({ success: false, error: error.message });
}
break;
case "checkDeletionStatus":
sendResponse({
success: true,
inProgress: accountDeletionService.isDeletionInProgress(),
});
break;
case "cancelDeletion":
accountDeletionService.cancelDeletion();
sendResponse({ success: true, message: "Deletion cancelled" });
break;
// ============= BYPASS TESTING HANDLERS =============
case "startBypassTest":
try {
console.log(
"[Background] Starting bypass test with URL:",
request.targetUrl
);
// Initialize bypass testing
const bypassTestId = Date.now().toString();
// Store initial test state
await chrome.storage.local.set({
bypassTest: {
id: bypassTestId,
targetUrl:
request.targetUrl ||
"https://cursor.com/dashboard?tab=settings",
techniques: request.techniques || ["all"],
running: true,
progress: 0,
total: 10, // We have 10 techniques
current: "Initializing...",
results: [],
},
});
// Open the target URL or navigate to settings page
const targetUrl =
request.targetUrl || "https://cursor.com/dashboard?tab=settings";
// Check if tab already exists with cursor.com
const existingTabs = await chrome.tabs.query({
url: "https://*.cursor.com/*",
});
let tab;
if (existingTabs.length > 0) {
// Use existing tab
tab = existingTabs[0];
await chrome.tabs.update(tab.id, {
url: targetUrl,
active: true,
});
} else {
// Create new tab
tab = await chrome.tabs.create({
url: targetUrl,
active: true,
});
}
// Wait for page to load then inject script
setTimeout(async () => {
try {
// Inject the working bypass script
await chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ["bypass_working.js"],
});
console.log("[Background] Bypass script injected");