background.js 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206
  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. async function sendToMailContentScriptResilient(mail, message, options = {}) {
  473. const { timeoutMs = 45000, maxRecoveryAttempts = 2 } = options;
  474. const start = Date.now();
  475. let lastError = null;
  476. let recoveries = 0;
  477. let logged = false;
  478. while (Date.now() - start < timeoutMs) {
  479. throwIfStopped();
  480. try {
  481. return await sendToContentScript(mail.source, message);
  482. } catch (err) {
  483. if (!isRetryableContentScriptTransportError(err)) {
  484. throw err;
  485. }
  486. lastError = err;
  487. if (!logged) {
  488. await addLog(`步骤 ${message.step}:${mail.label} 页面通信异常,正在尝试让邮箱页重新就绪...`, 'warn');
  489. logged = true;
  490. }
  491. if (recoveries >= maxRecoveryAttempts) {
  492. break;
  493. }
  494. recoveries += 1;
  495. await reuseOrCreateTab(mail.source, mail.url, {
  496. inject: mail.inject,
  497. injectSource: mail.injectSource,
  498. reloadIfSameUrl: true,
  499. });
  500. await new Promise((resolve) => setTimeout(resolve, 800));
  501. }
  502. }
  503. throw lastError || new Error(`${mail.label} 页面未能重新就绪。`);
  504. }
  505. // ============================================================
  506. // Logging
  507. // ============================================================
  508. async function addLog(message, level = 'info') {
  509. const state = await getState();
  510. const logs = state.logs || [];
  511. const entry = { message, level, timestamp: Date.now() };
  512. logs.push(entry);
  513. // Keep last 500 logs
  514. if (logs.length > 500) logs.splice(0, logs.length - 500);
  515. await setState({ logs });
  516. // Broadcast to side panel
  517. chrome.runtime.sendMessage({ type: 'LOG_ENTRY', payload: entry }).catch(() => {});
  518. }
  519. function getSourceLabel(source) {
  520. const labels = {
  521. 'sidepanel': '侧边栏',
  522. 'signup-page': '认证页',
  523. 'vps-panel': 'CPA 面板',
  524. 'qq-mail': 'QQ 邮箱',
  525. 'mail-163': '163 邮箱',
  526. 'inbucket-mail': 'Inbucket 邮箱',
  527. 'duck-mail': 'Duck 邮箱',
  528. };
  529. return labels[source] || source || '未知来源';
  530. }
  531. // ============================================================
  532. // Step Status Management
  533. // ============================================================
  534. async function setStepStatus(step, status) {
  535. const state = await getState();
  536. const statuses = { ...state.stepStatuses };
  537. statuses[step] = status;
  538. await setState({ stepStatuses: statuses, currentStep: step });
  539. // Broadcast to side panel
  540. chrome.runtime.sendMessage({
  541. type: 'STEP_STATUS_CHANGED',
  542. payload: { step, status },
  543. }).catch(() => {});
  544. }
  545. function isStopError(error) {
  546. const message = typeof error === 'string' ? error : error?.message;
  547. return message === STOP_ERROR_MESSAGE;
  548. }
  549. function isRetryableContentScriptTransportError(error) {
  550. const message = String(typeof error === 'string' ? error : error?.message || '');
  551. 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);
  552. }
  553. function isRestartCurrentAttemptError(error) {
  554. const message = String(typeof error === 'string' ? error : error?.message || '');
  555. return /当前邮箱已存在,需要重新开始新一轮/.test(message);
  556. }
  557. function isStepDoneStatus(status) {
  558. return status === 'completed' || status === 'manual_completed' || status === 'skipped';
  559. }
  560. function getFirstUnfinishedStep(statuses = {}) {
  561. for (let step = 1; step <= 9; step++) {
  562. if (!isStepDoneStatus(statuses[step] || 'pending')) {
  563. return step;
  564. }
  565. }
  566. return null;
  567. }
  568. function hasSavedProgress(statuses = {}) {
  569. return Object.values({ ...DEFAULT_STATE.stepStatuses, ...statuses }).some((status) => status !== 'pending');
  570. }
  571. function clearStopRequest() {
  572. stopRequested = false;
  573. }
  574. function getAutoRunStatusPayload(phase, payload = {}) {
  575. const currentRun = payload.currentRun ?? autoRunCurrentRun;
  576. const totalRuns = payload.totalRuns ?? autoRunTotalRuns;
  577. const attemptRun = payload.attemptRun ?? autoRunAttemptRun;
  578. const autoRunning = phase === 'running' || phase === 'waiting_email' || phase === 'retrying';
  579. return {
  580. autoRunning,
  581. autoRunPhase: phase,
  582. autoRunCurrentRun: currentRun,
  583. autoRunTotalRuns: totalRuns,
  584. autoRunAttemptRun: attemptRun,
  585. };
  586. }
  587. async function broadcastAutoRunStatus(phase, payload = {}) {
  588. const statusPayload = {
  589. phase,
  590. currentRun: payload.currentRun ?? autoRunCurrentRun,
  591. totalRuns: payload.totalRuns ?? autoRunTotalRuns,
  592. attemptRun: payload.attemptRun ?? autoRunAttemptRun,
  593. };
  594. await setState(getAutoRunStatusPayload(phase, statusPayload));
  595. chrome.runtime.sendMessage({
  596. type: 'AUTO_RUN_STATUS',
  597. payload: statusPayload,
  598. }).catch(() => {});
  599. }
  600. function isAutoRunLockedState(state) {
  601. return Boolean(state.autoRunning) && (state.autoRunPhase === 'running' || state.autoRunPhase === 'retrying');
  602. }
  603. function isAutoRunPausedState(state) {
  604. return Boolean(state.autoRunning) && state.autoRunPhase === 'waiting_email';
  605. }
  606. async function ensureManualInteractionAllowed(actionLabel) {
  607. const state = await getState();
  608. if (isAutoRunLockedState(state)) {
  609. throw new Error(`自动流程运行中,请先停止后再${actionLabel}。`);
  610. }
  611. if (isAutoRunPausedState(state)) {
  612. throw new Error(`自动流程当前已暂停。请点击“继续”,或先确认接管自动流程后再${actionLabel}。`);
  613. }
  614. return state;
  615. }
  616. async function skipStep(step) {
  617. const state = await ensureManualInteractionAllowed('跳过步骤');
  618. if (!Number.isInteger(step) || step < 1 || step > 9) {
  619. throw new Error(`无效步骤:${step}`);
  620. }
  621. const statuses = { ...(state.stepStatuses || {}) };
  622. const currentStatus = statuses[step];
  623. if (currentStatus === 'running') {
  624. throw new Error(`步骤 ${step} 正在运行中,不能跳过。`);
  625. }
  626. if (isStepDoneStatus(currentStatus)) {
  627. throw new Error(`步骤 ${step} 已完成,无需再跳过。`);
  628. }
  629. if (step > 1) {
  630. const prevStatus = statuses[step - 1];
  631. if (!isStepDoneStatus(prevStatus)) {
  632. throw new Error(`请先完成步骤 ${step - 1},再跳过步骤 ${step}。`);
  633. }
  634. }
  635. await setStepStatus(step, 'skipped');
  636. await addLog(`步骤 ${step} 已跳过`, 'warn');
  637. if (step === 1) {
  638. const latestState = await getState();
  639. const step2Status = latestState.stepStatuses?.[2];
  640. if (!isStepDoneStatus(step2Status) && step2Status !== 'running') {
  641. await setStepStatus(2, 'skipped');
  642. await addLog('步骤 1 已跳过,步骤 2 也已同时跳过。', 'warn');
  643. }
  644. }
  645. return { ok: true, step, status: 'skipped' };
  646. }
  647. function throwIfStopped() {
  648. if (stopRequested) {
  649. throw new Error(STOP_ERROR_MESSAGE);
  650. }
  651. }
  652. async function sleepWithStop(ms) {
  653. const start = Date.now();
  654. while (Date.now() - start < ms) {
  655. throwIfStopped();
  656. await new Promise(r => setTimeout(r, Math.min(100, ms - (Date.now() - start))));
  657. }
  658. }
  659. async function humanStepDelay(min = HUMAN_STEP_DELAY_MIN, max = HUMAN_STEP_DELAY_MAX) {
  660. const duration = Math.floor(Math.random() * (max - min + 1)) + min;
  661. await sleepWithStop(duration);
  662. }
  663. async function clickWithDebugger(tabId, rect) {
  664. if (!tabId) {
  665. throw new Error('未找到用于调试点击的认证页面标签页。');
  666. }
  667. if (!rect || !Number.isFinite(rect.centerX) || !Number.isFinite(rect.centerY)) {
  668. throw new Error('步骤 8 的调试器兜底点击需要有效的按钮坐标。');
  669. }
  670. const target = { tabId };
  671. try {
  672. await chrome.debugger.attach(target, '1.3');
  673. } catch (err) {
  674. throw new Error(
  675. `步骤 8 的调试器兜底点击附加失败:${err.message}。` +
  676. '如果认证页标签已打开 DevTools,请先关闭后重试。'
  677. );
  678. }
  679. try {
  680. const x = Math.round(rect.centerX);
  681. const y = Math.round(rect.centerY);
  682. await chrome.debugger.sendCommand(target, 'Page.bringToFront');
  683. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  684. type: 'mouseMoved',
  685. x,
  686. y,
  687. button: 'none',
  688. buttons: 0,
  689. clickCount: 0,
  690. });
  691. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  692. type: 'mousePressed',
  693. x,
  694. y,
  695. button: 'left',
  696. buttons: 1,
  697. clickCount: 1,
  698. });
  699. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  700. type: 'mouseReleased',
  701. x,
  702. y,
  703. button: 'left',
  704. buttons: 0,
  705. clickCount: 1,
  706. });
  707. } finally {
  708. await chrome.debugger.detach(target).catch(() => {});
  709. }
  710. }
  711. async function broadcastStopToContentScripts() {
  712. const registry = await getTabRegistry();
  713. for (const entry of Object.values(registry)) {
  714. if (!entry?.tabId) continue;
  715. try {
  716. await chrome.tabs.sendMessage(entry.tabId, {
  717. type: 'STOP_FLOW',
  718. source: 'background',
  719. payload: {},
  720. });
  721. } catch {}
  722. }
  723. }
  724. let stopRequested = false;
  725. // ============================================================
  726. // Message Handler (central router)
  727. // ============================================================
  728. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  729. console.log(LOG_PREFIX, `Received: ${message.type} from ${message.source || 'sidepanel'}`, message);
  730. handleMessage(message, sender).then(response => {
  731. sendResponse(response);
  732. }).catch(err => {
  733. console.error(LOG_PREFIX, 'Handler error:', err);
  734. sendResponse({ error: err.message });
  735. });
  736. return true; // async response
  737. });
  738. async function handleMessage(message, sender) {
  739. switch (message.type) {
  740. case 'CONTENT_SCRIPT_READY': {
  741. const tabId = sender.tab?.id;
  742. if (tabId && message.source) {
  743. await registerTab(message.source, tabId);
  744. flushCommand(message.source, tabId);
  745. await addLog(`内容脚本已就绪:${getSourceLabel(message.source)}(标签页 ${tabId})`);
  746. }
  747. return { ok: true };
  748. }
  749. case 'LOG': {
  750. const { message: msg, level } = message.payload;
  751. await addLog(`[${getSourceLabel(message.source)}] ${msg}`, level);
  752. return { ok: true };
  753. }
  754. case 'STEP_COMPLETE': {
  755. if (stopRequested) {
  756. await setStepStatus(message.step, 'stopped');
  757. notifyStepError(message.step, STOP_ERROR_MESSAGE);
  758. return { ok: true };
  759. }
  760. await setStepStatus(message.step, 'completed');
  761. await addLog(`步骤 ${message.step} 已完成`, 'ok');
  762. await handleStepData(message.step, message.payload);
  763. notifyStepComplete(message.step, message.payload);
  764. return { ok: true };
  765. }
  766. case 'STEP_ERROR': {
  767. if (isStopError(message.error)) {
  768. await setStepStatus(message.step, 'stopped');
  769. await addLog(`步骤 ${message.step} 已被用户停止`, 'warn');
  770. notifyStepError(message.step, message.error);
  771. } else {
  772. await setStepStatus(message.step, 'failed');
  773. await addLog(`步骤 ${message.step} 失败:${message.error}`, 'error');
  774. notifyStepError(message.step, message.error);
  775. }
  776. return { ok: true };
  777. }
  778. case 'GET_STATE': {
  779. return await getState();
  780. }
  781. case 'RESET': {
  782. clearStopRequest();
  783. await resetState();
  784. await addLog('流程已重置', 'info');
  785. return { ok: true };
  786. }
  787. case 'EXECUTE_STEP': {
  788. clearStopRequest();
  789. if (message.source === 'sidepanel') {
  790. await ensureManualInteractionAllowed('手动执行步骤');
  791. }
  792. const step = message.payload.step;
  793. // Save email if provided (from side panel step 3)
  794. if (message.payload.email) {
  795. await setEmailState(message.payload.email);
  796. }
  797. await executeStep(step);
  798. return { ok: true };
  799. }
  800. case 'AUTO_RUN': {
  801. clearStopRequest();
  802. const totalRuns = message.payload?.totalRuns || 1;
  803. const autoRunSkipFailures = Boolean(message.payload?.autoRunSkipFailures);
  804. const mode = message.payload?.mode === 'continue' ? 'continue' : 'restart';
  805. await setState({ autoRunSkipFailures });
  806. autoRunLoop(totalRuns, { autoRunSkipFailures, mode }); // fire-and-forget
  807. return { ok: true };
  808. }
  809. case 'RESUME_AUTO_RUN': {
  810. clearStopRequest();
  811. if (message.payload.email) {
  812. await setEmailState(message.payload.email);
  813. }
  814. resumeAutoRun(); // fire-and-forget
  815. return { ok: true };
  816. }
  817. case 'TAKEOVER_AUTO_RUN': {
  818. await requestStop({ logMessage: '已确认手动接管,正在停止自动流程并切换为手动控制...' });
  819. await addLog('自动流程已切换为手动控制。', 'warn');
  820. return { ok: true };
  821. }
  822. case 'SKIP_STEP': {
  823. const step = Number(message.payload?.step);
  824. return await skipStep(step);
  825. }
  826. case 'SAVE_SETTING': {
  827. const updates = {};
  828. if (message.payload.vpsUrl !== undefined) updates.vpsUrl = message.payload.vpsUrl;
  829. if (message.payload.vpsPassword !== undefined) updates.vpsPassword = message.payload.vpsPassword;
  830. if (message.payload.customPassword !== undefined) updates.customPassword = message.payload.customPassword;
  831. if (message.payload.autoRunSkipFailures !== undefined) updates.autoRunSkipFailures = Boolean(message.payload.autoRunSkipFailures);
  832. if (message.payload.mailProvider !== undefined) updates.mailProvider = message.payload.mailProvider;
  833. if (message.payload.inbucketHost !== undefined) updates.inbucketHost = message.payload.inbucketHost;
  834. if (message.payload.inbucketMailbox !== undefined) updates.inbucketMailbox = message.payload.inbucketMailbox;
  835. await setPersistentSettings(updates);
  836. await setState(updates);
  837. return { ok: true };
  838. }
  839. // Side panel data updates
  840. case 'SAVE_EMAIL': {
  841. const state = await getState();
  842. if (isAutoRunLockedState(state)) {
  843. throw new Error('自动流程运行中,当前不能手动修改邮箱。');
  844. }
  845. await setEmailState(message.payload.email);
  846. await resumeAutoRun();
  847. return { ok: true, email: message.payload.email };
  848. }
  849. case 'FETCH_DUCK_EMAIL': {
  850. clearStopRequest();
  851. const state = await getState();
  852. if (isAutoRunLockedState(state)) {
  853. throw new Error('自动流程运行中,当前不能手动获取 Duck 邮箱。');
  854. }
  855. const email = await fetchDuckEmail(message.payload || {});
  856. await resumeAutoRun();
  857. return { ok: true, email };
  858. }
  859. case 'STOP_FLOW': {
  860. await requestStop();
  861. return { ok: true };
  862. }
  863. default:
  864. console.warn(LOG_PREFIX, `Unknown message type: ${message.type}`);
  865. return { error: `Unknown message type: ${message.type}` };
  866. }
  867. }
  868. // ============================================================
  869. // Step Data Handlers
  870. // ============================================================
  871. async function handleStepData(step, payload) {
  872. switch (step) {
  873. case 1:
  874. if (payload.oauthUrl) {
  875. await setState({ oauthUrl: payload.oauthUrl });
  876. broadcastDataUpdate({ oauthUrl: payload.oauthUrl });
  877. }
  878. break;
  879. case 3:
  880. if (payload.email) await setEmailState(payload.email);
  881. break;
  882. case 4:
  883. if (payload.emailTimestamp) await setState({ lastEmailTimestamp: payload.emailTimestamp });
  884. break;
  885. case 8:
  886. if (payload.localhostUrl) {
  887. await setState({ localhostUrl: payload.localhostUrl });
  888. broadcastDataUpdate({ localhostUrl: payload.localhostUrl });
  889. }
  890. break;
  891. case 9: {
  892. const localhostPrefix = buildLocalhostCleanupPrefix(payload.localhostUrl);
  893. if (localhostPrefix) {
  894. await closeTabsByUrlPrefix(localhostPrefix);
  895. }
  896. break;
  897. }
  898. }
  899. }
  900. // ============================================================
  901. // Step Completion Waiting
  902. // ============================================================
  903. // Map of step -> { resolve, reject } for waiting on step completion
  904. const stepWaiters = new Map();
  905. let resumeWaiter = null;
  906. function waitForStepComplete(step, timeoutMs = 120000) {
  907. return new Promise((resolve, reject) => {
  908. throwIfStopped();
  909. const timer = setTimeout(() => {
  910. stepWaiters.delete(step);
  911. reject(new Error(`Step ${step} timed out after ${timeoutMs / 1000}s`));
  912. }, timeoutMs);
  913. stepWaiters.set(step, {
  914. resolve: (data) => { clearTimeout(timer); stepWaiters.delete(step); resolve(data); },
  915. reject: (err) => { clearTimeout(timer); stepWaiters.delete(step); reject(err); },
  916. });
  917. });
  918. }
  919. function notifyStepComplete(step, payload) {
  920. const waiter = stepWaiters.get(step);
  921. if (waiter) waiter.resolve(payload);
  922. }
  923. function notifyStepError(step, error) {
  924. const waiter = stepWaiters.get(step);
  925. if (waiter) waiter.reject(new Error(error));
  926. }
  927. async function completeStepFromBackground(step, payload = {}) {
  928. if (stopRequested) {
  929. await setStepStatus(step, 'stopped');
  930. notifyStepError(step, STOP_ERROR_MESSAGE);
  931. return;
  932. }
  933. await setStepStatus(step, 'completed');
  934. await addLog(`步骤 ${step} 已完成`, 'ok');
  935. await handleStepData(step, payload);
  936. notifyStepComplete(step, payload);
  937. }
  938. async function markRunningStepsStopped() {
  939. const state = await getState();
  940. const runningSteps = Object.entries(state.stepStatuses || {})
  941. .filter(([, status]) => status === 'running')
  942. .map(([step]) => Number(step));
  943. for (const step of runningSteps) {
  944. await setStepStatus(step, 'stopped');
  945. }
  946. }
  947. async function requestStop(options = {}) {
  948. const { logMessage = '已收到停止请求,正在取消当前操作...' } = options;
  949. if (stopRequested) return;
  950. stopRequested = true;
  951. cancelPendingCommands();
  952. if (webNavListener) {
  953. chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
  954. webNavListener = null;
  955. }
  956. await addLog(logMessage, 'warn');
  957. await broadcastStopToContentScripts();
  958. for (const waiter of stepWaiters.values()) {
  959. waiter.reject(new Error(STOP_ERROR_MESSAGE));
  960. }
  961. stepWaiters.clear();
  962. if (resumeWaiter) {
  963. resumeWaiter.reject(new Error(STOP_ERROR_MESSAGE));
  964. resumeWaiter = null;
  965. }
  966. await markRunningStepsStopped();
  967. autoRunActive = false;
  968. await broadcastAutoRunStatus('stopped', {
  969. currentRun: autoRunCurrentRun,
  970. totalRuns: autoRunTotalRuns,
  971. attemptRun: autoRunAttemptRun,
  972. });
  973. }
  974. // ============================================================
  975. // Step Execution
  976. // ============================================================
  977. async function executeStep(step) {
  978. console.log(LOG_PREFIX, `Executing step ${step}`);
  979. throwIfStopped();
  980. await setStepStatus(step, 'running');
  981. await addLog(`步骤 ${step} 开始执行`);
  982. await humanStepDelay();
  983. const state = await getState();
  984. // Set flow start time on first step
  985. if (step === 1 && !state.flowStartTime) {
  986. await setState({ flowStartTime: Date.now() });
  987. }
  988. try {
  989. switch (step) {
  990. case 1: await executeStep1(state); break;
  991. case 2: await executeStep2(state); break;
  992. case 3: await executeStep3(state); break;
  993. case 4: await executeStep4(state); break;
  994. case 5: await executeStep5(state); break;
  995. case 6: await executeStep6(state); break;
  996. case 7: await executeStep7(state); break;
  997. case 8: await executeStep8(state); break;
  998. case 9: await executeStep9(state); break;
  999. default:
  1000. throw new Error(`未知步骤:${step}`);
  1001. }
  1002. } catch (err) {
  1003. if (isStopError(err)) {
  1004. await setStepStatus(step, 'stopped');
  1005. await addLog(`步骤 ${step} 已被用户停止`, 'warn');
  1006. throw err;
  1007. }
  1008. await setStepStatus(step, 'failed');
  1009. await addLog(`步骤 ${step} 失败:${err.message}`, 'error');
  1010. throw err;
  1011. }
  1012. }
  1013. /**
  1014. * Execute a step and wait for it to complete before returning.
  1015. * @param {number} step
  1016. * @param {number} delayAfter - ms to wait after completion (for page transitions)
  1017. */
  1018. async function executeStepAndWait(step, delayAfter = 2000) {
  1019. throwIfStopped();
  1020. const promise = waitForStepComplete(step, 120000);
  1021. await executeStep(step);
  1022. await promise;
  1023. // Extra delay for page transitions / DOM updates
  1024. if (delayAfter > 0) {
  1025. await sleepWithStop(delayAfter + Math.floor(Math.random() * 1200));
  1026. }
  1027. }
  1028. async function fetchDuckEmail(options = {}) {
  1029. throwIfStopped();
  1030. const { generateNew = true } = options;
  1031. await addLog(`Duck 邮箱:正在打开自动填充设置(${generateNew ? '生成新地址' : '复用当前地址'})...`);
  1032. await reuseOrCreateTab('duck-mail', DUCK_AUTOFILL_URL);
  1033. const result = await sendToContentScript('duck-mail', {
  1034. type: 'FETCH_DUCK_EMAIL',
  1035. source: 'background',
  1036. payload: { generateNew },
  1037. });
  1038. if (result?.error) {
  1039. throw new Error(result.error);
  1040. }
  1041. if (!result?.email) {
  1042. throw new Error('未返回 Duck 邮箱地址。');
  1043. }
  1044. await setEmailState(result.email);
  1045. await addLog(`Duck 邮箱:${result.generated ? '已生成' : '已读取'} ${result.email}`, 'ok');
  1046. return result.email;
  1047. }
  1048. // ============================================================
  1049. // Auto Run Flow
  1050. // ============================================================
  1051. let autoRunActive = false;
  1052. let autoRunCurrentRun = 0;
  1053. let autoRunTotalRuns = 1;
  1054. let autoRunAttemptRun = 0;
  1055. const VERIFICATION_POLL_MAX_ROUNDS = 9;
  1056. const AUTO_STEP_DELAYS = {
  1057. 1: 2000,
  1058. 2: 2000,
  1059. 3: 3000,
  1060. 4: 2000,
  1061. 5: 3000,
  1062. 6: 3000,
  1063. 7: 2000,
  1064. 8: 2000,
  1065. 9: 1000,
  1066. };
  1067. async function resumeAutoRunIfWaitingForEmail(options = {}) {
  1068. const { silent = false } = options;
  1069. const state = await getState();
  1070. if (!state.email || !isAutoRunPausedState(state)) {
  1071. return false;
  1072. }
  1073. if (resumeWaiter) {
  1074. if (!silent) {
  1075. await addLog('邮箱已就绪,自动继续后续步骤...', 'info');
  1076. }
  1077. resumeWaiter.resolve();
  1078. resumeWaiter = null;
  1079. return true;
  1080. }
  1081. return false;
  1082. }
  1083. async function ensureAutoEmailReady(targetRun, totalRuns, attemptRuns) {
  1084. const currentState = await getState();
  1085. if (currentState.email) {
  1086. return currentState.email;
  1087. }
  1088. try {
  1089. const duckEmail = await fetchDuckEmail({ generateNew: true });
  1090. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:Duck 邮箱已就绪:${duckEmail}(第 ${attemptRuns} 次尝试)===`, 'ok');
  1091. return duckEmail;
  1092. } catch (err) {
  1093. await addLog(`Duck 邮箱自动获取失败:${err.message}`, 'warn');
  1094. }
  1095. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮已暂停:请先获取 Duck 邮箱或手动粘贴邮箱,然后继续 ===`, 'warn');
  1096. await broadcastAutoRunStatus('waiting_email', {
  1097. currentRun: targetRun,
  1098. totalRuns,
  1099. attemptRun: attemptRuns,
  1100. });
  1101. await waitForResume();
  1102. const resumedState = await getState();
  1103. if (!resumedState.email) {
  1104. throw new Error('无法继续:当前没有邮箱地址。');
  1105. }
  1106. return resumedState.email;
  1107. }
  1108. async function runAutoSequenceFromStep(startStep, context = {}) {
  1109. const { targetRun, totalRuns, attemptRuns, continued = false } = context;
  1110. if (continued) {
  1111. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:继续当前进度,从步骤 ${startStep} 开始(第 ${attemptRuns} 次尝试)===`, 'info');
  1112. } else {
  1113. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:第 ${attemptRuns} 次尝试,阶段 1,获取 OAuth 链接并打开注册页 ===`, 'info');
  1114. }
  1115. if (startStep <= 2) {
  1116. for (const step of [1, 2]) {
  1117. if (step < startStep) continue;
  1118. await executeStepAndWait(step, AUTO_STEP_DELAYS[step]);
  1119. }
  1120. }
  1121. if (startStep <= 3) {
  1122. await ensureAutoEmailReady(targetRun, totalRuns, attemptRuns);
  1123. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:阶段 2,注册、验证、登录并完成授权(第 ${attemptRuns} 次尝试)===`, 'info');
  1124. await broadcastAutoRunStatus('running', {
  1125. currentRun: targetRun,
  1126. totalRuns,
  1127. attemptRun: attemptRuns,
  1128. });
  1129. await executeStepAndWait(3, AUTO_STEP_DELAYS[3]);
  1130. } else {
  1131. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:继续执行剩余流程(第 ${attemptRuns} 次尝试)===`, 'info');
  1132. }
  1133. const signupTabId = await getTabId('signup-page');
  1134. if (signupTabId) {
  1135. await chrome.tabs.update(signupTabId, { active: true });
  1136. }
  1137. for (let step = Math.max(startStep, 4); step <= 9; step++) {
  1138. await executeStepAndWait(step, AUTO_STEP_DELAYS[step]);
  1139. }
  1140. }
  1141. // Outer loop: keep retrying until the target number of successful runs is reached.
  1142. async function autoRunLoop(totalRuns, options = {}) {
  1143. if (autoRunActive) {
  1144. await addLog('自动运行已在进行中', 'warn');
  1145. return;
  1146. }
  1147. clearStopRequest();
  1148. autoRunActive = true;
  1149. autoRunTotalRuns = totalRuns;
  1150. autoRunCurrentRun = 0;
  1151. autoRunAttemptRun = 0;
  1152. const autoRunSkipFailures = Boolean(options.autoRunSkipFailures);
  1153. const initialMode = options.mode === 'continue' ? 'continue' : 'restart';
  1154. const resumeCurrentRun = Number.isInteger(options.resumeCurrentRun) ? options.resumeCurrentRun : 0;
  1155. const resumeSuccessfulRuns = Number.isInteger(options.resumeSuccessfulRuns) ? options.resumeSuccessfulRuns : 0;
  1156. const resumeAttemptRunsProcessed = Number.isInteger(options.resumeAttemptRunsProcessed) ? options.resumeAttemptRunsProcessed : 0;
  1157. let maxAttempts = autoRunSkipFailures ? Math.max(totalRuns * 10, totalRuns + 20) : totalRuns;
  1158. const forcedRetryCap = Math.max(totalRuns * 10, totalRuns + 20);
  1159. let successfulRuns = Math.max(0, resumeSuccessfulRuns);
  1160. let attemptRuns = Math.max(0, resumeAttemptRunsProcessed);
  1161. let forceFreshTabsNextRun = false;
  1162. let continueCurrentOnFirstAttempt = initialMode === 'continue';
  1163. await setState({
  1164. autoRunSkipFailures,
  1165. ...getAutoRunStatusPayload('running', {
  1166. currentRun: resumeCurrentRun,
  1167. totalRuns,
  1168. attemptRun: resumeAttemptRunsProcessed,
  1169. }),
  1170. });
  1171. while (successfulRuns < totalRuns && attemptRuns < maxAttempts) {
  1172. attemptRuns += 1;
  1173. const targetRun = successfulRuns + 1;
  1174. autoRunCurrentRun = targetRun;
  1175. autoRunAttemptRun = attemptRuns;
  1176. let startStep = 1;
  1177. let useExistingProgress = false;
  1178. if (continueCurrentOnFirstAttempt) {
  1179. const currentState = await getState();
  1180. const resumeStep = getFirstUnfinishedStep(currentState.stepStatuses);
  1181. if (resumeStep && hasSavedProgress(currentState.stepStatuses)) {
  1182. startStep = resumeStep;
  1183. useExistingProgress = true;
  1184. } else if (hasSavedProgress(currentState.stepStatuses)) {
  1185. await addLog('当前流程已全部处理,将按“重新开始”新开一轮自动运行。', 'info');
  1186. }
  1187. continueCurrentOnFirstAttempt = false;
  1188. }
  1189. if (!useExistingProgress) {
  1190. // Reset everything at the start of each fresh attempt (keep user settings).
  1191. const prevState = await getState();
  1192. const keepSettings = {
  1193. vpsUrl: prevState.vpsUrl,
  1194. vpsPassword: prevState.vpsPassword,
  1195. customPassword: prevState.customPassword,
  1196. autoRunSkipFailures: prevState.autoRunSkipFailures,
  1197. mailProvider: prevState.mailProvider,
  1198. inbucketHost: prevState.inbucketHost,
  1199. inbucketMailbox: prevState.inbucketMailbox,
  1200. ...getAutoRunStatusPayload('running', { currentRun: targetRun, totalRuns, attemptRun: attemptRuns }),
  1201. ...(forceFreshTabsNextRun ? { tabRegistry: {} } : {}),
  1202. };
  1203. await resetState();
  1204. await setState(keepSettings);
  1205. chrome.runtime.sendMessage({ type: 'AUTO_RUN_RESET' }).catch(() => {});
  1206. await sleepWithStop(500);
  1207. } else {
  1208. await setState({
  1209. autoRunSkipFailures,
  1210. ...getAutoRunStatusPayload('running', { currentRun: targetRun, totalRuns, attemptRun: attemptRuns }),
  1211. });
  1212. }
  1213. if (forceFreshTabsNextRun) {
  1214. await addLog(`兜底模式:上一轮已放弃,当前开始第 ${attemptRuns} 次尝试,将使用新线程继续补足第 ${targetRun}/${totalRuns} 轮。`, 'warn');
  1215. forceFreshTabsNextRun = false;
  1216. }
  1217. try {
  1218. throwIfStopped();
  1219. await broadcastAutoRunStatus('running', {
  1220. currentRun: targetRun,
  1221. totalRuns,
  1222. attemptRun: attemptRuns,
  1223. });
  1224. await runAutoSequenceFromStep(startStep, {
  1225. targetRun,
  1226. totalRuns,
  1227. attemptRuns,
  1228. continued: useExistingProgress,
  1229. });
  1230. successfulRuns += 1;
  1231. autoRunCurrentRun = successfulRuns;
  1232. await addLog(`=== 目标 ${successfulRuns}/${totalRuns} 轮已完成(第 ${attemptRuns} 次尝试成功)===`, 'ok');
  1233. continue;
  1234. } catch (err) {
  1235. if (isStopError(err)) {
  1236. await addLog(`目标 ${targetRun}/${totalRuns} 轮已被用户停止`, 'warn');
  1237. await broadcastAutoRunStatus('stopped', {
  1238. currentRun: targetRun,
  1239. totalRuns,
  1240. attemptRun: attemptRuns,
  1241. });
  1242. break;
  1243. }
  1244. if (isRestartCurrentAttemptError(err)) {
  1245. await addLog(`目标 ${targetRun}/${totalRuns} 轮检测到当前邮箱已存在,当前线程已放弃,将重新开始新一轮。`, 'warn');
  1246. cancelPendingCommands('当前线程因邮箱已存在而放弃。');
  1247. await broadcastStopToContentScripts();
  1248. await broadcastAutoRunStatus('retrying', {
  1249. currentRun: targetRun,
  1250. totalRuns,
  1251. attemptRun: attemptRuns,
  1252. });
  1253. forceFreshTabsNextRun = true;
  1254. maxAttempts = Math.max(maxAttempts, Math.min(forcedRetryCap, attemptRuns + 1));
  1255. continue;
  1256. }
  1257. if (!autoRunSkipFailures) {
  1258. await addLog(`目标 ${targetRun}/${totalRuns} 轮失败:${err.message}`, 'error');
  1259. await broadcastAutoRunStatus('stopped', {
  1260. currentRun: targetRun,
  1261. totalRuns,
  1262. attemptRun: attemptRuns,
  1263. });
  1264. break;
  1265. }
  1266. await addLog(`目标 ${targetRun}/${totalRuns} 轮的第 ${attemptRuns} 次尝试失败:${err.message}`, 'error');
  1267. await addLog('兜底开关已开启:将放弃当前线程,重新开一轮继续补足目标次数。', 'warn');
  1268. cancelPendingCommands('当前尝试已放弃。');
  1269. await broadcastStopToContentScripts();
  1270. await broadcastAutoRunStatus('retrying', {
  1271. currentRun: targetRun,
  1272. totalRuns,
  1273. attemptRun: attemptRuns,
  1274. });
  1275. forceFreshTabsNextRun = true;
  1276. }
  1277. }
  1278. if (!stopRequested && autoRunSkipFailures && successfulRuns < totalRuns && attemptRuns >= maxAttempts) {
  1279. await addLog(`已达到安全重试上限(${attemptRuns} 次尝试),当前仅完成 ${successfulRuns}/${totalRuns} 轮。`, 'error');
  1280. await broadcastAutoRunStatus('stopped', {
  1281. currentRun: successfulRuns,
  1282. totalRuns: autoRunTotalRuns,
  1283. attemptRun: attemptRuns,
  1284. });
  1285. } else if (stopRequested) {
  1286. await addLog(`=== 已停止,完成 ${successfulRuns}/${autoRunTotalRuns} 轮,共尝试 ${attemptRuns} 次 ===`, 'warn');
  1287. await broadcastAutoRunStatus('stopped', {
  1288. currentRun: successfulRuns,
  1289. totalRuns: autoRunTotalRuns,
  1290. attemptRun: attemptRuns,
  1291. });
  1292. } else if (successfulRuns >= autoRunTotalRuns) {
  1293. await addLog(`=== 全部 ${autoRunTotalRuns} 轮均已成功完成,共尝试 ${attemptRuns} 次 ===`, 'ok');
  1294. await broadcastAutoRunStatus('complete', {
  1295. currentRun: successfulRuns,
  1296. totalRuns: autoRunTotalRuns,
  1297. attemptRun: attemptRuns,
  1298. });
  1299. } else {
  1300. await addLog(`=== 已停止,完成 ${successfulRuns}/${autoRunTotalRuns} 轮,共尝试 ${attemptRuns} 次 ===`, 'warn');
  1301. await broadcastAutoRunStatus('stopped', {
  1302. currentRun: successfulRuns,
  1303. totalRuns: autoRunTotalRuns,
  1304. attemptRun: attemptRuns,
  1305. });
  1306. }
  1307. autoRunActive = false;
  1308. autoRunAttemptRun = attemptRuns;
  1309. await setState(getAutoRunStatusPayload(stopRequested ? 'stopped' : (successfulRuns >= autoRunTotalRuns ? 'complete' : 'stopped'), {
  1310. currentRun: successfulRuns,
  1311. totalRuns: autoRunTotalRuns,
  1312. attemptRun: attemptRuns,
  1313. }));
  1314. clearStopRequest();
  1315. }
  1316. async function waitForResume() {
  1317. throwIfStopped();
  1318. const state = await getState();
  1319. if (state.email) {
  1320. await addLog('邮箱已就绪,自动继续后续步骤...', 'info');
  1321. return;
  1322. }
  1323. return new Promise((resolve, reject) => {
  1324. resumeWaiter = { resolve, reject };
  1325. });
  1326. }
  1327. async function resumeAutoRun() {
  1328. throwIfStopped();
  1329. const state = await getState();
  1330. if (!state.email) {
  1331. await addLog('无法继续:当前没有邮箱地址,请先在侧边栏填写邮箱。', 'error');
  1332. return false;
  1333. }
  1334. const resumedInMemory = await resumeAutoRunIfWaitingForEmail({ silent: true });
  1335. if (resumedInMemory) {
  1336. return true;
  1337. }
  1338. if (!isAutoRunPausedState(state)) {
  1339. return false;
  1340. }
  1341. if (autoRunActive) {
  1342. return false;
  1343. }
  1344. const totalRuns = state.autoRunTotalRuns || 1;
  1345. const currentRun = state.autoRunCurrentRun || 1;
  1346. const attemptRun = state.autoRunAttemptRun || 1;
  1347. const successfulRuns = Math.max(0, currentRun - 1);
  1348. await addLog('检测到自动流程暂停上下文已丢失,正在从当前进度恢复自动运行...', 'warn');
  1349. autoRunLoop(totalRuns, {
  1350. autoRunSkipFailures: Boolean(state.autoRunSkipFailures),
  1351. mode: 'continue',
  1352. resumeCurrentRun: currentRun,
  1353. resumeSuccessfulRuns: successfulRuns,
  1354. resumeAttemptRunsProcessed: Math.max(0, attemptRun - 1),
  1355. });
  1356. return true;
  1357. }
  1358. // ============================================================
  1359. // Step 1: Get OAuth Link (via vps-panel.js)
  1360. // ============================================================
  1361. async function executeStep1(state) {
  1362. if (!state.vpsUrl) {
  1363. throw new Error('尚未配置 CPA 地址,请先在侧边栏填写。');
  1364. }
  1365. await addLog('步骤 1:正在打开 CPA 面板...');
  1366. await reuseOrCreateTab('vps-panel', state.vpsUrl, {
  1367. inject: ['content/utils.js', 'content/vps-panel.js'],
  1368. reloadIfSameUrl: true,
  1369. });
  1370. await sendToContentScript('vps-panel', {
  1371. type: 'EXECUTE_STEP',
  1372. step: 1,
  1373. source: 'background',
  1374. payload: { vpsPassword: state.vpsPassword },
  1375. });
  1376. }
  1377. // ============================================================
  1378. // Step 2: Open Signup Page (Background opens tab, signup-page.js clicks Register)
  1379. // ============================================================
  1380. async function executeStep2(state) {
  1381. if (!state.oauthUrl) {
  1382. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  1383. }
  1384. await addLog('步骤 2:正在打开认证链接...');
  1385. await reuseOrCreateTab('signup-page', state.oauthUrl);
  1386. await sendToContentScript('signup-page', {
  1387. type: 'EXECUTE_STEP',
  1388. step: 2,
  1389. source: 'background',
  1390. payload: {},
  1391. });
  1392. }
  1393. // ============================================================
  1394. // Step 3: Fill Email & Password (via signup-page.js)
  1395. // ============================================================
  1396. async function executeStep3(state) {
  1397. if (!state.email) {
  1398. throw new Error('缺少邮箱地址,请先在侧边栏粘贴邮箱。');
  1399. }
  1400. const password = state.customPassword || generatePassword();
  1401. await setPasswordState(password);
  1402. // Save account record
  1403. const accounts = state.accounts || [];
  1404. accounts.push({ email: state.email, password, createdAt: new Date().toISOString() });
  1405. await setState({ accounts });
  1406. await addLog(
  1407. `步骤 3:正在填写邮箱 ${state.email},密码为${state.customPassword ? '自定义' : '自动生成'}(${password.length} 位)`
  1408. );
  1409. await sendToContentScript('signup-page', {
  1410. type: 'EXECUTE_STEP',
  1411. step: 3,
  1412. source: 'background',
  1413. payload: { email: state.email, password },
  1414. });
  1415. }
  1416. // ============================================================
  1417. // Step 4: Get Signup Verification Code (qq-mail.js polls, then fills in signup-page.js)
  1418. // ============================================================
  1419. function getMailConfig(state) {
  1420. const provider = state.mailProvider || 'qq';
  1421. if (provider === '163') {
  1422. 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 邮箱' };
  1423. }
  1424. if (provider === 'inbucket') {
  1425. const host = normalizeInbucketOrigin(state.inbucketHost);
  1426. const mailbox = (state.inbucketMailbox || '').trim();
  1427. if (!host) {
  1428. return { error: 'Inbucket 主机地址为空或无效。' };
  1429. }
  1430. if (!mailbox) {
  1431. return { error: 'Inbucket 邮箱名称为空。' };
  1432. }
  1433. return {
  1434. source: 'inbucket-mail',
  1435. url: `${host}/m/${encodeURIComponent(mailbox)}/`,
  1436. label: `Inbucket 邮箱(${mailbox})`,
  1437. navigateOnReuse: true,
  1438. inject: ['content/utils.js', 'content/inbucket-mail.js'],
  1439. injectSource: 'inbucket-mail',
  1440. };
  1441. }
  1442. return { source: 'qq-mail', url: 'https://wx.mail.qq.com/', label: 'QQ 邮箱' };
  1443. }
  1444. function normalizeInbucketOrigin(rawValue) {
  1445. const value = (rawValue || '').trim();
  1446. if (!value) return '';
  1447. const candidate = /^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(value) ? value : `https://${value}`;
  1448. try {
  1449. const parsed = new URL(candidate);
  1450. return parsed.origin;
  1451. } catch {
  1452. return '';
  1453. }
  1454. }
  1455. function getVerificationCodeStateKey(step) {
  1456. return step === 4 ? 'lastSignupCode' : 'lastLoginCode';
  1457. }
  1458. function getVerificationCodeLabel(step) {
  1459. return step === 4 ? '注册' : '登录';
  1460. }
  1461. function getVerificationPollPayload(step, state, overrides = {}) {
  1462. if (step === 4) {
  1463. return {
  1464. filterAfterTimestamp: state.flowStartTime || 0,
  1465. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'duckduckgo', 'forward'],
  1466. subjectFilters: ['verify', 'verification', 'code', '楠岃瘉', 'confirm'],
  1467. targetEmail: state.email,
  1468. maxAttempts: 5,
  1469. intervalMs: 3000,
  1470. ...overrides,
  1471. };
  1472. }
  1473. return {
  1474. filterAfterTimestamp: state.lastEmailTimestamp || state.flowStartTime || 0,
  1475. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'chatgpt', 'duckduckgo', 'forward'],
  1476. subjectFilters: ['verify', 'verification', 'code', '楠岃瘉', 'confirm', 'login'],
  1477. targetEmail: state.email,
  1478. maxAttempts: 5,
  1479. intervalMs: 3000,
  1480. ...overrides,
  1481. };
  1482. }
  1483. async function requestVerificationCodeResend(step) {
  1484. const signupTabId = await getTabId('signup-page');
  1485. if (!signupTabId) {
  1486. throw new Error('认证页面标签页已关闭,无法重新请求验证码。');
  1487. }
  1488. await chrome.tabs.update(signupTabId, { active: true });
  1489. await addLog(`步骤 ${step}:正在请求新的${getVerificationCodeLabel(step)}验证码...`, 'warn');
  1490. const result = await sendToContentScript('signup-page', {
  1491. type: 'RESEND_VERIFICATION_CODE',
  1492. step,
  1493. source: 'background',
  1494. payload: {},
  1495. });
  1496. if (result && result.error) {
  1497. throw new Error(result.error);
  1498. }
  1499. return Date.now();
  1500. }
  1501. async function pollFreshVerificationCode(step, state, mail, pollOverrides = {}) {
  1502. const stateKey = getVerificationCodeStateKey(step);
  1503. const rejectedCodes = new Set();
  1504. if (state[stateKey]) {
  1505. rejectedCodes.add(state[stateKey]);
  1506. }
  1507. for (const code of (pollOverrides.excludeCodes || [])) {
  1508. if (code) rejectedCodes.add(code);
  1509. }
  1510. let lastError = null;
  1511. let filterAfterTimestamp = pollOverrides.filterAfterTimestamp ?? getVerificationPollPayload(step, state).filterAfterTimestamp;
  1512. const maxRounds = pollOverrides.maxRounds || VERIFICATION_POLL_MAX_ROUNDS;
  1513. for (let round = 1; round <= maxRounds; round++) {
  1514. if (round > 1) {
  1515. filterAfterTimestamp = await requestVerificationCodeResend(step);
  1516. }
  1517. const payload = getVerificationPollPayload(step, state, {
  1518. ...pollOverrides,
  1519. filterAfterTimestamp,
  1520. excludeCodes: [...rejectedCodes],
  1521. });
  1522. try {
  1523. const result = await sendToMailContentScriptResilient(
  1524. mail,
  1525. {
  1526. type: 'POLL_EMAIL',
  1527. step,
  1528. source: 'background',
  1529. payload,
  1530. },
  1531. {
  1532. timeoutMs: 45000,
  1533. maxRecoveryAttempts: 2,
  1534. }
  1535. );
  1536. if (result && result.error) {
  1537. throw new Error(result.error);
  1538. }
  1539. if (!result || !result.code) {
  1540. throw new Error(`步骤 ${step}:邮箱轮询结束,但未获取到验证码。`);
  1541. }
  1542. if (rejectedCodes.has(result.code)) {
  1543. throw new Error(`步骤 ${step}:再次收到了相同的${getVerificationCodeLabel(step)}验证码:${result.code}`);
  1544. }
  1545. return result;
  1546. } catch (err) {
  1547. lastError = err;
  1548. await addLog(`步骤 ${step}:${err.message}`, 'warn');
  1549. if (round < maxRounds) {
  1550. await addLog(`步骤 ${step}:将重新发送验证码后重试(${round + 1}/${maxRounds})...`, 'warn');
  1551. }
  1552. }
  1553. }
  1554. throw lastError || new Error(`步骤 ${step}:无法获取新的${getVerificationCodeLabel(step)}验证码。`);
  1555. }
  1556. async function submitVerificationCode(step, code) {
  1557. const signupTabId = await getTabId('signup-page');
  1558. if (!signupTabId) {
  1559. throw new Error('认证页面标签页已关闭,无法填写验证码。');
  1560. }
  1561. await chrome.tabs.update(signupTabId, { active: true });
  1562. const result = await sendToContentScript('signup-page', {
  1563. type: 'FILL_CODE',
  1564. step,
  1565. source: 'background',
  1566. payload: { code },
  1567. });
  1568. if (result && result.error) {
  1569. throw new Error(result.error);
  1570. }
  1571. return result || {};
  1572. }
  1573. async function resolveVerificationStep(step, state, mail, options = {}) {
  1574. const stateKey = getVerificationCodeStateKey(step);
  1575. const rejectedCodes = new Set();
  1576. if (state[stateKey]) {
  1577. rejectedCodes.add(state[stateKey]);
  1578. }
  1579. let nextFilterAfterTimestamp = options.filterAfterTimestamp ?? null;
  1580. const requestFreshCodeFirst = Boolean(options.requestFreshCodeFirst);
  1581. const maxSubmitAttempts = 3;
  1582. if (requestFreshCodeFirst) {
  1583. try {
  1584. nextFilterAfterTimestamp = await requestVerificationCodeResend(step);
  1585. await addLog(`步骤 ${step}:已先请求一封新的${getVerificationCodeLabel(step)}验证码,再开始轮询邮箱。`, 'warn');
  1586. } catch (err) {
  1587. await addLog(`步骤 ${step}:首次重新获取验证码失败:${err.message},将继续使用当前时间窗口轮询。`, 'warn');
  1588. }
  1589. }
  1590. for (let attempt = 1; attempt <= maxSubmitAttempts; attempt++) {
  1591. const result = await pollFreshVerificationCode(step, state, mail, {
  1592. excludeCodes: [...rejectedCodes],
  1593. filterAfterTimestamp: nextFilterAfterTimestamp ?? undefined,
  1594. });
  1595. await addLog(`步骤 ${step}:已获取${getVerificationCodeLabel(step)}验证码:${result.code}`);
  1596. const submitResult = await submitVerificationCode(step, result.code);
  1597. if (submitResult.invalidCode) {
  1598. rejectedCodes.add(result.code);
  1599. await addLog(`步骤 ${step}:验证码被页面拒绝:${submitResult.errorText || result.code}`, 'warn');
  1600. if (attempt >= maxSubmitAttempts) {
  1601. throw new Error(`步骤 ${step}:验证码连续失败,已达到 ${maxSubmitAttempts} 次重试上限。`);
  1602. }
  1603. nextFilterAfterTimestamp = await requestVerificationCodeResend(step);
  1604. await addLog(`步骤 ${step}:提交失败后已请求新验证码(${attempt + 1}/${maxSubmitAttempts})...`, 'warn');
  1605. continue;
  1606. }
  1607. await setState({
  1608. lastEmailTimestamp: result.emailTimestamp,
  1609. [stateKey]: result.code,
  1610. });
  1611. await completeStepFromBackground(step, {
  1612. emailTimestamp: result.emailTimestamp,
  1613. code: result.code,
  1614. });
  1615. return;
  1616. }
  1617. }
  1618. async function executeStep4(state) {
  1619. const mail = getMailConfig(state);
  1620. if (mail.error) throw new Error(mail.error);
  1621. const stepStartedAt = Date.now();
  1622. const signupTabId = await getTabId('signup-page');
  1623. if (!signupTabId) {
  1624. throw new Error('认证页面标签页已关闭,无法继续步骤 4。');
  1625. }
  1626. await chrome.tabs.update(signupTabId, { active: true });
  1627. await addLog('步骤 4:正在确认注册验证码页面是否就绪,必要时自动恢复密码页超时报错...');
  1628. const prepareResult = await sendToContentScriptResilient(
  1629. 'signup-page',
  1630. {
  1631. type: 'PREPARE_SIGNUP_VERIFICATION',
  1632. step: 4,
  1633. source: 'background',
  1634. payload: { password: state.password || state.customPassword || '' },
  1635. },
  1636. {
  1637. timeoutMs: 30000,
  1638. retryDelayMs: 700,
  1639. logMessage: '步骤 4:认证页正在切换,等待页面重新就绪后继续检测...',
  1640. }
  1641. );
  1642. if (prepareResult && prepareResult.error) {
  1643. throw new Error(prepareResult.error);
  1644. }
  1645. if (prepareResult?.alreadyVerified) {
  1646. await completeStepFromBackground(4, {});
  1647. return;
  1648. }
  1649. await addLog(`步骤 4:正在打开${mail.label}...`);
  1650. // For mail tabs, only create if not alive — don't navigate (preserves login session)
  1651. const alive = await isTabAlive(mail.source);
  1652. if (alive) {
  1653. if (mail.navigateOnReuse) {
  1654. await reuseOrCreateTab(mail.source, mail.url, {
  1655. inject: mail.inject,
  1656. injectSource: mail.injectSource,
  1657. });
  1658. } else {
  1659. const tabId = await getTabId(mail.source);
  1660. await chrome.tabs.update(tabId, { active: true });
  1661. }
  1662. } else {
  1663. await reuseOrCreateTab(mail.source, mail.url, {
  1664. inject: mail.inject,
  1665. injectSource: mail.injectSource,
  1666. });
  1667. }
  1668. await resolveVerificationStep(4, state, mail, {
  1669. filterAfterTimestamp: stepStartedAt,
  1670. requestFreshCodeFirst: true,
  1671. });
  1672. return;
  1673. }
  1674. // ============================================================
  1675. // Step 5: Fill Name & Birthday (via signup-page.js)
  1676. // ============================================================
  1677. async function executeStep5(state) {
  1678. const { firstName, lastName } = generateRandomName();
  1679. const { year, month, day } = generateRandomBirthday();
  1680. await addLog(`步骤 5:已生成姓名 ${firstName} ${lastName},生日 ${year}-${month}-${day}`);
  1681. await sendToContentScript('signup-page', {
  1682. type: 'EXECUTE_STEP',
  1683. step: 5,
  1684. source: 'background',
  1685. payload: { firstName, lastName, year, month, day },
  1686. });
  1687. }
  1688. // ============================================================
  1689. // Step 6: Login ChatGPT (Background opens tab, chatgpt.js handles login)
  1690. // ============================================================
  1691. async function refreshOAuthUrlBeforeStep6(state) {
  1692. if (!state.vpsUrl) {
  1693. throw new Error('尚未配置 CPA 地址,请先在侧边栏填写。');
  1694. }
  1695. await addLog('步骤 6:正在刷新登录用的 CPA OAuth 链接...');
  1696. const waitForFreshOAuth = waitForStepComplete(1, 120000);
  1697. await executeStep1(state);
  1698. await waitForFreshOAuth;
  1699. const latestState = await getState();
  1700. if (!latestState.oauthUrl) {
  1701. throw new Error('刷新 OAuth 链接后仍未拿到可用链接。');
  1702. }
  1703. return latestState.oauthUrl;
  1704. }
  1705. async function executeStep6(state) {
  1706. if (!state.email) {
  1707. throw new Error('缺少邮箱地址,请先完成步骤 3。');
  1708. }
  1709. const oauthUrl = await refreshOAuthUrlBeforeStep6(state);
  1710. await addLog('步骤 6:正在打开最新 OAuth 链接并登录...');
  1711. // Reuse the signup-page tab — navigate it to the OAuth URL
  1712. await reuseOrCreateTab('signup-page', oauthUrl);
  1713. // signup-page.js will inject (same auth.openai.com domain) and handle login
  1714. await sendToContentScript('signup-page', {
  1715. type: 'EXECUTE_STEP',
  1716. step: 6,
  1717. source: 'background',
  1718. payload: { email: state.email, password: state.password },
  1719. });
  1720. }
  1721. // ============================================================
  1722. // Step 7: Get Login Verification Code (qq-mail.js polls, then fills in chatgpt.js)
  1723. // ============================================================
  1724. async function executeStep7(state) {
  1725. const mail = getMailConfig(state);
  1726. if (mail.error) throw new Error(mail.error);
  1727. const stepStartedAt = Date.now();
  1728. const authTabId = await getTabId('signup-page');
  1729. if (authTabId) {
  1730. await chrome.tabs.update(authTabId, { active: true });
  1731. } else {
  1732. if (!state.oauthUrl) {
  1733. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  1734. }
  1735. await reuseOrCreateTab('signup-page', state.oauthUrl);
  1736. }
  1737. await addLog('步骤 7:正在准备认证页,必要时切换到一次性验证码登录...');
  1738. const prepareResult = await sendToContentScript('signup-page', {
  1739. type: 'PREPARE_LOGIN_CODE',
  1740. step: 7,
  1741. source: 'background',
  1742. payload: {},
  1743. });
  1744. if (prepareResult && prepareResult.error) {
  1745. throw new Error(prepareResult.error);
  1746. }
  1747. await addLog(`步骤 7:正在打开${mail.label}...`);
  1748. const alive = await isTabAlive(mail.source);
  1749. if (alive) {
  1750. if (mail.navigateOnReuse) {
  1751. await reuseOrCreateTab(mail.source, mail.url, {
  1752. inject: mail.inject,
  1753. injectSource: mail.injectSource,
  1754. });
  1755. } else {
  1756. const tabId = await getTabId(mail.source);
  1757. await chrome.tabs.update(tabId, { active: true });
  1758. }
  1759. } else {
  1760. await reuseOrCreateTab(mail.source, mail.url, {
  1761. inject: mail.inject,
  1762. injectSource: mail.injectSource,
  1763. });
  1764. }
  1765. await resolveVerificationStep(7, state, mail, {
  1766. filterAfterTimestamp: stepStartedAt,
  1767. requestFreshCodeFirst: true,
  1768. });
  1769. return;
  1770. }
  1771. // ============================================================
  1772. // Step 8: Complete OAuth (auto click + localhost listener)
  1773. // ============================================================
  1774. let webNavListener = null;
  1775. async function executeStep8(state) {
  1776. if (!state.oauthUrl) {
  1777. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  1778. }
  1779. await addLog('步骤 8:正在监听 localhost 回调地址...');
  1780. // Register webNavigation listener (scoped to this step)
  1781. return new Promise((resolve, reject) => {
  1782. let resolved = false;
  1783. let resolveCaptureWait = null;
  1784. const captureWait = new Promise((resolveCapture) => {
  1785. resolveCaptureWait = resolveCapture;
  1786. });
  1787. const cleanupListener = () => {
  1788. if (webNavListener) {
  1789. chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
  1790. webNavListener = null;
  1791. }
  1792. };
  1793. const timeout = setTimeout(() => {
  1794. cleanupListener();
  1795. reject(new Error('120 秒内未捕获到 localhost 回调跳转,步骤 8 的点击可能被拦截了。'));
  1796. }, 120000);
  1797. webNavListener = (details) => {
  1798. if (details.url.startsWith('http://localhost')) {
  1799. console.log(LOG_PREFIX, `Captured localhost redirect: ${details.url}`);
  1800. resolved = true;
  1801. cleanupListener();
  1802. clearTimeout(timeout);
  1803. if (resolveCaptureWait) resolveCaptureWait(details.url);
  1804. setState({ localhostUrl: details.url }).then(() => {
  1805. addLog(`步骤 8:已捕获 localhost 地址:${details.url}`, 'ok');
  1806. setStepStatus(8, 'completed');
  1807. notifyStepComplete(8, { localhostUrl: details.url });
  1808. broadcastDataUpdate({ localhostUrl: details.url });
  1809. resolve();
  1810. });
  1811. }
  1812. };
  1813. chrome.webNavigation.onBeforeNavigate.addListener(webNavListener);
  1814. // After step 7, the auth page shows a consent screen ("使用 ChatGPT 登录到 Codex")
  1815. // with a "继续" button. We locate the button in-page, then click it through
  1816. // the debugger Input API directly.
  1817. (async () => {
  1818. try {
  1819. let signupTabId = await getTabId('signup-page');
  1820. if (signupTabId) {
  1821. await chrome.tabs.update(signupTabId, { active: true });
  1822. await addLog('步骤 8:已切回认证页,正在准备调试器点击...');
  1823. } else {
  1824. signupTabId = await reuseOrCreateTab('signup-page', state.oauthUrl);
  1825. await addLog('步骤 8:已重新打开认证页,正在准备调试器点击...');
  1826. }
  1827. const clickResult = await sendToContentScript('signup-page', {
  1828. type: 'STEP8_FIND_AND_CLICK',
  1829. source: 'background',
  1830. payload: {},
  1831. });
  1832. if (clickResult?.error) {
  1833. throw new Error(clickResult.error);
  1834. }
  1835. if (!resolved) {
  1836. await clickWithDebugger(signupTabId, clickResult?.rect);
  1837. await addLog('步骤 8:已发送调试器点击,正在等待跳转...');
  1838. }
  1839. } catch (err) {
  1840. clearTimeout(timeout);
  1841. cleanupListener();
  1842. reject(err);
  1843. }
  1844. })();
  1845. });
  1846. }
  1847. // ============================================================
  1848. // Step 9: VPS Verify (via vps-panel.js)
  1849. // ============================================================
  1850. async function executeStep9(state) {
  1851. if (!state.localhostUrl) {
  1852. throw new Error('缺少 localhost 回调地址,请先完成步骤 8。');
  1853. }
  1854. if (!state.vpsUrl) {
  1855. throw new Error('尚未填写 CPA 地址,请先在侧边栏输入。');
  1856. }
  1857. await addLog('步骤 9:正在打开 CPA 面板...');
  1858. let tabId = await getTabId('vps-panel');
  1859. const alive = tabId && await isTabAlive('vps-panel');
  1860. if (!alive) {
  1861. await closeConflictingTabsForSource('vps-panel', state.vpsUrl);
  1862. // Create new tab
  1863. const tab = await chrome.tabs.create({ url: state.vpsUrl, active: true });
  1864. tabId = tab.id;
  1865. await rememberSourceLastUrl('vps-panel', state.vpsUrl);
  1866. await new Promise(resolve => {
  1867. const listener = (tid, info) => {
  1868. if (tid === tabId && info.status === 'complete') {
  1869. chrome.tabs.onUpdated.removeListener(listener);
  1870. resolve();
  1871. }
  1872. };
  1873. chrome.tabs.onUpdated.addListener(listener);
  1874. });
  1875. } else {
  1876. await closeConflictingTabsForSource('vps-panel', state.vpsUrl, { excludeTabIds: [tabId] });
  1877. await chrome.tabs.update(tabId, { active: true });
  1878. await rememberSourceLastUrl('vps-panel', state.vpsUrl);
  1879. }
  1880. // Inject scripts directly and wait for them to be ready
  1881. await chrome.scripting.executeScript({
  1882. target: { tabId },
  1883. files: ['content/utils.js', 'content/vps-panel.js'],
  1884. });
  1885. await new Promise(r => setTimeout(r, 1000));
  1886. // Send command directly — bypass queue/ready mechanism
  1887. await addLog('步骤 9:正在填写回调地址...');
  1888. await chrome.tabs.sendMessage(tabId, {
  1889. type: 'EXECUTE_STEP',
  1890. step: 9,
  1891. source: 'background',
  1892. payload: { localhostUrl: state.localhostUrl, vpsPassword: state.vpsPassword },
  1893. });
  1894. }
  1895. // ============================================================
  1896. // Open Side Panel on extension icon click
  1897. // ============================================================
  1898. chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });