background.js 78 KB

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