background.js 64 KB

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