background.js 83 KB

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