background.js 120 KB

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