background.js 62 KB

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