background.js 96 KB

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