background.js 61 KB

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