background.js 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600
  1. // background.js — Service Worker: orchestration, state, tab management, message routing
  2. importScripts('data/names.js');
  3. const LOG_PREFIX = '[MultiPage:bg]';
  4. const DUCK_AUTOFILL_URL = 'https://duckduckgo.com/email/settings/autofill';
  5. const STOP_ERROR_MESSAGE = '流程已被用户停止。';
  6. const HUMAN_STEP_DELAY_MIN = 700;
  7. const HUMAN_STEP_DELAY_MAX = 2200;
  8. initializeSessionStorageAccess();
  9. // ============================================================
  10. // State Management (chrome.storage.session)
  11. // ============================================================
  12. const DEFAULT_STATE = {
  13. currentStep: 0,
  14. stepStatuses: {
  15. 1: 'pending', 2: 'pending', 3: 'pending', 4: 'pending', 5: 'pending',
  16. 6: 'pending', 7: 'pending', 8: 'pending', 9: 'pending',
  17. },
  18. oauthUrl: null,
  19. email: null,
  20. password: null,
  21. accounts: [], // { email, password, createdAt }
  22. lastEmailTimestamp: null,
  23. lastSignupCode: null,
  24. lastLoginCode: null,
  25. localhostUrl: null,
  26. flowStartTime: null,
  27. tabRegistry: {},
  28. logs: [],
  29. vpsUrl: '',
  30. vpsPassword: '',
  31. customPassword: '',
  32. autoRunSkipFailures: false,
  33. mailProvider: '163', // 'qq' or '163'
  34. inbucketHost: '',
  35. inbucketMailbox: '',
  36. };
  37. async function getState() {
  38. const state = await chrome.storage.session.get(null);
  39. return { ...DEFAULT_STATE, ...state };
  40. }
  41. async function initializeSessionStorageAccess() {
  42. try {
  43. if (chrome.storage?.session?.setAccessLevel) {
  44. await chrome.storage.session.setAccessLevel({
  45. accessLevel: 'TRUSTED_AND_UNTRUSTED_CONTEXTS',
  46. });
  47. console.log(LOG_PREFIX, 'Enabled storage.session for content scripts');
  48. }
  49. } catch (err) {
  50. console.warn(LOG_PREFIX, 'Failed to enable storage.session for content scripts:', err?.message || err);
  51. }
  52. }
  53. async function setState(updates) {
  54. console.log(LOG_PREFIX, 'storage.set:', JSON.stringify(updates).slice(0, 200));
  55. await chrome.storage.session.set(updates);
  56. }
  57. function broadcastDataUpdate(payload) {
  58. chrome.runtime.sendMessage({
  59. type: 'DATA_UPDATED',
  60. payload,
  61. }).catch(() => {});
  62. }
  63. async function setEmailState(email) {
  64. await setState({ email });
  65. broadcastDataUpdate({ email });
  66. }
  67. async function setPasswordState(password) {
  68. await setState({ password });
  69. broadcastDataUpdate({ password });
  70. }
  71. async function resetState() {
  72. console.log(LOG_PREFIX, 'Resetting all state');
  73. // Preserve settings and persistent data across resets
  74. const prev = await chrome.storage.session.get([
  75. 'seenCodes',
  76. 'seenInbucketMailIds',
  77. 'accounts',
  78. 'tabRegistry',
  79. 'vpsUrl',
  80. 'vpsPassword',
  81. 'customPassword',
  82. 'autoRunSkipFailures',
  83. 'mailProvider',
  84. 'inbucketHost',
  85. 'inbucketMailbox',
  86. ]);
  87. await chrome.storage.session.clear();
  88. await chrome.storage.session.set({
  89. ...DEFAULT_STATE,
  90. seenCodes: prev.seenCodes || [],
  91. seenInbucketMailIds: prev.seenInbucketMailIds || [],
  92. accounts: prev.accounts || [],
  93. tabRegistry: prev.tabRegistry || {},
  94. vpsUrl: prev.vpsUrl || '',
  95. vpsPassword: prev.vpsPassword || '',
  96. customPassword: prev.customPassword || '',
  97. autoRunSkipFailures: Boolean(prev.autoRunSkipFailures),
  98. mailProvider: prev.mailProvider || '163',
  99. inbucketHost: prev.inbucketHost || '',
  100. inbucketMailbox: prev.inbucketMailbox || '',
  101. });
  102. }
  103. /**
  104. * Generate a random password: 14 chars, mix of uppercase, lowercase, digits, symbols.
  105. */
  106. function generatePassword() {
  107. const upper = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
  108. const lower = 'abcdefghjkmnpqrstuvwxyz';
  109. const digits = '23456789';
  110. const symbols = '!@#$%&*?';
  111. const all = upper + lower + digits + symbols;
  112. // Ensure at least one of each type
  113. let pw = '';
  114. pw += upper[Math.floor(Math.random() * upper.length)];
  115. pw += lower[Math.floor(Math.random() * lower.length)];
  116. pw += digits[Math.floor(Math.random() * digits.length)];
  117. pw += symbols[Math.floor(Math.random() * symbols.length)];
  118. // Fill remaining 10 chars
  119. for (let i = 0; i < 10; i++) {
  120. pw += all[Math.floor(Math.random() * all.length)];
  121. }
  122. // Shuffle
  123. return pw.split('').sort(() => Math.random() - 0.5).join('');
  124. }
  125. // ============================================================
  126. // Tab Registry
  127. // ============================================================
  128. async function getTabRegistry() {
  129. const state = await getState();
  130. return state.tabRegistry || {};
  131. }
  132. async function registerTab(source, tabId) {
  133. const registry = await getTabRegistry();
  134. registry[source] = { tabId, ready: true };
  135. await setState({ tabRegistry: registry });
  136. console.log(LOG_PREFIX, `Tab registered: ${source} -> ${tabId}`);
  137. }
  138. async function isTabAlive(source) {
  139. const registry = await getTabRegistry();
  140. const entry = registry[source];
  141. if (!entry) return false;
  142. try {
  143. await chrome.tabs.get(entry.tabId);
  144. return true;
  145. } catch {
  146. // Tab no longer exists — clean up registry
  147. registry[source] = null;
  148. await setState({ tabRegistry: registry });
  149. return false;
  150. }
  151. }
  152. async function getTabId(source) {
  153. const registry = await getTabRegistry();
  154. return registry[source]?.tabId || null;
  155. }
  156. // ============================================================
  157. // Command Queue (for content scripts not yet ready)
  158. // ============================================================
  159. const pendingCommands = new Map(); // source -> { message, resolve, reject, timer }
  160. function queueCommand(source, message, timeout = 15000) {
  161. return new Promise((resolve, reject) => {
  162. const timer = setTimeout(() => {
  163. pendingCommands.delete(source);
  164. const err = `Content script on ${source} did not respond in ${timeout / 1000}s. Try refreshing the tab and retry.`;
  165. console.error(LOG_PREFIX, err);
  166. reject(new Error(err));
  167. }, timeout);
  168. pendingCommands.set(source, { message, resolve, reject, timer });
  169. console.log(LOG_PREFIX, `Command queued for ${source} (waiting for ready)`);
  170. });
  171. }
  172. function flushCommand(source, tabId) {
  173. const pending = pendingCommands.get(source);
  174. if (pending) {
  175. clearTimeout(pending.timer);
  176. pendingCommands.delete(source);
  177. chrome.tabs.sendMessage(tabId, pending.message).then(pending.resolve).catch(pending.reject);
  178. console.log(LOG_PREFIX, `Flushed queued command to ${source} (tab ${tabId})`);
  179. }
  180. }
  181. function cancelPendingCommands(reason = STOP_ERROR_MESSAGE) {
  182. for (const [source, pending] of pendingCommands.entries()) {
  183. clearTimeout(pending.timer);
  184. pending.reject(new Error(reason));
  185. pendingCommands.delete(source);
  186. console.log(LOG_PREFIX, `Cancelled queued command for ${source}`);
  187. }
  188. }
  189. // ============================================================
  190. // Reuse or create tab
  191. // ============================================================
  192. async function reuseOrCreateTab(source, url, options = {}) {
  193. const alive = await isTabAlive(source);
  194. if (alive) {
  195. const tabId = await getTabId(source);
  196. const currentTab = await chrome.tabs.get(tabId);
  197. const sameUrl = currentTab.url === url;
  198. const shouldReloadOnReuse = sameUrl && options.reloadIfSameUrl;
  199. const registry = await getTabRegistry();
  200. if (sameUrl) {
  201. await chrome.tabs.update(tabId, { active: true });
  202. console.log(LOG_PREFIX, `Reused tab ${source} (${tabId}) on same URL`);
  203. if (shouldReloadOnReuse) {
  204. if (registry[source]) registry[source].ready = false;
  205. await setState({ tabRegistry: registry });
  206. await chrome.tabs.reload(tabId);
  207. await new Promise((resolve) => {
  208. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  209. const listener = (tid, info) => {
  210. if (tid === tabId && info.status === 'complete') {
  211. chrome.tabs.onUpdated.removeListener(listener);
  212. clearTimeout(timer);
  213. resolve();
  214. }
  215. };
  216. chrome.tabs.onUpdated.addListener(listener);
  217. });
  218. }
  219. // For dynamically injected pages like the VPS panel, re-inject immediately.
  220. if (options.inject) {
  221. if (registry[source]) registry[source].ready = false;
  222. await setState({ tabRegistry: registry });
  223. if (options.injectSource) {
  224. await chrome.scripting.executeScript({
  225. target: { tabId },
  226. func: (injectedSource) => {
  227. window.__MULTIPAGE_SOURCE = injectedSource;
  228. },
  229. args: [options.injectSource],
  230. });
  231. }
  232. await chrome.scripting.executeScript({
  233. target: { tabId },
  234. files: options.inject,
  235. });
  236. await new Promise(r => setTimeout(r, 500));
  237. }
  238. return tabId;
  239. }
  240. // Mark as not ready BEFORE navigating — so READY signal from new page is captured correctly
  241. if (registry[source]) registry[source].ready = false;
  242. await setState({ tabRegistry: registry });
  243. // Navigate existing tab to new URL
  244. await chrome.tabs.update(tabId, { url, active: true });
  245. console.log(LOG_PREFIX, `Reused tab ${source} (${tabId}), navigated to ${url.slice(0, 60)}`);
  246. // Wait for page load complete (with 30s timeout)
  247. await new Promise((resolve) => {
  248. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  249. const listener = (tid, info) => {
  250. if (tid === tabId && info.status === 'complete') {
  251. chrome.tabs.onUpdated.removeListener(listener);
  252. clearTimeout(timer);
  253. resolve();
  254. }
  255. };
  256. chrome.tabs.onUpdated.addListener(listener);
  257. });
  258. // If dynamic injection needed (VPS panel), re-inject after navigation
  259. if (options.inject) {
  260. if (options.injectSource) {
  261. await chrome.scripting.executeScript({
  262. target: { tabId },
  263. func: (injectedSource) => {
  264. window.__MULTIPAGE_SOURCE = injectedSource;
  265. },
  266. args: [options.injectSource],
  267. });
  268. }
  269. await chrome.scripting.executeScript({
  270. target: { tabId },
  271. files: options.inject,
  272. });
  273. }
  274. // Wait a bit for content script to inject and send READY
  275. await new Promise(r => setTimeout(r, 500));
  276. return tabId;
  277. }
  278. // Create new tab
  279. const tab = await chrome.tabs.create({ url, active: true });
  280. console.log(LOG_PREFIX, `Created new tab ${source} (${tab.id})`);
  281. // If dynamic injection needed (VPS panel), inject scripts after load
  282. if (options.inject) {
  283. await new Promise((resolve) => {
  284. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  285. const listener = (tabId, info) => {
  286. if (tabId === tab.id && info.status === 'complete') {
  287. chrome.tabs.onUpdated.removeListener(listener);
  288. clearTimeout(timer);
  289. resolve();
  290. }
  291. };
  292. chrome.tabs.onUpdated.addListener(listener);
  293. });
  294. if (options.injectSource) {
  295. await chrome.scripting.executeScript({
  296. target: { tabId: tab.id },
  297. func: (injectedSource) => {
  298. window.__MULTIPAGE_SOURCE = injectedSource;
  299. },
  300. args: [options.injectSource],
  301. });
  302. }
  303. await chrome.scripting.executeScript({
  304. target: { tabId: tab.id },
  305. files: options.inject,
  306. });
  307. }
  308. return tab.id;
  309. }
  310. // ============================================================
  311. // Send command to content script (with readiness check)
  312. // ============================================================
  313. async function sendToContentScript(source, message) {
  314. const registry = await getTabRegistry();
  315. const entry = registry[source];
  316. if (!entry || !entry.ready) {
  317. console.log(LOG_PREFIX, `${source} not ready, queuing command`);
  318. return queueCommand(source, message);
  319. }
  320. // Verify tab is still alive
  321. const alive = await isTabAlive(source);
  322. if (!alive) {
  323. // Tab was closed — queue the command, it will be sent when tab is reopened
  324. console.log(LOG_PREFIX, `${source} tab was closed, queuing command`);
  325. return queueCommand(source, message);
  326. }
  327. console.log(LOG_PREFIX, `Sending to ${source} (tab ${entry.tabId}):`, message.type);
  328. return chrome.tabs.sendMessage(entry.tabId, message);
  329. }
  330. // ============================================================
  331. // Logging
  332. // ============================================================
  333. async function addLog(message, level = 'info') {
  334. const state = await getState();
  335. const logs = state.logs || [];
  336. const entry = { message, level, timestamp: Date.now() };
  337. logs.push(entry);
  338. // Keep last 500 logs
  339. if (logs.length > 500) logs.splice(0, logs.length - 500);
  340. await setState({ logs });
  341. // Broadcast to side panel
  342. chrome.runtime.sendMessage({ type: 'LOG_ENTRY', payload: entry }).catch(() => {});
  343. }
  344. function getSourceLabel(source) {
  345. const labels = {
  346. 'sidepanel': '侧边栏',
  347. 'signup-page': '认证页',
  348. 'vps-panel': 'VPS 面板',
  349. 'qq-mail': 'QQ 邮箱',
  350. 'mail-163': '163 邮箱',
  351. 'inbucket-mail': 'Inbucket 邮箱',
  352. 'duck-mail': 'Duck 邮箱',
  353. };
  354. return labels[source] || source || '未知来源';
  355. }
  356. // ============================================================
  357. // Step Status Management
  358. // ============================================================
  359. async function setStepStatus(step, status) {
  360. const state = await getState();
  361. const statuses = { ...state.stepStatuses };
  362. statuses[step] = status;
  363. await setState({ stepStatuses: statuses, currentStep: step });
  364. // Broadcast to side panel
  365. chrome.runtime.sendMessage({
  366. type: 'STEP_STATUS_CHANGED',
  367. payload: { step, status },
  368. }).catch(() => {});
  369. }
  370. function isStopError(error) {
  371. const message = typeof error === 'string' ? error : error?.message;
  372. return message === STOP_ERROR_MESSAGE;
  373. }
  374. function clearStopRequest() {
  375. stopRequested = false;
  376. }
  377. function throwIfStopped() {
  378. if (stopRequested) {
  379. throw new Error(STOP_ERROR_MESSAGE);
  380. }
  381. }
  382. async function sleepWithStop(ms) {
  383. const start = Date.now();
  384. while (Date.now() - start < ms) {
  385. throwIfStopped();
  386. await new Promise(r => setTimeout(r, Math.min(100, ms - (Date.now() - start))));
  387. }
  388. }
  389. async function humanStepDelay(min = HUMAN_STEP_DELAY_MIN, max = HUMAN_STEP_DELAY_MAX) {
  390. const duration = Math.floor(Math.random() * (max - min + 1)) + min;
  391. await sleepWithStop(duration);
  392. }
  393. async function clickWithDebugger(tabId, rect) {
  394. if (!tabId) {
  395. throw new Error('未找到用于调试点击的认证页面标签页。');
  396. }
  397. if (!rect || !Number.isFinite(rect.centerX) || !Number.isFinite(rect.centerY)) {
  398. throw new Error('步骤 8 的调试器兜底点击需要有效的按钮坐标。');
  399. }
  400. const target = { tabId };
  401. try {
  402. await chrome.debugger.attach(target, '1.3');
  403. } catch (err) {
  404. throw new Error(
  405. `步骤 8 的调试器兜底点击附加失败:${err.message}。` +
  406. '如果认证页标签已打开 DevTools,请先关闭后重试。'
  407. );
  408. }
  409. try {
  410. const x = Math.round(rect.centerX);
  411. const y = Math.round(rect.centerY);
  412. await chrome.debugger.sendCommand(target, 'Page.bringToFront');
  413. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  414. type: 'mouseMoved',
  415. x,
  416. y,
  417. button: 'none',
  418. buttons: 0,
  419. clickCount: 0,
  420. });
  421. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  422. type: 'mousePressed',
  423. x,
  424. y,
  425. button: 'left',
  426. buttons: 1,
  427. clickCount: 1,
  428. });
  429. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  430. type: 'mouseReleased',
  431. x,
  432. y,
  433. button: 'left',
  434. buttons: 0,
  435. clickCount: 1,
  436. });
  437. } finally {
  438. await chrome.debugger.detach(target).catch(() => {});
  439. }
  440. }
  441. async function broadcastStopToContentScripts() {
  442. const registry = await getTabRegistry();
  443. for (const entry of Object.values(registry)) {
  444. if (!entry?.tabId) continue;
  445. try {
  446. await chrome.tabs.sendMessage(entry.tabId, {
  447. type: 'STOP_FLOW',
  448. source: 'background',
  449. payload: {},
  450. });
  451. } catch {}
  452. }
  453. }
  454. let stopRequested = false;
  455. // ============================================================
  456. // Message Handler (central router)
  457. // ============================================================
  458. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  459. console.log(LOG_PREFIX, `Received: ${message.type} from ${message.source || 'sidepanel'}`, message);
  460. handleMessage(message, sender).then(response => {
  461. sendResponse(response);
  462. }).catch(err => {
  463. console.error(LOG_PREFIX, 'Handler error:', err);
  464. sendResponse({ error: err.message });
  465. });
  466. return true; // async response
  467. });
  468. async function handleMessage(message, sender) {
  469. switch (message.type) {
  470. case 'CONTENT_SCRIPT_READY': {
  471. const tabId = sender.tab?.id;
  472. if (tabId && message.source) {
  473. await registerTab(message.source, tabId);
  474. flushCommand(message.source, tabId);
  475. await addLog(`内容脚本已就绪:${getSourceLabel(message.source)}(标签页 ${tabId})`);
  476. }
  477. return { ok: true };
  478. }
  479. case 'LOG': {
  480. const { message: msg, level } = message.payload;
  481. await addLog(`[${getSourceLabel(message.source)}] ${msg}`, level);
  482. return { ok: true };
  483. }
  484. case 'STEP_COMPLETE': {
  485. if (stopRequested) {
  486. await setStepStatus(message.step, 'stopped');
  487. notifyStepError(message.step, STOP_ERROR_MESSAGE);
  488. return { ok: true };
  489. }
  490. await setStepStatus(message.step, 'completed');
  491. await addLog(`步骤 ${message.step} 已完成`, 'ok');
  492. await handleStepData(message.step, message.payload);
  493. notifyStepComplete(message.step, message.payload);
  494. return { ok: true };
  495. }
  496. case 'STEP_ERROR': {
  497. if (isStopError(message.error)) {
  498. await setStepStatus(message.step, 'stopped');
  499. await addLog(`步骤 ${message.step} 已被用户停止`, 'warn');
  500. notifyStepError(message.step, message.error);
  501. } else {
  502. await setStepStatus(message.step, 'failed');
  503. await addLog(`步骤 ${message.step} 失败:${message.error}`, 'error');
  504. notifyStepError(message.step, message.error);
  505. }
  506. return { ok: true };
  507. }
  508. case 'GET_STATE': {
  509. return await getState();
  510. }
  511. case 'RESET': {
  512. clearStopRequest();
  513. await resetState();
  514. await addLog('流程已重置', 'info');
  515. return { ok: true };
  516. }
  517. case 'EXECUTE_STEP': {
  518. clearStopRequest();
  519. const step = message.payload.step;
  520. // Save email if provided (from side panel step 3)
  521. if (message.payload.email) {
  522. await setEmailState(message.payload.email);
  523. }
  524. await executeStep(step);
  525. return { ok: true };
  526. }
  527. case 'AUTO_RUN': {
  528. clearStopRequest();
  529. const totalRuns = message.payload?.totalRuns || 1;
  530. const autoRunSkipFailures = Boolean(message.payload?.autoRunSkipFailures);
  531. await setState({ autoRunSkipFailures });
  532. autoRunLoop(totalRuns, { autoRunSkipFailures }); // fire-and-forget
  533. return { ok: true };
  534. }
  535. case 'RESUME_AUTO_RUN': {
  536. clearStopRequest();
  537. if (message.payload.email) {
  538. await setEmailState(message.payload.email);
  539. }
  540. resumeAutoRun(); // fire-and-forget
  541. return { ok: true };
  542. }
  543. case 'SAVE_SETTING': {
  544. const updates = {};
  545. if (message.payload.vpsUrl !== undefined) updates.vpsUrl = message.payload.vpsUrl;
  546. if (message.payload.vpsPassword !== undefined) updates.vpsPassword = message.payload.vpsPassword;
  547. if (message.payload.customPassword !== undefined) updates.customPassword = message.payload.customPassword;
  548. if (message.payload.autoRunSkipFailures !== undefined) updates.autoRunSkipFailures = Boolean(message.payload.autoRunSkipFailures);
  549. if (message.payload.mailProvider !== undefined) updates.mailProvider = message.payload.mailProvider;
  550. if (message.payload.inbucketHost !== undefined) updates.inbucketHost = message.payload.inbucketHost;
  551. if (message.payload.inbucketMailbox !== undefined) updates.inbucketMailbox = message.payload.inbucketMailbox;
  552. await setState(updates);
  553. return { ok: true };
  554. }
  555. // Side panel data updates
  556. case 'SAVE_EMAIL': {
  557. await setEmailState(message.payload.email);
  558. return { ok: true, email: message.payload.email };
  559. }
  560. case 'FETCH_DUCK_EMAIL': {
  561. clearStopRequest();
  562. const email = await fetchDuckEmail(message.payload || {});
  563. return { ok: true, email };
  564. }
  565. case 'STOP_FLOW': {
  566. await requestStop();
  567. return { ok: true };
  568. }
  569. default:
  570. console.warn(LOG_PREFIX, `Unknown message type: ${message.type}`);
  571. return { error: `Unknown message type: ${message.type}` };
  572. }
  573. }
  574. // ============================================================
  575. // Step Data Handlers
  576. // ============================================================
  577. async function handleStepData(step, payload) {
  578. switch (step) {
  579. case 1:
  580. if (payload.oauthUrl) {
  581. await setState({ oauthUrl: payload.oauthUrl });
  582. broadcastDataUpdate({ oauthUrl: payload.oauthUrl });
  583. }
  584. break;
  585. case 3:
  586. if (payload.email) await setEmailState(payload.email);
  587. break;
  588. case 4:
  589. if (payload.emailTimestamp) await setState({ lastEmailTimestamp: payload.emailTimestamp });
  590. break;
  591. case 8:
  592. if (payload.localhostUrl) {
  593. await setState({ localhostUrl: payload.localhostUrl });
  594. broadcastDataUpdate({ localhostUrl: payload.localhostUrl });
  595. }
  596. break;
  597. }
  598. }
  599. // ============================================================
  600. // Step Completion Waiting
  601. // ============================================================
  602. // Map of step -> { resolve, reject } for waiting on step completion
  603. const stepWaiters = new Map();
  604. let resumeWaiter = null;
  605. function waitForStepComplete(step, timeoutMs = 120000) {
  606. return new Promise((resolve, reject) => {
  607. throwIfStopped();
  608. const timer = setTimeout(() => {
  609. stepWaiters.delete(step);
  610. reject(new Error(`Step ${step} timed out after ${timeoutMs / 1000}s`));
  611. }, timeoutMs);
  612. stepWaiters.set(step, {
  613. resolve: (data) => { clearTimeout(timer); stepWaiters.delete(step); resolve(data); },
  614. reject: (err) => { clearTimeout(timer); stepWaiters.delete(step); reject(err); },
  615. });
  616. });
  617. }
  618. function notifyStepComplete(step, payload) {
  619. const waiter = stepWaiters.get(step);
  620. if (waiter) waiter.resolve(payload);
  621. }
  622. function notifyStepError(step, error) {
  623. const waiter = stepWaiters.get(step);
  624. if (waiter) waiter.reject(new Error(error));
  625. }
  626. async function completeStepFromBackground(step, payload = {}) {
  627. if (stopRequested) {
  628. await setStepStatus(step, 'stopped');
  629. notifyStepError(step, STOP_ERROR_MESSAGE);
  630. return;
  631. }
  632. await setStepStatus(step, 'completed');
  633. await addLog(`步骤 ${step} 已完成`, 'ok');
  634. await handleStepData(step, payload);
  635. notifyStepComplete(step, payload);
  636. }
  637. async function markRunningStepsStopped() {
  638. const state = await getState();
  639. const runningSteps = Object.entries(state.stepStatuses || {})
  640. .filter(([, status]) => status === 'running')
  641. .map(([step]) => Number(step));
  642. for (const step of runningSteps) {
  643. await setStepStatus(step, 'stopped');
  644. }
  645. }
  646. async function requestStop() {
  647. if (stopRequested) return;
  648. stopRequested = true;
  649. cancelPendingCommands();
  650. if (webNavListener) {
  651. chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
  652. webNavListener = null;
  653. }
  654. await addLog('已收到停止请求,正在取消当前操作...', 'warn');
  655. await broadcastStopToContentScripts();
  656. for (const waiter of stepWaiters.values()) {
  657. waiter.reject(new Error(STOP_ERROR_MESSAGE));
  658. }
  659. stepWaiters.clear();
  660. if (resumeWaiter) {
  661. resumeWaiter.reject(new Error(STOP_ERROR_MESSAGE));
  662. resumeWaiter = null;
  663. }
  664. await markRunningStepsStopped();
  665. autoRunActive = false;
  666. await setState({ autoRunning: false });
  667. chrome.runtime.sendMessage({
  668. type: 'AUTO_RUN_STATUS',
  669. payload: { phase: 'stopped', currentRun: autoRunCurrentRun, totalRuns: autoRunTotalRuns },
  670. }).catch(() => {});
  671. }
  672. // ============================================================
  673. // Step Execution
  674. // ============================================================
  675. async function executeStep(step) {
  676. console.log(LOG_PREFIX, `Executing step ${step}`);
  677. throwIfStopped();
  678. await setStepStatus(step, 'running');
  679. await addLog(`步骤 ${step} 开始执行`);
  680. await humanStepDelay();
  681. const state = await getState();
  682. // Set flow start time on first step
  683. if (step === 1 && !state.flowStartTime) {
  684. await setState({ flowStartTime: Date.now() });
  685. }
  686. try {
  687. switch (step) {
  688. case 1: await executeStep1(state); break;
  689. case 2: await executeStep2(state); break;
  690. case 3: await executeStep3(state); break;
  691. case 4: await executeStep4(state); break;
  692. case 5: await executeStep5(state); break;
  693. case 6: await executeStep6(state); break;
  694. case 7: await executeStep7(state); break;
  695. case 8: await executeStep8(state); break;
  696. case 9: await executeStep9(state); break;
  697. default:
  698. throw new Error(`未知步骤:${step}`);
  699. }
  700. } catch (err) {
  701. if (isStopError(err)) {
  702. await setStepStatus(step, 'stopped');
  703. await addLog(`步骤 ${step} 已被用户停止`, 'warn');
  704. throw err;
  705. }
  706. await setStepStatus(step, 'failed');
  707. await addLog(`步骤 ${step} 失败:${err.message}`, 'error');
  708. throw err;
  709. }
  710. }
  711. /**
  712. * Execute a step and wait for it to complete before returning.
  713. * @param {number} step
  714. * @param {number} delayAfter - ms to wait after completion (for page transitions)
  715. */
  716. async function executeStepAndWait(step, delayAfter = 2000) {
  717. throwIfStopped();
  718. const promise = waitForStepComplete(step, 120000);
  719. await executeStep(step);
  720. await promise;
  721. // Extra delay for page transitions / DOM updates
  722. if (delayAfter > 0) {
  723. await sleepWithStop(delayAfter + Math.floor(Math.random() * 1200));
  724. }
  725. }
  726. async function fetchDuckEmail(options = {}) {
  727. throwIfStopped();
  728. const { generateNew = true } = options;
  729. await addLog(`Duck 邮箱:正在打开自动填充设置(${generateNew ? '生成新地址' : '复用当前地址'})...`);
  730. await reuseOrCreateTab('duck-mail', DUCK_AUTOFILL_URL);
  731. const result = await sendToContentScript('duck-mail', {
  732. type: 'FETCH_DUCK_EMAIL',
  733. source: 'background',
  734. payload: { generateNew },
  735. });
  736. if (result?.error) {
  737. throw new Error(result.error);
  738. }
  739. if (!result?.email) {
  740. throw new Error('未返回 Duck 邮箱地址。');
  741. }
  742. await setEmailState(result.email);
  743. await addLog(`Duck 邮箱:${result.generated ? '已生成' : '已读取'} ${result.email}`, 'ok');
  744. return result.email;
  745. }
  746. // ============================================================
  747. // Auto Run Flow
  748. // ============================================================
  749. let autoRunActive = false;
  750. let autoRunCurrentRun = 0;
  751. let autoRunTotalRuns = 1;
  752. // Outer loop: keep retrying until the target number of successful runs is reached.
  753. async function autoRunLoop(totalRuns, options = {}) {
  754. if (autoRunActive) {
  755. await addLog('自动运行已在进行中', 'warn');
  756. return;
  757. }
  758. clearStopRequest();
  759. autoRunActive = true;
  760. autoRunTotalRuns = totalRuns;
  761. const autoRunSkipFailures = Boolean(options.autoRunSkipFailures);
  762. const maxAttempts = autoRunSkipFailures ? Math.max(totalRuns * 10, totalRuns + 20) : totalRuns;
  763. let successfulRuns = 0;
  764. let attemptRuns = 0;
  765. let forceFreshTabsNextRun = false;
  766. await setState({ autoRunning: true, autoRunSkipFailures });
  767. while (successfulRuns < totalRuns && attemptRuns < maxAttempts) {
  768. attemptRuns += 1;
  769. const targetRun = successfulRuns + 1;
  770. autoRunCurrentRun = targetRun;
  771. // Reset everything at the start of each attempt (keep user settings).
  772. const prevState = await getState();
  773. const keepSettings = {
  774. vpsUrl: prevState.vpsUrl,
  775. vpsPassword: prevState.vpsPassword,
  776. customPassword: prevState.customPassword,
  777. autoRunSkipFailures: prevState.autoRunSkipFailures,
  778. mailProvider: prevState.mailProvider,
  779. inbucketHost: prevState.inbucketHost,
  780. inbucketMailbox: prevState.inbucketMailbox,
  781. autoRunning: true,
  782. ...(forceFreshTabsNextRun ? { tabRegistry: {} } : {}),
  783. };
  784. await resetState();
  785. await setState(keepSettings);
  786. chrome.runtime.sendMessage({ type: 'AUTO_RUN_RESET' }).catch(() => {});
  787. await sleepWithStop(500);
  788. if (forceFreshTabsNextRun) {
  789. await addLog(`兜底模式:上一轮已放弃,当前开始第 ${attemptRuns} 次尝试,将使用新线程继续补足第 ${targetRun}/${totalRuns} 轮。`, 'warn');
  790. forceFreshTabsNextRun = false;
  791. }
  792. const status = (phase) => ({
  793. type: 'AUTO_RUN_STATUS',
  794. payload: { phase, currentRun: targetRun, totalRuns, attemptRun: attemptRuns },
  795. });
  796. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:第 ${attemptRuns} 次尝试,阶段 1,获取 OAuth 链接并打开注册页 ===`, 'info');
  797. try {
  798. throwIfStopped();
  799. chrome.runtime.sendMessage(status('running')).catch(() => {});
  800. await executeStepAndWait(1, 2000);
  801. await executeStepAndWait(2, 2000);
  802. let emailReady = false;
  803. try {
  804. const duckEmail = await fetchDuckEmail({ generateNew: true });
  805. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:Duck 邮箱已就绪:${duckEmail}(第 ${attemptRuns} 次尝试)===`, 'ok');
  806. emailReady = true;
  807. } catch (err) {
  808. await addLog(`Duck 邮箱自动获取失败:${err.message}`, 'warn');
  809. }
  810. if (!emailReady) {
  811. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮已暂停:请先获取 Duck 邮箱或手动粘贴邮箱,然后继续 ===`, 'warn');
  812. chrome.runtime.sendMessage(status('waiting_email')).catch(() => {});
  813. await waitForResume();
  814. const resumedState = await getState();
  815. if (!resumedState.email) {
  816. throw new Error('无法继续:当前没有邮箱地址。');
  817. }
  818. }
  819. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:阶段 2,注册、验证、登录并完成授权(第 ${attemptRuns} 次尝试)===`, 'info');
  820. chrome.runtime.sendMessage(status('running')).catch(() => {});
  821. const signupTabId = await getTabId('signup-page');
  822. if (signupTabId) {
  823. await chrome.tabs.update(signupTabId, { active: true });
  824. }
  825. await executeStepAndWait(3, 3000);
  826. await executeStepAndWait(4, 2000);
  827. await executeStepAndWait(5, 3000);
  828. await executeStepAndWait(6, 3000);
  829. await executeStepAndWait(7, 2000);
  830. await executeStepAndWait(8, 2000);
  831. await executeStepAndWait(9, 1000);
  832. successfulRuns += 1;
  833. autoRunCurrentRun = successfulRuns;
  834. await addLog(`=== 目标 ${successfulRuns}/${totalRuns} 轮已完成(第 ${attemptRuns} 次尝试成功)===`, 'ok');
  835. continue;
  836. } catch (err) {
  837. if (isStopError(err)) {
  838. await addLog(`目标 ${targetRun}/${totalRuns} 轮已被用户停止`, 'warn');
  839. chrome.runtime.sendMessage(status('stopped')).catch(() => {});
  840. break;
  841. }
  842. if (!autoRunSkipFailures) {
  843. await addLog(`目标 ${targetRun}/${totalRuns} 轮失败:${err.message}`, 'error');
  844. chrome.runtime.sendMessage(status('stopped')).catch(() => {});
  845. break;
  846. }
  847. await addLog(`目标 ${targetRun}/${totalRuns} 轮的第 ${attemptRuns} 次尝试失败:${err.message}`, 'error');
  848. await addLog('兜底开关已开启:将放弃当前线程,重新开一轮继续补足目标次数。', 'warn');
  849. cancelPendingCommands('当前尝试已放弃。');
  850. await broadcastStopToContentScripts();
  851. chrome.runtime.sendMessage(status('retrying')).catch(() => {});
  852. forceFreshTabsNextRun = true;
  853. }
  854. }
  855. if (!stopRequested && autoRunSkipFailures && successfulRuns < totalRuns && attemptRuns >= maxAttempts) {
  856. await addLog(`已达到安全重试上限(${attemptRuns} 次尝试),当前仅完成 ${successfulRuns}/${totalRuns} 轮。`, 'error');
  857. chrome.runtime.sendMessage({
  858. type: 'AUTO_RUN_STATUS',
  859. payload: { phase: 'stopped', currentRun: successfulRuns, totalRuns: autoRunTotalRuns, attemptRun: attemptRuns },
  860. }).catch(() => {});
  861. } else if (stopRequested) {
  862. await addLog(`=== 已停止,完成 ${successfulRuns}/${autoRunTotalRuns} 轮,共尝试 ${attemptRuns} 次 ===`, 'warn');
  863. chrome.runtime.sendMessage({
  864. type: 'AUTO_RUN_STATUS',
  865. payload: { phase: 'stopped', currentRun: successfulRuns, totalRuns: autoRunTotalRuns, attemptRun: attemptRuns },
  866. }).catch(() => {});
  867. } else if (successfulRuns >= autoRunTotalRuns) {
  868. await addLog(`=== 全部 ${autoRunTotalRuns} 轮均已成功完成,共尝试 ${attemptRuns} 次 ===`, 'ok');
  869. chrome.runtime.sendMessage({
  870. type: 'AUTO_RUN_STATUS',
  871. payload: { phase: 'complete', currentRun: successfulRuns, totalRuns: autoRunTotalRuns, attemptRun: attemptRuns },
  872. }).catch(() => {});
  873. } else {
  874. await addLog(`=== 已停止,完成 ${successfulRuns}/${autoRunTotalRuns} 轮,共尝试 ${attemptRuns} 次 ===`, 'warn');
  875. chrome.runtime.sendMessage({
  876. type: 'AUTO_RUN_STATUS',
  877. payload: { phase: 'stopped', currentRun: successfulRuns, totalRuns: autoRunTotalRuns, attemptRun: attemptRuns },
  878. }).catch(() => {});
  879. }
  880. autoRunActive = false;
  881. await setState({ autoRunning: false });
  882. clearStopRequest();
  883. }
  884. function waitForResume() {
  885. return new Promise((resolve, reject) => {
  886. throwIfStopped();
  887. resumeWaiter = { resolve, reject };
  888. });
  889. }
  890. async function resumeAutoRun() {
  891. throwIfStopped();
  892. const state = await getState();
  893. if (!state.email) {
  894. await addLog('无法继续:当前没有邮箱地址,请先在侧边栏填写邮箱。', 'error');
  895. return;
  896. }
  897. if (resumeWaiter) {
  898. resumeWaiter.resolve();
  899. resumeWaiter = null;
  900. }
  901. }
  902. // ============================================================
  903. // Step 1: Get OAuth Link (via vps-panel.js)
  904. // ============================================================
  905. async function executeStep1(state) {
  906. if (!state.vpsUrl) {
  907. throw new Error('尚未配置 VPS 地址,请先在侧边栏填写。');
  908. }
  909. await addLog('步骤 1:正在打开 VPS 面板...');
  910. await reuseOrCreateTab('vps-panel', state.vpsUrl, {
  911. inject: ['content/utils.js', 'content/vps-panel.js'],
  912. reloadIfSameUrl: true,
  913. });
  914. await sendToContentScript('vps-panel', {
  915. type: 'EXECUTE_STEP',
  916. step: 1,
  917. source: 'background',
  918. payload: { vpsPassword: state.vpsPassword },
  919. });
  920. }
  921. // ============================================================
  922. // Step 2: Open Signup Page (Background opens tab, signup-page.js clicks Register)
  923. // ============================================================
  924. async function executeStep2(state) {
  925. if (!state.oauthUrl) {
  926. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  927. }
  928. await addLog('步骤 2:正在打开认证链接...');
  929. await reuseOrCreateTab('signup-page', state.oauthUrl);
  930. await sendToContentScript('signup-page', {
  931. type: 'EXECUTE_STEP',
  932. step: 2,
  933. source: 'background',
  934. payload: {},
  935. });
  936. }
  937. // ============================================================
  938. // Step 3: Fill Email & Password (via signup-page.js)
  939. // ============================================================
  940. async function executeStep3(state) {
  941. if (!state.email) {
  942. throw new Error('缺少邮箱地址,请先在侧边栏粘贴邮箱。');
  943. }
  944. const password = state.customPassword || generatePassword();
  945. await setPasswordState(password);
  946. // Save account record
  947. const accounts = state.accounts || [];
  948. accounts.push({ email: state.email, password, createdAt: new Date().toISOString() });
  949. await setState({ accounts });
  950. await addLog(
  951. `步骤 3:正在填写邮箱 ${state.email},密码为${state.customPassword ? '自定义' : '自动生成'}(${password.length} 位)`
  952. );
  953. await sendToContentScript('signup-page', {
  954. type: 'EXECUTE_STEP',
  955. step: 3,
  956. source: 'background',
  957. payload: { email: state.email, password },
  958. });
  959. }
  960. // ============================================================
  961. // Step 4: Get Signup Verification Code (qq-mail.js polls, then fills in signup-page.js)
  962. // ============================================================
  963. function getMailConfig(state) {
  964. const provider = state.mailProvider || 'qq';
  965. if (provider === '163') {
  966. return { source: 'mail-163', url: 'https://mail.163.com/js6/main.jsp?df=mail163_letter#module=mbox.ListModule%7C%7B%22fid%22%3A1%2C%22order%22%3A%22date%22%2C%22desc%22%3Atrue%7D', label: '163 邮箱' };
  967. }
  968. if (provider === 'inbucket') {
  969. const host = normalizeInbucketOrigin(state.inbucketHost);
  970. const mailbox = (state.inbucketMailbox || '').trim();
  971. if (!host) {
  972. return { error: 'Inbucket 主机地址为空或无效。' };
  973. }
  974. if (!mailbox) {
  975. return { error: 'Inbucket 邮箱名称为空。' };
  976. }
  977. return {
  978. source: 'inbucket-mail',
  979. url: `${host}/m/${encodeURIComponent(mailbox)}/`,
  980. label: `Inbucket 邮箱(${mailbox})`,
  981. navigateOnReuse: true,
  982. inject: ['content/utils.js', 'content/inbucket-mail.js'],
  983. injectSource: 'inbucket-mail',
  984. };
  985. }
  986. return { source: 'qq-mail', url: 'https://wx.mail.qq.com/', label: 'QQ 邮箱' };
  987. }
  988. function normalizeInbucketOrigin(rawValue) {
  989. const value = (rawValue || '').trim();
  990. if (!value) return '';
  991. const candidate = /^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(value) ? value : `https://${value}`;
  992. try {
  993. const parsed = new URL(candidate);
  994. return parsed.origin;
  995. } catch {
  996. return '';
  997. }
  998. }
  999. function getVerificationCodeStateKey(step) {
  1000. return step === 4 ? 'lastSignupCode' : 'lastLoginCode';
  1001. }
  1002. function getVerificationCodeLabel(step) {
  1003. return step === 4 ? '注册' : '登录';
  1004. }
  1005. function getVerificationPollPayload(step, state, overrides = {}) {
  1006. if (step === 4) {
  1007. return {
  1008. filterAfterTimestamp: state.flowStartTime || 0,
  1009. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'duckduckgo', 'forward'],
  1010. subjectFilters: ['verify', 'verification', 'code', '楠岃瘉', 'confirm'],
  1011. targetEmail: state.email,
  1012. maxAttempts: 5,
  1013. intervalMs: 3000,
  1014. ...overrides,
  1015. };
  1016. }
  1017. return {
  1018. filterAfterTimestamp: state.lastEmailTimestamp || state.flowStartTime || 0,
  1019. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'chatgpt', 'duckduckgo', 'forward'],
  1020. subjectFilters: ['verify', 'verification', 'code', '楠岃瘉', 'confirm', 'login'],
  1021. targetEmail: state.email,
  1022. maxAttempts: 5,
  1023. intervalMs: 3000,
  1024. ...overrides,
  1025. };
  1026. }
  1027. async function requestVerificationCodeResend(step) {
  1028. const signupTabId = await getTabId('signup-page');
  1029. if (!signupTabId) {
  1030. throw new Error('认证页面标签页已关闭,无法重新请求验证码。');
  1031. }
  1032. await chrome.tabs.update(signupTabId, { active: true });
  1033. await addLog(`步骤 ${step}:正在请求新的${getVerificationCodeLabel(step)}验证码...`, 'warn');
  1034. const result = await sendToContentScript('signup-page', {
  1035. type: 'RESEND_VERIFICATION_CODE',
  1036. step,
  1037. source: 'background',
  1038. payload: {},
  1039. });
  1040. if (result && result.error) {
  1041. throw new Error(result.error);
  1042. }
  1043. return Date.now();
  1044. }
  1045. async function pollFreshVerificationCode(step, state, mail, pollOverrides = {}) {
  1046. const stateKey = getVerificationCodeStateKey(step);
  1047. const rejectedCodes = new Set();
  1048. if (state[stateKey]) {
  1049. rejectedCodes.add(state[stateKey]);
  1050. }
  1051. for (const code of (pollOverrides.excludeCodes || [])) {
  1052. if (code) rejectedCodes.add(code);
  1053. }
  1054. let lastError = null;
  1055. let filterAfterTimestamp = pollOverrides.filterAfterTimestamp ?? getVerificationPollPayload(step, state).filterAfterTimestamp;
  1056. const maxRounds = pollOverrides.maxRounds || 3;
  1057. for (let round = 1; round <= maxRounds; round++) {
  1058. if (round > 1) {
  1059. filterAfterTimestamp = await requestVerificationCodeResend(step);
  1060. }
  1061. const payload = getVerificationPollPayload(step, state, {
  1062. ...pollOverrides,
  1063. filterAfterTimestamp,
  1064. excludeCodes: [...rejectedCodes],
  1065. });
  1066. try {
  1067. const result = await sendToContentScript(mail.source, {
  1068. type: 'POLL_EMAIL',
  1069. step,
  1070. source: 'background',
  1071. payload,
  1072. });
  1073. if (result && result.error) {
  1074. throw new Error(result.error);
  1075. }
  1076. if (!result || !result.code) {
  1077. throw new Error(`步骤 ${step}:邮箱轮询结束,但未获取到验证码。`);
  1078. }
  1079. if (rejectedCodes.has(result.code)) {
  1080. throw new Error(`步骤 ${step}:再次收到了相同的${getVerificationCodeLabel(step)}验证码:${result.code}`);
  1081. }
  1082. return result;
  1083. } catch (err) {
  1084. lastError = err;
  1085. await addLog(`步骤 ${step}:${err.message}`, 'warn');
  1086. if (round < maxRounds) {
  1087. await addLog(`步骤 ${step}:将重新发送验证码后重试(${round + 1}/${maxRounds})...`, 'warn');
  1088. }
  1089. }
  1090. }
  1091. throw lastError || new Error(`步骤 ${step}:无法获取新的${getVerificationCodeLabel(step)}验证码。`);
  1092. }
  1093. async function submitVerificationCode(step, code) {
  1094. const signupTabId = await getTabId('signup-page');
  1095. if (!signupTabId) {
  1096. throw new Error('认证页面标签页已关闭,无法填写验证码。');
  1097. }
  1098. await chrome.tabs.update(signupTabId, { active: true });
  1099. const result = await sendToContentScript('signup-page', {
  1100. type: 'FILL_CODE',
  1101. step,
  1102. source: 'background',
  1103. payload: { code },
  1104. });
  1105. if (result && result.error) {
  1106. throw new Error(result.error);
  1107. }
  1108. return result || {};
  1109. }
  1110. async function resolveVerificationStep(step, state, mail) {
  1111. const stateKey = getVerificationCodeStateKey(step);
  1112. const rejectedCodes = new Set();
  1113. if (state[stateKey]) {
  1114. rejectedCodes.add(state[stateKey]);
  1115. }
  1116. let nextFilterAfterTimestamp = null;
  1117. const maxSubmitAttempts = 3;
  1118. for (let attempt = 1; attempt <= maxSubmitAttempts; attempt++) {
  1119. const result = await pollFreshVerificationCode(step, state, mail, {
  1120. excludeCodes: [...rejectedCodes],
  1121. filterAfterTimestamp: nextFilterAfterTimestamp ?? undefined,
  1122. });
  1123. await addLog(`步骤 ${step}:已获取${getVerificationCodeLabel(step)}验证码:${result.code}`);
  1124. const submitResult = await submitVerificationCode(step, result.code);
  1125. if (submitResult.invalidCode) {
  1126. rejectedCodes.add(result.code);
  1127. await addLog(`步骤 ${step}:验证码被页面拒绝:${submitResult.errorText || result.code}`, 'warn');
  1128. if (attempt >= maxSubmitAttempts) {
  1129. throw new Error(`步骤 ${step}:验证码连续失败,已达到 ${maxSubmitAttempts} 次重试上限。`);
  1130. }
  1131. nextFilterAfterTimestamp = await requestVerificationCodeResend(step);
  1132. await addLog(`步骤 ${step}:提交失败后已请求新验证码(${attempt + 1}/${maxSubmitAttempts})...`, 'warn');
  1133. continue;
  1134. }
  1135. await setState({
  1136. lastEmailTimestamp: result.emailTimestamp,
  1137. [stateKey]: result.code,
  1138. });
  1139. await completeStepFromBackground(step, {
  1140. emailTimestamp: result.emailTimestamp,
  1141. code: result.code,
  1142. });
  1143. return;
  1144. }
  1145. }
  1146. async function executeStep4(state) {
  1147. const mail = getMailConfig(state);
  1148. if (mail.error) throw new Error(mail.error);
  1149. await addLog(`步骤 4:正在打开${mail.label}...`);
  1150. // For mail tabs, only create if not alive — don't navigate (preserves login session)
  1151. const alive = await isTabAlive(mail.source);
  1152. if (alive) {
  1153. if (mail.navigateOnReuse) {
  1154. await reuseOrCreateTab(mail.source, mail.url, {
  1155. inject: mail.inject,
  1156. injectSource: mail.injectSource,
  1157. });
  1158. } else {
  1159. const tabId = await getTabId(mail.source);
  1160. await chrome.tabs.update(tabId, { active: true });
  1161. }
  1162. } else {
  1163. await reuseOrCreateTab(mail.source, mail.url, {
  1164. inject: mail.inject,
  1165. injectSource: mail.injectSource,
  1166. });
  1167. }
  1168. await resolveVerificationStep(4, state, mail);
  1169. return;
  1170. }
  1171. // ============================================================
  1172. // Step 5: Fill Name & Birthday (via signup-page.js)
  1173. // ============================================================
  1174. async function executeStep5(state) {
  1175. const { firstName, lastName } = generateRandomName();
  1176. const { year, month, day } = generateRandomBirthday();
  1177. await addLog(`步骤 5:已生成姓名 ${firstName} ${lastName},生日 ${year}-${month}-${day}`);
  1178. await sendToContentScript('signup-page', {
  1179. type: 'EXECUTE_STEP',
  1180. step: 5,
  1181. source: 'background',
  1182. payload: { firstName, lastName, year, month, day },
  1183. });
  1184. }
  1185. // ============================================================
  1186. // Step 6: Login ChatGPT (Background opens tab, chatgpt.js handles login)
  1187. // ============================================================
  1188. async function executeStep6(state) {
  1189. if (!state.oauthUrl) {
  1190. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  1191. }
  1192. if (!state.email) {
  1193. throw new Error('缺少邮箱地址,请先完成步骤 3。');
  1194. }
  1195. await addLog('步骤 6:正在打开用于登录的 OAuth 链接...');
  1196. // Reuse the signup-page tab — navigate it to the OAuth URL
  1197. await reuseOrCreateTab('signup-page', state.oauthUrl);
  1198. // signup-page.js will inject (same auth.openai.com domain) and handle login
  1199. await sendToContentScript('signup-page', {
  1200. type: 'EXECUTE_STEP',
  1201. step: 6,
  1202. source: 'background',
  1203. payload: { email: state.email, password: state.password },
  1204. });
  1205. }
  1206. // ============================================================
  1207. // Step 7: Get Login Verification Code (qq-mail.js polls, then fills in chatgpt.js)
  1208. // ============================================================
  1209. async function executeStep7(state) {
  1210. const mail = getMailConfig(state);
  1211. if (mail.error) throw new Error(mail.error);
  1212. const authTabId = await getTabId('signup-page');
  1213. if (authTabId) {
  1214. await chrome.tabs.update(authTabId, { active: true });
  1215. } else {
  1216. if (!state.oauthUrl) {
  1217. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  1218. }
  1219. await reuseOrCreateTab('signup-page', state.oauthUrl);
  1220. }
  1221. await addLog('步骤 7:正在准备认证页,必要时切换到一次性验证码登录...');
  1222. const prepareResult = await sendToContentScript('signup-page', {
  1223. type: 'PREPARE_LOGIN_CODE',
  1224. step: 7,
  1225. source: 'background',
  1226. payload: {},
  1227. });
  1228. if (prepareResult && prepareResult.error) {
  1229. throw new Error(prepareResult.error);
  1230. }
  1231. await addLog(`步骤 7:正在打开${mail.label}...`);
  1232. const alive = await isTabAlive(mail.source);
  1233. if (alive) {
  1234. if (mail.navigateOnReuse) {
  1235. await reuseOrCreateTab(mail.source, mail.url, {
  1236. inject: mail.inject,
  1237. injectSource: mail.injectSource,
  1238. });
  1239. } else {
  1240. const tabId = await getTabId(mail.source);
  1241. await chrome.tabs.update(tabId, { active: true });
  1242. }
  1243. } else {
  1244. await reuseOrCreateTab(mail.source, mail.url, {
  1245. inject: mail.inject,
  1246. injectSource: mail.injectSource,
  1247. });
  1248. }
  1249. await resolveVerificationStep(7, state, mail);
  1250. return;
  1251. }
  1252. // ============================================================
  1253. // Step 8: Complete OAuth (auto click + localhost listener)
  1254. // ============================================================
  1255. let webNavListener = null;
  1256. async function executeStep8(state) {
  1257. if (!state.oauthUrl) {
  1258. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  1259. }
  1260. await addLog('步骤 8:正在监听 localhost 回调地址...');
  1261. // Register webNavigation listener (scoped to this step)
  1262. return new Promise((resolve, reject) => {
  1263. let resolved = false;
  1264. let resolveCaptureWait = null;
  1265. const captureWait = new Promise((resolveCapture) => {
  1266. resolveCaptureWait = resolveCapture;
  1267. });
  1268. const cleanupListener = () => {
  1269. if (webNavListener) {
  1270. chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
  1271. webNavListener = null;
  1272. }
  1273. };
  1274. const timeout = setTimeout(() => {
  1275. cleanupListener();
  1276. reject(new Error('120 秒内未捕获到 localhost 回调跳转,步骤 8 的点击可能被拦截了。'));
  1277. }, 120000);
  1278. webNavListener = (details) => {
  1279. if (details.url.startsWith('http://localhost')) {
  1280. console.log(LOG_PREFIX, `Captured localhost redirect: ${details.url}`);
  1281. resolved = true;
  1282. cleanupListener();
  1283. clearTimeout(timeout);
  1284. if (resolveCaptureWait) resolveCaptureWait(details.url);
  1285. setState({ localhostUrl: details.url }).then(() => {
  1286. addLog(`步骤 8:已捕获 localhost 地址:${details.url}`, 'ok');
  1287. setStepStatus(8, 'completed');
  1288. notifyStepComplete(8, { localhostUrl: details.url });
  1289. broadcastDataUpdate({ localhostUrl: details.url });
  1290. resolve();
  1291. });
  1292. }
  1293. };
  1294. chrome.webNavigation.onBeforeNavigate.addListener(webNavListener);
  1295. // After step 7, the auth page shows a consent screen ("使用 ChatGPT 登录到 Codex")
  1296. // with a "继续" button. We locate the button in-page, then click it through
  1297. // the debugger Input API directly.
  1298. (async () => {
  1299. try {
  1300. let signupTabId = await getTabId('signup-page');
  1301. if (signupTabId) {
  1302. await chrome.tabs.update(signupTabId, { active: true });
  1303. await addLog('步骤 8:已切回认证页,正在准备调试器点击...');
  1304. } else {
  1305. signupTabId = await reuseOrCreateTab('signup-page', state.oauthUrl);
  1306. await addLog('步骤 8:已重新打开认证页,正在准备调试器点击...');
  1307. }
  1308. const clickResult = await sendToContentScript('signup-page', {
  1309. type: 'STEP8_FIND_AND_CLICK',
  1310. source: 'background',
  1311. payload: {},
  1312. });
  1313. if (clickResult?.error) {
  1314. throw new Error(clickResult.error);
  1315. }
  1316. if (!resolved) {
  1317. await clickWithDebugger(signupTabId, clickResult?.rect);
  1318. await addLog('步骤 8:已发送调试器点击,正在等待跳转...');
  1319. }
  1320. } catch (err) {
  1321. clearTimeout(timeout);
  1322. cleanupListener();
  1323. reject(err);
  1324. }
  1325. })();
  1326. });
  1327. }
  1328. // ============================================================
  1329. // Step 9: VPS Verify (via vps-panel.js)
  1330. // ============================================================
  1331. async function executeStep9(state) {
  1332. if (!state.localhostUrl) {
  1333. throw new Error('缺少 localhost 回调地址,请先完成步骤 8。');
  1334. }
  1335. if (!state.vpsUrl) {
  1336. throw new Error('尚未填写 VPS 地址,请先在侧边栏输入。');
  1337. }
  1338. await addLog('步骤 9:正在打开 VPS 面板...');
  1339. let tabId = await getTabId('vps-panel');
  1340. const alive = tabId && await isTabAlive('vps-panel');
  1341. if (!alive) {
  1342. // Create new tab
  1343. const tab = await chrome.tabs.create({ url: state.vpsUrl, active: true });
  1344. tabId = tab.id;
  1345. await new Promise(resolve => {
  1346. const listener = (tid, info) => {
  1347. if (tid === tabId && info.status === 'complete') {
  1348. chrome.tabs.onUpdated.removeListener(listener);
  1349. resolve();
  1350. }
  1351. };
  1352. chrome.tabs.onUpdated.addListener(listener);
  1353. });
  1354. } else {
  1355. await chrome.tabs.update(tabId, { active: true });
  1356. }
  1357. // Inject scripts directly and wait for them to be ready
  1358. await chrome.scripting.executeScript({
  1359. target: { tabId },
  1360. files: ['content/utils.js', 'content/vps-panel.js'],
  1361. });
  1362. await new Promise(r => setTimeout(r, 1000));
  1363. // Send command directly — bypass queue/ready mechanism
  1364. await addLog('步骤 9:正在填写回调地址...');
  1365. await chrome.tabs.sendMessage(tabId, {
  1366. type: 'EXECUTE_STEP',
  1367. step: 9,
  1368. source: 'background',
  1369. payload: { localhostUrl: state.localhostUrl, vpsPassword: state.vpsPassword },
  1370. });
  1371. }
  1372. // ============================================================
  1373. // Open Side Panel on extension icon click
  1374. // ============================================================
  1375. chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });