background.js 63 KB

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