background.js 70 KB

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