background.js 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158
  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 + chrome.storage.local)
  11. // ============================================================
  12. const PERSISTED_SETTING_DEFAULTS = {
  13. vpsUrl: '',
  14. vpsPassword: '',
  15. customPassword: '',
  16. autoRunSkipFailures: false,
  17. mailProvider: '163',
  18. inbucketHost: '',
  19. inbucketMailbox: '',
  20. };
  21. const PERSISTED_SETTING_KEYS = Object.keys(PERSISTED_SETTING_DEFAULTS);
  22. const DEFAULT_STATE = {
  23. currentStep: 0,
  24. stepStatuses: {
  25. 1: 'pending', 2: 'pending', 3: 'pending', 4: 'pending', 5: 'pending',
  26. 6: 'pending', 7: 'pending', 8: 'pending', 9: 'pending',
  27. },
  28. oauthUrl: null,
  29. email: null,
  30. password: null,
  31. accounts: [], // { email, password, createdAt }
  32. lastEmailTimestamp: null,
  33. lastSignupCode: null,
  34. lastLoginCode: null,
  35. localhostUrl: null,
  36. flowStartTime: null,
  37. tabRegistry: {},
  38. sourceLastUrls: {},
  39. logs: [],
  40. ...PERSISTED_SETTING_DEFAULTS,
  41. autoRunning: false,
  42. autoRunPhase: 'idle',
  43. autoRunCurrentRun: 0,
  44. autoRunTotalRuns: 1,
  45. autoRunAttemptRun: 0,
  46. };
  47. async function getPersistedSettings() {
  48. const stored = await chrome.storage.local.get(PERSISTED_SETTING_KEYS);
  49. return {
  50. ...PERSISTED_SETTING_DEFAULTS,
  51. ...stored,
  52. autoRunSkipFailures: Boolean(stored.autoRunSkipFailures ?? PERSISTED_SETTING_DEFAULTS.autoRunSkipFailures),
  53. };
  54. }
  55. async function getState() {
  56. const [state, persistedSettings] = await Promise.all([
  57. chrome.storage.session.get(null),
  58. getPersistedSettings(),
  59. ]);
  60. return { ...DEFAULT_STATE, ...persistedSettings, ...state };
  61. }
  62. async function initializeSessionStorageAccess() {
  63. try {
  64. if (chrome.storage?.session?.setAccessLevel) {
  65. await chrome.storage.session.setAccessLevel({
  66. accessLevel: 'TRUSTED_AND_UNTRUSTED_CONTEXTS',
  67. });
  68. console.log(LOG_PREFIX, 'Enabled storage.session for content scripts');
  69. }
  70. } catch (err) {
  71. console.warn(LOG_PREFIX, 'Failed to enable storage.session for content scripts:', err?.message || err);
  72. }
  73. }
  74. async function setState(updates) {
  75. console.log(LOG_PREFIX, 'storage.set:', JSON.stringify(updates).slice(0, 200));
  76. await chrome.storage.session.set(updates);
  77. }
  78. async function setPersistentSettings(updates) {
  79. const persistedUpdates = {};
  80. for (const key of PERSISTED_SETTING_KEYS) {
  81. if (updates[key] !== undefined) {
  82. persistedUpdates[key] = key === 'autoRunSkipFailures'
  83. ? Boolean(updates[key])
  84. : updates[key];
  85. }
  86. }
  87. if (Object.keys(persistedUpdates).length > 0) {
  88. await chrome.storage.local.set(persistedUpdates);
  89. }
  90. }
  91. function broadcastDataUpdate(payload) {
  92. chrome.runtime.sendMessage({
  93. type: 'DATA_UPDATED',
  94. payload,
  95. }).catch(() => {});
  96. }
  97. async function setEmailState(email) {
  98. await setState({ email });
  99. broadcastDataUpdate({ email });
  100. if (email) {
  101. await resumeAutoRunIfWaitingForEmail();
  102. }
  103. }
  104. async function setPasswordState(password) {
  105. await setState({ password });
  106. broadcastDataUpdate({ password });
  107. }
  108. async function resetState() {
  109. console.log(LOG_PREFIX, 'Resetting all state');
  110. // Preserve settings and persistent data across resets
  111. const [prev, persistedSettings] = await Promise.all([
  112. chrome.storage.session.get([
  113. 'seenCodes',
  114. 'seenInbucketMailIds',
  115. 'accounts',
  116. 'tabRegistry',
  117. 'sourceLastUrls',
  118. ]),
  119. getPersistedSettings(),
  120. ]);
  121. await chrome.storage.session.clear();
  122. await chrome.storage.session.set({
  123. ...DEFAULT_STATE,
  124. ...persistedSettings,
  125. seenCodes: prev.seenCodes || [],
  126. seenInbucketMailIds: prev.seenInbucketMailIds || [],
  127. accounts: prev.accounts || [],
  128. tabRegistry: prev.tabRegistry || {},
  129. sourceLastUrls: prev.sourceLastUrls || {},
  130. });
  131. }
  132. /**
  133. * Generate a random password: 14 chars, mix of uppercase, lowercase, digits, symbols.
  134. */
  135. function generatePassword() {
  136. const upper = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
  137. const lower = 'abcdefghjkmnpqrstuvwxyz';
  138. const digits = '23456789';
  139. const symbols = '!@#$%&*?';
  140. const all = upper + lower + digits + symbols;
  141. // Ensure at least one of each type
  142. let pw = '';
  143. pw += upper[Math.floor(Math.random() * upper.length)];
  144. pw += lower[Math.floor(Math.random() * lower.length)];
  145. pw += digits[Math.floor(Math.random() * digits.length)];
  146. pw += symbols[Math.floor(Math.random() * symbols.length)];
  147. // Fill remaining 10 chars
  148. for (let i = 0; i < 10; i++) {
  149. pw += all[Math.floor(Math.random() * all.length)];
  150. }
  151. // Shuffle
  152. return pw.split('').sort(() => Math.random() - 0.5).join('');
  153. }
  154. // ============================================================
  155. // Tab Registry
  156. // ============================================================
  157. async function getTabRegistry() {
  158. const state = await getState();
  159. return state.tabRegistry || {};
  160. }
  161. async function registerTab(source, tabId) {
  162. const registry = await getTabRegistry();
  163. registry[source] = { tabId, ready: true };
  164. await setState({ tabRegistry: registry });
  165. console.log(LOG_PREFIX, `Tab registered: ${source} -> ${tabId}`);
  166. }
  167. async function isTabAlive(source) {
  168. const registry = await getTabRegistry();
  169. const entry = registry[source];
  170. if (!entry) return false;
  171. try {
  172. await chrome.tabs.get(entry.tabId);
  173. return true;
  174. } catch {
  175. // Tab no longer exists — clean up registry
  176. registry[source] = null;
  177. await setState({ tabRegistry: registry });
  178. return false;
  179. }
  180. }
  181. async function getTabId(source) {
  182. const registry = await getTabRegistry();
  183. return registry[source]?.tabId || null;
  184. }
  185. function parseUrlSafely(rawUrl) {
  186. if (!rawUrl) return null;
  187. try {
  188. return new URL(rawUrl);
  189. } catch {
  190. return null;
  191. }
  192. }
  193. function isSignupPageHost(hostname = '') {
  194. return ['auth0.openai.com', 'auth.openai.com', 'accounts.openai.com'].includes(hostname);
  195. }
  196. function buildLocalhostCleanupPrefix(rawUrl) {
  197. const parsed = parseUrlSafely(rawUrl);
  198. if (!parsed || parsed.hostname !== 'localhost') return '';
  199. const segments = parsed.pathname.split('/').filter(Boolean);
  200. if (!segments.length) {
  201. return parsed.origin;
  202. }
  203. return `${parsed.origin}/${segments[0]}`;
  204. }
  205. function matchesSourceUrlFamily(source, candidateUrl, referenceUrl) {
  206. const candidate = parseUrlSafely(candidateUrl);
  207. if (!candidate) return false;
  208. const reference = parseUrlSafely(referenceUrl);
  209. switch (source) {
  210. case 'signup-page':
  211. return isSignupPageHost(candidate.hostname);
  212. case 'duck-mail':
  213. return candidate.hostname === 'duckduckgo.com' && candidate.pathname.startsWith('/email/');
  214. case 'qq-mail':
  215. return candidate.hostname === 'mail.qq.com' || candidate.hostname === 'wx.mail.qq.com';
  216. case 'mail-163':
  217. return candidate.hostname === 'mail.163.com';
  218. case 'inbucket-mail':
  219. return Boolean(reference)
  220. && candidate.origin === reference.origin
  221. && candidate.pathname.startsWith('/m/');
  222. case 'vps-panel':
  223. return Boolean(reference) && candidate.origin === reference.origin;
  224. default:
  225. return false;
  226. }
  227. }
  228. async function rememberSourceLastUrl(source, url) {
  229. if (!source || !url) return;
  230. const state = await getState();
  231. const sourceLastUrls = { ...(state.sourceLastUrls || {}) };
  232. sourceLastUrls[source] = url;
  233. await setState({ sourceLastUrls });
  234. }
  235. async function closeConflictingTabsForSource(source, currentUrl, options = {}) {
  236. const { excludeTabIds = [] } = options;
  237. const excluded = new Set(excludeTabIds.filter(id => Number.isInteger(id)));
  238. const state = await getState();
  239. const lastUrl = state.sourceLastUrls?.[source];
  240. const referenceUrls = [currentUrl, lastUrl].filter(Boolean);
  241. if (!referenceUrls.length) return;
  242. const tabs = await chrome.tabs.query({});
  243. const matchedIds = tabs
  244. .filter((tab) => Number.isInteger(tab.id) && !excluded.has(tab.id))
  245. .filter((tab) => referenceUrls.some((refUrl) => matchesSourceUrlFamily(source, tab.url, refUrl)))
  246. .map(tab => tab.id);
  247. if (!matchedIds.length) return;
  248. await chrome.tabs.remove(matchedIds).catch(() => {});
  249. const registry = await getTabRegistry();
  250. if (registry[source]?.tabId && matchedIds.includes(registry[source].tabId)) {
  251. registry[source] = null;
  252. await setState({ tabRegistry: registry });
  253. }
  254. await addLog(`已关闭 ${matchedIds.length} 个旧的${getSourceLabel(source)}标签页。`, 'info');
  255. }
  256. async function closeTabsByUrlPrefix(prefix, options = {}) {
  257. if (!prefix) return 0;
  258. const { excludeTabIds = [] } = options;
  259. const excluded = new Set(excludeTabIds.filter(id => Number.isInteger(id)));
  260. const tabs = await chrome.tabs.query({});
  261. const matchedIds = tabs
  262. .filter((tab) => Number.isInteger(tab.id) && !excluded.has(tab.id))
  263. .filter((tab) => typeof tab.url === 'string' && tab.url.startsWith(prefix))
  264. .map((tab) => tab.id);
  265. if (!matchedIds.length) return 0;
  266. await chrome.tabs.remove(matchedIds).catch(() => {});
  267. await addLog(`已关闭 ${matchedIds.length} 个匹配 ${prefix} 的 localhost 残留标签页。`, 'info');
  268. return matchedIds.length;
  269. }
  270. // ============================================================
  271. // Command Queue (for content scripts not yet ready)
  272. // ============================================================
  273. const pendingCommands = new Map(); // source -> { message, resolve, reject, timer }
  274. function queueCommand(source, message, timeout = 15000) {
  275. return new Promise((resolve, reject) => {
  276. const timer = setTimeout(() => {
  277. pendingCommands.delete(source);
  278. const err = `Content script on ${source} did not respond in ${timeout / 1000}s. Try refreshing the tab and retry.`;
  279. console.error(LOG_PREFIX, err);
  280. reject(new Error(err));
  281. }, timeout);
  282. pendingCommands.set(source, { message, resolve, reject, timer });
  283. console.log(LOG_PREFIX, `Command queued for ${source} (waiting for ready)`);
  284. });
  285. }
  286. function flushCommand(source, tabId) {
  287. const pending = pendingCommands.get(source);
  288. if (pending) {
  289. clearTimeout(pending.timer);
  290. pendingCommands.delete(source);
  291. chrome.tabs.sendMessage(tabId, pending.message).then(pending.resolve).catch(pending.reject);
  292. console.log(LOG_PREFIX, `Flushed queued command to ${source} (tab ${tabId})`);
  293. }
  294. }
  295. function cancelPendingCommands(reason = STOP_ERROR_MESSAGE) {
  296. for (const [source, pending] of pendingCommands.entries()) {
  297. clearTimeout(pending.timer);
  298. pending.reject(new Error(reason));
  299. pendingCommands.delete(source);
  300. console.log(LOG_PREFIX, `Cancelled queued command for ${source}`);
  301. }
  302. }
  303. // ============================================================
  304. // Reuse or create tab
  305. // ============================================================
  306. async function reuseOrCreateTab(source, url, options = {}) {
  307. const alive = await isTabAlive(source);
  308. if (alive) {
  309. const tabId = await getTabId(source);
  310. await closeConflictingTabsForSource(source, url, { excludeTabIds: [tabId] });
  311. const currentTab = await chrome.tabs.get(tabId);
  312. const sameUrl = currentTab.url === url;
  313. const shouldReloadOnReuse = sameUrl && options.reloadIfSameUrl;
  314. const registry = await getTabRegistry();
  315. if (sameUrl) {
  316. await chrome.tabs.update(tabId, { active: true });
  317. console.log(LOG_PREFIX, `Reused tab ${source} (${tabId}) on same URL`);
  318. if (shouldReloadOnReuse) {
  319. if (registry[source]) registry[source].ready = false;
  320. await setState({ tabRegistry: registry });
  321. await chrome.tabs.reload(tabId);
  322. await new Promise((resolve) => {
  323. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  324. const listener = (tid, info) => {
  325. if (tid === tabId && info.status === 'complete') {
  326. chrome.tabs.onUpdated.removeListener(listener);
  327. clearTimeout(timer);
  328. resolve();
  329. }
  330. };
  331. chrome.tabs.onUpdated.addListener(listener);
  332. });
  333. }
  334. // For dynamically injected pages like the VPS panel, re-inject immediately.
  335. if (options.inject) {
  336. if (registry[source]) registry[source].ready = false;
  337. await setState({ tabRegistry: registry });
  338. if (options.injectSource) {
  339. await chrome.scripting.executeScript({
  340. target: { tabId },
  341. func: (injectedSource) => {
  342. window.__MULTIPAGE_SOURCE = injectedSource;
  343. },
  344. args: [options.injectSource],
  345. });
  346. }
  347. await chrome.scripting.executeScript({
  348. target: { tabId },
  349. files: options.inject,
  350. });
  351. await new Promise(r => setTimeout(r, 500));
  352. }
  353. await rememberSourceLastUrl(source, url);
  354. return tabId;
  355. }
  356. // Mark as not ready BEFORE navigating — so READY signal from new page is captured correctly
  357. if (registry[source]) registry[source].ready = false;
  358. await setState({ tabRegistry: registry });
  359. // Navigate existing tab to new URL
  360. await chrome.tabs.update(tabId, { url, active: true });
  361. console.log(LOG_PREFIX, `Reused tab ${source} (${tabId}), navigated to ${url.slice(0, 60)}`);
  362. // Wait for page load complete (with 30s timeout)
  363. await new Promise((resolve) => {
  364. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  365. const listener = (tid, info) => {
  366. if (tid === tabId && info.status === 'complete') {
  367. chrome.tabs.onUpdated.removeListener(listener);
  368. clearTimeout(timer);
  369. resolve();
  370. }
  371. };
  372. chrome.tabs.onUpdated.addListener(listener);
  373. });
  374. // If dynamic injection needed (VPS panel), re-inject after navigation
  375. if (options.inject) {
  376. if (options.injectSource) {
  377. await chrome.scripting.executeScript({
  378. target: { tabId },
  379. func: (injectedSource) => {
  380. window.__MULTIPAGE_SOURCE = injectedSource;
  381. },
  382. args: [options.injectSource],
  383. });
  384. }
  385. await chrome.scripting.executeScript({
  386. target: { tabId },
  387. files: options.inject,
  388. });
  389. }
  390. // Wait a bit for content script to inject and send READY
  391. await new Promise(r => setTimeout(r, 500));
  392. await rememberSourceLastUrl(source, url);
  393. return tabId;
  394. }
  395. // Create new tab
  396. await closeConflictingTabsForSource(source, url);
  397. const tab = await chrome.tabs.create({ url, active: true });
  398. console.log(LOG_PREFIX, `Created new tab ${source} (${tab.id})`);
  399. // If dynamic injection needed (VPS panel), inject scripts after load
  400. if (options.inject) {
  401. await new Promise((resolve) => {
  402. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  403. const listener = (tabId, info) => {
  404. if (tabId === tab.id && info.status === 'complete') {
  405. chrome.tabs.onUpdated.removeListener(listener);
  406. clearTimeout(timer);
  407. resolve();
  408. }
  409. };
  410. chrome.tabs.onUpdated.addListener(listener);
  411. });
  412. if (options.injectSource) {
  413. await chrome.scripting.executeScript({
  414. target: { tabId: tab.id },
  415. func: (injectedSource) => {
  416. window.__MULTIPAGE_SOURCE = injectedSource;
  417. },
  418. args: [options.injectSource],
  419. });
  420. }
  421. await chrome.scripting.executeScript({
  422. target: { tabId: tab.id },
  423. files: options.inject,
  424. });
  425. }
  426. await rememberSourceLastUrl(source, url);
  427. return tab.id;
  428. }
  429. // ============================================================
  430. // Send command to content script (with readiness check)
  431. // ============================================================
  432. async function sendToContentScript(source, message) {
  433. const registry = await getTabRegistry();
  434. const entry = registry[source];
  435. if (!entry || !entry.ready) {
  436. console.log(LOG_PREFIX, `${source} not ready, queuing command`);
  437. return queueCommand(source, message);
  438. }
  439. // Verify tab is still alive
  440. const alive = await isTabAlive(source);
  441. if (!alive) {
  442. // Tab was closed — queue the command, it will be sent when tab is reopened
  443. console.log(LOG_PREFIX, `${source} tab was closed, queuing command`);
  444. return queueCommand(source, message);
  445. }
  446. console.log(LOG_PREFIX, `Sending to ${source} (tab ${entry.tabId}):`, message.type);
  447. return chrome.tabs.sendMessage(entry.tabId, message);
  448. }
  449. async function sendToContentScriptResilient(source, message, options = {}) {
  450. const { timeoutMs = 30000, retryDelayMs = 600, logMessage = '' } = options;
  451. const start = Date.now();
  452. let lastError = null;
  453. let logged = false;
  454. while (Date.now() - start < timeoutMs) {
  455. throwIfStopped();
  456. try {
  457. return await sendToContentScript(source, message);
  458. } catch (err) {
  459. if (!isRetryableContentScriptTransportError(err)) {
  460. throw err;
  461. }
  462. lastError = err;
  463. if (logMessage && !logged) {
  464. await addLog(logMessage, 'warn');
  465. logged = true;
  466. }
  467. await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
  468. }
  469. }
  470. throw lastError || new Error(`等待 ${getSourceLabel(source)} 重新就绪超时。`);
  471. }
  472. // ============================================================
  473. // Logging
  474. // ============================================================
  475. async function addLog(message, level = 'info') {
  476. const state = await getState();
  477. const logs = state.logs || [];
  478. const entry = { message, level, timestamp: Date.now() };
  479. logs.push(entry);
  480. // Keep last 500 logs
  481. if (logs.length > 500) logs.splice(0, logs.length - 500);
  482. await setState({ logs });
  483. // Broadcast to side panel
  484. chrome.runtime.sendMessage({ type: 'LOG_ENTRY', payload: entry }).catch(() => {});
  485. }
  486. function getSourceLabel(source) {
  487. const labels = {
  488. 'sidepanel': '侧边栏',
  489. 'signup-page': '认证页',
  490. 'vps-panel': 'CPA 面板',
  491. 'qq-mail': 'QQ 邮箱',
  492. 'mail-163': '163 邮箱',
  493. 'inbucket-mail': 'Inbucket 邮箱',
  494. 'duck-mail': 'Duck 邮箱',
  495. };
  496. return labels[source] || source || '未知来源';
  497. }
  498. // ============================================================
  499. // Step Status Management
  500. // ============================================================
  501. async function setStepStatus(step, status) {
  502. const state = await getState();
  503. const statuses = { ...state.stepStatuses };
  504. statuses[step] = status;
  505. await setState({ stepStatuses: statuses, currentStep: step });
  506. // Broadcast to side panel
  507. chrome.runtime.sendMessage({
  508. type: 'STEP_STATUS_CHANGED',
  509. payload: { step, status },
  510. }).catch(() => {});
  511. }
  512. function isStopError(error) {
  513. const message = typeof error === 'string' ? error : error?.message;
  514. return message === STOP_ERROR_MESSAGE;
  515. }
  516. function isRetryableContentScriptTransportError(error) {
  517. const message = String(typeof error === 'string' ? error : error?.message || '');
  518. return /back\/forward cache|message channel is closed|Receiving end does not exist|port closed before a response was received|A listener indicated an asynchronous response/i.test(message);
  519. }
  520. function isRestartCurrentAttemptError(error) {
  521. const message = String(typeof error === 'string' ? error : error?.message || '');
  522. return /当前邮箱已存在,需要重新开始新一轮/.test(message);
  523. }
  524. function isStepDoneStatus(status) {
  525. return status === 'completed' || status === 'manual_completed' || status === 'skipped';
  526. }
  527. function getFirstUnfinishedStep(statuses = {}) {
  528. for (let step = 1; step <= 9; step++) {
  529. if (!isStepDoneStatus(statuses[step] || 'pending')) {
  530. return step;
  531. }
  532. }
  533. return null;
  534. }
  535. function hasSavedProgress(statuses = {}) {
  536. return Object.values({ ...DEFAULT_STATE.stepStatuses, ...statuses }).some((status) => status !== 'pending');
  537. }
  538. function clearStopRequest() {
  539. stopRequested = false;
  540. }
  541. function getAutoRunStatusPayload(phase, payload = {}) {
  542. const currentRun = payload.currentRun ?? autoRunCurrentRun;
  543. const totalRuns = payload.totalRuns ?? autoRunTotalRuns;
  544. const attemptRun = payload.attemptRun ?? autoRunAttemptRun;
  545. const autoRunning = phase === 'running' || phase === 'waiting_email' || phase === 'retrying';
  546. return {
  547. autoRunning,
  548. autoRunPhase: phase,
  549. autoRunCurrentRun: currentRun,
  550. autoRunTotalRuns: totalRuns,
  551. autoRunAttemptRun: attemptRun,
  552. };
  553. }
  554. async function broadcastAutoRunStatus(phase, payload = {}) {
  555. const statusPayload = {
  556. phase,
  557. currentRun: payload.currentRun ?? autoRunCurrentRun,
  558. totalRuns: payload.totalRuns ?? autoRunTotalRuns,
  559. attemptRun: payload.attemptRun ?? autoRunAttemptRun,
  560. };
  561. await setState(getAutoRunStatusPayload(phase, statusPayload));
  562. chrome.runtime.sendMessage({
  563. type: 'AUTO_RUN_STATUS',
  564. payload: statusPayload,
  565. }).catch(() => {});
  566. }
  567. function isAutoRunLockedState(state) {
  568. return Boolean(state.autoRunning) && (state.autoRunPhase === 'running' || state.autoRunPhase === 'retrying');
  569. }
  570. function isAutoRunPausedState(state) {
  571. return Boolean(state.autoRunning) && state.autoRunPhase === 'waiting_email';
  572. }
  573. async function ensureManualInteractionAllowed(actionLabel) {
  574. const state = await getState();
  575. if (isAutoRunLockedState(state)) {
  576. throw new Error(`自动流程运行中,请先停止后再${actionLabel}。`);
  577. }
  578. if (isAutoRunPausedState(state)) {
  579. throw new Error(`自动流程当前已暂停。请点击“继续”,或先确认接管自动流程后再${actionLabel}。`);
  580. }
  581. return state;
  582. }
  583. async function skipStep(step) {
  584. const state = await ensureManualInteractionAllowed('跳过步骤');
  585. if (!Number.isInteger(step) || step < 1 || step > 9) {
  586. throw new Error(`无效步骤:${step}`);
  587. }
  588. const statuses = { ...(state.stepStatuses || {}) };
  589. const currentStatus = statuses[step];
  590. if (currentStatus === 'running') {
  591. throw new Error(`步骤 ${step} 正在运行中,不能跳过。`);
  592. }
  593. if (isStepDoneStatus(currentStatus)) {
  594. throw new Error(`步骤 ${step} 已完成,无需再跳过。`);
  595. }
  596. if (step > 1) {
  597. const prevStatus = statuses[step - 1];
  598. if (!isStepDoneStatus(prevStatus)) {
  599. throw new Error(`请先完成步骤 ${step - 1},再跳过步骤 ${step}。`);
  600. }
  601. }
  602. await setStepStatus(step, 'skipped');
  603. await addLog(`步骤 ${step} 已跳过`, 'warn');
  604. if (step === 1) {
  605. const latestState = await getState();
  606. const step2Status = latestState.stepStatuses?.[2];
  607. if (!isStepDoneStatus(step2Status) && step2Status !== 'running') {
  608. await setStepStatus(2, 'skipped');
  609. await addLog('步骤 1 已跳过,步骤 2 也已同时跳过。', 'warn');
  610. }
  611. }
  612. return { ok: true, step, status: 'skipped' };
  613. }
  614. function throwIfStopped() {
  615. if (stopRequested) {
  616. throw new Error(STOP_ERROR_MESSAGE);
  617. }
  618. }
  619. async function sleepWithStop(ms) {
  620. const start = Date.now();
  621. while (Date.now() - start < ms) {
  622. throwIfStopped();
  623. await new Promise(r => setTimeout(r, Math.min(100, ms - (Date.now() - start))));
  624. }
  625. }
  626. async function humanStepDelay(min = HUMAN_STEP_DELAY_MIN, max = HUMAN_STEP_DELAY_MAX) {
  627. const duration = Math.floor(Math.random() * (max - min + 1)) + min;
  628. await sleepWithStop(duration);
  629. }
  630. async function clickWithDebugger(tabId, rect) {
  631. if (!tabId) {
  632. throw new Error('未找到用于调试点击的认证页面标签页。');
  633. }
  634. if (!rect || !Number.isFinite(rect.centerX) || !Number.isFinite(rect.centerY)) {
  635. throw new Error('步骤 8 的调试器兜底点击需要有效的按钮坐标。');
  636. }
  637. const target = { tabId };
  638. try {
  639. await chrome.debugger.attach(target, '1.3');
  640. } catch (err) {
  641. throw new Error(
  642. `步骤 8 的调试器兜底点击附加失败:${err.message}。` +
  643. '如果认证页标签已打开 DevTools,请先关闭后重试。'
  644. );
  645. }
  646. try {
  647. const x = Math.round(rect.centerX);
  648. const y = Math.round(rect.centerY);
  649. await chrome.debugger.sendCommand(target, 'Page.bringToFront');
  650. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  651. type: 'mouseMoved',
  652. x,
  653. y,
  654. button: 'none',
  655. buttons: 0,
  656. clickCount: 0,
  657. });
  658. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  659. type: 'mousePressed',
  660. x,
  661. y,
  662. button: 'left',
  663. buttons: 1,
  664. clickCount: 1,
  665. });
  666. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  667. type: 'mouseReleased',
  668. x,
  669. y,
  670. button: 'left',
  671. buttons: 0,
  672. clickCount: 1,
  673. });
  674. } finally {
  675. await chrome.debugger.detach(target).catch(() => {});
  676. }
  677. }
  678. async function broadcastStopToContentScripts() {
  679. const registry = await getTabRegistry();
  680. for (const entry of Object.values(registry)) {
  681. if (!entry?.tabId) continue;
  682. try {
  683. await chrome.tabs.sendMessage(entry.tabId, {
  684. type: 'STOP_FLOW',
  685. source: 'background',
  686. payload: {},
  687. });
  688. } catch {}
  689. }
  690. }
  691. let stopRequested = false;
  692. // ============================================================
  693. // Message Handler (central router)
  694. // ============================================================
  695. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  696. console.log(LOG_PREFIX, `Received: ${message.type} from ${message.source || 'sidepanel'}`, message);
  697. handleMessage(message, sender).then(response => {
  698. sendResponse(response);
  699. }).catch(err => {
  700. console.error(LOG_PREFIX, 'Handler error:', err);
  701. sendResponse({ error: err.message });
  702. });
  703. return true; // async response
  704. });
  705. async function handleMessage(message, sender) {
  706. switch (message.type) {
  707. case 'CONTENT_SCRIPT_READY': {
  708. const tabId = sender.tab?.id;
  709. if (tabId && message.source) {
  710. await registerTab(message.source, tabId);
  711. flushCommand(message.source, tabId);
  712. await addLog(`内容脚本已就绪:${getSourceLabel(message.source)}(标签页 ${tabId})`);
  713. }
  714. return { ok: true };
  715. }
  716. case 'LOG': {
  717. const { message: msg, level } = message.payload;
  718. await addLog(`[${getSourceLabel(message.source)}] ${msg}`, level);
  719. return { ok: true };
  720. }
  721. case 'STEP_COMPLETE': {
  722. if (stopRequested) {
  723. await setStepStatus(message.step, 'stopped');
  724. notifyStepError(message.step, STOP_ERROR_MESSAGE);
  725. return { ok: true };
  726. }
  727. await setStepStatus(message.step, 'completed');
  728. await addLog(`步骤 ${message.step} 已完成`, 'ok');
  729. await handleStepData(message.step, message.payload);
  730. notifyStepComplete(message.step, message.payload);
  731. return { ok: true };
  732. }
  733. case 'STEP_ERROR': {
  734. if (isStopError(message.error)) {
  735. await setStepStatus(message.step, 'stopped');
  736. await addLog(`步骤 ${message.step} 已被用户停止`, 'warn');
  737. notifyStepError(message.step, message.error);
  738. } else {
  739. await setStepStatus(message.step, 'failed');
  740. await addLog(`步骤 ${message.step} 失败:${message.error}`, 'error');
  741. notifyStepError(message.step, message.error);
  742. }
  743. return { ok: true };
  744. }
  745. case 'GET_STATE': {
  746. return await getState();
  747. }
  748. case 'RESET': {
  749. clearStopRequest();
  750. await resetState();
  751. await addLog('流程已重置', 'info');
  752. return { ok: true };
  753. }
  754. case 'EXECUTE_STEP': {
  755. clearStopRequest();
  756. if (message.source === 'sidepanel') {
  757. await ensureManualInteractionAllowed('手动执行步骤');
  758. }
  759. const step = message.payload.step;
  760. // Save email if provided (from side panel step 3)
  761. if (message.payload.email) {
  762. await setEmailState(message.payload.email);
  763. }
  764. await executeStep(step);
  765. return { ok: true };
  766. }
  767. case 'AUTO_RUN': {
  768. clearStopRequest();
  769. const totalRuns = message.payload?.totalRuns || 1;
  770. const autoRunSkipFailures = Boolean(message.payload?.autoRunSkipFailures);
  771. const mode = message.payload?.mode === 'continue' ? 'continue' : 'restart';
  772. await setState({ autoRunSkipFailures });
  773. autoRunLoop(totalRuns, { autoRunSkipFailures, mode }); // fire-and-forget
  774. return { ok: true };
  775. }
  776. case 'RESUME_AUTO_RUN': {
  777. clearStopRequest();
  778. if (message.payload.email) {
  779. await setEmailState(message.payload.email);
  780. }
  781. resumeAutoRun(); // fire-and-forget
  782. return { ok: true };
  783. }
  784. case 'TAKEOVER_AUTO_RUN': {
  785. await requestStop({ logMessage: '已确认手动接管,正在停止自动流程并切换为手动控制...' });
  786. await addLog('自动流程已切换为手动控制。', 'warn');
  787. return { ok: true };
  788. }
  789. case 'SKIP_STEP': {
  790. const step = Number(message.payload?.step);
  791. return await skipStep(step);
  792. }
  793. case 'SAVE_SETTING': {
  794. const updates = {};
  795. if (message.payload.vpsUrl !== undefined) updates.vpsUrl = message.payload.vpsUrl;
  796. if (message.payload.vpsPassword !== undefined) updates.vpsPassword = message.payload.vpsPassword;
  797. if (message.payload.customPassword !== undefined) updates.customPassword = message.payload.customPassword;
  798. if (message.payload.autoRunSkipFailures !== undefined) updates.autoRunSkipFailures = Boolean(message.payload.autoRunSkipFailures);
  799. if (message.payload.mailProvider !== undefined) updates.mailProvider = message.payload.mailProvider;
  800. if (message.payload.inbucketHost !== undefined) updates.inbucketHost = message.payload.inbucketHost;
  801. if (message.payload.inbucketMailbox !== undefined) updates.inbucketMailbox = message.payload.inbucketMailbox;
  802. await setPersistentSettings(updates);
  803. await setState(updates);
  804. return { ok: true };
  805. }
  806. // Side panel data updates
  807. case 'SAVE_EMAIL': {
  808. const state = await getState();
  809. if (isAutoRunLockedState(state)) {
  810. throw new Error('自动流程运行中,当前不能手动修改邮箱。');
  811. }
  812. await setEmailState(message.payload.email);
  813. await resumeAutoRun();
  814. return { ok: true, email: message.payload.email };
  815. }
  816. case 'FETCH_DUCK_EMAIL': {
  817. clearStopRequest();
  818. const state = await getState();
  819. if (isAutoRunLockedState(state)) {
  820. throw new Error('自动流程运行中,当前不能手动获取 Duck 邮箱。');
  821. }
  822. const email = await fetchDuckEmail(message.payload || {});
  823. await resumeAutoRun();
  824. return { ok: true, email };
  825. }
  826. case 'STOP_FLOW': {
  827. await requestStop();
  828. return { ok: true };
  829. }
  830. default:
  831. console.warn(LOG_PREFIX, `Unknown message type: ${message.type}`);
  832. return { error: `Unknown message type: ${message.type}` };
  833. }
  834. }
  835. // ============================================================
  836. // Step Data Handlers
  837. // ============================================================
  838. async function handleStepData(step, payload) {
  839. switch (step) {
  840. case 1:
  841. if (payload.oauthUrl) {
  842. await setState({ oauthUrl: payload.oauthUrl });
  843. broadcastDataUpdate({ oauthUrl: payload.oauthUrl });
  844. }
  845. break;
  846. case 3:
  847. if (payload.email) await setEmailState(payload.email);
  848. break;
  849. case 4:
  850. if (payload.emailTimestamp) await setState({ lastEmailTimestamp: payload.emailTimestamp });
  851. break;
  852. case 8:
  853. if (payload.localhostUrl) {
  854. await setState({ localhostUrl: payload.localhostUrl });
  855. broadcastDataUpdate({ localhostUrl: payload.localhostUrl });
  856. }
  857. break;
  858. case 9: {
  859. const localhostPrefix = buildLocalhostCleanupPrefix(payload.localhostUrl);
  860. if (localhostPrefix) {
  861. await closeTabsByUrlPrefix(localhostPrefix);
  862. }
  863. break;
  864. }
  865. }
  866. }
  867. // ============================================================
  868. // Step Completion Waiting
  869. // ============================================================
  870. // Map of step -> { resolve, reject } for waiting on step completion
  871. const stepWaiters = new Map();
  872. let resumeWaiter = null;
  873. function waitForStepComplete(step, timeoutMs = 120000) {
  874. return new Promise((resolve, reject) => {
  875. throwIfStopped();
  876. const timer = setTimeout(() => {
  877. stepWaiters.delete(step);
  878. reject(new Error(`Step ${step} timed out after ${timeoutMs / 1000}s`));
  879. }, timeoutMs);
  880. stepWaiters.set(step, {
  881. resolve: (data) => { clearTimeout(timer); stepWaiters.delete(step); resolve(data); },
  882. reject: (err) => { clearTimeout(timer); stepWaiters.delete(step); reject(err); },
  883. });
  884. });
  885. }
  886. function notifyStepComplete(step, payload) {
  887. const waiter = stepWaiters.get(step);
  888. if (waiter) waiter.resolve(payload);
  889. }
  890. function notifyStepError(step, error) {
  891. const waiter = stepWaiters.get(step);
  892. if (waiter) waiter.reject(new Error(error));
  893. }
  894. async function completeStepFromBackground(step, payload = {}) {
  895. if (stopRequested) {
  896. await setStepStatus(step, 'stopped');
  897. notifyStepError(step, STOP_ERROR_MESSAGE);
  898. return;
  899. }
  900. await setStepStatus(step, 'completed');
  901. await addLog(`步骤 ${step} 已完成`, 'ok');
  902. await handleStepData(step, payload);
  903. notifyStepComplete(step, payload);
  904. }
  905. async function markRunningStepsStopped() {
  906. const state = await getState();
  907. const runningSteps = Object.entries(state.stepStatuses || {})
  908. .filter(([, status]) => status === 'running')
  909. .map(([step]) => Number(step));
  910. for (const step of runningSteps) {
  911. await setStepStatus(step, 'stopped');
  912. }
  913. }
  914. async function requestStop(options = {}) {
  915. const { logMessage = '已收到停止请求,正在取消当前操作...' } = options;
  916. if (stopRequested) return;
  917. stopRequested = true;
  918. cancelPendingCommands();
  919. if (webNavListener) {
  920. chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
  921. webNavListener = null;
  922. }
  923. await addLog(logMessage, 'warn');
  924. await broadcastStopToContentScripts();
  925. for (const waiter of stepWaiters.values()) {
  926. waiter.reject(new Error(STOP_ERROR_MESSAGE));
  927. }
  928. stepWaiters.clear();
  929. if (resumeWaiter) {
  930. resumeWaiter.reject(new Error(STOP_ERROR_MESSAGE));
  931. resumeWaiter = null;
  932. }
  933. await markRunningStepsStopped();
  934. autoRunActive = false;
  935. await broadcastAutoRunStatus('stopped', {
  936. currentRun: autoRunCurrentRun,
  937. totalRuns: autoRunTotalRuns,
  938. attemptRun: autoRunAttemptRun,
  939. });
  940. }
  941. // ============================================================
  942. // Step Execution
  943. // ============================================================
  944. async function executeStep(step) {
  945. console.log(LOG_PREFIX, `Executing step ${step}`);
  946. throwIfStopped();
  947. await setStepStatus(step, 'running');
  948. await addLog(`步骤 ${step} 开始执行`);
  949. await humanStepDelay();
  950. const state = await getState();
  951. // Set flow start time on first step
  952. if (step === 1 && !state.flowStartTime) {
  953. await setState({ flowStartTime: Date.now() });
  954. }
  955. try {
  956. switch (step) {
  957. case 1: await executeStep1(state); break;
  958. case 2: await executeStep2(state); break;
  959. case 3: await executeStep3(state); break;
  960. case 4: await executeStep4(state); break;
  961. case 5: await executeStep5(state); break;
  962. case 6: await executeStep6(state); break;
  963. case 7: await executeStep7(state); break;
  964. case 8: await executeStep8(state); break;
  965. case 9: await executeStep9(state); break;
  966. default:
  967. throw new Error(`未知步骤:${step}`);
  968. }
  969. } catch (err) {
  970. if (isStopError(err)) {
  971. await setStepStatus(step, 'stopped');
  972. await addLog(`步骤 ${step} 已被用户停止`, 'warn');
  973. throw err;
  974. }
  975. await setStepStatus(step, 'failed');
  976. await addLog(`步骤 ${step} 失败:${err.message}`, 'error');
  977. throw err;
  978. }
  979. }
  980. /**
  981. * Execute a step and wait for it to complete before returning.
  982. * @param {number} step
  983. * @param {number} delayAfter - ms to wait after completion (for page transitions)
  984. */
  985. async function executeStepAndWait(step, delayAfter = 2000) {
  986. throwIfStopped();
  987. const promise = waitForStepComplete(step, 120000);
  988. await executeStep(step);
  989. await promise;
  990. // Extra delay for page transitions / DOM updates
  991. if (delayAfter > 0) {
  992. await sleepWithStop(delayAfter + Math.floor(Math.random() * 1200));
  993. }
  994. }
  995. async function fetchDuckEmail(options = {}) {
  996. throwIfStopped();
  997. const { generateNew = true } = options;
  998. await addLog(`Duck 邮箱:正在打开自动填充设置(${generateNew ? '生成新地址' : '复用当前地址'})...`);
  999. await reuseOrCreateTab('duck-mail', DUCK_AUTOFILL_URL);
  1000. const result = await sendToContentScript('duck-mail', {
  1001. type: 'FETCH_DUCK_EMAIL',
  1002. source: 'background',
  1003. payload: { generateNew },
  1004. });
  1005. if (result?.error) {
  1006. throw new Error(result.error);
  1007. }
  1008. if (!result?.email) {
  1009. throw new Error('未返回 Duck 邮箱地址。');
  1010. }
  1011. await setEmailState(result.email);
  1012. await addLog(`Duck 邮箱:${result.generated ? '已生成' : '已读取'} ${result.email}`, 'ok');
  1013. return result.email;
  1014. }
  1015. // ============================================================
  1016. // Auto Run Flow
  1017. // ============================================================
  1018. let autoRunActive = false;
  1019. let autoRunCurrentRun = 0;
  1020. let autoRunTotalRuns = 1;
  1021. let autoRunAttemptRun = 0;
  1022. const AUTO_STEP_DELAYS = {
  1023. 1: 2000,
  1024. 2: 2000,
  1025. 3: 3000,
  1026. 4: 2000,
  1027. 5: 3000,
  1028. 6: 3000,
  1029. 7: 2000,
  1030. 8: 2000,
  1031. 9: 1000,
  1032. };
  1033. async function resumeAutoRunIfWaitingForEmail(options = {}) {
  1034. const { silent = false } = options;
  1035. const state = await getState();
  1036. if (!state.email || !isAutoRunPausedState(state)) {
  1037. return false;
  1038. }
  1039. if (resumeWaiter) {
  1040. if (!silent) {
  1041. await addLog('邮箱已就绪,自动继续后续步骤...', 'info');
  1042. }
  1043. resumeWaiter.resolve();
  1044. resumeWaiter = null;
  1045. return true;
  1046. }
  1047. return false;
  1048. }
  1049. async function ensureAutoEmailReady(targetRun, totalRuns, attemptRuns) {
  1050. const currentState = await getState();
  1051. if (currentState.email) {
  1052. return currentState.email;
  1053. }
  1054. try {
  1055. const duckEmail = await fetchDuckEmail({ generateNew: true });
  1056. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:Duck 邮箱已就绪:${duckEmail}(第 ${attemptRuns} 次尝试)===`, 'ok');
  1057. return duckEmail;
  1058. } catch (err) {
  1059. await addLog(`Duck 邮箱自动获取失败:${err.message}`, 'warn');
  1060. }
  1061. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮已暂停:请先获取 Duck 邮箱或手动粘贴邮箱,然后继续 ===`, 'warn');
  1062. await broadcastAutoRunStatus('waiting_email', {
  1063. currentRun: targetRun,
  1064. totalRuns,
  1065. attemptRun: attemptRuns,
  1066. });
  1067. await waitForResume();
  1068. const resumedState = await getState();
  1069. if (!resumedState.email) {
  1070. throw new Error('无法继续:当前没有邮箱地址。');
  1071. }
  1072. return resumedState.email;
  1073. }
  1074. async function runAutoSequenceFromStep(startStep, context = {}) {
  1075. const { targetRun, totalRuns, attemptRuns, continued = false } = context;
  1076. if (continued) {
  1077. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:继续当前进度,从步骤 ${startStep} 开始(第 ${attemptRuns} 次尝试)===`, 'info');
  1078. } else {
  1079. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:第 ${attemptRuns} 次尝试,阶段 1,获取 OAuth 链接并打开注册页 ===`, 'info');
  1080. }
  1081. if (startStep <= 2) {
  1082. for (const step of [1, 2]) {
  1083. if (step < startStep) continue;
  1084. await executeStepAndWait(step, AUTO_STEP_DELAYS[step]);
  1085. }
  1086. }
  1087. if (startStep <= 3) {
  1088. await ensureAutoEmailReady(targetRun, totalRuns, attemptRuns);
  1089. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:阶段 2,注册、验证、登录并完成授权(第 ${attemptRuns} 次尝试)===`, 'info');
  1090. await broadcastAutoRunStatus('running', {
  1091. currentRun: targetRun,
  1092. totalRuns,
  1093. attemptRun: attemptRuns,
  1094. });
  1095. await executeStepAndWait(3, AUTO_STEP_DELAYS[3]);
  1096. } else {
  1097. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:继续执行剩余流程(第 ${attemptRuns} 次尝试)===`, 'info');
  1098. }
  1099. const signupTabId = await getTabId('signup-page');
  1100. if (signupTabId) {
  1101. await chrome.tabs.update(signupTabId, { active: true });
  1102. }
  1103. for (let step = Math.max(startStep, 4); step <= 9; step++) {
  1104. await executeStepAndWait(step, AUTO_STEP_DELAYS[step]);
  1105. }
  1106. }
  1107. // Outer loop: keep retrying until the target number of successful runs is reached.
  1108. async function autoRunLoop(totalRuns, options = {}) {
  1109. if (autoRunActive) {
  1110. await addLog('自动运行已在进行中', 'warn');
  1111. return;
  1112. }
  1113. clearStopRequest();
  1114. autoRunActive = true;
  1115. autoRunTotalRuns = totalRuns;
  1116. autoRunCurrentRun = 0;
  1117. autoRunAttemptRun = 0;
  1118. const autoRunSkipFailures = Boolean(options.autoRunSkipFailures);
  1119. const initialMode = options.mode === 'continue' ? 'continue' : 'restart';
  1120. const resumeCurrentRun = Number.isInteger(options.resumeCurrentRun) ? options.resumeCurrentRun : 0;
  1121. const resumeSuccessfulRuns = Number.isInteger(options.resumeSuccessfulRuns) ? options.resumeSuccessfulRuns : 0;
  1122. const resumeAttemptRunsProcessed = Number.isInteger(options.resumeAttemptRunsProcessed) ? options.resumeAttemptRunsProcessed : 0;
  1123. let maxAttempts = autoRunSkipFailures ? Math.max(totalRuns * 10, totalRuns + 20) : totalRuns;
  1124. const forcedRetryCap = Math.max(totalRuns * 10, totalRuns + 20);
  1125. let successfulRuns = Math.max(0, resumeSuccessfulRuns);
  1126. let attemptRuns = Math.max(0, resumeAttemptRunsProcessed);
  1127. let forceFreshTabsNextRun = false;
  1128. let continueCurrentOnFirstAttempt = initialMode === 'continue';
  1129. await setState({
  1130. autoRunSkipFailures,
  1131. ...getAutoRunStatusPayload('running', {
  1132. currentRun: resumeCurrentRun,
  1133. totalRuns,
  1134. attemptRun: resumeAttemptRunsProcessed,
  1135. }),
  1136. });
  1137. while (successfulRuns < totalRuns && attemptRuns < maxAttempts) {
  1138. attemptRuns += 1;
  1139. const targetRun = successfulRuns + 1;
  1140. autoRunCurrentRun = targetRun;
  1141. autoRunAttemptRun = attemptRuns;
  1142. let startStep = 1;
  1143. let useExistingProgress = false;
  1144. if (continueCurrentOnFirstAttempt) {
  1145. const currentState = await getState();
  1146. const resumeStep = getFirstUnfinishedStep(currentState.stepStatuses);
  1147. if (resumeStep && hasSavedProgress(currentState.stepStatuses)) {
  1148. startStep = resumeStep;
  1149. useExistingProgress = true;
  1150. } else if (hasSavedProgress(currentState.stepStatuses)) {
  1151. await addLog('当前流程已全部处理,将按“重新开始”新开一轮自动运行。', 'info');
  1152. }
  1153. continueCurrentOnFirstAttempt = false;
  1154. }
  1155. if (!useExistingProgress) {
  1156. // Reset everything at the start of each fresh attempt (keep user settings).
  1157. const prevState = await getState();
  1158. const keepSettings = {
  1159. vpsUrl: prevState.vpsUrl,
  1160. vpsPassword: prevState.vpsPassword,
  1161. customPassword: prevState.customPassword,
  1162. autoRunSkipFailures: prevState.autoRunSkipFailures,
  1163. mailProvider: prevState.mailProvider,
  1164. inbucketHost: prevState.inbucketHost,
  1165. inbucketMailbox: prevState.inbucketMailbox,
  1166. ...getAutoRunStatusPayload('running', { currentRun: targetRun, totalRuns, attemptRun: attemptRuns }),
  1167. ...(forceFreshTabsNextRun ? { tabRegistry: {} } : {}),
  1168. };
  1169. await resetState();
  1170. await setState(keepSettings);
  1171. chrome.runtime.sendMessage({ type: 'AUTO_RUN_RESET' }).catch(() => {});
  1172. await sleepWithStop(500);
  1173. } else {
  1174. await setState({
  1175. autoRunSkipFailures,
  1176. ...getAutoRunStatusPayload('running', { currentRun: targetRun, totalRuns, attemptRun: attemptRuns }),
  1177. });
  1178. }
  1179. if (forceFreshTabsNextRun) {
  1180. await addLog(`兜底模式:上一轮已放弃,当前开始第 ${attemptRuns} 次尝试,将使用新线程继续补足第 ${targetRun}/${totalRuns} 轮。`, 'warn');
  1181. forceFreshTabsNextRun = false;
  1182. }
  1183. try {
  1184. throwIfStopped();
  1185. await broadcastAutoRunStatus('running', {
  1186. currentRun: targetRun,
  1187. totalRuns,
  1188. attemptRun: attemptRuns,
  1189. });
  1190. await runAutoSequenceFromStep(startStep, {
  1191. targetRun,
  1192. totalRuns,
  1193. attemptRuns,
  1194. continued: useExistingProgress,
  1195. });
  1196. successfulRuns += 1;
  1197. autoRunCurrentRun = successfulRuns;
  1198. await addLog(`=== 目标 ${successfulRuns}/${totalRuns} 轮已完成(第 ${attemptRuns} 次尝试成功)===`, 'ok');
  1199. continue;
  1200. } catch (err) {
  1201. if (isStopError(err)) {
  1202. await addLog(`目标 ${targetRun}/${totalRuns} 轮已被用户停止`, 'warn');
  1203. await broadcastAutoRunStatus('stopped', {
  1204. currentRun: targetRun,
  1205. totalRuns,
  1206. attemptRun: attemptRuns,
  1207. });
  1208. break;
  1209. }
  1210. if (isRestartCurrentAttemptError(err)) {
  1211. await addLog(`目标 ${targetRun}/${totalRuns} 轮检测到当前邮箱已存在,当前线程已放弃,将重新开始新一轮。`, 'warn');
  1212. cancelPendingCommands('当前线程因邮箱已存在而放弃。');
  1213. await broadcastStopToContentScripts();
  1214. await broadcastAutoRunStatus('retrying', {
  1215. currentRun: targetRun,
  1216. totalRuns,
  1217. attemptRun: attemptRuns,
  1218. });
  1219. forceFreshTabsNextRun = true;
  1220. maxAttempts = Math.max(maxAttempts, Math.min(forcedRetryCap, attemptRuns + 1));
  1221. continue;
  1222. }
  1223. if (!autoRunSkipFailures) {
  1224. await addLog(`目标 ${targetRun}/${totalRuns} 轮失败:${err.message}`, 'error');
  1225. await broadcastAutoRunStatus('stopped', {
  1226. currentRun: targetRun,
  1227. totalRuns,
  1228. attemptRun: attemptRuns,
  1229. });
  1230. break;
  1231. }
  1232. await addLog(`目标 ${targetRun}/${totalRuns} 轮的第 ${attemptRuns} 次尝试失败:${err.message}`, 'error');
  1233. await addLog('兜底开关已开启:将放弃当前线程,重新开一轮继续补足目标次数。', 'warn');
  1234. cancelPendingCommands('当前尝试已放弃。');
  1235. await broadcastStopToContentScripts();
  1236. await broadcastAutoRunStatus('retrying', {
  1237. currentRun: targetRun,
  1238. totalRuns,
  1239. attemptRun: attemptRuns,
  1240. });
  1241. forceFreshTabsNextRun = true;
  1242. }
  1243. }
  1244. if (!stopRequested && autoRunSkipFailures && successfulRuns < totalRuns && attemptRuns >= maxAttempts) {
  1245. await addLog(`已达到安全重试上限(${attemptRuns} 次尝试),当前仅完成 ${successfulRuns}/${totalRuns} 轮。`, 'error');
  1246. await broadcastAutoRunStatus('stopped', {
  1247. currentRun: successfulRuns,
  1248. totalRuns: autoRunTotalRuns,
  1249. attemptRun: attemptRuns,
  1250. });
  1251. } else if (stopRequested) {
  1252. await addLog(`=== 已停止,完成 ${successfulRuns}/${autoRunTotalRuns} 轮,共尝试 ${attemptRuns} 次 ===`, 'warn');
  1253. await broadcastAutoRunStatus('stopped', {
  1254. currentRun: successfulRuns,
  1255. totalRuns: autoRunTotalRuns,
  1256. attemptRun: attemptRuns,
  1257. });
  1258. } else if (successfulRuns >= autoRunTotalRuns) {
  1259. await addLog(`=== 全部 ${autoRunTotalRuns} 轮均已成功完成,共尝试 ${attemptRuns} 次 ===`, 'ok');
  1260. await broadcastAutoRunStatus('complete', {
  1261. currentRun: successfulRuns,
  1262. totalRuns: autoRunTotalRuns,
  1263. attemptRun: attemptRuns,
  1264. });
  1265. } else {
  1266. await addLog(`=== 已停止,完成 ${successfulRuns}/${autoRunTotalRuns} 轮,共尝试 ${attemptRuns} 次 ===`, 'warn');
  1267. await broadcastAutoRunStatus('stopped', {
  1268. currentRun: successfulRuns,
  1269. totalRuns: autoRunTotalRuns,
  1270. attemptRun: attemptRuns,
  1271. });
  1272. }
  1273. autoRunActive = false;
  1274. autoRunAttemptRun = attemptRuns;
  1275. await setState(getAutoRunStatusPayload(stopRequested ? 'stopped' : (successfulRuns >= autoRunTotalRuns ? 'complete' : 'stopped'), {
  1276. currentRun: successfulRuns,
  1277. totalRuns: autoRunTotalRuns,
  1278. attemptRun: attemptRuns,
  1279. }));
  1280. clearStopRequest();
  1281. }
  1282. async function waitForResume() {
  1283. throwIfStopped();
  1284. const state = await getState();
  1285. if (state.email) {
  1286. await addLog('邮箱已就绪,自动继续后续步骤...', 'info');
  1287. return;
  1288. }
  1289. return new Promise((resolve, reject) => {
  1290. resumeWaiter = { resolve, reject };
  1291. });
  1292. }
  1293. async function resumeAutoRun() {
  1294. throwIfStopped();
  1295. const state = await getState();
  1296. if (!state.email) {
  1297. await addLog('无法继续:当前没有邮箱地址,请先在侧边栏填写邮箱。', 'error');
  1298. return false;
  1299. }
  1300. const resumedInMemory = await resumeAutoRunIfWaitingForEmail({ silent: true });
  1301. if (resumedInMemory) {
  1302. return true;
  1303. }
  1304. if (!isAutoRunPausedState(state)) {
  1305. return false;
  1306. }
  1307. if (autoRunActive) {
  1308. return false;
  1309. }
  1310. const totalRuns = state.autoRunTotalRuns || 1;
  1311. const currentRun = state.autoRunCurrentRun || 1;
  1312. const attemptRun = state.autoRunAttemptRun || 1;
  1313. const successfulRuns = Math.max(0, currentRun - 1);
  1314. await addLog('检测到自动流程暂停上下文已丢失,正在从当前进度恢复自动运行...', 'warn');
  1315. autoRunLoop(totalRuns, {
  1316. autoRunSkipFailures: Boolean(state.autoRunSkipFailures),
  1317. mode: 'continue',
  1318. resumeCurrentRun: currentRun,
  1319. resumeSuccessfulRuns: successfulRuns,
  1320. resumeAttemptRunsProcessed: Math.max(0, attemptRun - 1),
  1321. });
  1322. return true;
  1323. }
  1324. // ============================================================
  1325. // Step 1: Get OAuth Link (via vps-panel.js)
  1326. // ============================================================
  1327. async function executeStep1(state) {
  1328. if (!state.vpsUrl) {
  1329. throw new Error('尚未配置 CPA 地址,请先在侧边栏填写。');
  1330. }
  1331. await addLog('步骤 1:正在打开 CPA 面板...');
  1332. await reuseOrCreateTab('vps-panel', state.vpsUrl, {
  1333. inject: ['content/utils.js', 'content/vps-panel.js'],
  1334. reloadIfSameUrl: true,
  1335. });
  1336. await sendToContentScript('vps-panel', {
  1337. type: 'EXECUTE_STEP',
  1338. step: 1,
  1339. source: 'background',
  1340. payload: { vpsPassword: state.vpsPassword },
  1341. });
  1342. }
  1343. // ============================================================
  1344. // Step 2: Open Signup Page (Background opens tab, signup-page.js clicks Register)
  1345. // ============================================================
  1346. async function executeStep2(state) {
  1347. if (!state.oauthUrl) {
  1348. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  1349. }
  1350. await addLog('步骤 2:正在打开认证链接...');
  1351. await reuseOrCreateTab('signup-page', state.oauthUrl);
  1352. await sendToContentScript('signup-page', {
  1353. type: 'EXECUTE_STEP',
  1354. step: 2,
  1355. source: 'background',
  1356. payload: {},
  1357. });
  1358. }
  1359. // ============================================================
  1360. // Step 3: Fill Email & Password (via signup-page.js)
  1361. // ============================================================
  1362. async function executeStep3(state) {
  1363. if (!state.email) {
  1364. throw new Error('缺少邮箱地址,请先在侧边栏粘贴邮箱。');
  1365. }
  1366. const password = state.customPassword || generatePassword();
  1367. await setPasswordState(password);
  1368. // Save account record
  1369. const accounts = state.accounts || [];
  1370. accounts.push({ email: state.email, password, createdAt: new Date().toISOString() });
  1371. await setState({ accounts });
  1372. await addLog(
  1373. `步骤 3:正在填写邮箱 ${state.email},密码为${state.customPassword ? '自定义' : '自动生成'}(${password.length} 位)`
  1374. );
  1375. await sendToContentScript('signup-page', {
  1376. type: 'EXECUTE_STEP',
  1377. step: 3,
  1378. source: 'background',
  1379. payload: { email: state.email, password },
  1380. });
  1381. }
  1382. // ============================================================
  1383. // Step 4: Get Signup Verification Code (qq-mail.js polls, then fills in signup-page.js)
  1384. // ============================================================
  1385. function getMailConfig(state) {
  1386. const provider = state.mailProvider || 'qq';
  1387. if (provider === '163') {
  1388. 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 邮箱' };
  1389. }
  1390. if (provider === 'inbucket') {
  1391. const host = normalizeInbucketOrigin(state.inbucketHost);
  1392. const mailbox = (state.inbucketMailbox || '').trim();
  1393. if (!host) {
  1394. return { error: 'Inbucket 主机地址为空或无效。' };
  1395. }
  1396. if (!mailbox) {
  1397. return { error: 'Inbucket 邮箱名称为空。' };
  1398. }
  1399. return {
  1400. source: 'inbucket-mail',
  1401. url: `${host}/m/${encodeURIComponent(mailbox)}/`,
  1402. label: `Inbucket 邮箱(${mailbox})`,
  1403. navigateOnReuse: true,
  1404. inject: ['content/utils.js', 'content/inbucket-mail.js'],
  1405. injectSource: 'inbucket-mail',
  1406. };
  1407. }
  1408. return { source: 'qq-mail', url: 'https://wx.mail.qq.com/', label: 'QQ 邮箱' };
  1409. }
  1410. function normalizeInbucketOrigin(rawValue) {
  1411. const value = (rawValue || '').trim();
  1412. if (!value) return '';
  1413. const candidate = /^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(value) ? value : `https://${value}`;
  1414. try {
  1415. const parsed = new URL(candidate);
  1416. return parsed.origin;
  1417. } catch {
  1418. return '';
  1419. }
  1420. }
  1421. function getVerificationCodeStateKey(step) {
  1422. return step === 4 ? 'lastSignupCode' : 'lastLoginCode';
  1423. }
  1424. function getVerificationCodeLabel(step) {
  1425. return step === 4 ? '注册' : '登录';
  1426. }
  1427. function getVerificationPollPayload(step, state, overrides = {}) {
  1428. if (step === 4) {
  1429. return {
  1430. filterAfterTimestamp: state.flowStartTime || 0,
  1431. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'duckduckgo', 'forward'],
  1432. subjectFilters: ['verify', 'verification', 'code', '楠岃瘉', 'confirm'],
  1433. targetEmail: state.email,
  1434. maxAttempts: 5,
  1435. intervalMs: 3000,
  1436. ...overrides,
  1437. };
  1438. }
  1439. return {
  1440. filterAfterTimestamp: state.lastEmailTimestamp || state.flowStartTime || 0,
  1441. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'chatgpt', 'duckduckgo', 'forward'],
  1442. subjectFilters: ['verify', 'verification', 'code', '楠岃瘉', 'confirm', 'login'],
  1443. targetEmail: state.email,
  1444. maxAttempts: 5,
  1445. intervalMs: 3000,
  1446. ...overrides,
  1447. };
  1448. }
  1449. async function requestVerificationCodeResend(step) {
  1450. const signupTabId = await getTabId('signup-page');
  1451. if (!signupTabId) {
  1452. throw new Error('认证页面标签页已关闭,无法重新请求验证码。');
  1453. }
  1454. await chrome.tabs.update(signupTabId, { active: true });
  1455. await addLog(`步骤 ${step}:正在请求新的${getVerificationCodeLabel(step)}验证码...`, 'warn');
  1456. const result = await sendToContentScript('signup-page', {
  1457. type: 'RESEND_VERIFICATION_CODE',
  1458. step,
  1459. source: 'background',
  1460. payload: {},
  1461. });
  1462. if (result && result.error) {
  1463. throw new Error(result.error);
  1464. }
  1465. return Date.now();
  1466. }
  1467. async function pollFreshVerificationCode(step, state, mail, pollOverrides = {}) {
  1468. const stateKey = getVerificationCodeStateKey(step);
  1469. const rejectedCodes = new Set();
  1470. if (state[stateKey]) {
  1471. rejectedCodes.add(state[stateKey]);
  1472. }
  1473. for (const code of (pollOverrides.excludeCodes || [])) {
  1474. if (code) rejectedCodes.add(code);
  1475. }
  1476. let lastError = null;
  1477. let filterAfterTimestamp = pollOverrides.filterAfterTimestamp ?? getVerificationPollPayload(step, state).filterAfterTimestamp;
  1478. const maxRounds = pollOverrides.maxRounds || 3;
  1479. for (let round = 1; round <= maxRounds; round++) {
  1480. if (round > 1) {
  1481. filterAfterTimestamp = await requestVerificationCodeResend(step);
  1482. }
  1483. const payload = getVerificationPollPayload(step, state, {
  1484. ...pollOverrides,
  1485. filterAfterTimestamp,
  1486. excludeCodes: [...rejectedCodes],
  1487. });
  1488. try {
  1489. const result = await sendToContentScript(mail.source, {
  1490. type: 'POLL_EMAIL',
  1491. step,
  1492. source: 'background',
  1493. payload,
  1494. });
  1495. if (result && result.error) {
  1496. throw new Error(result.error);
  1497. }
  1498. if (!result || !result.code) {
  1499. throw new Error(`步骤 ${step}:邮箱轮询结束,但未获取到验证码。`);
  1500. }
  1501. if (rejectedCodes.has(result.code)) {
  1502. throw new Error(`步骤 ${step}:再次收到了相同的${getVerificationCodeLabel(step)}验证码:${result.code}`);
  1503. }
  1504. return result;
  1505. } catch (err) {
  1506. lastError = err;
  1507. await addLog(`步骤 ${step}:${err.message}`, 'warn');
  1508. if (round < maxRounds) {
  1509. await addLog(`步骤 ${step}:将重新发送验证码后重试(${round + 1}/${maxRounds})...`, 'warn');
  1510. }
  1511. }
  1512. }
  1513. throw lastError || new Error(`步骤 ${step}:无法获取新的${getVerificationCodeLabel(step)}验证码。`);
  1514. }
  1515. async function submitVerificationCode(step, code) {
  1516. const signupTabId = await getTabId('signup-page');
  1517. if (!signupTabId) {
  1518. throw new Error('认证页面标签页已关闭,无法填写验证码。');
  1519. }
  1520. await chrome.tabs.update(signupTabId, { active: true });
  1521. const result = await sendToContentScript('signup-page', {
  1522. type: 'FILL_CODE',
  1523. step,
  1524. source: 'background',
  1525. payload: { code },
  1526. });
  1527. if (result && result.error) {
  1528. throw new Error(result.error);
  1529. }
  1530. return result || {};
  1531. }
  1532. async function resolveVerificationStep(step, state, mail, options = {}) {
  1533. const stateKey = getVerificationCodeStateKey(step);
  1534. const rejectedCodes = new Set();
  1535. if (state[stateKey]) {
  1536. rejectedCodes.add(state[stateKey]);
  1537. }
  1538. let nextFilterAfterTimestamp = options.filterAfterTimestamp ?? null;
  1539. const requestFreshCodeFirst = Boolean(options.requestFreshCodeFirst);
  1540. const maxSubmitAttempts = 3;
  1541. if (requestFreshCodeFirst) {
  1542. try {
  1543. nextFilterAfterTimestamp = await requestVerificationCodeResend(step);
  1544. await addLog(`步骤 ${step}:已先请求一封新的${getVerificationCodeLabel(step)}验证码,再开始轮询邮箱。`, 'warn');
  1545. } catch (err) {
  1546. await addLog(`步骤 ${step}:首次重新获取验证码失败:${err.message},将继续使用当前时间窗口轮询。`, 'warn');
  1547. }
  1548. }
  1549. for (let attempt = 1; attempt <= maxSubmitAttempts; attempt++) {
  1550. const result = await pollFreshVerificationCode(step, state, mail, {
  1551. excludeCodes: [...rejectedCodes],
  1552. filterAfterTimestamp: nextFilterAfterTimestamp ?? undefined,
  1553. });
  1554. await addLog(`步骤 ${step}:已获取${getVerificationCodeLabel(step)}验证码:${result.code}`);
  1555. const submitResult = await submitVerificationCode(step, result.code);
  1556. if (submitResult.invalidCode) {
  1557. rejectedCodes.add(result.code);
  1558. await addLog(`步骤 ${step}:验证码被页面拒绝:${submitResult.errorText || result.code}`, 'warn');
  1559. if (attempt >= maxSubmitAttempts) {
  1560. throw new Error(`步骤 ${step}:验证码连续失败,已达到 ${maxSubmitAttempts} 次重试上限。`);
  1561. }
  1562. nextFilterAfterTimestamp = await requestVerificationCodeResend(step);
  1563. await addLog(`步骤 ${step}:提交失败后已请求新验证码(${attempt + 1}/${maxSubmitAttempts})...`, 'warn');
  1564. continue;
  1565. }
  1566. await setState({
  1567. lastEmailTimestamp: result.emailTimestamp,
  1568. [stateKey]: result.code,
  1569. });
  1570. await completeStepFromBackground(step, {
  1571. emailTimestamp: result.emailTimestamp,
  1572. code: result.code,
  1573. });
  1574. return;
  1575. }
  1576. }
  1577. async function executeStep4(state) {
  1578. const mail = getMailConfig(state);
  1579. if (mail.error) throw new Error(mail.error);
  1580. const stepStartedAt = Date.now();
  1581. const signupTabId = await getTabId('signup-page');
  1582. if (!signupTabId) {
  1583. throw new Error('认证页面标签页已关闭,无法继续步骤 4。');
  1584. }
  1585. await chrome.tabs.update(signupTabId, { active: true });
  1586. await addLog('步骤 4:正在确认注册验证码页面是否就绪,必要时自动恢复密码页超时报错...');
  1587. const prepareResult = await sendToContentScriptResilient(
  1588. 'signup-page',
  1589. {
  1590. type: 'PREPARE_SIGNUP_VERIFICATION',
  1591. step: 4,
  1592. source: 'background',
  1593. payload: { password: state.password || state.customPassword || '' },
  1594. },
  1595. {
  1596. timeoutMs: 30000,
  1597. retryDelayMs: 700,
  1598. logMessage: '步骤 4:认证页正在切换,等待页面重新就绪后继续检测...',
  1599. }
  1600. );
  1601. if (prepareResult && prepareResult.error) {
  1602. throw new Error(prepareResult.error);
  1603. }
  1604. if (prepareResult?.alreadyVerified) {
  1605. await completeStepFromBackground(4, {});
  1606. return;
  1607. }
  1608. await addLog(`步骤 4:正在打开${mail.label}...`);
  1609. // For mail tabs, only create if not alive — don't navigate (preserves login session)
  1610. const alive = await isTabAlive(mail.source);
  1611. if (alive) {
  1612. if (mail.navigateOnReuse) {
  1613. await reuseOrCreateTab(mail.source, mail.url, {
  1614. inject: mail.inject,
  1615. injectSource: mail.injectSource,
  1616. });
  1617. } else {
  1618. const tabId = await getTabId(mail.source);
  1619. await chrome.tabs.update(tabId, { active: true });
  1620. }
  1621. } else {
  1622. await reuseOrCreateTab(mail.source, mail.url, {
  1623. inject: mail.inject,
  1624. injectSource: mail.injectSource,
  1625. });
  1626. }
  1627. await resolveVerificationStep(4, state, mail, {
  1628. filterAfterTimestamp: stepStartedAt,
  1629. requestFreshCodeFirst: true,
  1630. });
  1631. return;
  1632. }
  1633. // ============================================================
  1634. // Step 5: Fill Name & Birthday (via signup-page.js)
  1635. // ============================================================
  1636. async function executeStep5(state) {
  1637. const { firstName, lastName } = generateRandomName();
  1638. const { year, month, day } = generateRandomBirthday();
  1639. await addLog(`步骤 5:已生成姓名 ${firstName} ${lastName},生日 ${year}-${month}-${day}`);
  1640. await sendToContentScript('signup-page', {
  1641. type: 'EXECUTE_STEP',
  1642. step: 5,
  1643. source: 'background',
  1644. payload: { firstName, lastName, year, month, day },
  1645. });
  1646. }
  1647. // ============================================================
  1648. // Step 6: Login ChatGPT (Background opens tab, chatgpt.js handles login)
  1649. // ============================================================
  1650. async function refreshOAuthUrlBeforeStep6(state) {
  1651. if (!state.vpsUrl) {
  1652. throw new Error('尚未配置 CPA 地址,请先在侧边栏填写。');
  1653. }
  1654. await addLog('步骤 6:正在刷新登录用的 CPA OAuth 链接...');
  1655. const waitForFreshOAuth = waitForStepComplete(1, 120000);
  1656. await executeStep1(state);
  1657. await waitForFreshOAuth;
  1658. const latestState = await getState();
  1659. if (!latestState.oauthUrl) {
  1660. throw new Error('刷新 OAuth 链接后仍未拿到可用链接。');
  1661. }
  1662. return latestState.oauthUrl;
  1663. }
  1664. async function executeStep6(state) {
  1665. if (!state.email) {
  1666. throw new Error('缺少邮箱地址,请先完成步骤 3。');
  1667. }
  1668. const oauthUrl = await refreshOAuthUrlBeforeStep6(state);
  1669. await addLog('步骤 6:正在打开最新 OAuth 链接并登录...');
  1670. // Reuse the signup-page tab — navigate it to the OAuth URL
  1671. await reuseOrCreateTab('signup-page', oauthUrl);
  1672. // signup-page.js will inject (same auth.openai.com domain) and handle login
  1673. await sendToContentScript('signup-page', {
  1674. type: 'EXECUTE_STEP',
  1675. step: 6,
  1676. source: 'background',
  1677. payload: { email: state.email, password: state.password },
  1678. });
  1679. }
  1680. // ============================================================
  1681. // Step 7: Get Login Verification Code (qq-mail.js polls, then fills in chatgpt.js)
  1682. // ============================================================
  1683. async function executeStep7(state) {
  1684. const mail = getMailConfig(state);
  1685. if (mail.error) throw new Error(mail.error);
  1686. const stepStartedAt = Date.now();
  1687. const authTabId = await getTabId('signup-page');
  1688. if (authTabId) {
  1689. await chrome.tabs.update(authTabId, { active: true });
  1690. } else {
  1691. if (!state.oauthUrl) {
  1692. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  1693. }
  1694. await reuseOrCreateTab('signup-page', state.oauthUrl);
  1695. }
  1696. await addLog('步骤 7:正在准备认证页,必要时切换到一次性验证码登录...');
  1697. const prepareResult = await sendToContentScript('signup-page', {
  1698. type: 'PREPARE_LOGIN_CODE',
  1699. step: 7,
  1700. source: 'background',
  1701. payload: {},
  1702. });
  1703. if (prepareResult && prepareResult.error) {
  1704. throw new Error(prepareResult.error);
  1705. }
  1706. await addLog(`步骤 7:正在打开${mail.label}...`);
  1707. const alive = await isTabAlive(mail.source);
  1708. if (alive) {
  1709. if (mail.navigateOnReuse) {
  1710. await reuseOrCreateTab(mail.source, mail.url, {
  1711. inject: mail.inject,
  1712. injectSource: mail.injectSource,
  1713. });
  1714. } else {
  1715. const tabId = await getTabId(mail.source);
  1716. await chrome.tabs.update(tabId, { active: true });
  1717. }
  1718. } else {
  1719. await reuseOrCreateTab(mail.source, mail.url, {
  1720. inject: mail.inject,
  1721. injectSource: mail.injectSource,
  1722. });
  1723. }
  1724. await resolveVerificationStep(7, state, mail, {
  1725. filterAfterTimestamp: stepStartedAt,
  1726. requestFreshCodeFirst: true,
  1727. });
  1728. return;
  1729. }
  1730. // ============================================================
  1731. // Step 8: Complete OAuth (auto click + localhost listener)
  1732. // ============================================================
  1733. let webNavListener = null;
  1734. async function executeStep8(state) {
  1735. if (!state.oauthUrl) {
  1736. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  1737. }
  1738. await addLog('步骤 8:正在监听 localhost 回调地址...');
  1739. // Register webNavigation listener (scoped to this step)
  1740. return new Promise((resolve, reject) => {
  1741. let resolved = false;
  1742. let resolveCaptureWait = null;
  1743. const captureWait = new Promise((resolveCapture) => {
  1744. resolveCaptureWait = resolveCapture;
  1745. });
  1746. const cleanupListener = () => {
  1747. if (webNavListener) {
  1748. chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
  1749. webNavListener = null;
  1750. }
  1751. };
  1752. const timeout = setTimeout(() => {
  1753. cleanupListener();
  1754. reject(new Error('120 秒内未捕获到 localhost 回调跳转,步骤 8 的点击可能被拦截了。'));
  1755. }, 120000);
  1756. webNavListener = (details) => {
  1757. if (details.url.startsWith('http://localhost')) {
  1758. console.log(LOG_PREFIX, `Captured localhost redirect: ${details.url}`);
  1759. resolved = true;
  1760. cleanupListener();
  1761. clearTimeout(timeout);
  1762. if (resolveCaptureWait) resolveCaptureWait(details.url);
  1763. setState({ localhostUrl: details.url }).then(() => {
  1764. addLog(`步骤 8:已捕获 localhost 地址:${details.url}`, 'ok');
  1765. setStepStatus(8, 'completed');
  1766. notifyStepComplete(8, { localhostUrl: details.url });
  1767. broadcastDataUpdate({ localhostUrl: details.url });
  1768. resolve();
  1769. });
  1770. }
  1771. };
  1772. chrome.webNavigation.onBeforeNavigate.addListener(webNavListener);
  1773. // After step 7, the auth page shows a consent screen ("使用 ChatGPT 登录到 Codex")
  1774. // with a "继续" button. We locate the button in-page, then click it through
  1775. // the debugger Input API directly.
  1776. (async () => {
  1777. try {
  1778. let signupTabId = await getTabId('signup-page');
  1779. if (signupTabId) {
  1780. await chrome.tabs.update(signupTabId, { active: true });
  1781. await addLog('步骤 8:已切回认证页,正在准备调试器点击...');
  1782. } else {
  1783. signupTabId = await reuseOrCreateTab('signup-page', state.oauthUrl);
  1784. await addLog('步骤 8:已重新打开认证页,正在准备调试器点击...');
  1785. }
  1786. const clickResult = await sendToContentScript('signup-page', {
  1787. type: 'STEP8_FIND_AND_CLICK',
  1788. source: 'background',
  1789. payload: {},
  1790. });
  1791. if (clickResult?.error) {
  1792. throw new Error(clickResult.error);
  1793. }
  1794. if (!resolved) {
  1795. await clickWithDebugger(signupTabId, clickResult?.rect);
  1796. await addLog('步骤 8:已发送调试器点击,正在等待跳转...');
  1797. }
  1798. } catch (err) {
  1799. clearTimeout(timeout);
  1800. cleanupListener();
  1801. reject(err);
  1802. }
  1803. })();
  1804. });
  1805. }
  1806. // ============================================================
  1807. // Step 9: VPS Verify (via vps-panel.js)
  1808. // ============================================================
  1809. async function executeStep9(state) {
  1810. if (!state.localhostUrl) {
  1811. throw new Error('缺少 localhost 回调地址,请先完成步骤 8。');
  1812. }
  1813. if (!state.vpsUrl) {
  1814. throw new Error('尚未填写 CPA 地址,请先在侧边栏输入。');
  1815. }
  1816. await addLog('步骤 9:正在打开 CPA 面板...');
  1817. let tabId = await getTabId('vps-panel');
  1818. const alive = tabId && await isTabAlive('vps-panel');
  1819. if (!alive) {
  1820. await closeConflictingTabsForSource('vps-panel', state.vpsUrl);
  1821. // Create new tab
  1822. const tab = await chrome.tabs.create({ url: state.vpsUrl, active: true });
  1823. tabId = tab.id;
  1824. await rememberSourceLastUrl('vps-panel', state.vpsUrl);
  1825. await new Promise(resolve => {
  1826. const listener = (tid, info) => {
  1827. if (tid === tabId && info.status === 'complete') {
  1828. chrome.tabs.onUpdated.removeListener(listener);
  1829. resolve();
  1830. }
  1831. };
  1832. chrome.tabs.onUpdated.addListener(listener);
  1833. });
  1834. } else {
  1835. await closeConflictingTabsForSource('vps-panel', state.vpsUrl, { excludeTabIds: [tabId] });
  1836. await chrome.tabs.update(tabId, { active: true });
  1837. await rememberSourceLastUrl('vps-panel', state.vpsUrl);
  1838. }
  1839. // Inject scripts directly and wait for them to be ready
  1840. await chrome.scripting.executeScript({
  1841. target: { tabId },
  1842. files: ['content/utils.js', 'content/vps-panel.js'],
  1843. });
  1844. await new Promise(r => setTimeout(r, 1000));
  1845. // Send command directly — bypass queue/ready mechanism
  1846. await addLog('步骤 9:正在填写回调地址...');
  1847. await chrome.tabs.sendMessage(tabId, {
  1848. type: 'EXECUTE_STEP',
  1849. step: 9,
  1850. source: 'background',
  1851. payload: { localhostUrl: state.localhostUrl, vpsPassword: state.vpsPassword },
  1852. });
  1853. }
  1854. // ============================================================
  1855. // Open Side Panel on extension icon click
  1856. // ============================================================
  1857. chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });