Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
1496 lines (1297 loc) · 46.8 KB
/
Copy pathbackground.js
File metadata and controls
1496 lines (1297 loc) · 46.8 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.js — Service Worker: orchestration, state, tab management, message routing
importScripts('data/names.js');
const LOG_PREFIX = '[MultiPage:bg]';
const DUCK_AUTOFILL_URL = 'https://duckduckgo.com/email/settings/autofill';
const STOP_ERROR_MESSAGE = 'Flow stopped by user.';
const HUMAN_STEP_DELAY_MIN = 700;
const HUMAN_STEP_DELAY_MAX = 2200;
initializeSessionStorageAccess();
let automationWindowId = null;
async function ensureAutomationWindowId() {
if (automationWindowId != null) {
try {
await chrome.windows.get(automationWindowId);
return automationWindowId;
} catch {
automationWindowId = null;
}
}
const registry = await getTabRegistry();
for (const entry of Object.values(registry)) {
if (!entry?.tabId) continue;
try {
const tab = await chrome.tabs.get(entry.tabId);
automationWindowId = tab.windowId;
return automationWindowId;
} catch {}
}
const win = await chrome.windows.getLastFocused();
automationWindowId = win.id;
return automationWindowId;
}
// ============================================================
// State Management (chrome.storage.session)
// ============================================================
const DEFAULT_STATE = {
currentStep: 0,
stepStatuses: {
1: 'pending', 2: 'pending', 3: 'pending', 4: 'pending', 5: 'pending',
6: 'pending', 7: 'pending', 8: 'pending', 9: 'pending',
},
oauthUrl: null,
email: null,
password: null,
accounts: [], // { email, password, createdAt }
lastEmailTimestamp: null,
localhostUrl: null,
flowStartTime: null,
tabRegistry: {},
logs: [],
vpsUrl: '',
customPassword: '',
mailProvider: '163', // 'qq' or '163'
inbucketHost: '',
inbucketMailbox: '',
};
async function getState() {
const state = await chrome.storage.session.get(null);
return { ...DEFAULT_STATE, ...state };
}
async function initializeSessionStorageAccess() {
try {
if (chrome.storage?.session?.setAccessLevel) {
await chrome.storage.session.setAccessLevel({
accessLevel: 'TRUSTED_AND_UNTRUSTED_CONTEXTS',
});
console.log(LOG_PREFIX, 'Enabled storage.session for content scripts');
}
} catch (err) {
console.warn(LOG_PREFIX, 'Failed to enable storage.session for content scripts:', err?.message || err);
}
}
async function setState(updates) {
console.log(LOG_PREFIX, 'storage.set:', JSON.stringify(updates).slice(0, 200));
await chrome.storage.session.set(updates);
}
function broadcastDataUpdate(payload) {
chrome.runtime.sendMessage({
type: 'DATA_UPDATED',
payload,
}).catch(() => {});
}
async function setEmailState(email) {
await setState({ email });
broadcastDataUpdate({ email });
}
async function setPasswordState(password) {
await setState({ password });
broadcastDataUpdate({ password });
}
async function resetState() {
console.log(LOG_PREFIX, 'Resetting all state');
// Preserve settings and persistent data across resets
const prev = await chrome.storage.session.get([
'seenCodes',
'seenInbucketMailIds',
'accounts',
'tabRegistry',
'vpsUrl',
'customPassword',
'mailProvider',
'inbucketHost',
'inbucketMailbox',
]);
await chrome.storage.session.clear();
await chrome.storage.session.set({
...DEFAULT_STATE,
seenCodes: prev.seenCodes || [],
seenInbucketMailIds: prev.seenInbucketMailIds || [],
accounts: prev.accounts || [],
tabRegistry: prev.tabRegistry || {},
vpsUrl: prev.vpsUrl || '',
customPassword: prev.customPassword || '',
mailProvider: prev.mailProvider || '163',
inbucketHost: prev.inbucketHost || '',
inbucketMailbox: prev.inbucketMailbox || '',
});
}
/**
* Generate a random password: 14 chars, mix of uppercase, lowercase, digits, symbols.
*/
function generatePassword() {
const upper = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
const lower = 'abcdefghjkmnpqrstuvwxyz';
const digits = '23456789';
const symbols = '!@#$%&*?';
const all = upper + lower + digits + symbols;
// Ensure at least one of each type
let pw = '';
pw += upper[Math.floor(Math.random() * upper.length)];
pw += lower[Math.floor(Math.random() * lower.length)];
pw += digits[Math.floor(Math.random() * digits.length)];
pw += symbols[Math.floor(Math.random() * symbols.length)];
// Fill remaining 10 chars
for (let i = 0; i < 10; i++) {
pw += all[Math.floor(Math.random() * all.length)];
}
// Shuffle
return pw.split('').sort(() => Math.random() - 0.5).join('');
}
// ============================================================
// Tab Registry
// ============================================================
async function getTabRegistry() {
const state = await getState();
return state.tabRegistry || {};
}
async function registerTab(source, tabId) {
const registry = await getTabRegistry();
registry[source] = { tabId, ready: true };
await setState({ tabRegistry: registry });
console.log(LOG_PREFIX, `Tab registered: ${source} -> ${tabId}`);
}
async function isTabAlive(source) {
const registry = await getTabRegistry();
const entry = registry[source];
if (!entry) return false;
try {
await chrome.tabs.get(entry.tabId);
return true;
} catch {
// Tab no longer exists — clean up registry
delete registry[source];
await setState({ tabRegistry: registry });
return false;
}
}
async function getTabId(source) {
const registry = await getTabRegistry();
return registry[source]?.tabId || null;
}
// ============================================================
// Command Queue (for content scripts not yet ready)
// ============================================================
const pendingCommands = new Map(); // source -> { message, resolve, reject, timer }
function queueCommand(source, message, timeout = 15000) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
pendingCommands.delete(source);
const err = `Content script on ${source} did not respond in ${timeout / 1000}s. Try refreshing the tab and retry.`;
console.error(LOG_PREFIX, err);
reject(new Error(err));
}, timeout);
pendingCommands.set(source, { message, resolve, reject, timer });
console.log(LOG_PREFIX, `Command queued for ${source} (waiting for ready)`);
});
}
function flushCommand(source, tabId) {
const pending = pendingCommands.get(source);
if (pending) {
clearTimeout(pending.timer);
pendingCommands.delete(source);
chrome.tabs.sendMessage(tabId, pending.message).then(pending.resolve).catch(pending.reject);
console.log(LOG_PREFIX, `Flushed queued command to ${source} (tab ${tabId})`);
}
}
function cancelPendingCommands(reason = STOP_ERROR_MESSAGE) {
for (const [source, pending] of pendingCommands.entries()) {
clearTimeout(pending.timer);
pending.reject(new Error(reason));
pendingCommands.delete(source);
console.log(LOG_PREFIX, `Cancelled queued command for ${source}`);
}
}
// ============================================================
// Reuse or create tab
// ============================================================
async function reuseOrCreateTab(source, url, options = {}) {
const alive = await isTabAlive(source);
if (alive) {
const tabId = await getTabId(source);
const currentTab = await chrome.tabs.get(tabId);
const sameUrl = currentTab.url === url;
const shouldReloadOnReuse = sameUrl && options.reloadIfSameUrl;
const registry = await getTabRegistry();
if (sameUrl) {
await chrome.tabs.update(tabId, { active: true });
console.log(LOG_PREFIX, `Reused tab ${source} (${tabId}) on same URL`);
if (shouldReloadOnReuse) {
if (registry[source]) registry[source].ready = false;
await setState({ tabRegistry: registry });
await chrome.tabs.reload(tabId);
await new Promise((resolve) => {
const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
const listener = (tid, info) => {
if (tid === tabId && info.status === 'complete') {
chrome.tabs.onUpdated.removeListener(listener);
clearTimeout(timer);
resolve();
}
};
chrome.tabs.onUpdated.addListener(listener);
});
}
// For dynamically injected pages like the VPS panel, re-inject immediately.
if (options.inject) {
if (registry[source]) registry[source].ready = false;
await setState({ tabRegistry: registry });
if (options.injectSource) {
await chrome.scripting.executeScript({
target: { tabId },
func: (injectedSource) => {
window.__MULTIPAGE_SOURCE = injectedSource;
},
args: [options.injectSource],
});
}
await chrome.scripting.executeScript({
target: { tabId },
files: options.inject,
});
await new Promise(r => setTimeout(r, 500));
}
return tabId;
}
// Mark as not ready BEFORE navigating — so READY signal from new page is captured correctly
if (registry[source]) registry[source].ready = false;
await setState({ tabRegistry: registry });
// Navigate existing tab to new URL
await chrome.tabs.update(tabId, { url, active: true });
console.log(LOG_PREFIX, `Reused tab ${source} (${tabId}), navigated to ${url.slice(0, 60)}`);
// Wait for page load complete (with 30s timeout)
await new Promise((resolve) => {
const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
const listener = (tid, info) => {
if (tid === tabId && info.status === 'complete') {
chrome.tabs.onUpdated.removeListener(listener);
clearTimeout(timer);
resolve();
}
};
chrome.tabs.onUpdated.addListener(listener);
});
// If dynamic injection needed (VPS panel), re-inject after navigation
if (options.inject) {
if (options.injectSource) {
await chrome.scripting.executeScript({
target: { tabId },
func: (injectedSource) => {
window.__MULTIPAGE_SOURCE = injectedSource;
},
args: [options.injectSource],
});
}
await chrome.scripting.executeScript({
target: { tabId },
files: options.inject,
});
}
// Wait a bit for content script to inject and send READY
await new Promise(r => setTimeout(r, 500));
return tabId;
}
// Create new tab in the automation window
const wid = await ensureAutomationWindowId();
const tab = await chrome.tabs.create({ url, active: true, windowId: wid });
console.log(LOG_PREFIX, `Created new tab ${source} (${tab.id})`);
// If dynamic injection needed (VPS panel), inject scripts after load
if (options.inject) {
await new Promise((resolve) => {
const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
const listener = (tabId, info) => {
if (tabId === tab.id && info.status === 'complete') {
chrome.tabs.onUpdated.removeListener(listener);
clearTimeout(timer);
resolve();
}
};
chrome.tabs.onUpdated.addListener(listener);
});
if (options.injectSource) {
await chrome.scripting.executeScript({
target: { tabId: tab.id },
func: (injectedSource) => {
window.__MULTIPAGE_SOURCE = injectedSource;
},
args: [options.injectSource],
});
}
await chrome.scripting.executeScript({
target: { tabId: tab.id },
files: options.inject,
});
}
return tab.id;
}
// ============================================================
// Send command to content script (with readiness check)
// ============================================================
async function sendToContentScript(source, message) {
throwIfStopped();
const registry = await getTabRegistry();
const entry = registry[source];
if (!entry || !entry.ready) {
console.log(LOG_PREFIX, `${source} not ready, queuing command`);
return queueCommand(source, message);
}
// Verify tab is still alive
const alive = await isTabAlive(source);
if (!alive) {
// Tab was closed — queue the command, it will be sent when tab is reopened
console.log(LOG_PREFIX, `${source} tab was closed, queuing command`);
return queueCommand(source, message);
}
console.log(LOG_PREFIX, `Sending to ${source} (tab ${entry.tabId}):`, message.type);
return chrome.tabs.sendMessage(entry.tabId, message);
}
// ============================================================
// Logging
// ============================================================
async function addLog(message, level = 'info') {
const state = await getState();
const logs = state.logs || [];
const entry = { message, level, timestamp: Date.now() };
logs.push(entry);
// Keep last 500 logs
if (logs.length > 500) logs.splice(0, logs.length - 500);
await setState({ logs });
// Broadcast to side panel
chrome.runtime.sendMessage({ type: 'LOG_ENTRY', payload: entry }).catch(() => {});
}
// ============================================================
// Step Status Management
// ============================================================
async function setStepStatus(step, status) {
const state = await getState();
const statuses = { ...state.stepStatuses };
statuses[step] = status;
await setState({ stepStatuses: statuses, currentStep: step });
// Broadcast to side panel
chrome.runtime.sendMessage({
type: 'STEP_STATUS_CHANGED',
payload: { step, status },
}).catch(() => {});
}
function isStopError(error) {
const message = typeof error === 'string' ? error : error?.message;
return message === STOP_ERROR_MESSAGE;
}
function clearStopRequest() {
stopRequested = false;
}
function throwIfStopped() {
if (stopRequested) {
throw new Error(STOP_ERROR_MESSAGE);
}
}
async function sleepWithStop(ms) {
const start = Date.now();
while (Date.now() - start < ms) {
throwIfStopped();
await new Promise(r => setTimeout(r, Math.min(100, ms - (Date.now() - start))));
}
}
async function humanStepDelay(min = HUMAN_STEP_DELAY_MIN, max = HUMAN_STEP_DELAY_MAX) {
const duration = Math.floor(Math.random() * (max - min + 1)) + min;
await sleepWithStop(duration);
}
async function clickWithDebugger(tabId, rect) {
if (!tabId) {
throw new Error('No auth tab found for debugger click.');
}
if (!rect || !Number.isFinite(rect.centerX) || !Number.isFinite(rect.centerY)) {
throw new Error('Step 8 debugger fallback needs a valid button position.');
}
const target = { tabId };
try {
await chrome.debugger.attach(target, '1.3');
} catch (err) {
throw new Error(
`Debugger attach failed during step 8 fallback: ${err.message}. ` +
'If DevTools is open on the auth tab, close it and retry.'
);
}
try {
const x = Math.round(rect.centerX);
const y = Math.round(rect.centerY);
await chrome.debugger.sendCommand(target, 'Page.bringToFront');
await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
type: 'mouseMoved',
x,
y,
button: 'none',
buttons: 0,
clickCount: 0,
});
await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
type: 'mousePressed',
x,
y,
button: 'left',
buttons: 1,
clickCount: 1,
});
await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
type: 'mouseReleased',
x,
y,
button: 'left',
buttons: 0,
clickCount: 1,
});
} finally {
await chrome.debugger.detach(target).catch(() => {});
}
}
async function broadcastStopToContentScripts() {
const registry = await getTabRegistry();
for (const entry of Object.values(registry)) {
if (!entry?.tabId) continue;
try {
await chrome.tabs.sendMessage(entry.tabId, {
type: 'STOP_FLOW',
source: 'background',
payload: {},
});
} catch {}
}
}
let stopRequested = false;
let suppressContentMessages = false;
// ============================================================
// Message Handler (central router)
// ============================================================
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
console.log(LOG_PREFIX, `Received: ${message.type} from ${message.source || 'sidepanel'}`, message);
handleMessage(message, sender).then(response => {
sendResponse(response);
}).catch(err => {
console.error(LOG_PREFIX, 'Handler error:', err);
sendResponse({ error: err.message });
});
return true; // async response
});
async function handleMessage(message, sender) {
switch (message.type) {
case 'CONTENT_SCRIPT_READY': {
const tabId = sender.tab?.id;
if (tabId && message.source) {
await registerTab(message.source, tabId);
flushCommand(message.source, tabId);
await addLog(`Content script ready: ${message.source} (tab ${tabId})`);
}
return { ok: true };
}
case 'LOG': {
if (suppressContentMessages) {
return { ok: true };
}
const { message: msg, level } = message.payload;
await addLog(`[${message.source}] ${msg}`, level);
return { ok: true };
}
case 'STEP_COMPLETE': {
if (suppressContentMessages) {
return { ok: true };
}
if (stopRequested) {
await setStepStatus(message.step, 'stopped');
notifyStepError(message.step, STOP_ERROR_MESSAGE);
return { ok: true };
}
await setStepStatus(message.step, 'completed');
await addLog(`Step ${message.step} completed`, 'ok');
await handleStepData(message.step, message.payload);
notifyStepComplete(message.step, message.payload);
return { ok: true };
}
case 'STEP_ERROR': {
if (suppressContentMessages) {
return { ok: true };
}
if (isStopError(message.error)) {
await setStepStatus(message.step, 'stopped');
await addLog(`Step ${message.step} stopped by user`, 'warn');
notifyStepError(message.step, message.error);
} else {
await setStepStatus(message.step, 'failed');
await addLog(`Step ${message.step} failed: ${message.error}`, 'error');
notifyStepError(message.step, message.error);
}
return { ok: true };
}
case 'GET_STATE': {
return await getState();
}
case 'RESET': {
suppressContentMessages = true;
await requestStop();
await resetState();
await addLog('Flow reset', 'info');
return { ok: true };
}
case 'EXECUTE_STEP': {
suppressContentMessages = false;
clearStopRequest();
const step = message.payload.step;
// Save email if provided (from side panel step 3)
if (message.payload.email) {
await setEmailState(message.payload.email);
}
await executeStep(step);
return { ok: true };
}
case 'AUTO_RUN': {
suppressContentMessages = false;
clearStopRequest();
const totalRuns = message.payload?.totalRuns || 1;
autoRunLoop(totalRuns); // fire-and-forget
return { ok: true };
}
case 'RESUME_AUTO_RUN': {
suppressContentMessages = false;
clearStopRequest();
if (message.payload.email) {
await setEmailState(message.payload.email);
}
resumeAutoRun(); // fire-and-forget
return { ok: true };
}
case 'SAVE_SETTING': {
const updates = {};
if (message.payload.vpsUrl !== undefined) updates.vpsUrl = message.payload.vpsUrl;
if (message.payload.customPassword !== undefined) updates.customPassword = message.payload.customPassword;
if (message.payload.mailProvider !== undefined) updates.mailProvider = message.payload.mailProvider;
if (message.payload.inbucketHost !== undefined) updates.inbucketHost = message.payload.inbucketHost;
if (message.payload.inbucketMailbox !== undefined) updates.inbucketMailbox = message.payload.inbucketMailbox;
await setState(updates);
return { ok: true };
}
// Side panel data updates
case 'SAVE_EMAIL': {
await setEmailState(message.payload.email);
return { ok: true, email: message.payload.email };
}
case 'FETCH_DUCK_EMAIL': {
suppressContentMessages = false;
clearStopRequest();
const email = await fetchDuckEmail(message.payload || {});
return { ok: true, email };
}
case 'STOP_FLOW': {
await requestStop();
return { ok: true };
}
default:
console.warn(LOG_PREFIX, `Unknown message type: ${message.type}`);
return { error: `Unknown message type: ${message.type}` };
}
}
// ============================================================
// Step Data Handlers
// ============================================================
async function handleStepData(step, payload) {
switch (step) {
case 1:
if (payload.oauthUrl) {
await setState({ oauthUrl: payload.oauthUrl });
broadcastDataUpdate({ oauthUrl: payload.oauthUrl });
}
break;
case 3:
if (payload.email) await setEmailState(payload.email);
break;
case 4:
if (payload.emailTimestamp) await setState({ lastEmailTimestamp: payload.emailTimestamp });
break;
case 8:
if (payload.localhostUrl) {
await setState({ localhostUrl: payload.localhostUrl });
broadcastDataUpdate({ localhostUrl: payload.localhostUrl });
}
break;
}
}
// ============================================================
// Step Completion Waiting
// ============================================================
// Map of step -> { resolve, reject } for waiting on step completion
const stepWaiters = new Map();
let resumeWaiter = null;
function waitForStepComplete(step, timeoutMs = 120000) {
return new Promise((resolve, reject) => {
throwIfStopped();
const timer = setTimeout(() => {
stepWaiters.delete(step);
reject(new Error(`Step ${step} timed out after ${timeoutMs / 1000}s`));
}, timeoutMs);
stepWaiters.set(step, {
resolve: (data) => { clearTimeout(timer); stepWaiters.delete(step); resolve(data); },
reject: (err) => { clearTimeout(timer); stepWaiters.delete(step); reject(err); },
});
});
}
function notifyStepComplete(step, payload) {
const waiter = stepWaiters.get(step);
if (waiter) waiter.resolve(payload);
}
function notifyStepError(step, error) {
const waiter = stepWaiters.get(step);
if (waiter) waiter.reject(new Error(error));
}
async function markRunningStepsStopped() {
const state = await getState();
const runningSteps = Object.entries(state.stepStatuses || {})
.filter(([, status]) => status === 'running')
.map(([step]) => Number(step));
for (const step of runningSteps) {
await setStepStatus(step, 'stopped');
}
}
async function requestStop() {
if (stopRequested) return;
stopRequested = true;
cancelPendingCommands();
if (webNavListener) {
chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
webNavListener = null;
}
await addLog('Stop requested. Cancelling current operations...', 'warn');
await broadcastStopToContentScripts();
for (const waiter of stepWaiters.values()) {
waiter.reject(new Error(STOP_ERROR_MESSAGE));
}
stepWaiters.clear();
if (resumeWaiter) {
resumeWaiter.reject(new Error(STOP_ERROR_MESSAGE));
resumeWaiter = null;
}
await markRunningStepsStopped();
autoRunActive = false;
await setState({ autoRunning: false });
chrome.runtime.sendMessage({
type: 'AUTO_RUN_STATUS',
payload: { phase: 'stopped', currentRun: autoRunCurrentRun, totalRuns: autoRunTotalRuns },
}).catch(() => {});
}
// ============================================================
// Step Execution
// ============================================================
async function executeStep(step) {
console.log(LOG_PREFIX, `Executing step ${step}`);
throwIfStopped();
await setStepStatus(step, 'running');
await addLog(`Step ${step} started`);
await humanStepDelay();
const state = await getState();
// Set flow start time on first step
if (step === 1 && !state.flowStartTime) {
await setState({ flowStartTime: Date.now() });
}
try {
switch (step) {
case 1: await executeStep1(state); break;
case 2: await executeStep2(state); break;
case 3: await executeStep3(state); break;
case 4: await executeStep4(state); break;
case 5: await executeStep5(state); break;
case 6: await executeStep6(state); break;
case 7: await executeStep7(state); break;
case 8: await executeStep8(state); break;
case 9: await executeStep9(state); break;
default:
throw new Error(`Unknown step: ${step}`);
}
} catch (err) {
if (isStopError(err)) {
await setStepStatus(step, 'stopped');
await addLog(`Step ${step} stopped by user`, 'warn');
throw err;
}
await setStepStatus(step, 'failed');
await addLog(`Step ${step} failed: ${err.message}`, 'error');
throw err;
}
}
/**
* Execute a step and wait for it to complete before returning.
* @param {number} step
* @param {number} delayAfter - ms to wait after completion (for page transitions)
*/
async function executeStepAndWait(step, delayAfter = 2000) {
throwIfStopped();
const promise = waitForStepComplete(step, 120000);
await executeStep(step);
await promise;
// Extra delay for page transitions / DOM updates
if (delayAfter > 0) {
await sleepWithStop(delayAfter + Math.floor(Math.random() * 1200));
}
}
async function fetchDuckEmail(options = {}) {
throwIfStopped();
const { generateNew = true } = options;
await addLog(`Duck Mail: Opening autofill settings (${generateNew ? 'generate new' : 'reuse current'})...`);
await reuseOrCreateTab('duck-mail', DUCK_AUTOFILL_URL);
const result = await sendToContentScript('duck-mail', {
type: 'FETCH_DUCK_EMAIL',
source: 'background',
payload: { generateNew },
});
if (result?.error) {
throw new Error(result.error);
}
if (!result?.email) {
throw new Error('Duck email not returned.');
}
throwIfStopped();
await setEmailState(result.email);
await addLog(`Duck Mail: ${result.generated ? 'Generated' : 'Loaded'} ${result.email}`, 'ok');
return result.email;
}
// ============================================================
// Auto Run Flow
// ============================================================
let autoRunActive = false;
let autoRunCurrentRun = 0;
let autoRunTotalRuns = 1;
// Outer loop: runs the full flow N times
async function autoRunLoop(totalRuns) {
if (autoRunActive) {
await addLog('Auto run already in progress', 'warn');
return;
}
clearStopRequest();
autoRunActive = true;
autoRunTotalRuns = totalRuns;
await setState({ autoRunning: true });
let successfulRuns = 0;
let endedEarly = false;
for (let run = 1; run <= totalRuns; run++) {
autoRunCurrentRun = run;
// Reset everything at the start of each run (keep VPS/mail settings)
const prevState = await getState();
const keepSettings = {
vpsUrl: prevState.vpsUrl,
mailProvider: prevState.mailProvider,
inbucketHost: prevState.inbucketHost,
inbucketMailbox: prevState.inbucketMailbox,
autoRunning: true,
};
await resetState();
await setState(keepSettings);
// Tell side panel to reset all UI
chrome.runtime.sendMessage({ type: 'AUTO_RUN_RESET' }).catch(() => {});
await sleepWithStop(500);
await addLog(`=== Auto Run ${run}/${totalRuns} — Phase 1: Get OAuth link & open signup ===`, 'info');
const status = (phase) => ({ type: 'AUTO_RUN_STATUS', payload: { phase, currentRun: run, totalRuns } });
try {
throwIfStopped();
chrome.runtime.sendMessage(status('running')).catch(() => {});
await executeStepAndWait(1, 2000);
await executeStepAndWait(2, 2000);
let emailReady = false;
try {
const duckEmail = await fetchDuckEmail({ generateNew: true });
await addLog(`=== Run ${run}/${totalRuns} — Duck email ready: ${duckEmail} ===`, 'ok');
emailReady = true;
} catch (err) {
await addLog(`Duck Mail auto-fetch failed: ${err.message}`, 'warn');
}
if (!emailReady) {
await addLog(`=== Run ${run}/${totalRuns} PAUSED: Fetch Duck email or paste manually, then continue ===`, 'warn');
chrome.runtime.sendMessage(status('waiting_email')).catch(() => {});
// Wait for RESUME_AUTO_RUN — sets a promise that resumeAutoRun resolves
await waitForResume();
const resumedState = await getState();
if (!resumedState.email) {
await addLog('Cannot resume: no email address.', 'error');
endedEarly = true;
break;
}
}
await addLog(`=== Run ${run}/${totalRuns} — Phase 2: Register, verify, login, complete ===`, 'info');
chrome.runtime.sendMessage(status('running')).catch(() => {});
const signupTabId = await getTabId('signup-page');
if (signupTabId) {
await chrome.tabs.update(signupTabId, { active: true });
}
await executeStepAndWait(3, 3000);
await executeStepAndWait(4, 2000);
await executeStepAndWait(5, 3000);
await executeStepAndWait(6, 3000);
await executeStepAndWait(7, 2000);
await executeStepAndWait(8, 2000);
await executeStepAndWait(9, 1000);
await addLog(`=== Run ${run}/${totalRuns} COMPLETE! ===`, 'ok');
successfulRuns += 1;
} catch (err) {
endedEarly = true;
if (isStopError(err)) {
await addLog(`Run ${run}/${totalRuns} stopped by user`, 'warn');
} else {
await addLog(`Run ${run}/${totalRuns} failed: ${err.message}`, 'error');
}
chrome.runtime.sendMessage(status('stopped')).catch(() => {});
break; // Stop on error
}
}
const attemptedRuns = autoRunCurrentRun;
if (stopRequested) {
await addLog(`=== Stopped after ${successfulRuns}/${autoRunTotalRuns} runs ===`, 'warn');
chrome.runtime.sendMessage({ type: 'AUTO_RUN_STATUS', payload: { phase: 'stopped', currentRun: attemptedRuns, totalRuns: autoRunTotalRuns } }).catch(() => {});
} else if (endedEarly) {
await addLog(`=== Stopped after ${successfulRuns}/${autoRunTotalRuns} runs ===`, 'warn');
chrome.runtime.sendMessage({ type: 'AUTO_RUN_STATUS', payload: { phase: 'stopped', currentRun: attemptedRuns, totalRuns: autoRunTotalRuns } }).catch(() => {});
} else {
await addLog(`=== All ${autoRunTotalRuns} runs completed successfully ===`, 'ok');
chrome.runtime.sendMessage({ type: 'AUTO_RUN_STATUS', payload: { phase: 'complete', currentRun: attemptedRuns, totalRuns: autoRunTotalRuns } }).catch(() => {});
}
autoRunActive = false;
await setState({ autoRunning: false });
clearStopRequest();
}
function waitForResume() {
return new Promise((resolve, reject) => {
throwIfStopped();
resumeWaiter = { resolve, reject };
});
}
async function resumeAutoRun() {
throwIfStopped();
const state = await getState();
if (!state.email) {
await addLog('Cannot resume: no email address. Paste email in Side Panel first.', 'error');
return;
}
if (resumeWaiter) {
resumeWaiter.resolve();
resumeWaiter = null;