background.js 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978
  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 refreshOAuthUrlBeforeStep6(state) {
  1498. if (!state.vpsUrl) {
  1499. throw new Error('尚未配置 VPS 地址,请先在侧边栏填写。');
  1500. }
  1501. await addLog('步骤 6:正在刷新登录用的 OAuth 链接...');
  1502. const waitForFreshOAuth = waitForStepComplete(1, 120000);
  1503. await executeStep1(state);
  1504. await waitForFreshOAuth;
  1505. const latestState = await getState();
  1506. if (!latestState.oauthUrl) {
  1507. throw new Error('刷新 OAuth 链接后仍未拿到可用链接。');
  1508. }
  1509. return latestState.oauthUrl;
  1510. }
  1511. async function executeStep6(state) {
  1512. if (!state.email) {
  1513. throw new Error('缺少邮箱地址,请先完成步骤 3。');
  1514. }
  1515. const oauthUrl = await refreshOAuthUrlBeforeStep6(state);
  1516. await addLog('步骤 6:正在打开最新 OAuth 链接并登录...');
  1517. // Reuse the signup-page tab — navigate it to the OAuth URL
  1518. await reuseOrCreateTab('signup-page', oauthUrl);
  1519. // signup-page.js will inject (same auth.openai.com domain) and handle login
  1520. await sendToContentScript('signup-page', {
  1521. type: 'EXECUTE_STEP',
  1522. step: 6,
  1523. source: 'background',
  1524. payload: { email: state.email, password: state.password },
  1525. });
  1526. }
  1527. // ============================================================
  1528. // Step 7: Get Login Verification Code (qq-mail.js polls, then fills in chatgpt.js)
  1529. // ============================================================
  1530. async function executeStep7(state) {
  1531. const mail = getMailConfig(state);
  1532. if (mail.error) throw new Error(mail.error);
  1533. const authTabId = await getTabId('signup-page');
  1534. if (authTabId) {
  1535. await chrome.tabs.update(authTabId, { active: true });
  1536. } else {
  1537. if (!state.oauthUrl) {
  1538. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  1539. }
  1540. await reuseOrCreateTab('signup-page', state.oauthUrl);
  1541. }
  1542. await addLog('步骤 7:正在准备认证页,必要时切换到一次性验证码登录...');
  1543. const prepareResult = await sendToContentScript('signup-page', {
  1544. type: 'PREPARE_LOGIN_CODE',
  1545. step: 7,
  1546. source: 'background',
  1547. payload: {},
  1548. });
  1549. if (prepareResult && prepareResult.error) {
  1550. throw new Error(prepareResult.error);
  1551. }
  1552. await addLog(`步骤 7:正在打开${mail.label}...`);
  1553. const alive = await isTabAlive(mail.source);
  1554. if (alive) {
  1555. if (mail.navigateOnReuse) {
  1556. await reuseOrCreateTab(mail.source, mail.url, {
  1557. inject: mail.inject,
  1558. injectSource: mail.injectSource,
  1559. });
  1560. } else {
  1561. const tabId = await getTabId(mail.source);
  1562. await chrome.tabs.update(tabId, { active: true });
  1563. }
  1564. } else {
  1565. await reuseOrCreateTab(mail.source, mail.url, {
  1566. inject: mail.inject,
  1567. injectSource: mail.injectSource,
  1568. });
  1569. }
  1570. await resolveVerificationStep(7, state, mail);
  1571. return;
  1572. }
  1573. // ============================================================
  1574. // Step 8: Complete OAuth (auto click + localhost listener)
  1575. // ============================================================
  1576. let webNavListener = null;
  1577. async function executeStep8(state) {
  1578. if (!state.oauthUrl) {
  1579. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  1580. }
  1581. await addLog('步骤 8:正在监听 localhost 回调地址...');
  1582. // Register webNavigation listener (scoped to this step)
  1583. return new Promise((resolve, reject) => {
  1584. let resolved = false;
  1585. let resolveCaptureWait = null;
  1586. const captureWait = new Promise((resolveCapture) => {
  1587. resolveCaptureWait = resolveCapture;
  1588. });
  1589. const cleanupListener = () => {
  1590. if (webNavListener) {
  1591. chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
  1592. webNavListener = null;
  1593. }
  1594. };
  1595. const timeout = setTimeout(() => {
  1596. cleanupListener();
  1597. reject(new Error('120 秒内未捕获到 localhost 回调跳转,步骤 8 的点击可能被拦截了。'));
  1598. }, 120000);
  1599. webNavListener = (details) => {
  1600. if (details.url.startsWith('http://localhost')) {
  1601. console.log(LOG_PREFIX, `Captured localhost redirect: ${details.url}`);
  1602. resolved = true;
  1603. cleanupListener();
  1604. clearTimeout(timeout);
  1605. if (resolveCaptureWait) resolveCaptureWait(details.url);
  1606. setState({ localhostUrl: details.url }).then(() => {
  1607. addLog(`步骤 8:已捕获 localhost 地址:${details.url}`, 'ok');
  1608. setStepStatus(8, 'completed');
  1609. notifyStepComplete(8, { localhostUrl: details.url });
  1610. broadcastDataUpdate({ localhostUrl: details.url });
  1611. resolve();
  1612. });
  1613. }
  1614. };
  1615. chrome.webNavigation.onBeforeNavigate.addListener(webNavListener);
  1616. // After step 7, the auth page shows a consent screen ("使用 ChatGPT 登录到 Codex")
  1617. // with a "继续" button. We locate the button in-page, then click it through
  1618. // the debugger Input API directly.
  1619. (async () => {
  1620. try {
  1621. let signupTabId = await getTabId('signup-page');
  1622. if (signupTabId) {
  1623. await chrome.tabs.update(signupTabId, { active: true });
  1624. await addLog('步骤 8:已切回认证页,正在准备调试器点击...');
  1625. } else {
  1626. signupTabId = await reuseOrCreateTab('signup-page', state.oauthUrl);
  1627. await addLog('步骤 8:已重新打开认证页,正在准备调试器点击...');
  1628. }
  1629. const clickResult = await sendToContentScript('signup-page', {
  1630. type: 'STEP8_FIND_AND_CLICK',
  1631. source: 'background',
  1632. payload: {},
  1633. });
  1634. if (clickResult?.error) {
  1635. throw new Error(clickResult.error);
  1636. }
  1637. if (!resolved) {
  1638. await clickWithDebugger(signupTabId, clickResult?.rect);
  1639. await addLog('步骤 8:已发送调试器点击,正在等待跳转...');
  1640. }
  1641. } catch (err) {
  1642. clearTimeout(timeout);
  1643. cleanupListener();
  1644. reject(err);
  1645. }
  1646. })();
  1647. });
  1648. }
  1649. // ============================================================
  1650. // Step 9: VPS Verify (via vps-panel.js)
  1651. // ============================================================
  1652. async function executeStep9(state) {
  1653. if (!state.localhostUrl) {
  1654. throw new Error('缺少 localhost 回调地址,请先完成步骤 8。');
  1655. }
  1656. if (!state.vpsUrl) {
  1657. throw new Error('尚未填写 VPS 地址,请先在侧边栏输入。');
  1658. }
  1659. await addLog('步骤 9:正在打开 VPS 面板...');
  1660. let tabId = await getTabId('vps-panel');
  1661. const alive = tabId && await isTabAlive('vps-panel');
  1662. if (!alive) {
  1663. await closeConflictingTabsForSource('vps-panel', state.vpsUrl);
  1664. // Create new tab
  1665. const tab = await chrome.tabs.create({ url: state.vpsUrl, active: true });
  1666. tabId = tab.id;
  1667. await rememberSourceLastUrl('vps-panel', state.vpsUrl);
  1668. await new Promise(resolve => {
  1669. const listener = (tid, info) => {
  1670. if (tid === tabId && info.status === 'complete') {
  1671. chrome.tabs.onUpdated.removeListener(listener);
  1672. resolve();
  1673. }
  1674. };
  1675. chrome.tabs.onUpdated.addListener(listener);
  1676. });
  1677. } else {
  1678. await closeConflictingTabsForSource('vps-panel', state.vpsUrl, { excludeTabIds: [tabId] });
  1679. await chrome.tabs.update(tabId, { active: true });
  1680. await rememberSourceLastUrl('vps-panel', state.vpsUrl);
  1681. }
  1682. // Inject scripts directly and wait for them to be ready
  1683. await chrome.scripting.executeScript({
  1684. target: { tabId },
  1685. files: ['content/utils.js', 'content/vps-panel.js'],
  1686. });
  1687. await new Promise(r => setTimeout(r, 1000));
  1688. // Send command directly — bypass queue/ready mechanism
  1689. await addLog('步骤 9:正在填写回调地址...');
  1690. await chrome.tabs.sendMessage(tabId, {
  1691. type: 'EXECUTE_STEP',
  1692. step: 9,
  1693. source: 'background',
  1694. payload: { localhostUrl: state.localhostUrl, vpsPassword: state.vpsPassword },
  1695. });
  1696. }
  1697. // ============================================================
  1698. // Open Side Panel on extension icon click
  1699. // ============================================================
  1700. chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });