background.js 101 KB

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