background.js 79 KB

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