background.js 67 KB

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