background.js 152 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568
  1. // background.js — Service Worker: orchestration, state, tab management, message routing
  2. importScripts('data/names.js', 'hotmail-utils.js', 'content/activation-utils.js');
  3. const {
  4. buildHotmailGraphMessagesUrl,
  5. extractVerificationCodeFromMessage,
  6. filterHotmailAccountsByUsage,
  7. getLatestHotmailMessage,
  8. getHotmailGraphRequestConfig,
  9. getHotmailVerificationPollConfig,
  10. getHotmailVerificationRequestTimestamp,
  11. normalizeHotmailMailApiMessages,
  12. pickHotmailAccountForRun,
  13. pickVerificationMessage,
  14. pickVerificationMessageWithFallback,
  15. pickVerificationMessageWithTimeFallback,
  16. shouldClearHotmailCurrentSelection,
  17. } = self.HotmailUtils;
  18. const {
  19. isRecoverableStep9AuthFailure,
  20. } = self.MultiPageActivationUtils;
  21. const buildHotmailMailApiLatestUrl = buildHotmailGraphMessagesUrl;
  22. const getHotmailMailApiRequestConfig = getHotmailGraphRequestConfig;
  23. const LOG_PREFIX = '[MultiPage:bg]';
  24. const DUCK_AUTOFILL_URL = 'https://duckduckgo.com/email/settings/autofill';
  25. const HOTMAIL_PROVIDER = 'hotmail-api';
  26. const HOTMAIL_MAILBOXES = ['INBOX', 'Junk'];
  27. const STOP_ERROR_MESSAGE = '流程已被用户停止。';
  28. const HUMAN_STEP_DELAY_MIN = 700;
  29. const HUMAN_STEP_DELAY_MAX = 2200;
  30. const STEP7_RESTART_MAX_ROUNDS = 8;
  31. const SUB2API_STEP1_RESPONSE_TIMEOUT_MS = 90000;
  32. const SUB2API_STEP9_RESPONSE_TIMEOUT_MS = 120000;
  33. const DEFAULT_SUB2API_URL = 'https://sub2api.hisence.fun/admin/accounts';
  34. const DEFAULT_SUB2API_GROUP_NAME = 'codex';
  35. const DEFAULT_SUB2API_REDIRECT_URI = 'http://localhost:1455/auth/callback';
  36. const AUTO_RUN_ALARM_NAME = 'scheduled-auto-run';
  37. const AUTO_RUN_DELAY_MIN_MINUTES = 1;
  38. const AUTO_RUN_DELAY_MAX_MINUTES = 1440;
  39. initializeSessionStorageAccess();
  40. // ============================================================
  41. // 状态管理(chrome.storage.session + chrome.storage.local)
  42. // ============================================================
  43. const PERSISTED_SETTING_DEFAULTS = {
  44. panelMode: 'cpa', // Step 1 / Step 9 的来源模式:cpa | sub2api。
  45. vpsUrl: '', // VPS 面板地址,可手动填写。
  46. vpsPassword: '', // VPS 面板登录密码,可手动填写。
  47. sub2apiUrl: DEFAULT_SUB2API_URL, // SUB2API 管理后台地址。
  48. sub2apiEmail: '', // SUB2API 登录邮箱。
  49. sub2apiPassword: '', // SUB2API 登录密码。
  50. sub2apiGroupName: DEFAULT_SUB2API_GROUP_NAME, // SUB2API 创建账号时绑定的分组名。
  51. customPassword: '', // 自定义账号密码;留空时由程序自动生成随机密码。
  52. autoRunSkipFailures: false, // 自动运行遇到失败步骤后,是否继续执行后续流程。
  53. autoRunDelayEnabled: false, // 自动运行是否启用启动前倒计时。
  54. autoRunDelayMinutes: 30, // 自动运行倒计时分钟数。
  55. mailProvider: '163', // 验证码邮箱来源(163 / 163-vip / qq / inbucket)。
  56. emailGenerator: 'duck', // 注册邮箱生成方式:duck / cloudflare。
  57. inbucketHost: '', // 仅当 mailProvider 为 inbucket 时填写 Inbucket 地址,其他情况保持为空。
  58. inbucketMailbox: '', // 仅当 mailProvider 为 inbucket 时填写邮箱名,其他情况保持为空。
  59. cloudflareDomain: '', // 仅当 emailGenerator=cloudflare 时填写自定义域名。
  60. cloudflareDomains: [], // Cloudflare 可选域名列表。
  61. hotmailAccounts: [],
  62. };
  63. const PERSISTED_SETTING_KEYS = Object.keys(PERSISTED_SETTING_DEFAULTS);
  64. const DEFAULT_STATE = {
  65. currentStep: 0, // 当前流程执行到的步骤编号。
  66. stepStatuses: {
  67. 1: 'pending', 2: 'pending', 3: 'pending', 4: 'pending', 5: 'pending', // 运行时步骤状态映射,不要手动预填。
  68. 6: 'pending', 7: 'pending', 8: 'pending', 9: 'pending',
  69. },
  70. oauthUrl: null, // 运行时抓取到的 OAuth 地址,不要手动预填。
  71. email: null, // 运行时邮箱,由程序自动获取并写入,不能手动预填。
  72. password: null, // 运行时实际密码,由 customPassword 或程序自动生成后写入。
  73. accounts: [], // 已生成账号记录:{ email, password, createdAt }。
  74. lastEmailTimestamp: null, // 最近一次获取到邮箱数据的运行时时间戳。
  75. lastSignupCode: null, // 注册验证码,运行时由程序自动读取并写入。
  76. lastLoginCode: null, // 登录验证码,运行时由程序自动读取并写入。
  77. localhostUrl: null, // 运行时捕获到的 localhost 回调地址,不要手动预填。
  78. sub2apiSessionId: null, // SUB2API OpenAI Auth 会话 ID。
  79. sub2apiOAuthState: null, // SUB2API OpenAI Auth state。
  80. sub2apiGroupId: null, // SUB2API 目标分组 ID。
  81. sub2apiDraftName: null, // SUB2API 本轮预生成的账号名称。
  82. flowStartTime: null, // 当前流程开始时间。
  83. tabRegistry: {}, // 程序维护的标签页注册表。
  84. sourceLastUrls: {}, // 各来源页面最近一次打开的地址记录。
  85. logs: [], // 侧边栏展示的运行日志。
  86. ...PERSISTED_SETTING_DEFAULTS, // 合并 chrome.storage.local 中持久化保存的用户配置。
  87. autoRunning: false, // 当前是否处于自动运行中。
  88. autoRunPhase: 'idle', // 当前自动运行阶段。
  89. autoRunCurrentRun: 0, // 自动运行当前执行到第几轮。
  90. autoRunTotalRuns: 1, // 自动运行计划总轮数。
  91. autoRunAttemptRun: 0, // 当前轮次的重试序号。
  92. scheduledAutoRunAt: null, // 自动运行计划启动时间戳。
  93. scheduledAutoRunPlan: null, // 自动运行计划参数快照。
  94. signupVerificationRequestedAt: null,
  95. loginVerificationRequestedAt: null,
  96. currentHotmailAccountId: null,
  97. };
  98. function normalizeAutoRunDelayMinutes(value) {
  99. const numeric = Number(value);
  100. if (!Number.isFinite(numeric)) {
  101. return PERSISTED_SETTING_DEFAULTS.autoRunDelayMinutes;
  102. }
  103. return Math.min(
  104. AUTO_RUN_DELAY_MAX_MINUTES,
  105. Math.max(AUTO_RUN_DELAY_MIN_MINUTES, Math.floor(numeric))
  106. );
  107. }
  108. function normalizeRunCount(value) {
  109. const numeric = Number(value);
  110. if (!Number.isFinite(numeric)) {
  111. return 1;
  112. }
  113. return Math.min(50, Math.max(1, Math.floor(numeric)));
  114. }
  115. function normalizeScheduledAutoRunPlan(plan) {
  116. if (!plan || typeof plan !== 'object') {
  117. return null;
  118. }
  119. return {
  120. totalRuns: normalizeRunCount(plan.totalRuns),
  121. autoRunSkipFailures: Boolean(plan.autoRunSkipFailures),
  122. mode: plan.mode === 'continue' ? 'continue' : 'restart',
  123. };
  124. }
  125. function normalizeEmailGenerator(value = '') {
  126. return String(value || '').trim().toLowerCase() === 'cloudflare' ? 'cloudflare' : 'duck';
  127. }
  128. function normalizeCloudflareDomain(rawValue = '') {
  129. let value = String(rawValue || '').trim().toLowerCase();
  130. if (!value) return '';
  131. value = value.replace(/^@+/, '');
  132. value = value.replace(/^https?:\/\//, '');
  133. value = value.replace(/\/.*$/, '');
  134. if (!/^[a-z0-9.-]+\.[a-z]{2,}$/.test(value)) return '';
  135. return value;
  136. }
  137. async function getPersistedSettings() {
  138. const stored = await chrome.storage.local.get(PERSISTED_SETTING_KEYS);
  139. return {
  140. ...PERSISTED_SETTING_DEFAULTS,
  141. ...stored,
  142. autoRunSkipFailures: Boolean(stored.autoRunSkipFailures ?? PERSISTED_SETTING_DEFAULTS.autoRunSkipFailures),
  143. autoRunDelayEnabled: Boolean(stored.autoRunDelayEnabled ?? PERSISTED_SETTING_DEFAULTS.autoRunDelayEnabled),
  144. autoRunDelayMinutes: normalizeAutoRunDelayMinutes(stored.autoRunDelayMinutes ?? PERSISTED_SETTING_DEFAULTS.autoRunDelayMinutes),
  145. emailGenerator: normalizeEmailGenerator(stored.emailGenerator ?? PERSISTED_SETTING_DEFAULTS.emailGenerator),
  146. hotmailAccounts: normalizeHotmailAccounts(stored.hotmailAccounts),
  147. };
  148. }
  149. async function getState() {
  150. const [state, persistedSettings] = await Promise.all([
  151. chrome.storage.session.get(null),
  152. getPersistedSettings(),
  153. ]);
  154. return { ...DEFAULT_STATE, ...persistedSettings, ...state };
  155. }
  156. async function initializeSessionStorageAccess() {
  157. try {
  158. if (chrome.storage?.session?.setAccessLevel) {
  159. await chrome.storage.session.setAccessLevel({
  160. accessLevel: 'TRUSTED_AND_UNTRUSTED_CONTEXTS',
  161. });
  162. console.log(LOG_PREFIX, 'Enabled storage.session for content scripts');
  163. }
  164. } catch (err) {
  165. console.warn(LOG_PREFIX, 'Failed to enable storage.session for content scripts:', err?.message || err);
  166. }
  167. }
  168. async function setState(updates) {
  169. console.log(LOG_PREFIX, 'storage.set:', JSON.stringify(updates).slice(0, 200));
  170. if (Object.keys(updates || {}).length > 0) {
  171. await chrome.storage.session.set(updates);
  172. }
  173. }
  174. async function setPersistentSettings(updates) {
  175. const persistedUpdates = {};
  176. for (const key of PERSISTED_SETTING_KEYS) {
  177. if (updates[key] !== undefined) {
  178. if (key === 'autoRunSkipFailures' || key === 'autoRunDelayEnabled') {
  179. persistedUpdates[key] = Boolean(updates[key]);
  180. } else if (key === 'autoRunDelayMinutes') {
  181. persistedUpdates[key] = normalizeAutoRunDelayMinutes(updates[key]);
  182. } else if (key === 'hotmailAccounts') {
  183. persistedUpdates[key] = normalizeHotmailAccounts(updates[key]);
  184. } else {
  185. persistedUpdates[key] = updates[key];
  186. }
  187. }
  188. }
  189. if (Object.keys(persistedUpdates).length > 0) {
  190. await chrome.storage.local.set(persistedUpdates);
  191. }
  192. }
  193. function broadcastDataUpdate(payload) {
  194. chrome.runtime.sendMessage({
  195. type: 'DATA_UPDATED',
  196. payload,
  197. }).catch(() => { });
  198. }
  199. async function setEmailState(email) {
  200. await setState({ email });
  201. broadcastDataUpdate({ email });
  202. if (email) {
  203. await resumeAutoRunIfWaitingForEmail();
  204. }
  205. }
  206. async function setPasswordState(password) {
  207. await setState({ password });
  208. broadcastDataUpdate({ password });
  209. }
  210. async function resetState() {
  211. console.log(LOG_PREFIX, 'Resetting all state');
  212. // Preserve settings and persistent data across resets
  213. const [prev, persistedSettings] = await Promise.all([
  214. chrome.storage.session.get([
  215. 'seenCodes',
  216. 'seenInbucketMailIds',
  217. 'accounts',
  218. 'tabRegistry',
  219. 'sourceLastUrls',
  220. ]),
  221. getPersistedSettings(),
  222. ]);
  223. await chrome.storage.session.clear();
  224. await chrome.storage.session.set({
  225. ...DEFAULT_STATE,
  226. ...persistedSettings,
  227. seenCodes: prev.seenCodes || [],
  228. seenInbucketMailIds: prev.seenInbucketMailIds || [],
  229. accounts: prev.accounts || [],
  230. tabRegistry: prev.tabRegistry || {},
  231. sourceLastUrls: prev.sourceLastUrls || {},
  232. });
  233. }
  234. /**
  235. * Generate a random password: 14 chars, mix of uppercase, lowercase, digits, symbols.
  236. */
  237. function generatePassword() {
  238. const upper = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
  239. const lower = 'abcdefghjkmnpqrstuvwxyz';
  240. const digits = '23456789';
  241. const symbols = '!@#$%&*?';
  242. const all = upper + lower + digits + symbols;
  243. // Ensure at least one of each type
  244. let pw = '';
  245. pw += upper[Math.floor(Math.random() * upper.length)];
  246. pw += lower[Math.floor(Math.random() * lower.length)];
  247. pw += digits[Math.floor(Math.random() * digits.length)];
  248. pw += symbols[Math.floor(Math.random() * symbols.length)];
  249. // Fill remaining 10 chars
  250. for (let i = 0; i < 10; i++) {
  251. pw += all[Math.floor(Math.random() * all.length)];
  252. }
  253. // Shuffle
  254. return pw.split('').sort(() => Math.random() - 0.5).join('');
  255. }
  256. function normalizeHotmailAccount(account = {}) {
  257. const normalizedLastAuthAt = Number.isFinite(Number(account.lastAuthAt)) ? Number(account.lastAuthAt) : 0;
  258. const normalizedStatus = String(
  259. account.status
  260. || (normalizedLastAuthAt > 0 || account.accessToken ? 'authorized' : 'pending')
  261. );
  262. return {
  263. id: String(account.id || crypto.randomUUID()),
  264. email: String(account.email || '').trim(),
  265. password: String(account.password || ''),
  266. clientId: String(account.clientId || '').trim(),
  267. accessToken: String(account.accessToken || ''),
  268. refreshToken: String(account.refreshToken || ''),
  269. expiresAt: Number.isFinite(Number(account.expiresAt)) ? Number(account.expiresAt) : 0,
  270. status: normalizedStatus,
  271. enabled: account.enabled !== undefined ? Boolean(account.enabled) : true,
  272. used: Boolean(account.used),
  273. lastUsedAt: Number.isFinite(Number(account.lastUsedAt)) ? Number(account.lastUsedAt) : 0,
  274. lastAuthAt: normalizedLastAuthAt,
  275. lastError: String(account.lastError || ''),
  276. };
  277. }
  278. function normalizeHotmailAccounts(accounts) {
  279. if (!Array.isArray(accounts)) return [];
  280. const deduped = new Map();
  281. for (const account of accounts) {
  282. const normalized = normalizeHotmailAccount(account);
  283. if (!normalized.email && !normalized.id) continue;
  284. deduped.set(normalized.id, normalized);
  285. }
  286. return [...deduped.values()];
  287. }
  288. function findHotmailAccount(accounts, accountId) {
  289. return normalizeHotmailAccounts(accounts).find((account) => account.id === accountId) || null;
  290. }
  291. function isHotmailProvider(stateOrProvider) {
  292. const provider = typeof stateOrProvider === 'string'
  293. ? stateOrProvider
  294. : stateOrProvider?.mailProvider;
  295. return provider === HOTMAIL_PROVIDER;
  296. }
  297. async function syncHotmailAccounts(accounts) {
  298. const normalized = normalizeHotmailAccounts(accounts);
  299. await setPersistentSettings({ hotmailAccounts: normalized });
  300. await setState({ hotmailAccounts: normalized });
  301. broadcastDataUpdate({ hotmailAccounts: normalized });
  302. return normalized;
  303. }
  304. async function upsertHotmailAccount(input) {
  305. const state = await getState();
  306. const accounts = normalizeHotmailAccounts(state.hotmailAccounts);
  307. const normalizedEmail = String(input?.email || '').trim().toLowerCase();
  308. const existing = input?.id
  309. ? findHotmailAccount(accounts, input.id)
  310. : accounts.find((account) => account.email.toLowerCase() === normalizedEmail) || null;
  311. const credentialsChanged = !existing
  312. || (input?.clientId !== undefined && String(input.clientId).trim() !== existing.clientId)
  313. || (input?.refreshToken !== undefined && String(input.refreshToken).trim() !== existing.refreshToken)
  314. || (input?.email !== undefined && String(input.email).trim().toLowerCase() !== existing.email.toLowerCase());
  315. const normalized = normalizeHotmailAccount({
  316. ...(existing || {}),
  317. ...(credentialsChanged ? {
  318. accessToken: '',
  319. expiresAt: 0,
  320. status: 'pending',
  321. lastAuthAt: 0,
  322. lastError: '',
  323. } : {}),
  324. ...input,
  325. id: input?.id || existing?.id || crypto.randomUUID(),
  326. });
  327. const nextAccounts = existing
  328. ? accounts.map((account) => (account.id === normalized.id ? normalized : account))
  329. : [...accounts, normalized];
  330. await syncHotmailAccounts(nextAccounts);
  331. return normalized;
  332. }
  333. async function deleteHotmailAccount(accountId) {
  334. const state = await getState();
  335. const accounts = normalizeHotmailAccounts(state.hotmailAccounts);
  336. const nextAccounts = accounts.filter((account) => account.id !== accountId);
  337. await syncHotmailAccounts(nextAccounts);
  338. if (state.currentHotmailAccountId === accountId) {
  339. await setState({ currentHotmailAccountId: null });
  340. if (isHotmailProvider(state)) {
  341. await setEmailState(null);
  342. }
  343. broadcastDataUpdate({ currentHotmailAccountId: null });
  344. }
  345. }
  346. async function deleteHotmailAccounts(mode = 'all') {
  347. const state = await getState();
  348. const accounts = normalizeHotmailAccounts(state.hotmailAccounts);
  349. const targets = filterHotmailAccountsByUsage(accounts, mode);
  350. const targetIds = new Set(targets.map((account) => account.id));
  351. const nextAccounts = mode === 'used'
  352. ? accounts.filter((account) => !targetIds.has(account.id))
  353. : [];
  354. await syncHotmailAccounts(nextAccounts);
  355. if (state.currentHotmailAccountId && targetIds.has(state.currentHotmailAccountId)) {
  356. await setState({ currentHotmailAccountId: null });
  357. if (isHotmailProvider(state)) {
  358. await setEmailState(null);
  359. }
  360. broadcastDataUpdate({ currentHotmailAccountId: null });
  361. }
  362. return {
  363. deletedCount: targets.length,
  364. remainingCount: nextAccounts.length,
  365. };
  366. }
  367. async function patchHotmailAccount(accountId, updates = {}) {
  368. const state = await getState();
  369. const accounts = normalizeHotmailAccounts(state.hotmailAccounts);
  370. const account = findHotmailAccount(accounts, accountId);
  371. if (!account) {
  372. throw new Error('未找到对应的 Hotmail 账号。');
  373. }
  374. const nextAccount = normalizeHotmailAccount({
  375. ...account,
  376. ...updates,
  377. id: account.id,
  378. });
  379. await syncHotmailAccounts(accounts.map((item) => (item.id === account.id ? nextAccount : item)));
  380. if (state.currentHotmailAccountId === account.id && shouldClearHotmailCurrentSelection(nextAccount)) {
  381. await setState({ currentHotmailAccountId: null });
  382. broadcastDataUpdate({ currentHotmailAccountId: null });
  383. if (isHotmailProvider(state)) {
  384. await setEmailState(null);
  385. }
  386. }
  387. return nextAccount;
  388. }
  389. async function setCurrentHotmailAccount(accountId, options = {}) {
  390. const { markUsed = false, syncEmail = true } = options;
  391. const state = await getState();
  392. const accounts = normalizeHotmailAccounts(state.hotmailAccounts);
  393. const account = findHotmailAccount(accounts, accountId);
  394. if (!account) {
  395. throw new Error('未找到对应的 Hotmail 账号。');
  396. }
  397. if (markUsed) {
  398. account.lastUsedAt = Date.now();
  399. await syncHotmailAccounts(accounts.map((item) => (item.id === account.id ? account : item)));
  400. }
  401. await setState({ currentHotmailAccountId: account.id });
  402. broadcastDataUpdate({ currentHotmailAccountId: account.id });
  403. if (syncEmail) {
  404. await setEmailState(account.email || null);
  405. }
  406. return account;
  407. }
  408. async function ensureHotmailAccountForFlow(options = {}) {
  409. const { allowAllocate = true, markUsed = false, preferredAccountId = null } = options;
  410. const state = await getState();
  411. const accounts = normalizeHotmailAccounts(state.hotmailAccounts);
  412. const isAccountAllocatable = (candidate) => Boolean(candidate)
  413. && candidate.status === 'authorized'
  414. && !candidate.used
  415. && Boolean(candidate.refreshToken);
  416. let account = null;
  417. if (preferredAccountId) {
  418. account = findHotmailAccount(accounts, preferredAccountId);
  419. }
  420. if (!account && state.currentHotmailAccountId) {
  421. account = findHotmailAccount(accounts, state.currentHotmailAccountId);
  422. }
  423. if ((!account || !isAccountAllocatable(account)) && allowAllocate) {
  424. account = pickHotmailAccountForRun(accounts, {});
  425. }
  426. if (!account) {
  427. throw new Error('没有可用的 Hotmail 账号。请先在侧边栏添加至少一个带刷新令牌(refresh token)的账号。');
  428. }
  429. if (!isAccountAllocatable(account)) {
  430. throw new Error(`Hotmail 账号 ${account.email || account.id} 尚未就绪,无法读取邮件。`);
  431. }
  432. return setCurrentHotmailAccount(account.id, { markUsed, syncEmail: true });
  433. }
  434. async function requestHotmailMailApiLegacy(account, mailbox = 'INBOX') {
  435. if (!account?.email) {
  436. throw new Error('Hotmail 账号缺少邮箱地址。');
  437. }
  438. if (!account?.clientId) {
  439. throw new Error(`Hotmail 账号 ${account.email || account.id} 缺少客户端 ID。`);
  440. }
  441. if (!account?.refreshToken) {
  442. throw new Error(`Hotmail 账号 ${account.email || account.id} 缺少刷新令牌(refresh token)。`);
  443. }
  444. const url = buildHotmailMailApiLatestUrl({
  445. clientId: account.clientId,
  446. email: account.email,
  447. refreshToken: account.refreshToken,
  448. mailbox,
  449. responseType: 'json',
  450. });
  451. const { timeoutMs } = getHotmailMailApiRequestConfig();
  452. const controller = new AbortController();
  453. const timeoutId = setTimeout(() => controller.abort(new Error('timeout')), timeoutMs);
  454. let response;
  455. try {
  456. response = await fetch(url, { method: 'GET', signal: controller.signal });
  457. } catch (err) {
  458. if (err?.name === 'AbortError') {
  459. throw new Error(`Hotmail API 请求超时(>${Math.round(timeoutMs / 1000)} 秒):${mailbox}`);
  460. }
  461. throw new Error(`Hotmail API 请求失败:${err.message}`);
  462. } finally {
  463. clearTimeout(timeoutId);
  464. }
  465. const text = await response.text();
  466. let payload = {};
  467. try {
  468. payload = text ? JSON.parse(text) : {};
  469. } catch {
  470. payload = { raw: text };
  471. }
  472. if (!response.ok) {
  473. const errorText = payload?.message || payload?.error || payload?.msg || text || `HTTP ${response.status}`;
  474. throw new Error(`Hotmail API 请求失败:${errorText}`);
  475. }
  476. if (payload && payload.success === false) {
  477. const errorText = payload?.message || payload?.msg || payload?.error || '未知错误';
  478. throw new Error(`Hotmail API 返回失败:${errorText}`);
  479. }
  480. return {
  481. mailbox,
  482. payload,
  483. messages: normalizeHotmailMailApiMessages(payload?.data),
  484. nextRefreshToken: String(payload?.new_refresh_token || payload?.newRefreshToken || '').trim(),
  485. };
  486. }
  487. function applyHotmailApiResultToAccountLegacy(account, apiResult) {
  488. const nextRefreshToken = String(apiResult?.nextRefreshToken || '').trim();
  489. return {
  490. ...account,
  491. accessToken: '',
  492. expiresAt: 0,
  493. refreshToken: nextRefreshToken || account.refreshToken,
  494. status: 'authorized',
  495. lastAuthAt: Date.now(),
  496. lastError: '',
  497. };
  498. }
  499. async function fetchHotmailMailboxMessagesLegacy(account, mailboxes = HOTMAIL_MAILBOXES) {
  500. let workingAccount = normalizeHotmailAccount(account);
  501. const mailboxResults = [];
  502. for (const mailbox of mailboxes) {
  503. const result = await requestHotmailMailApiLegacy(workingAccount, mailbox);
  504. workingAccount = applyHotmailApiResultToAccountLegacy(workingAccount, result);
  505. mailboxResults.push({
  506. mailbox,
  507. count: result.messages.length,
  508. messages: result.messages.map((message) => ({ ...message, mailbox })),
  509. });
  510. }
  511. const savedAccount = await upsertHotmailAccount(workingAccount);
  512. return {
  513. account: savedAccount,
  514. mailboxResults,
  515. messages: mailboxResults.flatMap((item) => item.messages),
  516. };
  517. }
  518. function isHotmailAccessTokenUsable(account, now = Date.now()) {
  519. return Boolean(account?.accessToken)
  520. && Number(account?.expiresAt || 0) > now + 60_000;
  521. }
  522. async function refreshHotmailAccessToken(account) {
  523. if (!account?.email) {
  524. throw new Error('Hotmail 账号缺少邮箱地址。');
  525. }
  526. if (!account?.clientId) {
  527. throw new Error(`Hotmail 账号 ${account.email || account.id} 缺少客户端 ID。`);
  528. }
  529. if (!account?.refreshToken) {
  530. throw new Error(`Hotmail 账号 ${account.email || account.id} 缺少刷新令牌(refresh token)。`);
  531. }
  532. const { timeoutMs, scopes, tokenUrl } = getHotmailGraphRequestConfig();
  533. const controller = new AbortController();
  534. const timeoutId = setTimeout(() => controller.abort(new Error('timeout')), timeoutMs);
  535. const formData = new URLSearchParams();
  536. formData.set('client_id', account.clientId);
  537. formData.set('grant_type', 'refresh_token');
  538. formData.set('refresh_token', account.refreshToken);
  539. formData.set('scope', scopes.join(' '));
  540. let response;
  541. try {
  542. response = await fetch(tokenUrl, {
  543. method: 'POST',
  544. headers: {
  545. 'Content-Type': 'application/x-www-form-urlencoded',
  546. },
  547. body: formData.toString(),
  548. signal: controller.signal,
  549. });
  550. } catch (err) {
  551. const error = new Error(
  552. err?.name === 'AbortError'
  553. ? `Hotmail 令牌刷新超时(>${Math.round(timeoutMs / 1000)} 秒)`
  554. : `Hotmail 令牌刷新失败:${err.message}`
  555. );
  556. error.code = 'HOTMAIL_TOKEN_REFRESH_FAILED';
  557. throw error;
  558. } finally {
  559. clearTimeout(timeoutId);
  560. }
  561. const text = await response.text();
  562. let payload = {};
  563. try {
  564. payload = text ? JSON.parse(text) : {};
  565. } catch {
  566. payload = { raw: text };
  567. }
  568. if (!response.ok || !payload?.access_token) {
  569. const errorText = payload?.error_description || payload?.error?.message || payload?.error || payload?.message || text || `HTTP ${response.status}`;
  570. const error = new Error(`Hotmail 令牌刷新失败:${errorText}`);
  571. error.code = 'HOTMAIL_TOKEN_REFRESH_FAILED';
  572. throw error;
  573. }
  574. const expiresInSeconds = Math.max(60, Number(payload.expires_in || payload.expiresIn || 0) || 3600);
  575. return normalizeHotmailAccount({
  576. ...account,
  577. accessToken: String(payload.access_token || ''),
  578. refreshToken: String(payload.refresh_token || '').trim() || account.refreshToken,
  579. expiresAt: Date.now() + expiresInSeconds * 1000,
  580. status: 'authorized',
  581. lastAuthAt: Date.now(),
  582. lastError: '',
  583. });
  584. }
  585. async function requestHotmailGraphMessages(account, mailbox = 'INBOX') {
  586. const { timeoutMs, pageSize, messageFields } = getHotmailGraphRequestConfig();
  587. const controller = new AbortController();
  588. const timeoutId = setTimeout(() => controller.abort(new Error('timeout')), timeoutMs);
  589. const url = buildHotmailGraphMessagesUrl({
  590. mailbox,
  591. top: pageSize,
  592. selectFields: messageFields,
  593. });
  594. let response;
  595. try {
  596. response = await fetch(url, {
  597. method: 'GET',
  598. headers: {
  599. Accept: 'application/json',
  600. Authorization: `Bearer ${account.accessToken}`,
  601. },
  602. signal: controller.signal,
  603. });
  604. } catch (err) {
  605. const error = new Error(
  606. err?.name === 'AbortError'
  607. ? `Hotmail 邮件请求超时(>${Math.round(timeoutMs / 1000)} 秒):${mailbox}`
  608. : `Hotmail 邮件请求失败:${err.message}`
  609. );
  610. error.code = 'HOTMAIL_GRAPH_REQUEST_FAILED';
  611. throw error;
  612. } finally {
  613. clearTimeout(timeoutId);
  614. }
  615. const text = await response.text();
  616. let payload = {};
  617. try {
  618. payload = text ? JSON.parse(text) : {};
  619. } catch {
  620. payload = { raw: text };
  621. }
  622. if (!response.ok) {
  623. const errorText = payload?.error?.message || payload?.error_description || payload?.message || text || `HTTP ${response.status}`;
  624. const error = new Error(`Hotmail 邮件请求失败:${errorText}`);
  625. error.code = response.status === 401 || response.status === 403
  626. ? 'HOTMAIL_GRAPH_AUTH_FAILED'
  627. : 'HOTMAIL_GRAPH_REQUEST_FAILED';
  628. throw error;
  629. }
  630. return {
  631. mailbox,
  632. payload,
  633. messages: normalizeHotmailMailApiMessages(payload?.value),
  634. };
  635. }
  636. function buildHotmailAuthFailureAccount(account, errorMessage) {
  637. return normalizeHotmailAccount({
  638. ...account,
  639. accessToken: '',
  640. expiresAt: 0,
  641. status: 'error',
  642. lastError: String(errorMessage || ''),
  643. });
  644. }
  645. async function fetchHotmailMailboxMessages(account, mailboxes = HOTMAIL_MAILBOXES) {
  646. let workingAccount = normalizeHotmailAccount(account);
  647. const mailboxResults = [];
  648. try {
  649. if (!isHotmailAccessTokenUsable(workingAccount)) {
  650. workingAccount = await refreshHotmailAccessToken(workingAccount);
  651. }
  652. for (const mailbox of mailboxes) {
  653. let result;
  654. try {
  655. result = await requestHotmailGraphMessages(workingAccount, mailbox);
  656. } catch (err) {
  657. if (err?.code !== 'HOTMAIL_GRAPH_AUTH_FAILED') {
  658. throw err;
  659. }
  660. workingAccount = await refreshHotmailAccessToken({
  661. ...workingAccount,
  662. accessToken: '',
  663. expiresAt: 0,
  664. });
  665. result = await requestHotmailGraphMessages(workingAccount, mailbox);
  666. }
  667. mailboxResults.push({
  668. mailbox,
  669. count: result.messages.length,
  670. messages: result.messages.map((message) => ({ ...message, mailbox })),
  671. });
  672. }
  673. } catch (err) {
  674. if (err?.code === 'HOTMAIL_TOKEN_REFRESH_FAILED' || err?.code === 'HOTMAIL_GRAPH_AUTH_FAILED') {
  675. const failedAccount = buildHotmailAuthFailureAccount(workingAccount, err.message);
  676. await upsertHotmailAccount(failedAccount);
  677. }
  678. throw err;
  679. }
  680. const savedAccount = await upsertHotmailAccount(workingAccount);
  681. return {
  682. account: savedAccount,
  683. mailboxResults,
  684. messages: mailboxResults.flatMap((item) => item.messages),
  685. };
  686. }
  687. async function verifyHotmailAccount(accountId) {
  688. const state = await getState();
  689. const account = findHotmailAccount(state.hotmailAccounts, accountId);
  690. if (!account) {
  691. throw new Error('未找到需要校验的 Hotmail 账号。');
  692. }
  693. const result = await fetchHotmailMailboxMessages(account, ['INBOX']);
  694. return {
  695. account: result.account,
  696. messageCount: result.mailboxResults[0]?.count || 0,
  697. };
  698. }
  699. async function testHotmailAccountMailAccess(accountId) {
  700. const state = await getState();
  701. const account = findHotmailAccount(state.hotmailAccounts, accountId);
  702. if (!account) {
  703. throw new Error('未找到需要测试的 Hotmail 账号。');
  704. }
  705. const result = await fetchHotmailMailboxMessages(account, HOTMAIL_MAILBOXES);
  706. const latestMessage = getLatestHotmailMessage(result.messages);
  707. const latestCode = latestMessage ? extractVerificationCodeFromMessage(latestMessage) : null;
  708. return {
  709. account: result.account,
  710. accountId: result.account.id,
  711. email: result.account.email,
  712. messageCount: result.messages.length,
  713. latestSubject: latestMessage?.subject || '',
  714. latestMailbox: latestMessage?.mailbox || '',
  715. latestCode: latestCode || '',
  716. inboxCount: result.mailboxResults.find((item) => item.mailbox === 'INBOX')?.count || 0,
  717. junkCount: result.mailboxResults.find((item) => item.mailbox === 'Junk')?.count || 0,
  718. };
  719. }
  720. async function pollHotmailVerificationCode(step, state, pollPayload = {}) {
  721. await addLog(`步骤 ${step}:正在确定 Hotmail 收信账号...`, 'info');
  722. let account = await ensureHotmailAccountForFlow({
  723. allowAllocate: true,
  724. markUsed: false,
  725. preferredAccountId: state.currentHotmailAccountId || null,
  726. });
  727. await addLog(`步骤 ${step}:当前使用 Hotmail 账号 ${account.email} 轮询收件箱。`, 'info');
  728. const maxAttempts = Number(pollPayload.maxAttempts) || 5;
  729. const intervalMs = Number(pollPayload.intervalMs) || 3000;
  730. let lastError = null;
  731. function summarizeMessagesForLog(messages) {
  732. return (messages || [])
  733. .slice()
  734. .sort((left, right) => {
  735. const leftTime = Date.parse(left.receivedDateTime || '') || 0;
  736. const rightTime = Date.parse(right.receivedDateTime || '') || 0;
  737. return rightTime - leftTime;
  738. })
  739. .slice(0, 3)
  740. .map((message) => {
  741. const receivedAt = message?.receivedDateTime || '未知时间';
  742. const sender = message?.from?.emailAddress?.address || '未知发件人';
  743. const subject = message?.subject || '(无主题)';
  744. const preview = String(message?.bodyPreview || '').replace(/\s+/g, ' ').trim().slice(0, 80);
  745. return `[${message.mailbox || 'INBOX'}] ${receivedAt} | ${sender} | ${subject} | ${preview}`;
  746. })
  747. .join(' || ');
  748. }
  749. for (let attempt = 1; attempt <= maxAttempts; attempt++) {
  750. throwIfStopped();
  751. try {
  752. await addLog(`步骤 ${step}:正在轮询 Hotmail 邮件(${attempt}/${maxAttempts})...`, 'info');
  753. const fetchResult = await fetchHotmailMailboxMessages(account, HOTMAIL_MAILBOXES);
  754. account = fetchResult.account;
  755. const matchResult = pickVerificationMessageWithTimeFallback(fetchResult.messages, {
  756. afterTimestamp: pollPayload.filterAfterTimestamp || 0,
  757. senderFilters: pollPayload.senderFilters || [],
  758. subjectFilters: pollPayload.subjectFilters || [],
  759. excludeCodes: pollPayload.excludeCodes || [],
  760. });
  761. const match = matchResult.match;
  762. if (match?.code) {
  763. const mailboxLabel = match.message?.mailbox || 'INBOX';
  764. if (matchResult.usedRelaxedFilters) {
  765. const fallbackLabel = matchResult.usedTimeFallback ? '宽松匹配 + 时间回退' : '宽松匹配';
  766. await addLog(`步骤 ${step}:严格规则未命中,已改用 ${fallbackLabel} 并命中 Hotmail ${mailboxLabel} 验证码。`, 'warn');
  767. }
  768. await addLog(`步骤 ${step}:已在 Hotmail ${mailboxLabel} 中找到验证码:${match.code}`, 'ok');
  769. return {
  770. ok: true,
  771. code: match.code,
  772. emailTimestamp: match.receivedAt || Date.now(),
  773. mailId: match.message?.id || '',
  774. };
  775. }
  776. lastError = new Error(`步骤 ${step}:暂未在 Hotmail 收件箱中找到匹配验证码(${attempt}/${maxAttempts})。`);
  777. await addLog(lastError.message, attempt === maxAttempts ? 'warn' : 'info');
  778. const mailSummary = summarizeMessagesForLog(fetchResult.messages);
  779. if (mailSummary) {
  780. await addLog(`步骤 ${step}:最近邮件样本:${mailSummary}`, 'info');
  781. }
  782. } catch (err) {
  783. lastError = err;
  784. await addLog(`步骤 ${step}:Hotmail 收件箱轮询失败:${err.message}`, 'warn');
  785. }
  786. if (attempt < maxAttempts) {
  787. await sleepWithStop(intervalMs);
  788. }
  789. }
  790. throw lastError || new Error(`步骤 ${step}:未在 Hotmail 收件箱中找到新的匹配验证码。`);
  791. }
  792. // ============================================================
  793. // Tab Registry
  794. // ============================================================
  795. async function getTabRegistry() {
  796. const state = await getState();
  797. return state.tabRegistry || {};
  798. }
  799. async function registerTab(source, tabId) {
  800. const registry = await getTabRegistry();
  801. registry[source] = { tabId, ready: true };
  802. await setState({ tabRegistry: registry });
  803. console.log(LOG_PREFIX, `Tab registered: ${source} -> ${tabId}`);
  804. }
  805. async function isTabAlive(source) {
  806. const registry = await getTabRegistry();
  807. const entry = registry[source];
  808. if (!entry) return false;
  809. try {
  810. await chrome.tabs.get(entry.tabId);
  811. return true;
  812. } catch {
  813. // Tab no longer exists — clean up registry
  814. registry[source] = null;
  815. await setState({ tabRegistry: registry });
  816. return false;
  817. }
  818. }
  819. async function getTabId(source) {
  820. const registry = await getTabRegistry();
  821. return registry[source]?.tabId || null;
  822. }
  823. function parseUrlSafely(rawUrl) {
  824. if (!rawUrl) return null;
  825. try {
  826. return new URL(rawUrl);
  827. } catch {
  828. return null;
  829. }
  830. }
  831. function normalizeSub2ApiUrl(rawUrl) {
  832. const input = (rawUrl || '').trim() || DEFAULT_SUB2API_URL;
  833. const withProtocol = /^https?:\/\//i.test(input) ? input : `https://${input}`;
  834. const parsed = new URL(withProtocol);
  835. if (!parsed.pathname || parsed.pathname === '/') {
  836. parsed.pathname = '/admin/accounts';
  837. }
  838. parsed.hash = '';
  839. return parsed.toString();
  840. }
  841. function getPanelMode(state = {}) {
  842. return state.panelMode === 'sub2api' ? 'sub2api' : 'cpa';
  843. }
  844. function getPanelModeLabel(modeOrState) {
  845. const mode = typeof modeOrState === 'string' ? modeOrState : getPanelMode(modeOrState);
  846. return mode === 'sub2api' ? 'SUB2API' : 'CPA';
  847. }
  848. function isSignupPageHost(hostname = '') {
  849. return ['auth0.openai.com', 'auth.openai.com', 'accounts.openai.com'].includes(hostname);
  850. }
  851. function is163MailHost(hostname = '') {
  852. return hostname === 'mail.163.com'
  853. || hostname.endsWith('.mail.163.com')
  854. || hostname === 'webmail.vip.163.com';
  855. }
  856. function isLocalhostOAuthCallbackUrl(rawUrl) {
  857. const parsed = parseUrlSafely(rawUrl);
  858. if (!parsed) return false;
  859. if (!['http:', 'https:'].includes(parsed.protocol)) return false;
  860. if (!['localhost', '127.0.0.1'].includes(parsed.hostname)) return false;
  861. if (!['/auth/callback', '/codex/callback'].includes(parsed.pathname)) return false;
  862. const code = (parsed.searchParams.get('code') || '').trim();
  863. const state = (parsed.searchParams.get('state') || '').trim();
  864. return Boolean(code && state);
  865. }
  866. function isLocalCpaUrl(rawUrl) {
  867. const parsed = parseUrlSafely(rawUrl);
  868. if (!parsed) return false;
  869. if (!['http:', 'https:'].includes(parsed.protocol)) return false;
  870. return ['localhost', '127.0.0.1'].includes(parsed.hostname);
  871. }
  872. function shouldBypassStep9ForLocalCpa(state) {
  873. return Boolean(state?.localhostUrl) && isLocalCpaUrl(state?.vpsUrl);
  874. }
  875. function matchesSourceUrlFamily(source, candidateUrl, referenceUrl) {
  876. const candidate = parseUrlSafely(candidateUrl);
  877. if (!candidate) return false;
  878. const reference = parseUrlSafely(referenceUrl);
  879. switch (source) {
  880. case 'signup-page':
  881. return isSignupPageHost(candidate.hostname);
  882. case 'duck-mail':
  883. return candidate.hostname === 'duckduckgo.com' && candidate.pathname.startsWith('/email/');
  884. case 'qq-mail':
  885. return candidate.hostname === 'mail.qq.com' || candidate.hostname === 'wx.mail.qq.com';
  886. case 'mail-163':
  887. return is163MailHost(candidate.hostname);
  888. case 'inbucket-mail':
  889. return Boolean(reference)
  890. && candidate.origin === reference.origin
  891. && candidate.pathname.startsWith('/m/');
  892. case 'vps-panel':
  893. return Boolean(reference)
  894. && candidate.origin === reference.origin
  895. && candidate.pathname === reference.pathname;
  896. case 'sub2api-panel':
  897. return Boolean(reference)
  898. && candidate.origin === reference.origin
  899. && (
  900. candidate.pathname.startsWith('/admin/accounts')
  901. || candidate.pathname.startsWith('/login')
  902. || candidate.pathname === '/'
  903. );
  904. default:
  905. return false;
  906. }
  907. }
  908. async function rememberSourceLastUrl(source, url) {
  909. if (!source || !url) return;
  910. const state = await getState();
  911. const sourceLastUrls = { ...(state.sourceLastUrls || {}) };
  912. sourceLastUrls[source] = url;
  913. await setState({ sourceLastUrls });
  914. }
  915. async function closeConflictingTabsForSource(source, currentUrl, options = {}) {
  916. const { excludeTabIds = [] } = options;
  917. const excluded = new Set(excludeTabIds.filter(id => Number.isInteger(id)));
  918. const state = await getState();
  919. const lastUrl = state.sourceLastUrls?.[source];
  920. const referenceUrls = [currentUrl, lastUrl].filter(Boolean);
  921. if (!referenceUrls.length) return;
  922. const tabs = await chrome.tabs.query({});
  923. const matchedIds = tabs
  924. .filter((tab) => Number.isInteger(tab.id) && !excluded.has(tab.id))
  925. .filter((tab) => referenceUrls.some((refUrl) => matchesSourceUrlFamily(source, tab.url, refUrl)))
  926. .map(tab => tab.id);
  927. if (!matchedIds.length) return;
  928. await chrome.tabs.remove(matchedIds).catch(() => { });
  929. const registry = await getTabRegistry();
  930. if (registry[source]?.tabId && matchedIds.includes(registry[source].tabId)) {
  931. registry[source] = null;
  932. await setState({ tabRegistry: registry });
  933. }
  934. await addLog(`已关闭 ${matchedIds.length} 个旧的${getSourceLabel(source)}标签页。`, 'info');
  935. }
  936. function isLocalhostOAuthCallbackTabMatch(callbackUrl, candidateUrl) {
  937. if (!isLocalhostOAuthCallbackUrl(callbackUrl) || !isLocalhostOAuthCallbackUrl(candidateUrl)) {
  938. return false;
  939. }
  940. const callback = parseUrlSafely(callbackUrl);
  941. const candidate = parseUrlSafely(candidateUrl);
  942. if (!callback || !candidate) return false;
  943. return callback.origin === candidate.origin
  944. && callback.pathname === candidate.pathname
  945. && callback.searchParams.get('code') === candidate.searchParams.get('code')
  946. && callback.searchParams.get('state') === candidate.searchParams.get('state');
  947. }
  948. async function closeLocalhostCallbackTabs(callbackUrl, options = {}) {
  949. if (!isLocalhostOAuthCallbackUrl(callbackUrl)) return 0;
  950. const { excludeTabIds = [] } = options;
  951. const excluded = new Set(excludeTabIds.filter(id => Number.isInteger(id)));
  952. const tabs = await chrome.tabs.query({});
  953. const matchedIds = tabs
  954. .filter((tab) => Number.isInteger(tab.id) && !excluded.has(tab.id))
  955. .filter((tab) => isLocalhostOAuthCallbackTabMatch(callbackUrl, tab.url))
  956. .map((tab) => tab.id);
  957. if (!matchedIds.length) return 0;
  958. await chrome.tabs.remove(matchedIds).catch(() => { });
  959. const registry = await getTabRegistry();
  960. if (registry['signup-page']?.tabId && matchedIds.includes(registry['signup-page'].tabId)) {
  961. registry['signup-page'] = null;
  962. await setState({ tabRegistry: registry });
  963. }
  964. await addLog(`已关闭 ${matchedIds.length} 个匹配当前 OAuth callback 的 localhost 残留标签页。`, 'info');
  965. return matchedIds.length;
  966. }
  967. async function pingContentScriptOnTab(tabId) {
  968. if (!Number.isInteger(tabId)) return null;
  969. try {
  970. return await chrome.tabs.sendMessage(tabId, {
  971. type: 'PING',
  972. source: 'background',
  973. payload: {},
  974. });
  975. } catch {
  976. return null;
  977. }
  978. }
  979. async function waitForTabUrlFamily(source, tabId, referenceUrl, options = {}) {
  980. const { timeoutMs = 15000, retryDelayMs = 400 } = options;
  981. const start = Date.now();
  982. while (Date.now() - start < timeoutMs) {
  983. try {
  984. const tab = await chrome.tabs.get(tabId);
  985. if (matchesSourceUrlFamily(source, tab.url, referenceUrl)) {
  986. return tab;
  987. }
  988. } catch {
  989. return null;
  990. }
  991. await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
  992. }
  993. return null;
  994. }
  995. async function ensureContentScriptReadyOnTab(source, tabId, options = {}) {
  996. const {
  997. inject = null,
  998. injectSource = null,
  999. timeoutMs = 30000,
  1000. retryDelayMs = 700,
  1001. logMessage = '',
  1002. } = options;
  1003. const start = Date.now();
  1004. let lastError = null;
  1005. let logged = false;
  1006. let attempt = 0;
  1007. console.log(
  1008. LOG_PREFIX,
  1009. `[ensureContentScriptReadyOnTab] start ${source} tab=${tabId}, timeout=${timeoutMs}ms, inject=${Array.isArray(inject) ? inject.join(',') : 'none'}`
  1010. );
  1011. while (Date.now() - start < timeoutMs) {
  1012. attempt += 1;
  1013. const pong = await pingContentScriptOnTab(tabId);
  1014. if (pong?.ok && (!pong.source || pong.source === source)) {
  1015. console.log(
  1016. LOG_PREFIX,
  1017. `[ensureContentScriptReadyOnTab] ready ${source} tab=${tabId} on attempt ${attempt} after ${Date.now() - start}ms`
  1018. );
  1019. await registerTab(source, tabId);
  1020. return;
  1021. }
  1022. if (!inject || !inject.length) {
  1023. throw new Error(`${getSourceLabel(source)} 内容脚本未就绪,且未提供可用的注入文件。`);
  1024. }
  1025. const registry = await getTabRegistry();
  1026. if (registry[source]) {
  1027. registry[source].ready = false;
  1028. await setState({ tabRegistry: registry });
  1029. }
  1030. try {
  1031. if (injectSource) {
  1032. await chrome.scripting.executeScript({
  1033. target: { tabId },
  1034. func: (injectedSource) => {
  1035. window.__MULTIPAGE_SOURCE = injectedSource;
  1036. },
  1037. args: [injectSource],
  1038. });
  1039. }
  1040. await chrome.scripting.executeScript({
  1041. target: { tabId },
  1042. files: inject,
  1043. });
  1044. } catch (err) {
  1045. lastError = err;
  1046. console.warn(
  1047. LOG_PREFIX,
  1048. `[ensureContentScriptReadyOnTab] inject attempt ${attempt} failed for ${source} tab=${tabId}: ${err?.message || err}`
  1049. );
  1050. }
  1051. const pongAfterInject = await pingContentScriptOnTab(tabId);
  1052. if (pongAfterInject?.ok && (!pongAfterInject.source || pongAfterInject.source === source)) {
  1053. console.log(
  1054. LOG_PREFIX,
  1055. `[ensureContentScriptReadyOnTab] ready after inject ${source} tab=${tabId} on attempt ${attempt} after ${Date.now() - start}ms`
  1056. );
  1057. await registerTab(source, tabId);
  1058. return;
  1059. }
  1060. if (logMessage && !logged) {
  1061. console.warn(
  1062. LOG_PREFIX,
  1063. `[ensureContentScriptReadyOnTab] ${source} tab=${tabId} still not ready after ${Date.now() - start}ms`
  1064. );
  1065. await addLog(logMessage, 'warn');
  1066. logged = true;
  1067. }
  1068. await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
  1069. }
  1070. throw lastError || new Error(`${getSourceLabel(source)} 内容脚本长时间未就绪。`);
  1071. }
  1072. // ============================================================
  1073. // Command Queue (for content scripts not yet ready)
  1074. // ============================================================
  1075. const pendingCommands = new Map(); // source -> { message, resolve, reject, timer }
  1076. function getContentScriptResponseTimeoutMs(message) {
  1077. if (!message || typeof message !== 'object') {
  1078. return 30000;
  1079. }
  1080. if (message.type === 'POLL_EMAIL') {
  1081. const maxAttempts = Math.max(1, Number(message.payload?.maxAttempts) || 1);
  1082. const intervalMs = Math.max(0, Number(message.payload?.intervalMs) || 0);
  1083. return Math.max(45000, maxAttempts * intervalMs + 25000);
  1084. }
  1085. if (message.type === 'FILL_CODE') {
  1086. return Number(message.step) === 7 ? 45000 : 30000;
  1087. }
  1088. if (message.type === 'PREPARE_SIGNUP_VERIFICATION') {
  1089. return 45000;
  1090. }
  1091. return 30000;
  1092. }
  1093. function getMessageDebugLabel(source, message, tabId = null) {
  1094. const parts = [source || 'unknown', message?.type || 'UNKNOWN'];
  1095. if (Number.isInteger(message?.step)) {
  1096. parts.push(`step=${message.step}`);
  1097. }
  1098. if (Number.isInteger(tabId)) {
  1099. parts.push(`tab=${tabId}`);
  1100. }
  1101. return parts.join(' ');
  1102. }
  1103. function summarizeMessageResultForDebug(result) {
  1104. if (result === undefined) return 'undefined';
  1105. if (result === null) return 'null';
  1106. if (typeof result !== 'object') return JSON.stringify(result);
  1107. const summary = {};
  1108. for (const key of ['ok', 'error', 'stopped', 'source', 'step']) {
  1109. if (key in result) summary[key] = result[key];
  1110. }
  1111. if (result.payload && typeof result.payload === 'object') {
  1112. summary.payloadKeys = Object.keys(result.payload);
  1113. }
  1114. return JSON.stringify(summary);
  1115. }
  1116. function sendTabMessageWithTimeout(tabId, source, message, responseTimeoutMs = getContentScriptResponseTimeoutMs(message)) {
  1117. return new Promise((resolve, reject) => {
  1118. let settled = false;
  1119. const startedAt = Date.now();
  1120. const debugLabel = getMessageDebugLabel(source, message, tabId);
  1121. console.log(LOG_PREFIX, `[sendTabMessageWithTimeout] dispatch ${debugLabel}, timeout=${responseTimeoutMs}ms`);
  1122. const timer = setTimeout(() => {
  1123. if (settled) return;
  1124. settled = true;
  1125. const seconds = Math.ceil(responseTimeoutMs / 1000);
  1126. console.warn(LOG_PREFIX, `[sendTabMessageWithTimeout] timeout ${debugLabel} after ${Date.now() - startedAt}ms`);
  1127. reject(new Error(`Content script on ${source} did not respond in ${seconds}s. Try refreshing the tab and retry.`));
  1128. }, responseTimeoutMs);
  1129. chrome.tabs.sendMessage(tabId, message)
  1130. .then((value) => {
  1131. const elapsed = Date.now() - startedAt;
  1132. if (settled) {
  1133. console.warn(
  1134. LOG_PREFIX,
  1135. `[sendTabMessageWithTimeout] late response ignored for ${debugLabel} after ${elapsed}ms: ${summarizeMessageResultForDebug(value)}`
  1136. );
  1137. return;
  1138. }
  1139. settled = true;
  1140. clearTimeout(timer);
  1141. console.log(
  1142. LOG_PREFIX,
  1143. `[sendTabMessageWithTimeout] response ${debugLabel} after ${elapsed}ms: ${summarizeMessageResultForDebug(value)}`
  1144. );
  1145. resolve(value);
  1146. })
  1147. .catch((error) => {
  1148. const elapsed = Date.now() - startedAt;
  1149. const errorMessage = error?.message || String(error);
  1150. if (settled) {
  1151. console.warn(
  1152. LOG_PREFIX,
  1153. `[sendTabMessageWithTimeout] late rejection ignored for ${debugLabel} after ${elapsed}ms: ${errorMessage}`
  1154. );
  1155. return;
  1156. }
  1157. settled = true;
  1158. clearTimeout(timer);
  1159. console.warn(
  1160. LOG_PREFIX,
  1161. `[sendTabMessageWithTimeout] rejection ${debugLabel} after ${elapsed}ms: ${errorMessage}`
  1162. );
  1163. reject(error);
  1164. });
  1165. });
  1166. }
  1167. function queueCommand(source, message, timeout = 15000) {
  1168. return new Promise((resolve, reject) => {
  1169. const timer = setTimeout(() => {
  1170. pendingCommands.delete(source);
  1171. const err = `Content script on ${source} did not respond in ${timeout / 1000}s. Try refreshing the tab and retry.`;
  1172. console.error(LOG_PREFIX, err);
  1173. reject(new Error(err));
  1174. }, timeout);
  1175. pendingCommands.set(source, { message, resolve, reject, timer });
  1176. console.log(LOG_PREFIX, `Command queued for ${source} (waiting for ready)`);
  1177. });
  1178. }
  1179. function flushCommand(source, tabId) {
  1180. const pending = pendingCommands.get(source);
  1181. if (pending) {
  1182. clearTimeout(pending.timer);
  1183. pendingCommands.delete(source);
  1184. sendTabMessageWithTimeout(tabId, source, pending.message).then(pending.resolve).catch(pending.reject);
  1185. console.log(LOG_PREFIX, `Flushed queued command to ${source} (tab ${tabId})`);
  1186. }
  1187. }
  1188. function cancelPendingCommands(reason = STOP_ERROR_MESSAGE) {
  1189. for (const [source, pending] of pendingCommands.entries()) {
  1190. clearTimeout(pending.timer);
  1191. pending.reject(new Error(reason));
  1192. pendingCommands.delete(source);
  1193. console.log(LOG_PREFIX, `Cancelled queued command for ${source}`);
  1194. }
  1195. }
  1196. // ============================================================
  1197. // Reuse or create tab
  1198. // ============================================================
  1199. async function reuseOrCreateTab(source, url, options = {}) {
  1200. const alive = await isTabAlive(source);
  1201. if (alive) {
  1202. const tabId = await getTabId(source);
  1203. await closeConflictingTabsForSource(source, url, { excludeTabIds: [tabId] });
  1204. const currentTab = await chrome.tabs.get(tabId);
  1205. const sameUrl = currentTab.url === url;
  1206. const shouldReloadOnReuse = sameUrl && options.reloadIfSameUrl;
  1207. const registry = await getTabRegistry();
  1208. if (sameUrl) {
  1209. await chrome.tabs.update(tabId, { active: true });
  1210. console.log(LOG_PREFIX, `Reused tab ${source} (${tabId}) on same URL`);
  1211. if (shouldReloadOnReuse) {
  1212. if (registry[source]) registry[source].ready = false;
  1213. await setState({ tabRegistry: registry });
  1214. await chrome.tabs.reload(tabId);
  1215. await new Promise((resolve) => {
  1216. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  1217. const listener = (tid, info) => {
  1218. if (tid === tabId && info.status === 'complete') {
  1219. chrome.tabs.onUpdated.removeListener(listener);
  1220. clearTimeout(timer);
  1221. resolve();
  1222. }
  1223. };
  1224. chrome.tabs.onUpdated.addListener(listener);
  1225. });
  1226. }
  1227. // For dynamically injected pages like the VPS panel, re-inject immediately.
  1228. if (options.inject) {
  1229. if (registry[source]) registry[source].ready = false;
  1230. await setState({ tabRegistry: registry });
  1231. if (options.injectSource) {
  1232. await chrome.scripting.executeScript({
  1233. target: { tabId },
  1234. func: (injectedSource) => {
  1235. window.__MULTIPAGE_SOURCE = injectedSource;
  1236. },
  1237. args: [options.injectSource],
  1238. });
  1239. }
  1240. await chrome.scripting.executeScript({
  1241. target: { tabId },
  1242. files: options.inject,
  1243. });
  1244. await new Promise(r => setTimeout(r, 500));
  1245. }
  1246. await rememberSourceLastUrl(source, url);
  1247. return tabId;
  1248. }
  1249. // Mark as not ready BEFORE navigating — so READY signal from new page is captured correctly
  1250. if (registry[source]) registry[source].ready = false;
  1251. await setState({ tabRegistry: registry });
  1252. // Navigate existing tab to new URL
  1253. await chrome.tabs.update(tabId, { url, active: true });
  1254. console.log(LOG_PREFIX, `Reused tab ${source} (${tabId}), navigated to ${url.slice(0, 60)}`);
  1255. // Wait for page load complete (with 30s timeout)
  1256. await new Promise((resolve) => {
  1257. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  1258. const listener = (tid, info) => {
  1259. if (tid === tabId && info.status === 'complete') {
  1260. chrome.tabs.onUpdated.removeListener(listener);
  1261. clearTimeout(timer);
  1262. resolve();
  1263. }
  1264. };
  1265. chrome.tabs.onUpdated.addListener(listener);
  1266. });
  1267. // If dynamic injection needed (VPS panel), re-inject after navigation
  1268. if (options.inject) {
  1269. if (options.injectSource) {
  1270. await chrome.scripting.executeScript({
  1271. target: { tabId },
  1272. func: (injectedSource) => {
  1273. window.__MULTIPAGE_SOURCE = injectedSource;
  1274. },
  1275. args: [options.injectSource],
  1276. });
  1277. }
  1278. await chrome.scripting.executeScript({
  1279. target: { tabId },
  1280. files: options.inject,
  1281. });
  1282. }
  1283. // Wait a bit for content script to inject and send READY
  1284. await new Promise(r => setTimeout(r, 500));
  1285. await rememberSourceLastUrl(source, url);
  1286. return tabId;
  1287. }
  1288. // Create new tab
  1289. await closeConflictingTabsForSource(source, url);
  1290. const tab = await chrome.tabs.create({ url, active: true });
  1291. console.log(LOG_PREFIX, `Created new tab ${source} (${tab.id})`);
  1292. // If dynamic injection needed (VPS panel), inject scripts after load
  1293. if (options.inject) {
  1294. await new Promise((resolve) => {
  1295. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  1296. const listener = (tabId, info) => {
  1297. if (tabId === tab.id && info.status === 'complete') {
  1298. chrome.tabs.onUpdated.removeListener(listener);
  1299. clearTimeout(timer);
  1300. resolve();
  1301. }
  1302. };
  1303. chrome.tabs.onUpdated.addListener(listener);
  1304. });
  1305. if (options.injectSource) {
  1306. await chrome.scripting.executeScript({
  1307. target: { tabId: tab.id },
  1308. func: (injectedSource) => {
  1309. window.__MULTIPAGE_SOURCE = injectedSource;
  1310. },
  1311. args: [options.injectSource],
  1312. });
  1313. }
  1314. await chrome.scripting.executeScript({
  1315. target: { tabId: tab.id },
  1316. files: options.inject,
  1317. });
  1318. }
  1319. await rememberSourceLastUrl(source, url);
  1320. return tab.id;
  1321. }
  1322. // ============================================================
  1323. // Send command to content script (with readiness check)
  1324. // ============================================================
  1325. async function sendToContentScript(source, message, options = {}) {
  1326. const { responseTimeoutMs = getContentScriptResponseTimeoutMs(message) } = options;
  1327. const registry = await getTabRegistry();
  1328. const entry = registry[source];
  1329. if (!entry || !entry.ready) {
  1330. console.log(LOG_PREFIX, `${source} not ready, queuing command`);
  1331. return queueCommand(source, message);
  1332. }
  1333. // Verify tab is still alive
  1334. const alive = await isTabAlive(source);
  1335. if (!alive) {
  1336. // Tab was closed — queue the command, it will be sent when tab is reopened
  1337. console.log(LOG_PREFIX, `${source} tab was closed, queuing command`);
  1338. return queueCommand(source, message);
  1339. }
  1340. console.log(LOG_PREFIX, `Sending to ${source} (tab ${entry.tabId}):`, message.type);
  1341. return sendTabMessageWithTimeout(entry.tabId, source, message, responseTimeoutMs);
  1342. }
  1343. async function sendToContentScriptResilient(source, message, options = {}) {
  1344. const { timeoutMs = 30000, retryDelayMs = 600, logMessage = '' } = options;
  1345. const start = Date.now();
  1346. let lastError = null;
  1347. let logged = false;
  1348. let attempt = 0;
  1349. const debugLabel = getMessageDebugLabel(source, message);
  1350. console.log(
  1351. LOG_PREFIX,
  1352. `[sendToContentScriptResilient] start ${debugLabel}, totalTimeout=${timeoutMs}ms, retryDelay=${retryDelayMs}ms`
  1353. );
  1354. while (Date.now() - start < timeoutMs) {
  1355. throwIfStopped();
  1356. attempt += 1;
  1357. try {
  1358. console.log(
  1359. LOG_PREFIX,
  1360. `[sendToContentScriptResilient] attempt ${attempt} -> ${debugLabel}, elapsed=${Date.now() - start}ms`
  1361. );
  1362. const result = await sendToContentScript(source, message);
  1363. console.log(
  1364. LOG_PREFIX,
  1365. `[sendToContentScriptResilient] success ${debugLabel} on attempt ${attempt} after ${Date.now() - start}ms`
  1366. );
  1367. return result;
  1368. } catch (err) {
  1369. const retryable = isRetryableContentScriptTransportError(err);
  1370. console.warn(
  1371. LOG_PREFIX,
  1372. `[sendToContentScriptResilient] attempt ${attempt} failed for ${debugLabel}, retryable=${retryable}, elapsed=${Date.now() - start}ms: ${err?.message || err}`
  1373. );
  1374. if (!retryable) {
  1375. throw err;
  1376. }
  1377. lastError = err;
  1378. if (logMessage && !logged) {
  1379. await addLog(logMessage, 'warn');
  1380. logged = true;
  1381. }
  1382. await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
  1383. }
  1384. }
  1385. throw lastError || new Error(`等待 ${getSourceLabel(source)} 重新就绪超时。`);
  1386. }
  1387. async function sendToMailContentScriptResilient(mail, message, options = {}) {
  1388. const { timeoutMs = 45000, maxRecoveryAttempts = 2 } = options;
  1389. const start = Date.now();
  1390. let lastError = null;
  1391. let recoveries = 0;
  1392. let logged = false;
  1393. while (Date.now() - start < timeoutMs) {
  1394. throwIfStopped();
  1395. try {
  1396. return await sendToContentScript(mail.source, message);
  1397. } catch (err) {
  1398. if (!isRetryableContentScriptTransportError(err)) {
  1399. throw err;
  1400. }
  1401. lastError = err;
  1402. if (!logged) {
  1403. await addLog(`步骤 ${message.step}:${mail.label} 页面通信异常,正在尝试让邮箱页重新就绪...`, 'warn');
  1404. logged = true;
  1405. }
  1406. if (recoveries >= maxRecoveryAttempts) {
  1407. break;
  1408. }
  1409. recoveries += 1;
  1410. await reuseOrCreateTab(mail.source, mail.url, {
  1411. inject: mail.inject,
  1412. injectSource: mail.injectSource,
  1413. reloadIfSameUrl: true,
  1414. });
  1415. await new Promise((resolve) => setTimeout(resolve, 800));
  1416. }
  1417. }
  1418. throw lastError || new Error(`${mail.label} 页面未能重新就绪。`);
  1419. }
  1420. // ============================================================
  1421. // Logging
  1422. // ============================================================
  1423. async function addLog(message, level = 'info') {
  1424. const state = await getState();
  1425. const logs = state.logs || [];
  1426. const entry = { message, level, timestamp: Date.now() };
  1427. logs.push(entry);
  1428. // Keep last 500 logs
  1429. if (logs.length > 500) logs.splice(0, logs.length - 500);
  1430. await setState({ logs });
  1431. // Broadcast to side panel
  1432. chrome.runtime.sendMessage({ type: 'LOG_ENTRY', payload: entry }).catch(() => { });
  1433. }
  1434. function getStep8CallbackUrlFromNavigation(details, signupTabId) {
  1435. if (!Number.isInteger(signupTabId) || !details) return '';
  1436. if (details.tabId !== signupTabId) return '';
  1437. if (details.frameId !== 0) return '';
  1438. return isLocalhostOAuthCallbackUrl(details.url) ? details.url : '';
  1439. }
  1440. function getStep8CallbackUrlFromTabUpdate(tabId, changeInfo, tab, signupTabId) {
  1441. if (!Number.isInteger(signupTabId) || tabId !== signupTabId) return '';
  1442. const candidates = [changeInfo?.url, tab?.url];
  1443. for (const candidate of candidates) {
  1444. if (isLocalhostOAuthCallbackUrl(candidate)) {
  1445. return candidate;
  1446. }
  1447. }
  1448. return '';
  1449. }
  1450. function getSourceLabel(source) {
  1451. const labels = {
  1452. 'sidepanel': '侧边栏',
  1453. 'signup-page': '认证页',
  1454. 'vps-panel': 'CPA 面板',
  1455. 'sub2api-panel': 'SUB2API 后台',
  1456. 'qq-mail': 'QQ 邮箱',
  1457. 'mail-163': '163 邮箱',
  1458. 'inbucket-mail': 'Inbucket 邮箱',
  1459. 'duck-mail': 'Duck 邮箱',
  1460. 'hotmail-api': 'Hotmail(微软 Graph)',
  1461. };
  1462. return labels[source] || source || '未知来源';
  1463. }
  1464. // ============================================================
  1465. // Step Status Management
  1466. // ============================================================
  1467. async function setStepStatus(step, status) {
  1468. const state = await getState();
  1469. const statuses = { ...state.stepStatuses };
  1470. statuses[step] = status;
  1471. await setState({ stepStatuses: statuses, currentStep: step });
  1472. // Broadcast to side panel
  1473. chrome.runtime.sendMessage({
  1474. type: 'STEP_STATUS_CHANGED',
  1475. payload: { step, status },
  1476. }).catch(() => { });
  1477. }
  1478. function isStopError(error) {
  1479. const message = typeof error === 'string' ? error : error?.message;
  1480. return message === STOP_ERROR_MESSAGE;
  1481. }
  1482. function isRetryableContentScriptTransportError(error) {
  1483. const message = String(typeof error === 'string' ? error : error?.message || '');
  1484. 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);
  1485. }
  1486. function getErrorMessage(error) {
  1487. return String(typeof error === 'string' ? error : error?.message || '');
  1488. }
  1489. function isVerificationMailPollingError(error) {
  1490. const message = getErrorMessage(error);
  1491. return /未在 .*邮箱中找到新的匹配邮件|未在 Hotmail 收件箱中找到新的匹配验证码|邮箱轮询结束,但未获取到验证码|无法获取新的(?:注册|登录)验证码|页面未能重新就绪|页面通信异常|did not respond in \d+s/i.test(message);
  1492. }
  1493. const STEP7_RESTART_FROM_STEP6_ERROR_CODE = 'STEP7_RESTART_FROM_STEP6';
  1494. const STEP7_RESTART_FROM_STEP6_MARKER_PATTERN = /^STEP7_RESTART_FROM_STEP6::([^:]+)::(.*)$/;
  1495. function createStep7RestartFromStep6Error(details = {}) {
  1496. const { reason = 'unknown', url = '' } = details || {};
  1497. const reasonLabel = reason === 'login_timeout_error_page'
  1498. ? '检测到登录页超时报错'
  1499. : '步骤 7 请求回到步骤 6';
  1500. const error = new Error(`步骤 7:${reasonLabel}。${url ? `URL: ${url}` : ''}`.trim());
  1501. error.code = STEP7_RESTART_FROM_STEP6_ERROR_CODE;
  1502. error.restartReason = reason;
  1503. error.restartUrl = url;
  1504. return error;
  1505. }
  1506. function parseStep7RestartFromStep6Marker(message) {
  1507. const normalized = getErrorMessage(message);
  1508. const match = normalized.match(STEP7_RESTART_FROM_STEP6_MARKER_PATTERN);
  1509. if (!match) {
  1510. return null;
  1511. }
  1512. return {
  1513. reason: match[1] || 'unknown',
  1514. url: match[2] || '',
  1515. };
  1516. }
  1517. function getStep7RestartFromStep6Error(result) {
  1518. if (result?.restartFromStep6) {
  1519. return createStep7RestartFromStep6Error(result);
  1520. }
  1521. const parsed = parseStep7RestartFromStep6Marker(result?.error);
  1522. if (!parsed) {
  1523. return null;
  1524. }
  1525. return createStep7RestartFromStep6Error(parsed);
  1526. }
  1527. function isStep7RestartFromStep6Error(error) {
  1528. return error?.code === STEP7_RESTART_FROM_STEP6_ERROR_CODE
  1529. || Boolean(parseStep7RestartFromStep6Marker(error));
  1530. }
  1531. function isStep7RecoverableError(error) {
  1532. return isVerificationMailPollingError(error) || isStep7RestartFromStep6Error(error);
  1533. }
  1534. function isRestartCurrentAttemptError(error) {
  1535. const message = String(typeof error === 'string' ? error : error?.message || '');
  1536. return /当前邮箱已存在,需要重新开始新一轮/.test(message);
  1537. }
  1538. function isStep9RecoverableAuthError(error) {
  1539. const message = String(typeof error === 'string' ? error : error?.message || '');
  1540. return /STEP9_OAUTH_RETRY::/i.test(message)
  1541. || isRecoverableStep9AuthFailure(message);
  1542. }
  1543. function isLegacyStep9RecoverableAuthError(error) {
  1544. const message = String(typeof error === 'string' ? error : error?.message || '');
  1545. return /STEP9_OAUTH_TIMEOUT::|认证失败:\s*Timeout waiting for OAuth callback/i.test(message);
  1546. }
  1547. function isStepDoneStatus(status) {
  1548. return status === 'completed' || status === 'manual_completed' || status === 'skipped';
  1549. }
  1550. function getFirstUnfinishedStep(statuses = {}) {
  1551. for (let step = 1; step <= 9; step++) {
  1552. if (!isStepDoneStatus(statuses[step] || 'pending')) {
  1553. return step;
  1554. }
  1555. }
  1556. return null;
  1557. }
  1558. function hasSavedProgress(statuses = {}) {
  1559. return Object.values({ ...DEFAULT_STATE.stepStatuses, ...statuses }).some((status) => status !== 'pending');
  1560. }
  1561. function getDownstreamStateResets(step) {
  1562. if (step <= 1) {
  1563. return {
  1564. oauthUrl: null,
  1565. sub2apiSessionId: null,
  1566. sub2apiOAuthState: null,
  1567. sub2apiGroupId: null,
  1568. sub2apiDraftName: null,
  1569. flowStartTime: null,
  1570. password: null,
  1571. lastEmailTimestamp: null,
  1572. signupVerificationRequestedAt: null,
  1573. loginVerificationRequestedAt: null,
  1574. lastSignupCode: null,
  1575. lastLoginCode: null,
  1576. localhostUrl: null,
  1577. };
  1578. }
  1579. if (step === 2) {
  1580. return {
  1581. password: null,
  1582. lastEmailTimestamp: null,
  1583. signupVerificationRequestedAt: null,
  1584. loginVerificationRequestedAt: null,
  1585. lastSignupCode: null,
  1586. lastLoginCode: null,
  1587. localhostUrl: null,
  1588. };
  1589. }
  1590. if (step === 3 || step === 4) {
  1591. return {
  1592. lastEmailTimestamp: null,
  1593. signupVerificationRequestedAt: null,
  1594. loginVerificationRequestedAt: null,
  1595. lastSignupCode: null,
  1596. lastLoginCode: null,
  1597. localhostUrl: null,
  1598. };
  1599. }
  1600. if (step === 5 || step === 6 || step === 7) {
  1601. return {
  1602. lastLoginCode: null,
  1603. loginVerificationRequestedAt: null,
  1604. localhostUrl: null,
  1605. };
  1606. }
  1607. if (step === 8) {
  1608. return {
  1609. localhostUrl: null,
  1610. };
  1611. }
  1612. return {};
  1613. }
  1614. async function invalidateDownstreamAfterStepRestart(step, options = {}) {
  1615. const { logLabel = `步骤 ${step} 重新执行` } = options;
  1616. const state = await getState();
  1617. const statuses = { ...(state.stepStatuses || {}) };
  1618. const changedSteps = [];
  1619. for (let downstream = step + 1; downstream <= 9; downstream++) {
  1620. if (statuses[downstream] !== 'pending') {
  1621. statuses[downstream] = 'pending';
  1622. changedSteps.push(downstream);
  1623. }
  1624. }
  1625. if (changedSteps.length) {
  1626. await setState({ stepStatuses: statuses });
  1627. for (const downstream of changedSteps) {
  1628. chrome.runtime.sendMessage({
  1629. type: 'STEP_STATUS_CHANGED',
  1630. payload: { step: downstream, status: 'pending' },
  1631. }).catch(() => { });
  1632. }
  1633. await addLog(`${logLabel},已重置后续步骤状态:${changedSteps.join(', ')}`, 'warn');
  1634. }
  1635. const resets = getDownstreamStateResets(step);
  1636. if (Object.keys(resets).length) {
  1637. await setState(resets);
  1638. broadcastDataUpdate(resets);
  1639. }
  1640. }
  1641. function clearStopRequest() {
  1642. stopRequested = false;
  1643. }
  1644. function getAutoRunStatusPayload(phase, payload = {}) {
  1645. const currentRun = payload.currentRun ?? autoRunCurrentRun;
  1646. const totalRuns = payload.totalRuns ?? autoRunTotalRuns;
  1647. const attemptRun = payload.attemptRun ?? autoRunAttemptRun;
  1648. const rawScheduledAt = phase === 'scheduled'
  1649. ? (payload.scheduledAt ?? payload.scheduledAutoRunAt ?? null)
  1650. : null;
  1651. const scheduledAt = rawScheduledAt === null ? null : Number(rawScheduledAt);
  1652. const autoRunning = phase === 'scheduled' || phase === 'running' || phase === 'waiting_email' || phase === 'retrying';
  1653. return {
  1654. autoRunning,
  1655. autoRunPhase: phase,
  1656. autoRunCurrentRun: currentRun,
  1657. autoRunTotalRuns: totalRuns,
  1658. autoRunAttemptRun: attemptRun,
  1659. scheduledAutoRunAt: Number.isFinite(scheduledAt) ? scheduledAt : null,
  1660. };
  1661. }
  1662. async function broadcastAutoRunStatus(phase, payload = {}, extraState = {}) {
  1663. const rawScheduledAt = phase === 'scheduled'
  1664. ? (payload.scheduledAt ?? payload.scheduledAutoRunAt ?? null)
  1665. : null;
  1666. const statusPayload = {
  1667. phase,
  1668. currentRun: payload.currentRun ?? autoRunCurrentRun,
  1669. totalRuns: payload.totalRuns ?? autoRunTotalRuns,
  1670. attemptRun: payload.attemptRun ?? autoRunAttemptRun,
  1671. scheduledAt: rawScheduledAt === null ? null : Number(rawScheduledAt),
  1672. };
  1673. await setState({
  1674. ...extraState,
  1675. ...getAutoRunStatusPayload(phase, statusPayload),
  1676. });
  1677. chrome.runtime.sendMessage({
  1678. type: 'AUTO_RUN_STATUS',
  1679. payload: statusPayload,
  1680. }).catch(() => { });
  1681. }
  1682. function isAutoRunLockedState(state) {
  1683. return Boolean(state.autoRunning) && (state.autoRunPhase === 'running' || state.autoRunPhase === 'retrying');
  1684. }
  1685. function isAutoRunPausedState(state) {
  1686. return Boolean(state.autoRunning) && state.autoRunPhase === 'waiting_email';
  1687. }
  1688. function isAutoRunScheduledState(state) {
  1689. const scheduledAt = state.scheduledAutoRunAt === null ? null : Number(state.scheduledAutoRunAt);
  1690. return Boolean(state.autoRunning)
  1691. && state.autoRunPhase === 'scheduled'
  1692. && Number.isFinite(scheduledAt)
  1693. && Boolean(normalizeScheduledAutoRunPlan(state.scheduledAutoRunPlan));
  1694. }
  1695. function formatAutoRunScheduleTime(timestamp) {
  1696. return new Date(timestamp).toLocaleString('zh-CN', {
  1697. hour12: false,
  1698. month: '2-digit',
  1699. day: '2-digit',
  1700. hour: '2-digit',
  1701. minute: '2-digit',
  1702. second: '2-digit',
  1703. });
  1704. }
  1705. async function setAutoRunDelayEnabledState(enabled) {
  1706. const normalized = Boolean(enabled);
  1707. await setPersistentSettings({ autoRunDelayEnabled: normalized });
  1708. await setState({ autoRunDelayEnabled: normalized });
  1709. broadcastDataUpdate({ autoRunDelayEnabled: normalized });
  1710. }
  1711. async function ensureScheduledAutoRunAlarm(scheduledAt) {
  1712. if (!Number.isFinite(scheduledAt) || scheduledAt <= Date.now()) {
  1713. return false;
  1714. }
  1715. const existingAlarm = await chrome.alarms.get(AUTO_RUN_ALARM_NAME);
  1716. if (!existingAlarm || Math.abs((existingAlarm.scheduledTime || 0) - scheduledAt) > 1000) {
  1717. await chrome.alarms.clear(AUTO_RUN_ALARM_NAME);
  1718. await chrome.alarms.create(AUTO_RUN_ALARM_NAME, { when: scheduledAt });
  1719. }
  1720. return true;
  1721. }
  1722. async function clearScheduledAutoRunAlarm() {
  1723. await chrome.alarms.clear(AUTO_RUN_ALARM_NAME);
  1724. }
  1725. async function scheduleAutoRun(totalRuns, options = {}) {
  1726. const state = await getState();
  1727. if (isAutoRunLockedState(state) || isAutoRunPausedState(state) || autoRunActive) {
  1728. throw new Error('自动运行已在进行中,请先停止后再重新计划。');
  1729. }
  1730. if (isAutoRunScheduledState(state)) {
  1731. throw new Error('已有自动运行倒计时计划,请先取消或立即开始。');
  1732. }
  1733. const delayMinutes = normalizeAutoRunDelayMinutes(options.delayMinutes);
  1734. const plan = normalizeScheduledAutoRunPlan({
  1735. totalRuns,
  1736. autoRunSkipFailures: options.autoRunSkipFailures,
  1737. mode: options.mode,
  1738. });
  1739. const scheduledAt = Date.now() + delayMinutes * 60 * 1000;
  1740. autoRunCurrentRun = 0;
  1741. autoRunTotalRuns = plan.totalRuns;
  1742. autoRunAttemptRun = 0;
  1743. await ensureScheduledAutoRunAlarm(scheduledAt);
  1744. await broadcastAutoRunStatus(
  1745. 'scheduled',
  1746. {
  1747. currentRun: 0,
  1748. totalRuns: plan.totalRuns,
  1749. attemptRun: 0,
  1750. scheduledAt,
  1751. },
  1752. {
  1753. autoRunSkipFailures: plan.autoRunSkipFailures,
  1754. scheduledAutoRunPlan: plan,
  1755. }
  1756. );
  1757. await addLog(
  1758. `自动运行已计划:${delayMinutes} 分钟后启动(${formatAutoRunScheduleTime(scheduledAt)}),目标 ${plan.totalRuns} 轮。`,
  1759. 'info'
  1760. );
  1761. return { ok: true, scheduledAt };
  1762. }
  1763. let scheduledAutoRunLaunching = false;
  1764. async function launchScheduledAutoRun(trigger = 'alarm') {
  1765. if (scheduledAutoRunLaunching) {
  1766. return false;
  1767. }
  1768. scheduledAutoRunLaunching = true;
  1769. try {
  1770. const state = await getState();
  1771. if (!isAutoRunScheduledState(state)) {
  1772. return false;
  1773. }
  1774. if (autoRunActive) {
  1775. return false;
  1776. }
  1777. const plan = normalizeScheduledAutoRunPlan(state.scheduledAutoRunPlan);
  1778. if (!plan) {
  1779. await clearScheduledAutoRunAlarm();
  1780. await broadcastAutoRunStatus('idle', {
  1781. currentRun: 0,
  1782. totalRuns: 1,
  1783. attemptRun: 0,
  1784. }, {
  1785. scheduledAutoRunPlan: null,
  1786. });
  1787. return false;
  1788. }
  1789. await clearScheduledAutoRunAlarm();
  1790. if (trigger !== 'manual' && state.autoRunDelayEnabled) {
  1791. await setAutoRunDelayEnabledState(false);
  1792. }
  1793. await broadcastAutoRunStatus(
  1794. 'running',
  1795. {
  1796. currentRun: 0,
  1797. totalRuns: plan.totalRuns,
  1798. attemptRun: 0,
  1799. },
  1800. {
  1801. autoRunSkipFailures: plan.autoRunSkipFailures,
  1802. scheduledAutoRunPlan: null,
  1803. }
  1804. );
  1805. clearStopRequest();
  1806. await addLog(
  1807. trigger === 'manual'
  1808. ? '已手动跳过倒计时,自动运行立即开始。'
  1809. : '倒计时结束,自动运行开始执行。',
  1810. 'info'
  1811. );
  1812. autoRunLoop(plan.totalRuns, {
  1813. autoRunSkipFailures: plan.autoRunSkipFailures,
  1814. mode: plan.mode,
  1815. });
  1816. return true;
  1817. } finally {
  1818. scheduledAutoRunLaunching = false;
  1819. }
  1820. }
  1821. async function cancelScheduledAutoRun(options = {}) {
  1822. const state = await getState();
  1823. if (!isAutoRunScheduledState(state)) {
  1824. return false;
  1825. }
  1826. const plan = normalizeScheduledAutoRunPlan(state.scheduledAutoRunPlan);
  1827. await clearScheduledAutoRunAlarm();
  1828. autoRunCurrentRun = 0;
  1829. autoRunTotalRuns = plan?.totalRuns || 1;
  1830. autoRunAttemptRun = 0;
  1831. await broadcastAutoRunStatus(
  1832. 'idle',
  1833. {
  1834. currentRun: 0,
  1835. totalRuns: plan?.totalRuns || 1,
  1836. attemptRun: 0,
  1837. },
  1838. {
  1839. scheduledAutoRunPlan: null,
  1840. }
  1841. );
  1842. if (options.logMessage !== false) {
  1843. await addLog(options.logMessage || '已取消自动运行倒计时计划。', 'warn');
  1844. }
  1845. return true;
  1846. }
  1847. async function restoreScheduledAutoRunIfNeeded() {
  1848. const state = await getState();
  1849. if (state.autoRunPhase !== 'scheduled') {
  1850. return;
  1851. }
  1852. const plan = normalizeScheduledAutoRunPlan(state.scheduledAutoRunPlan);
  1853. const scheduledAt = state.scheduledAutoRunAt === null ? null : Number(state.scheduledAutoRunAt);
  1854. if (!plan || !Number.isFinite(scheduledAt)) {
  1855. await clearScheduledAutoRunAlarm();
  1856. await broadcastAutoRunStatus('idle', {
  1857. currentRun: 0,
  1858. totalRuns: 1,
  1859. attemptRun: 0,
  1860. }, {
  1861. scheduledAutoRunPlan: null,
  1862. });
  1863. return;
  1864. }
  1865. if (scheduledAt <= Date.now()) {
  1866. await launchScheduledAutoRun('restore');
  1867. return;
  1868. }
  1869. await ensureScheduledAutoRunAlarm(scheduledAt);
  1870. }
  1871. async function ensureManualInteractionAllowed(actionLabel) {
  1872. const state = await getState();
  1873. if (isAutoRunLockedState(state)) {
  1874. throw new Error(`自动流程运行中,请先停止后再${actionLabel}。`);
  1875. }
  1876. if (isAutoRunPausedState(state)) {
  1877. throw new Error(`自动流程当前已暂停。请点击“继续”,或先确认接管自动流程后再${actionLabel}。`);
  1878. }
  1879. if (isAutoRunScheduledState(state)) {
  1880. throw new Error(`自动流程已计划启动。请先取消计划,或立即开始后再${actionLabel}。`);
  1881. }
  1882. return state;
  1883. }
  1884. async function skipStep(step) {
  1885. const state = await ensureManualInteractionAllowed('跳过步骤');
  1886. if (!Number.isInteger(step) || step < 1 || step > 9) {
  1887. throw new Error(`无效步骤:${step}`);
  1888. }
  1889. const statuses = { ...(state.stepStatuses || {}) };
  1890. const currentStatus = statuses[step];
  1891. if (currentStatus === 'running') {
  1892. throw new Error(`步骤 ${step} 正在运行中,不能跳过。`);
  1893. }
  1894. if (isStepDoneStatus(currentStatus)) {
  1895. throw new Error(`步骤 ${step} 已完成,无需再跳过。`);
  1896. }
  1897. if (step > 1) {
  1898. const prevStatus = statuses[step - 1];
  1899. if (!isStepDoneStatus(prevStatus)) {
  1900. throw new Error(`请先完成步骤 ${step - 1},再跳过步骤 ${step}。`);
  1901. }
  1902. }
  1903. await setStepStatus(step, 'skipped');
  1904. await addLog(`步骤 ${step} 已跳过`, 'warn');
  1905. if (step === 1) {
  1906. const latestState = await getState();
  1907. const step2Status = latestState.stepStatuses?.[2];
  1908. if (!isStepDoneStatus(step2Status) && step2Status !== 'running') {
  1909. await setStepStatus(2, 'skipped');
  1910. await addLog('步骤 1 已跳过,步骤 2 也已同时跳过。', 'warn');
  1911. }
  1912. }
  1913. return { ok: true, step, status: 'skipped' };
  1914. }
  1915. function throwIfStopped() {
  1916. if (stopRequested) {
  1917. throw new Error(STOP_ERROR_MESSAGE);
  1918. }
  1919. }
  1920. async function sleepWithStop(ms) {
  1921. const start = Date.now();
  1922. while (Date.now() - start < ms) {
  1923. throwIfStopped();
  1924. await new Promise(r => setTimeout(r, Math.min(100, ms - (Date.now() - start))));
  1925. }
  1926. }
  1927. async function humanStepDelay(min = HUMAN_STEP_DELAY_MIN, max = HUMAN_STEP_DELAY_MAX) {
  1928. const duration = Math.floor(Math.random() * (max - min + 1)) + min;
  1929. await sleepWithStop(duration);
  1930. }
  1931. async function clickWithDebugger(tabId, rect) {
  1932. throwIfStopped();
  1933. if (!tabId) {
  1934. throw new Error('未找到用于调试点击的认证页面标签页。');
  1935. }
  1936. if (!rect || !Number.isFinite(rect.centerX) || !Number.isFinite(rect.centerY)) {
  1937. throw new Error('步骤 8 的调试器兜底点击需要有效的按钮坐标。');
  1938. }
  1939. const target = { tabId };
  1940. try {
  1941. await chrome.debugger.attach(target, '1.3');
  1942. } catch (err) {
  1943. throw new Error(
  1944. `步骤 8 的调试器兜底点击附加失败:${err.message}。` +
  1945. '如果认证页标签已打开 DevTools,请先关闭后重试。'
  1946. );
  1947. }
  1948. try {
  1949. throwIfStopped();
  1950. const x = Math.round(rect.centerX);
  1951. const y = Math.round(rect.centerY);
  1952. await chrome.debugger.sendCommand(target, 'Page.bringToFront');
  1953. throwIfStopped();
  1954. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  1955. type: 'mouseMoved',
  1956. x,
  1957. y,
  1958. button: 'none',
  1959. buttons: 0,
  1960. clickCount: 0,
  1961. });
  1962. throwIfStopped();
  1963. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  1964. type: 'mousePressed',
  1965. x,
  1966. y,
  1967. button: 'left',
  1968. buttons: 1,
  1969. clickCount: 1,
  1970. });
  1971. throwIfStopped();
  1972. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  1973. type: 'mouseReleased',
  1974. x,
  1975. y,
  1976. button: 'left',
  1977. buttons: 0,
  1978. clickCount: 1,
  1979. });
  1980. } finally {
  1981. await chrome.debugger.detach(target).catch(() => { });
  1982. }
  1983. }
  1984. async function broadcastStopToContentScripts() {
  1985. const registry = await getTabRegistry();
  1986. for (const entry of Object.values(registry)) {
  1987. if (!entry?.tabId) continue;
  1988. try {
  1989. await chrome.tabs.sendMessage(entry.tabId, {
  1990. type: 'STOP_FLOW',
  1991. source: 'background',
  1992. payload: {},
  1993. });
  1994. } catch { }
  1995. }
  1996. }
  1997. let stopRequested = false;
  1998. // ============================================================
  1999. // Message Handler (central router)
  2000. // ============================================================
  2001. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  2002. console.log(LOG_PREFIX, `Received: ${message.type} from ${message.source || 'sidepanel'}`, message);
  2003. handleMessage(message, sender).then(response => {
  2004. sendResponse(response);
  2005. }).catch(err => {
  2006. console.error(LOG_PREFIX, 'Handler error:', err);
  2007. sendResponse({ error: err.message });
  2008. });
  2009. return true; // async response
  2010. });
  2011. async function handleMessage(message, sender) {
  2012. switch (message.type) {
  2013. case 'CONTENT_SCRIPT_READY': {
  2014. const tabId = sender.tab?.id;
  2015. if (tabId && message.source) {
  2016. await registerTab(message.source, tabId);
  2017. flushCommand(message.source, tabId);
  2018. await addLog(`内容脚本已就绪:${getSourceLabel(message.source)}(标签页 ${tabId})`);
  2019. }
  2020. return { ok: true };
  2021. }
  2022. case 'LOG': {
  2023. const { message: msg, level } = message.payload;
  2024. await addLog(`[${getSourceLabel(message.source)}] ${msg}`, level);
  2025. return { ok: true };
  2026. }
  2027. case 'STEP_COMPLETE': {
  2028. if (stopRequested) {
  2029. await setStepStatus(message.step, 'stopped');
  2030. notifyStepError(message.step, STOP_ERROR_MESSAGE);
  2031. return { ok: true };
  2032. }
  2033. await setStepStatus(message.step, 'completed');
  2034. await addLog(`步骤 ${message.step} 已完成`, 'ok');
  2035. await handleStepData(message.step, message.payload);
  2036. notifyStepComplete(message.step, message.payload);
  2037. return { ok: true };
  2038. }
  2039. case 'STEP_ERROR': {
  2040. if (isStopError(message.error)) {
  2041. await setStepStatus(message.step, 'stopped');
  2042. await addLog(`步骤 ${message.step} 已被用户停止`, 'warn');
  2043. notifyStepError(message.step, message.error);
  2044. } else {
  2045. await setStepStatus(message.step, 'failed');
  2046. await addLog(`步骤 ${message.step} 失败:${message.error}`, 'error');
  2047. notifyStepError(message.step, message.error);
  2048. }
  2049. return { ok: true };
  2050. }
  2051. case 'GET_STATE': {
  2052. return await getState();
  2053. }
  2054. case 'RESET': {
  2055. clearStopRequest();
  2056. await clearScheduledAutoRunAlarm();
  2057. await resetState();
  2058. await addLog('流程已重置', 'info');
  2059. return { ok: true };
  2060. }
  2061. case 'EXECUTE_STEP': {
  2062. clearStopRequest();
  2063. if (message.source === 'sidepanel') {
  2064. await ensureManualInteractionAllowed('手动执行步骤');
  2065. }
  2066. const step = message.payload.step;
  2067. if (message.source === 'sidepanel') {
  2068. await invalidateDownstreamAfterStepRestart(step, { logLabel: `步骤 ${step} 重新执行` });
  2069. }
  2070. // Save email if provided (from side panel step 3)
  2071. if (message.payload.email) {
  2072. await setEmailState(message.payload.email);
  2073. }
  2074. await executeStep(step);
  2075. return { ok: true };
  2076. }
  2077. case 'AUTO_RUN': {
  2078. clearStopRequest();
  2079. const state = await getState();
  2080. if (isAutoRunScheduledState(state)) {
  2081. throw new Error('已有自动运行倒计时计划,请先取消或立即开始。');
  2082. }
  2083. const totalRuns = normalizeRunCount(message.payload?.totalRuns || 1);
  2084. const autoRunSkipFailures = Boolean(message.payload?.autoRunSkipFailures);
  2085. const mode = message.payload?.mode === 'continue' ? 'continue' : 'restart';
  2086. await setState({ autoRunSkipFailures });
  2087. autoRunLoop(totalRuns, { autoRunSkipFailures, mode }); // fire-and-forget
  2088. return { ok: true };
  2089. }
  2090. case 'SCHEDULE_AUTO_RUN': {
  2091. clearStopRequest();
  2092. const totalRuns = normalizeRunCount(message.payload?.totalRuns || 1);
  2093. return await scheduleAutoRun(totalRuns, {
  2094. delayMinutes: message.payload?.delayMinutes,
  2095. autoRunSkipFailures: Boolean(message.payload?.autoRunSkipFailures),
  2096. mode: message.payload?.mode,
  2097. });
  2098. }
  2099. case 'START_SCHEDULED_AUTO_RUN_NOW': {
  2100. clearStopRequest();
  2101. const started = await launchScheduledAutoRun('manual');
  2102. if (!started) {
  2103. throw new Error('当前没有可立即开始的倒计时计划。');
  2104. }
  2105. return { ok: true };
  2106. }
  2107. case 'CANCEL_SCHEDULED_AUTO_RUN': {
  2108. const cancelled = await cancelScheduledAutoRun();
  2109. if (!cancelled) {
  2110. throw new Error('当前没有可取消的倒计时计划。');
  2111. }
  2112. return { ok: true };
  2113. }
  2114. case 'RESUME_AUTO_RUN': {
  2115. clearStopRequest();
  2116. if (message.payload.email) {
  2117. await setEmailState(message.payload.email);
  2118. }
  2119. resumeAutoRun(); // fire-and-forget
  2120. return { ok: true };
  2121. }
  2122. case 'TAKEOVER_AUTO_RUN': {
  2123. await requestStop({ logMessage: '已确认手动接管,正在停止自动流程并切换为手动控制...' });
  2124. await addLog('自动流程已切换为手动控制。', 'warn');
  2125. return { ok: true };
  2126. }
  2127. case 'SKIP_STEP': {
  2128. const step = Number(message.payload?.step);
  2129. return await skipStep(step);
  2130. }
  2131. case 'SAVE_SETTING': {
  2132. const updates = {};
  2133. if (message.payload.panelMode !== undefined) updates.panelMode = message.payload.panelMode;
  2134. if (message.payload.vpsUrl !== undefined) updates.vpsUrl = message.payload.vpsUrl;
  2135. if (message.payload.vpsPassword !== undefined) updates.vpsPassword = message.payload.vpsPassword;
  2136. if (message.payload.sub2apiUrl !== undefined) updates.sub2apiUrl = message.payload.sub2apiUrl;
  2137. if (message.payload.sub2apiEmail !== undefined) updates.sub2apiEmail = message.payload.sub2apiEmail;
  2138. if (message.payload.sub2apiPassword !== undefined) updates.sub2apiPassword = message.payload.sub2apiPassword;
  2139. if (message.payload.sub2apiGroupName !== undefined) updates.sub2apiGroupName = message.payload.sub2apiGroupName;
  2140. if (message.payload.customPassword !== undefined) updates.customPassword = message.payload.customPassword;
  2141. if (message.payload.autoRunSkipFailures !== undefined) updates.autoRunSkipFailures = Boolean(message.payload.autoRunSkipFailures);
  2142. if (message.payload.autoRunDelayEnabled !== undefined) updates.autoRunDelayEnabled = Boolean(message.payload.autoRunDelayEnabled);
  2143. if (message.payload.autoRunDelayMinutes !== undefined) updates.autoRunDelayMinutes = normalizeAutoRunDelayMinutes(message.payload.autoRunDelayMinutes);
  2144. if (message.payload.mailProvider !== undefined) updates.mailProvider = message.payload.mailProvider;
  2145. if (message.payload.emailGenerator !== undefined) updates.emailGenerator = normalizeEmailGenerator(message.payload.emailGenerator);
  2146. if (message.payload.inbucketHost !== undefined) updates.inbucketHost = message.payload.inbucketHost;
  2147. if (message.payload.inbucketMailbox !== undefined) updates.inbucketMailbox = message.payload.inbucketMailbox;
  2148. if (message.payload.cloudflareDomain !== undefined) updates.cloudflareDomain = normalizeCloudflareDomain(message.payload.cloudflareDomain);
  2149. if (message.payload.cloudflareDomains !== undefined) updates.cloudflareDomains = Array.isArray(message.payload.cloudflareDomains)
  2150. ? message.payload.cloudflareDomains.map(domain => normalizeCloudflareDomain(domain)).filter(Boolean)
  2151. : [];
  2152. await setPersistentSettings(updates);
  2153. await setState(updates);
  2154. return { ok: true };
  2155. }
  2156. case 'UPSERT_HOTMAIL_ACCOUNT': {
  2157. const account = await upsertHotmailAccount(message.payload || {});
  2158. return { ok: true, account };
  2159. }
  2160. case 'DELETE_HOTMAIL_ACCOUNT': {
  2161. await deleteHotmailAccount(String(message.payload?.accountId || ''));
  2162. return { ok: true };
  2163. }
  2164. case 'DELETE_HOTMAIL_ACCOUNTS': {
  2165. const result = await deleteHotmailAccounts(String(message.payload?.mode || 'all'));
  2166. return { ok: true, ...result };
  2167. }
  2168. case 'SELECT_HOTMAIL_ACCOUNT': {
  2169. const account = await setCurrentHotmailAccount(String(message.payload?.accountId || ''), {
  2170. markUsed: false,
  2171. syncEmail: true,
  2172. });
  2173. return { ok: true, account };
  2174. }
  2175. case 'PATCH_HOTMAIL_ACCOUNT': {
  2176. const account = await patchHotmailAccount(
  2177. String(message.payload?.accountId || ''),
  2178. message.payload?.updates || {}
  2179. );
  2180. return { ok: true, account };
  2181. }
  2182. case 'VERIFY_HOTMAIL_ACCOUNT':
  2183. case 'AUTHORIZE_HOTMAIL_ACCOUNT': {
  2184. const accountId = String(message.payload?.accountId || '');
  2185. try {
  2186. const result = await verifyHotmailAccount(accountId);
  2187. await setCurrentHotmailAccount(result.account.id, { markUsed: false, syncEmail: true });
  2188. await addLog(`Hotmail 账号 ${result.account.email} 校验通过,可直接用于收信。`, 'ok');
  2189. return { ok: true, account: result.account, messageCount: result.messageCount };
  2190. } catch (err) {
  2191. const state = await getState();
  2192. const accounts = normalizeHotmailAccounts(state.hotmailAccounts);
  2193. const target = findHotmailAccount(accounts, accountId);
  2194. if (target) {
  2195. target.status = 'error';
  2196. target.lastError = err.message;
  2197. await syncHotmailAccounts(accounts.map((item) => (item.id === target.id ? target : item)));
  2198. }
  2199. throw err;
  2200. }
  2201. }
  2202. case 'TEST_HOTMAIL_ACCOUNT': {
  2203. const result = await testHotmailAccountMailAccess(String(message.payload?.accountId || ''));
  2204. return { ok: true, ...result };
  2205. }
  2206. // Side panel data updates
  2207. case 'SAVE_EMAIL': {
  2208. const state = await getState();
  2209. if (isAutoRunLockedState(state)) {
  2210. throw new Error('自动流程运行中,当前不能手动修改邮箱。');
  2211. }
  2212. await setEmailState(message.payload.email);
  2213. await resumeAutoRun();
  2214. return { ok: true, email: message.payload.email };
  2215. }
  2216. case 'FETCH_GENERATED_EMAIL': {
  2217. clearStopRequest();
  2218. const state = await getState();
  2219. if (isAutoRunLockedState(state)) {
  2220. throw new Error('自动流程运行中,当前不能手动获取邮箱。');
  2221. }
  2222. const email = await fetchGeneratedEmail(state, message.payload || {});
  2223. await resumeAutoRun();
  2224. return { ok: true, email };
  2225. }
  2226. case 'FETCH_DUCK_EMAIL': {
  2227. clearStopRequest();
  2228. const state = await getState();
  2229. if (isAutoRunLockedState(state)) {
  2230. throw new Error('自动流程运行中,当前不能手动获取邮箱。');
  2231. }
  2232. const email = await fetchGeneratedEmail(state, { ...(message.payload || {}), generator: 'duck' });
  2233. await resumeAutoRun();
  2234. return { ok: true, email };
  2235. }
  2236. case 'STOP_FLOW': {
  2237. await requestStop();
  2238. return { ok: true };
  2239. }
  2240. default:
  2241. console.warn(LOG_PREFIX, `Unknown message type: ${message.type}`);
  2242. return { error: `Unknown message type: ${message.type}` };
  2243. }
  2244. }
  2245. // ============================================================
  2246. // Step Data Handlers
  2247. // ============================================================
  2248. async function handleStepData(step, payload) {
  2249. switch (step) {
  2250. case 1: {
  2251. const updates = {};
  2252. if (payload.oauthUrl) {
  2253. updates.oauthUrl = payload.oauthUrl;
  2254. broadcastDataUpdate({ oauthUrl: payload.oauthUrl });
  2255. }
  2256. if (payload.sub2apiSessionId !== undefined) updates.sub2apiSessionId = payload.sub2apiSessionId || null;
  2257. if (payload.sub2apiOAuthState !== undefined) updates.sub2apiOAuthState = payload.sub2apiOAuthState || null;
  2258. if (payload.sub2apiGroupId !== undefined) updates.sub2apiGroupId = payload.sub2apiGroupId || null;
  2259. if (payload.sub2apiDraftName !== undefined) updates.sub2apiDraftName = payload.sub2apiDraftName || null;
  2260. if (Object.keys(updates).length) {
  2261. await setState(updates);
  2262. }
  2263. break;
  2264. }
  2265. case 3:
  2266. if (payload.email) await setEmailState(payload.email);
  2267. if (payload.signupVerificationRequestedAt) {
  2268. await setState({ signupVerificationRequestedAt: payload.signupVerificationRequestedAt });
  2269. }
  2270. if (payload.loginVerificationRequestedAt) {
  2271. await setState({ loginVerificationRequestedAt: payload.loginVerificationRequestedAt });
  2272. }
  2273. break;
  2274. case 6:
  2275. if (payload.loginVerificationRequestedAt) {
  2276. await setState({ loginVerificationRequestedAt: payload.loginVerificationRequestedAt });
  2277. }
  2278. break;
  2279. case 4:
  2280. await setState({
  2281. lastEmailTimestamp: payload.emailTimestamp || null,
  2282. signupVerificationRequestedAt: null,
  2283. });
  2284. break;
  2285. case 7:
  2286. await setState({
  2287. lastEmailTimestamp: payload.emailTimestamp || null,
  2288. loginVerificationRequestedAt: null,
  2289. });
  2290. break;
  2291. case 8:
  2292. if (payload.localhostUrl) {
  2293. if (!isLocalhostOAuthCallbackUrl(payload.localhostUrl)) {
  2294. throw new Error('步骤 8 返回了无效的 localhost OAuth 回调地址。');
  2295. }
  2296. await setState({ localhostUrl: payload.localhostUrl });
  2297. broadcastDataUpdate({ localhostUrl: payload.localhostUrl });
  2298. }
  2299. break;
  2300. case 9: {
  2301. if (payload.localhostUrl) {
  2302. await closeLocalhostCallbackTabs(payload.localhostUrl);
  2303. }
  2304. const latestState = await getState();
  2305. if (latestState.currentHotmailAccountId && isHotmailProvider(latestState)) {
  2306. await patchHotmailAccount(latestState.currentHotmailAccountId, {
  2307. used: true,
  2308. lastUsedAt: Date.now(),
  2309. });
  2310. await addLog('当前 Hotmail 账号已自动标记为已用。', 'ok');
  2311. }
  2312. const localhostPrefix = buildLocalhostCleanupPrefix(payload.localhostUrl);
  2313. if (localhostPrefix) {
  2314. await closeTabsByUrlPrefix(localhostPrefix);
  2315. }
  2316. break;
  2317. }
  2318. }
  2319. }
  2320. // ============================================================
  2321. // Step Completion Waiting
  2322. // ============================================================
  2323. // Map of step -> { resolve, reject } for waiting on step completion
  2324. const stepWaiters = new Map();
  2325. let resumeWaiter = null;
  2326. const AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS = 120000;
  2327. const AUTO_RUN_BACKGROUND_COMPLETED_STEPS = new Set([4, 7, 8]);
  2328. function waitForStepComplete(step, timeoutMs = 120000) {
  2329. return new Promise((resolve, reject) => {
  2330. throwIfStopped();
  2331. if (stepWaiters.has(step)) {
  2332. console.warn(LOG_PREFIX, `[waitForStepComplete] replacing existing waiter for step ${step}`);
  2333. }
  2334. console.log(LOG_PREFIX, `[waitForStepComplete] register step ${step}, timeout=${timeoutMs}ms`);
  2335. const timer = setTimeout(() => {
  2336. stepWaiters.delete(step);
  2337. console.warn(LOG_PREFIX, `[waitForStepComplete] timeout for step ${step} after ${timeoutMs}ms`);
  2338. reject(new Error(`步骤 ${step} 等待超时(>${timeoutMs / 1000} 秒)`));
  2339. }, timeoutMs);
  2340. stepWaiters.set(step, {
  2341. resolve: (data) => { clearTimeout(timer); stepWaiters.delete(step); resolve(data); },
  2342. reject: (err) => { clearTimeout(timer); stepWaiters.delete(step); reject(err); },
  2343. });
  2344. });
  2345. }
  2346. function notifyStepComplete(step, payload) {
  2347. const waiter = stepWaiters.get(step);
  2348. console.log(LOG_PREFIX, `[notifyStepComplete] step ${step}, hasWaiter=${Boolean(waiter)}`);
  2349. if (waiter) waiter.resolve(payload);
  2350. }
  2351. function notifyStepError(step, error) {
  2352. const waiter = stepWaiters.get(step);
  2353. console.warn(LOG_PREFIX, `[notifyStepError] step ${step}, hasWaiter=${Boolean(waiter)}, error=${error}`);
  2354. if (waiter) waiter.reject(new Error(error));
  2355. }
  2356. async function completeStepFromBackground(step, payload = {}) {
  2357. if (stopRequested) {
  2358. await setStepStatus(step, 'stopped');
  2359. notifyStepError(step, STOP_ERROR_MESSAGE);
  2360. return;
  2361. }
  2362. await setStepStatus(step, 'completed');
  2363. await addLog(`步骤 ${step} 已完成`, 'ok');
  2364. await handleStepData(step, payload);
  2365. notifyStepComplete(step, payload);
  2366. }
  2367. async function markRunningStepsStopped() {
  2368. const state = await getState();
  2369. const runningSteps = Object.entries(state.stepStatuses || {})
  2370. .filter(([, status]) => status === 'running')
  2371. .map(([step]) => Number(step));
  2372. for (const step of runningSteps) {
  2373. await setStepStatus(step, 'stopped');
  2374. }
  2375. }
  2376. async function requestStop(options = {}) {
  2377. const { logMessage = '已收到停止请求,正在取消当前操作...' } = options;
  2378. const state = await getState();
  2379. if (isAutoRunScheduledState(state) && !autoRunActive) {
  2380. await cancelScheduledAutoRun({
  2381. logMessage: options.logMessage === false
  2382. ? false
  2383. : (options.logMessage || '已取消自动运行倒计时计划。'),
  2384. });
  2385. return;
  2386. }
  2387. if (stopRequested) return;
  2388. stopRequested = true;
  2389. cancelPendingCommands();
  2390. cleanupStep8NavigationListeners();
  2391. rejectPendingStep8(new Error(STOP_ERROR_MESSAGE));
  2392. await addLog(logMessage, 'warn');
  2393. await broadcastStopToContentScripts();
  2394. for (const waiter of stepWaiters.values()) {
  2395. waiter.reject(new Error(STOP_ERROR_MESSAGE));
  2396. }
  2397. stepWaiters.clear();
  2398. if (resumeWaiter) {
  2399. resumeWaiter.reject(new Error(STOP_ERROR_MESSAGE));
  2400. resumeWaiter = null;
  2401. }
  2402. await markRunningStepsStopped();
  2403. autoRunActive = false;
  2404. await broadcastAutoRunStatus('stopped', {
  2405. currentRun: autoRunCurrentRun,
  2406. totalRuns: autoRunTotalRuns,
  2407. attemptRun: autoRunAttemptRun,
  2408. });
  2409. }
  2410. // ============================================================
  2411. // Step Execution
  2412. // ============================================================
  2413. async function executeStep(step) {
  2414. console.log(LOG_PREFIX, `Executing step ${step}`);
  2415. throwIfStopped();
  2416. await setStepStatus(step, 'running');
  2417. await addLog(`步骤 ${step} 开始执行`);
  2418. await humanStepDelay();
  2419. const state = await getState();
  2420. // Set flow start time on first step
  2421. if (step === 1 && !state.flowStartTime) {
  2422. await setState({ flowStartTime: Date.now() });
  2423. }
  2424. try {
  2425. switch (step) {
  2426. case 1: await executeStep1(state); break;
  2427. case 2: await executeStep2(state); break;
  2428. case 3: await executeStep3(state); break;
  2429. case 4: await executeStep4(state); break;
  2430. case 5: await executeStep5(state); break;
  2431. case 6: await executeStep6(state); break;
  2432. case 7: await executeStep7(state); break;
  2433. case 8: await executeStep8(state); break;
  2434. case 9: await executeStep9(state); break;
  2435. default:
  2436. throw new Error(`未知步骤:${step}`);
  2437. }
  2438. } catch (err) {
  2439. if (isStopError(err)) {
  2440. await setStepStatus(step, 'stopped');
  2441. await addLog(`步骤 ${step} 已被用户停止`, 'warn');
  2442. throw err;
  2443. }
  2444. await setStepStatus(step, 'failed');
  2445. await addLog(`步骤 ${step} 失败:${err.message}`, 'error');
  2446. throw err;
  2447. }
  2448. }
  2449. /**
  2450. * Execute a step and wait for it to complete before returning.
  2451. * @param {number} step
  2452. * @param {number} delayAfter - ms to wait after completion (for page transitions)
  2453. */
  2454. async function executeStepAndWait(step, delayAfter = 2000) {
  2455. throwIfStopped();
  2456. if (AUTO_RUN_BACKGROUND_COMPLETED_STEPS.has(step)) {
  2457. await addLog(`自动运行:步骤 ${step} 由后台流程负责收尾,执行函数返回后将直接进入下一步。`, 'info');
  2458. await executeStep(step);
  2459. const latestState = await getState();
  2460. await addLog(`自动运行:步骤 ${step} 已执行返回,当前状态为 ${latestState.stepStatuses?.[step] || 'pending'},准备继续后续步骤。`, 'info');
  2461. } else {
  2462. await addLog(`自动运行:步骤 ${step} 已发起,正在等待完成信号(超时 ${AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS / 1000} 秒)。`, 'info');
  2463. const completionResultPromise = waitForStepComplete(step, AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS).then(
  2464. payload => ({ ok: true, payload }),
  2465. error => ({ ok: false, error }),
  2466. );
  2467. try {
  2468. await executeStep(step);
  2469. } catch (err) {
  2470. notifyStepError(step, getErrorMessage(err));
  2471. await completionResultPromise;
  2472. throw err;
  2473. }
  2474. const completionResult = await completionResultPromise;
  2475. if (!completionResult.ok) {
  2476. throw completionResult.error;
  2477. }
  2478. await addLog(`自动运行:步骤 ${step} 已收到完成信号,准备继续后续步骤。`, 'info');
  2479. }
  2480. // Extra delay for page transitions / DOM updates
  2481. if (delayAfter > 0) {
  2482. await sleepWithStop(delayAfter + Math.floor(Math.random() * 1200));
  2483. }
  2484. }
  2485. function getEmailGeneratorLabel(generator) {
  2486. return generator === 'cloudflare' ? 'Cloudflare 邮箱' : 'Duck 邮箱';
  2487. }
  2488. function generateCloudflareAliasLocalPart() {
  2489. const now = new Date();
  2490. const stamp = [
  2491. now.getFullYear(),
  2492. String(now.getMonth() + 1).padStart(2, '0'),
  2493. String(now.getDate()).padStart(2, '0'),
  2494. String(now.getHours()).padStart(2, '0'),
  2495. String(now.getMinutes()).padStart(2, '0'),
  2496. String(now.getSeconds()).padStart(2, '0'),
  2497. ].join('');
  2498. const randomPart = String(Math.floor(Math.random() * 900) + 100);
  2499. return `user${stamp}${randomPart}`.toLowerCase();
  2500. }
  2501. async function fetchCloudflareEmail(state, options = {}) {
  2502. throwIfStopped();
  2503. const latestState = state || await getState();
  2504. const domain = normalizeCloudflareDomain(latestState.cloudflareDomain);
  2505. if (!domain) {
  2506. throw new Error('Cloudflare 域名为空或格式无效。');
  2507. }
  2508. const localPart = String(options.localPart || '').trim().toLowerCase() || generateCloudflareAliasLocalPart();
  2509. const aliasEmail = `${localPart}@${domain}`;
  2510. await setEmailState(aliasEmail);
  2511. await addLog(`Cloudflare 邮箱:已生成 ${aliasEmail}`, 'ok');
  2512. return aliasEmail;
  2513. }
  2514. async function fetchDuckEmail(options = {}) {
  2515. throwIfStopped();
  2516. const { generateNew = true } = options;
  2517. await addLog(`Duck 邮箱:正在打开自动填充设置(${generateNew ? '生成新地址' : '复用当前地址'})...`);
  2518. await reuseOrCreateTab('duck-mail', DUCK_AUTOFILL_URL);
  2519. const result = await sendToContentScript('duck-mail', {
  2520. type: 'FETCH_DUCK_EMAIL',
  2521. source: 'background',
  2522. payload: { generateNew },
  2523. });
  2524. if (result?.error) {
  2525. throw new Error(result.error);
  2526. }
  2527. if (!result?.email) {
  2528. throw new Error('未返回 Duck 邮箱地址。');
  2529. }
  2530. await setEmailState(result.email);
  2531. await addLog(`Duck 邮箱:${result.generated ? '已生成' : '已读取'} ${result.email}`, 'ok');
  2532. return result.email;
  2533. }
  2534. async function fetchGeneratedEmail(state, options = {}) {
  2535. const currentState = state || await getState();
  2536. const generator = normalizeEmailGenerator(options.generator ?? currentState.emailGenerator);
  2537. if (generator === 'cloudflare') {
  2538. return fetchCloudflareEmail(currentState, options);
  2539. }
  2540. return fetchDuckEmail(options);
  2541. }
  2542. // ============================================================
  2543. // Auto Run Flow
  2544. // ============================================================
  2545. let autoRunActive = false;
  2546. let autoRunCurrentRun = 0;
  2547. let autoRunTotalRuns = 1;
  2548. let autoRunAttemptRun = 0;
  2549. const EMAIL_FETCH_MAX_ATTEMPTS = 5;
  2550. const VERIFICATION_POLL_MAX_ROUNDS = 5;
  2551. const AUTO_STEP_DELAYS = {
  2552. 1: 2000,
  2553. 2: 2000,
  2554. 3: 3000,
  2555. 4: 2000,
  2556. 5: 3000,
  2557. 6: 3000,
  2558. 7: 2000,
  2559. 8: 2000,
  2560. 9: 1000,
  2561. };
  2562. async function resumeAutoRunIfWaitingForEmail(options = {}) {
  2563. const { silent = false } = options;
  2564. const state = await getState();
  2565. if (!state.email || !isAutoRunPausedState(state)) {
  2566. return false;
  2567. }
  2568. if (resumeWaiter) {
  2569. if (!silent) {
  2570. await addLog('邮箱已就绪,自动继续后续步骤...', 'info');
  2571. }
  2572. resumeWaiter.resolve();
  2573. resumeWaiter = null;
  2574. return true;
  2575. }
  2576. return false;
  2577. }
  2578. async function ensureAutoEmailReady(targetRun, totalRuns, attemptRuns) {
  2579. const currentState = await getState();
  2580. if (isHotmailProvider(currentState)) {
  2581. const account = await ensureHotmailAccountForFlow({
  2582. allowAllocate: true,
  2583. markUsed: true,
  2584. preferredAccountId: null,
  2585. });
  2586. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:已分配 Hotmail 账号 ${account.email}(第 ${attemptRuns} 次尝试)===`, 'ok');
  2587. return account.email;
  2588. }
  2589. if (currentState.email) {
  2590. return currentState.email;
  2591. }
  2592. const generator = normalizeEmailGenerator(currentState.emailGenerator);
  2593. const generatorLabel = getEmailGeneratorLabel(generator);
  2594. let lastError = null;
  2595. for (let attempt = 1; attempt <= EMAIL_FETCH_MAX_ATTEMPTS; attempt++) {
  2596. try {
  2597. if (attempt > 1) {
  2598. await addLog(`${generatorLabel}:正在进行第 ${attempt}/${EMAIL_FETCH_MAX_ATTEMPTS} 次自动获取重试...`, 'warn');
  2599. }
  2600. const generatedEmail = await fetchGeneratedEmail(currentState, { generateNew: true, generator });
  2601. await addLog(
  2602. `=== 目标 ${targetRun}/${totalRuns} 轮:${generatorLabel}已就绪:${generatedEmail}(第 ${attemptRuns} 次尝试,第 ${attempt}/${EMAIL_FETCH_MAX_ATTEMPTS} 次获取)===`,
  2603. 'ok'
  2604. );
  2605. return generatedEmail;
  2606. } catch (err) {
  2607. lastError = err;
  2608. await addLog(`${generatorLabel}自动获取失败(${attempt}/${EMAIL_FETCH_MAX_ATTEMPTS}):${err.message}`, 'warn');
  2609. if (generator === 'cloudflare' && /域名/.test(String(err.message || ''))) {
  2610. break;
  2611. }
  2612. }
  2613. }
  2614. await addLog(`${generatorLabel}自动获取已连续失败 ${EMAIL_FETCH_MAX_ATTEMPTS} 次:${lastError?.message || '未知错误'}`, 'error');
  2615. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮已暂停:请先自动获取邮箱或手动粘贴邮箱,然后继续 ===`, 'warn');
  2616. await broadcastAutoRunStatus('waiting_email', {
  2617. currentRun: targetRun,
  2618. totalRuns,
  2619. attemptRun: attemptRuns,
  2620. });
  2621. await waitForResume();
  2622. const resumedState = await getState();
  2623. if (!resumedState.email) {
  2624. throw new Error('无法继续:当前没有邮箱地址。');
  2625. }
  2626. return resumedState.email;
  2627. }
  2628. async function runAutoSequenceFromStep(startStep, context = {}) {
  2629. const { targetRun, totalRuns, attemptRuns, continued = false } = context;
  2630. const maxStep9RestartAttempts = 5;
  2631. let step9RestartAttempts = 0;
  2632. if (continued) {
  2633. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:继续当前进度,从步骤 ${startStep} 开始(第 ${attemptRuns} 次尝试)===`, 'info');
  2634. } else {
  2635. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:第 ${attemptRuns} 次尝试,阶段 1,获取 OAuth 链接并打开注册页 ===`, 'info');
  2636. }
  2637. if (startStep <= 2) {
  2638. for (const step of [1, 2]) {
  2639. if (step < startStep) continue;
  2640. await executeStepAndWait(step, AUTO_STEP_DELAYS[step]);
  2641. }
  2642. }
  2643. if (startStep <= 3) {
  2644. await ensureAutoEmailReady(targetRun, totalRuns, attemptRuns);
  2645. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:阶段 2,注册、验证、登录并完成授权(第 ${attemptRuns} 次尝试)===`, 'info');
  2646. await broadcastAutoRunStatus('running', {
  2647. currentRun: targetRun,
  2648. totalRuns,
  2649. attemptRun: attemptRuns,
  2650. });
  2651. await executeStepAndWait(3, AUTO_STEP_DELAYS[3]);
  2652. } else {
  2653. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:继续执行剩余流程(第 ${attemptRuns} 次尝试)===`, 'info');
  2654. }
  2655. const signupTabId = await getTabId('signup-page');
  2656. if (signupTabId) {
  2657. await chrome.tabs.update(signupTabId, { active: true });
  2658. }
  2659. let step = Math.max(startStep, 4);
  2660. while (step <= 9) {
  2661. try {
  2662. await executeStepAndWait(step, AUTO_STEP_DELAYS[step]);
  2663. step += 1;
  2664. } catch (err) {
  2665. const latestState = await getState();
  2666. const currentMail = getMailConfig(latestState);
  2667. const shouldRetryStep9 = step === 9
  2668. && (
  2669. isLegacyStep9RecoverableAuthError(err)
  2670. || (currentMail.provider === HOTMAIL_PROVIDER && isStep9RecoverableAuthError(err))
  2671. )
  2672. && step9RestartAttempts < maxStep9RestartAttempts;
  2673. if (shouldRetryStep9) {
  2674. step9RestartAttempts += 1;
  2675. await addLog(
  2676. `步骤 9:检测到 CPA 认证失败,正在回到步骤 6 重新开始授权流程(${step9RestartAttempts}/${maxStep9RestartAttempts})...`,
  2677. 'warn'
  2678. );
  2679. await invalidateDownstreamAfterStepRestart(6, {
  2680. logLabel: `步骤 9 认证失败后准备回到步骤 6 重试(${step9RestartAttempts}/${maxStep9RestartAttempts})`,
  2681. });
  2682. step = 6;
  2683. continue;
  2684. }
  2685. throw err;
  2686. }
  2687. }
  2688. }
  2689. // Outer loop: keep retrying until the target number of successful runs is reached.
  2690. async function autoRunLoop(totalRuns, options = {}) {
  2691. if (autoRunActive) {
  2692. await addLog('自动运行已在进行中', 'warn');
  2693. return;
  2694. }
  2695. clearStopRequest();
  2696. autoRunActive = true;
  2697. autoRunTotalRuns = totalRuns;
  2698. autoRunCurrentRun = 0;
  2699. autoRunAttemptRun = 0;
  2700. const autoRunSkipFailures = Boolean(options.autoRunSkipFailures);
  2701. const initialMode = options.mode === 'continue' ? 'continue' : 'restart';
  2702. const resumeCurrentRun = Number.isInteger(options.resumeCurrentRun) ? options.resumeCurrentRun : 0;
  2703. const resumeSuccessfulRuns = Number.isInteger(options.resumeSuccessfulRuns) ? options.resumeSuccessfulRuns : 0;
  2704. const resumeAttemptRunsProcessed = Number.isInteger(options.resumeAttemptRunsProcessed) ? options.resumeAttemptRunsProcessed : 0;
  2705. let maxAttempts = autoRunSkipFailures ? Math.max(totalRuns * 10, totalRuns + 20) : totalRuns;
  2706. const forcedRetryCap = Math.max(totalRuns * 10, totalRuns + 20);
  2707. let successfulRuns = Math.max(0, resumeSuccessfulRuns);
  2708. let attemptRuns = Math.max(0, resumeAttemptRunsProcessed);
  2709. let forceFreshTabsNextRun = false;
  2710. let continueCurrentOnFirstAttempt = initialMode === 'continue';
  2711. await setState({
  2712. autoRunSkipFailures,
  2713. ...getAutoRunStatusPayload('running', {
  2714. currentRun: resumeCurrentRun,
  2715. totalRuns,
  2716. attemptRun: resumeAttemptRunsProcessed,
  2717. }),
  2718. });
  2719. while (successfulRuns < totalRuns && attemptRuns < maxAttempts) {
  2720. attemptRuns += 1;
  2721. const targetRun = successfulRuns + 1;
  2722. autoRunCurrentRun = targetRun;
  2723. autoRunAttemptRun = attemptRuns;
  2724. let startStep = 1;
  2725. let useExistingProgress = false;
  2726. if (continueCurrentOnFirstAttempt) {
  2727. const currentState = await getState();
  2728. const resumeStep = getFirstUnfinishedStep(currentState.stepStatuses);
  2729. if (resumeStep && hasSavedProgress(currentState.stepStatuses)) {
  2730. startStep = resumeStep;
  2731. useExistingProgress = true;
  2732. } else if (hasSavedProgress(currentState.stepStatuses)) {
  2733. await addLog('当前流程已全部处理,将按“重新开始”新开一轮自动运行。', 'info');
  2734. }
  2735. continueCurrentOnFirstAttempt = false;
  2736. }
  2737. if (!useExistingProgress) {
  2738. // Reset everything at the start of each fresh attempt (keep user settings).
  2739. const prevState = await getState();
  2740. const keepSettings = {
  2741. vpsUrl: prevState.vpsUrl,
  2742. vpsPassword: prevState.vpsPassword,
  2743. customPassword: prevState.customPassword,
  2744. autoRunSkipFailures: prevState.autoRunSkipFailures,
  2745. autoRunDelayEnabled: prevState.autoRunDelayEnabled,
  2746. autoRunDelayMinutes: prevState.autoRunDelayMinutes,
  2747. mailProvider: prevState.mailProvider,
  2748. emailGenerator: prevState.emailGenerator,
  2749. inbucketHost: prevState.inbucketHost,
  2750. inbucketMailbox: prevState.inbucketMailbox,
  2751. cloudflareDomain: prevState.cloudflareDomain,
  2752. cloudflareDomains: prevState.cloudflareDomains,
  2753. ...getAutoRunStatusPayload('running', { currentRun: targetRun, totalRuns, attemptRun: attemptRuns }),
  2754. ...(forceFreshTabsNextRun ? { tabRegistry: {} } : {}),
  2755. };
  2756. await resetState();
  2757. await setState(keepSettings);
  2758. chrome.runtime.sendMessage({ type: 'AUTO_RUN_RESET' }).catch(() => { });
  2759. await sleepWithStop(500);
  2760. } else {
  2761. await setState({
  2762. autoRunSkipFailures,
  2763. ...getAutoRunStatusPayload('running', { currentRun: targetRun, totalRuns, attemptRun: attemptRuns }),
  2764. });
  2765. }
  2766. if (forceFreshTabsNextRun) {
  2767. await addLog(`兜底模式:上一轮已放弃,当前开始第 ${attemptRuns} 次尝试,将使用新线程继续补足第 ${targetRun}/${totalRuns} 轮。`, 'warn');
  2768. forceFreshTabsNextRun = false;
  2769. }
  2770. try {
  2771. throwIfStopped();
  2772. await broadcastAutoRunStatus('running', {
  2773. currentRun: targetRun,
  2774. totalRuns,
  2775. attemptRun: attemptRuns,
  2776. });
  2777. await runAutoSequenceFromStep(startStep, {
  2778. targetRun,
  2779. totalRuns,
  2780. attemptRuns,
  2781. continued: useExistingProgress,
  2782. });
  2783. successfulRuns += 1;
  2784. autoRunCurrentRun = successfulRuns;
  2785. await addLog(`=== 目标 ${successfulRuns}/${totalRuns} 轮已完成(第 ${attemptRuns} 次尝试成功)===`, 'ok');
  2786. continue;
  2787. } catch (err) {
  2788. if (isStopError(err)) {
  2789. await addLog(`目标 ${targetRun}/${totalRuns} 轮已被用户停止`, 'warn');
  2790. await broadcastAutoRunStatus('stopped', {
  2791. currentRun: targetRun,
  2792. totalRuns,
  2793. attemptRun: attemptRuns,
  2794. });
  2795. break;
  2796. }
  2797. if (isRestartCurrentAttemptError(err)) {
  2798. await addLog(`目标 ${targetRun}/${totalRuns} 轮检测到当前邮箱已存在,当前线程已放弃,将重新开始新一轮。`, 'warn');
  2799. cancelPendingCommands('当前线程因邮箱已存在而放弃。');
  2800. await broadcastStopToContentScripts();
  2801. await broadcastAutoRunStatus('retrying', {
  2802. currentRun: targetRun,
  2803. totalRuns,
  2804. attemptRun: attemptRuns,
  2805. });
  2806. forceFreshTabsNextRun = true;
  2807. maxAttempts = Math.max(maxAttempts, Math.min(forcedRetryCap, attemptRuns + 1));
  2808. continue;
  2809. }
  2810. if (!autoRunSkipFailures) {
  2811. await addLog(`目标 ${targetRun}/${totalRuns} 轮失败:${err.message}`, 'error');
  2812. await broadcastAutoRunStatus('stopped', {
  2813. currentRun: targetRun,
  2814. totalRuns,
  2815. attemptRun: attemptRuns,
  2816. });
  2817. break;
  2818. }
  2819. await addLog(`目标 ${targetRun}/${totalRuns} 轮的第 ${attemptRuns} 次尝试失败:${err.message}`, 'error');
  2820. await addLog('兜底开关已开启:将放弃当前线程,重新开一轮继续补足目标次数。', 'warn');
  2821. cancelPendingCommands('当前尝试已放弃。');
  2822. await broadcastStopToContentScripts();
  2823. await broadcastAutoRunStatus('retrying', {
  2824. currentRun: targetRun,
  2825. totalRuns,
  2826. attemptRun: attemptRuns,
  2827. });
  2828. forceFreshTabsNextRun = true;
  2829. }
  2830. }
  2831. if (!stopRequested && autoRunSkipFailures && successfulRuns < totalRuns && attemptRuns >= maxAttempts) {
  2832. await addLog(`已达到安全重试上限(${attemptRuns} 次尝试),当前仅完成 ${successfulRuns}/${totalRuns} 轮。`, 'error');
  2833. await broadcastAutoRunStatus('stopped', {
  2834. currentRun: successfulRuns,
  2835. totalRuns: autoRunTotalRuns,
  2836. attemptRun: attemptRuns,
  2837. });
  2838. } else if (stopRequested) {
  2839. await addLog(`=== 已停止,完成 ${successfulRuns}/${autoRunTotalRuns} 轮,共尝试 ${attemptRuns} 次 ===`, 'warn');
  2840. await broadcastAutoRunStatus('stopped', {
  2841. currentRun: successfulRuns,
  2842. totalRuns: autoRunTotalRuns,
  2843. attemptRun: attemptRuns,
  2844. });
  2845. } else if (successfulRuns >= autoRunTotalRuns) {
  2846. await addLog(`=== 全部 ${autoRunTotalRuns} 轮均已成功完成,共尝试 ${attemptRuns} 次 ===`, 'ok');
  2847. await broadcastAutoRunStatus('complete', {
  2848. currentRun: successfulRuns,
  2849. totalRuns: autoRunTotalRuns,
  2850. attemptRun: attemptRuns,
  2851. });
  2852. } else {
  2853. await addLog(`=== 已停止,完成 ${successfulRuns}/${autoRunTotalRuns} 轮,共尝试 ${attemptRuns} 次 ===`, 'warn');
  2854. await broadcastAutoRunStatus('stopped', {
  2855. currentRun: successfulRuns,
  2856. totalRuns: autoRunTotalRuns,
  2857. attemptRun: attemptRuns,
  2858. });
  2859. }
  2860. autoRunActive = false;
  2861. autoRunAttemptRun = attemptRuns;
  2862. await setState(getAutoRunStatusPayload(stopRequested ? 'stopped' : (successfulRuns >= autoRunTotalRuns ? 'complete' : 'stopped'), {
  2863. currentRun: successfulRuns,
  2864. totalRuns: autoRunTotalRuns,
  2865. attemptRun: attemptRuns,
  2866. }));
  2867. clearStopRequest();
  2868. }
  2869. async function waitForResume() {
  2870. throwIfStopped();
  2871. const state = await getState();
  2872. if (state.email) {
  2873. await addLog('邮箱已就绪,自动继续后续步骤...', 'info');
  2874. return;
  2875. }
  2876. return new Promise((resolve, reject) => {
  2877. resumeWaiter = { resolve, reject };
  2878. });
  2879. }
  2880. async function resumeAutoRun() {
  2881. throwIfStopped();
  2882. const state = await getState();
  2883. if (!state.email) {
  2884. await addLog('无法继续:当前没有邮箱地址,请先在侧边栏填写邮箱。', 'error');
  2885. return false;
  2886. }
  2887. const resumedInMemory = await resumeAutoRunIfWaitingForEmail({ silent: true });
  2888. if (resumedInMemory) {
  2889. return true;
  2890. }
  2891. if (!isAutoRunPausedState(state)) {
  2892. return false;
  2893. }
  2894. if (autoRunActive) {
  2895. return false;
  2896. }
  2897. const totalRuns = state.autoRunTotalRuns || 1;
  2898. const currentRun = state.autoRunCurrentRun || 1;
  2899. const attemptRun = state.autoRunAttemptRun || 1;
  2900. const successfulRuns = Math.max(0, currentRun - 1);
  2901. await addLog('检测到自动流程暂停上下文已丢失,正在从当前进度恢复自动运行...', 'warn');
  2902. autoRunLoop(totalRuns, {
  2903. autoRunSkipFailures: Boolean(state.autoRunSkipFailures),
  2904. mode: 'continue',
  2905. resumeCurrentRun: currentRun,
  2906. resumeSuccessfulRuns: successfulRuns,
  2907. resumeAttemptRunsProcessed: Math.max(0, attemptRun - 1),
  2908. });
  2909. return true;
  2910. }
  2911. // ============================================================
  2912. // Step 1: Get OAuth Link
  2913. // ============================================================
  2914. async function executeStep1(state) {
  2915. if (getPanelMode(state) === 'sub2api') {
  2916. return executeSub2ApiStep1(state);
  2917. }
  2918. return executeCpaStep1(state);
  2919. }
  2920. async function executeCpaStep1(state) {
  2921. if (!state.vpsUrl) {
  2922. throw new Error('尚未配置 CPA 地址,请先在侧边栏填写。');
  2923. }
  2924. await addLog('步骤 1:正在打开 CPA 面板...');
  2925. const injectFiles = ['content/activation-utils.js', 'content/utils.js', 'content/vps-panel.js'];
  2926. await closeConflictingTabsForSource('vps-panel', state.vpsUrl);
  2927. const tab = await chrome.tabs.create({ url: state.vpsUrl, active: true });
  2928. const tabId = tab.id;
  2929. await rememberSourceLastUrl('vps-panel', state.vpsUrl);
  2930. await addLog('步骤 1:CPA 面板已打开,正在等待页面进入目标地址...');
  2931. const matchedTab = await waitForTabUrlFamily('vps-panel', tabId, state.vpsUrl, {
  2932. timeoutMs: 15000,
  2933. retryDelayMs: 400,
  2934. });
  2935. if (!matchedTab) {
  2936. await addLog('步骤 1:CPA 页面尚未完全进入目标地址,继续尝试连接内容脚本...', 'warn');
  2937. }
  2938. await ensureContentScriptReadyOnTab('vps-panel', tabId, {
  2939. inject: injectFiles,
  2940. timeoutMs: 45000,
  2941. retryDelayMs: 900,
  2942. logMessage: '步骤 1:CPA 面板仍在加载,正在重试连接内容脚本...',
  2943. });
  2944. const result = await sendToContentScriptResilient('vps-panel', {
  2945. type: 'EXECUTE_STEP',
  2946. step: 1,
  2947. source: 'background',
  2948. payload: { vpsPassword: state.vpsPassword },
  2949. }, {
  2950. timeoutMs: 30000,
  2951. retryDelayMs: 700,
  2952. logMessage: '步骤 1:CPA 面板通信未就绪,正在等待页面恢复...',
  2953. });
  2954. if (result?.error) {
  2955. throw new Error(result.error);
  2956. }
  2957. }
  2958. async function executeSub2ApiStep1(state) {
  2959. const sub2apiUrl = normalizeSub2ApiUrl(state.sub2apiUrl);
  2960. const groupName = (state.sub2apiGroupName || DEFAULT_SUB2API_GROUP_NAME).trim() || DEFAULT_SUB2API_GROUP_NAME;
  2961. if (!state.sub2apiEmail) {
  2962. throw new Error('尚未配置 SUB2API 登录邮箱,请先在侧边栏填写。');
  2963. }
  2964. if (!state.sub2apiPassword) {
  2965. throw new Error('尚未配置 SUB2API 登录密码,请先在侧边栏填写。');
  2966. }
  2967. await addLog('步骤 1:正在打开 SUB2API 后台...');
  2968. const injectFiles = ['content/utils.js', 'content/sub2api-panel.js'];
  2969. await closeConflictingTabsForSource('sub2api-panel', sub2apiUrl);
  2970. const tab = await chrome.tabs.create({ url: sub2apiUrl, active: true });
  2971. const tabId = tab.id;
  2972. await rememberSourceLastUrl('sub2api-panel', sub2apiUrl);
  2973. await addLog('步骤 1:SUB2API 页面已打开,正在等待页面进入目标地址...');
  2974. const matchedTab = await waitForTabUrlFamily('sub2api-panel', tabId, sub2apiUrl, {
  2975. timeoutMs: 15000,
  2976. retryDelayMs: 400,
  2977. });
  2978. if (!matchedTab) {
  2979. await addLog('步骤 1:SUB2API 页面尚未稳定,继续尝试连接内容脚本...', 'warn');
  2980. }
  2981. await ensureContentScriptReadyOnTab('sub2api-panel', tabId, {
  2982. inject: injectFiles,
  2983. injectSource: 'sub2api-panel',
  2984. timeoutMs: 45000,
  2985. retryDelayMs: 900,
  2986. logMessage: '步骤 1:SUB2API 页面仍在加载,正在重试连接内容脚本...',
  2987. });
  2988. const result = await sendToContentScript('sub2api-panel', {
  2989. type: 'EXECUTE_STEP',
  2990. step: 1,
  2991. source: 'background',
  2992. payload: {
  2993. sub2apiUrl,
  2994. sub2apiEmail: state.sub2apiEmail,
  2995. sub2apiPassword: state.sub2apiPassword,
  2996. sub2apiGroupName: groupName,
  2997. },
  2998. }, {
  2999. responseTimeoutMs: SUB2API_STEP1_RESPONSE_TIMEOUT_MS,
  3000. });
  3001. if (result?.error) {
  3002. throw new Error(result.error);
  3003. }
  3004. }
  3005. // ============================================================
  3006. // Step 2: Open Signup Page (Background opens tab, signup-page.js clicks Register)
  3007. // ============================================================
  3008. async function executeStep2(state) {
  3009. if (!state.oauthUrl) {
  3010. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  3011. }
  3012. await addLog('步骤 2:正在打开认证链接...');
  3013. await reuseOrCreateTab('signup-page', state.oauthUrl);
  3014. await sendToContentScript('signup-page', {
  3015. type: 'EXECUTE_STEP',
  3016. step: 2,
  3017. source: 'background',
  3018. payload: {},
  3019. });
  3020. }
  3021. // ============================================================
  3022. // Step 3: Fill Email & Password (via signup-page.js)
  3023. // ============================================================
  3024. async function executeStep3(state) {
  3025. let resolvedEmail = state.email;
  3026. if (isHotmailProvider(state)) {
  3027. const account = await ensureHotmailAccountForFlow({
  3028. allowAllocate: true,
  3029. markUsed: true,
  3030. preferredAccountId: state.currentHotmailAccountId || null,
  3031. });
  3032. resolvedEmail = account.email;
  3033. }
  3034. if (!resolvedEmail) {
  3035. throw new Error('缺少邮箱地址,请先在侧边栏粘贴邮箱。');
  3036. }
  3037. const password = state.customPassword || generatePassword();
  3038. if (resolvedEmail !== state.email) {
  3039. await setEmailState(resolvedEmail);
  3040. }
  3041. await setPasswordState(password);
  3042. // Save account record
  3043. const accounts = state.accounts || [];
  3044. accounts.push({ email: resolvedEmail, password, createdAt: new Date().toISOString() });
  3045. await setState({ accounts });
  3046. await addLog(
  3047. `步骤 3:正在填写邮箱 ${resolvedEmail},密码为${state.customPassword ? '自定义' : '自动生成'}(${password.length} 位)`
  3048. );
  3049. await sendToContentScript('signup-page', {
  3050. type: 'EXECUTE_STEP',
  3051. step: 3,
  3052. source: 'background',
  3053. payload: { email: resolvedEmail, password },
  3054. });
  3055. }
  3056. // ============================================================
  3057. // Step 4: Get Signup Verification Code (qq-mail.js polls, then fills in signup-page.js)
  3058. // ============================================================
  3059. function getMailConfig(state) {
  3060. const provider = state.mailProvider || 'qq';
  3061. if (provider === HOTMAIL_PROVIDER) {
  3062. return { provider: HOTMAIL_PROVIDER, label: 'Hotmail(微软 Graph)' };
  3063. }
  3064. if (provider === '163') {
  3065. 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 邮箱' };
  3066. }
  3067. if (provider === '163-vip') {
  3068. 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 邮箱' };
  3069. }
  3070. if (provider === 'inbucket') {
  3071. const host = normalizeInbucketOrigin(state.inbucketHost);
  3072. const mailbox = (state.inbucketMailbox || '').trim();
  3073. if (!host) {
  3074. return { error: 'Inbucket 主机地址为空或无效。' };
  3075. }
  3076. if (!mailbox) {
  3077. return { error: 'Inbucket 邮箱名称为空。' };
  3078. }
  3079. return {
  3080. source: 'inbucket-mail',
  3081. url: `${host}/m/${encodeURIComponent(mailbox)}/`,
  3082. label: `Inbucket 邮箱(${mailbox})`,
  3083. navigateOnReuse: true,
  3084. inject: ['content/activation-utils.js', 'content/utils.js', 'content/inbucket-mail.js'],
  3085. injectSource: 'inbucket-mail',
  3086. };
  3087. }
  3088. return { source: 'qq-mail', url: 'https://wx.mail.qq.com/', label: 'QQ 邮箱' };
  3089. }
  3090. function normalizeInbucketOrigin(rawValue) {
  3091. const value = (rawValue || '').trim();
  3092. if (!value) return '';
  3093. const candidate = /^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(value) ? value : `https://${value}`;
  3094. try {
  3095. const parsed = new URL(candidate);
  3096. return parsed.origin;
  3097. } catch {
  3098. return '';
  3099. }
  3100. }
  3101. function getVerificationCodeStateKey(step) {
  3102. return step === 4 ? 'lastSignupCode' : 'lastLoginCode';
  3103. }
  3104. function getVerificationCodeLabel(step) {
  3105. return step === 4 ? '注册' : '登录';
  3106. }
  3107. function getVerificationPollPayload(step, state, overrides = {}) {
  3108. if (step === 4) {
  3109. return {
  3110. filterAfterTimestamp: getHotmailVerificationRequestTimestamp(4, state),
  3111. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'duckduckgo', 'forward'],
  3112. subjectFilters: ['verify', 'verification', 'code', '楠岃瘉', 'confirm'],
  3113. targetEmail: state.email,
  3114. maxAttempts: 5,
  3115. intervalMs: 3000,
  3116. ...overrides,
  3117. };
  3118. }
  3119. return {
  3120. filterAfterTimestamp: getHotmailVerificationRequestTimestamp(7, state),
  3121. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'chatgpt', 'duckduckgo', 'forward'],
  3122. subjectFilters: ['verify', 'verification', 'code', '楠岃瘉', 'confirm', 'login'],
  3123. targetEmail: state.email,
  3124. maxAttempts: 5,
  3125. intervalMs: 3000,
  3126. ...overrides,
  3127. };
  3128. }
  3129. async function requestVerificationCodeResend(step) {
  3130. const signupTabId = await getTabId('signup-page');
  3131. if (!signupTabId) {
  3132. throw new Error('认证页面标签页已关闭,无法重新请求验证码。');
  3133. }
  3134. await chrome.tabs.update(signupTabId, { active: true });
  3135. await addLog(`步骤 ${step}:正在请求新的${getVerificationCodeLabel(step)}验证码...`, 'warn');
  3136. const result = await sendToContentScript('signup-page', {
  3137. type: 'RESEND_VERIFICATION_CODE',
  3138. step,
  3139. source: 'background',
  3140. payload: {},
  3141. });
  3142. if (step === 7) {
  3143. const restartError = getStep7RestartFromStep6Error(result);
  3144. if (restartError) {
  3145. throw restartError;
  3146. }
  3147. }
  3148. if (result && result.error) {
  3149. throw new Error(result.error);
  3150. }
  3151. return Date.now();
  3152. }
  3153. async function pollFreshVerificationCode(step, state, mail, pollOverrides = {}) {
  3154. if (mail.provider === HOTMAIL_PROVIDER) {
  3155. const hotmailPollConfig = getHotmailVerificationPollConfig(step);
  3156. return pollHotmailVerificationCode(step, state, {
  3157. ...getVerificationPollPayload(step, state),
  3158. ...hotmailPollConfig,
  3159. ...pollOverrides,
  3160. });
  3161. }
  3162. const stateKey = getVerificationCodeStateKey(step);
  3163. const rejectedCodes = new Set();
  3164. if (state[stateKey]) {
  3165. rejectedCodes.add(state[stateKey]);
  3166. }
  3167. for (const code of (pollOverrides.excludeCodes || [])) {
  3168. if (code) rejectedCodes.add(code);
  3169. }
  3170. let lastError = null;
  3171. const filterAfterTimestamp = pollOverrides.filterAfterTimestamp ?? getVerificationPollPayload(step, state).filterAfterTimestamp;
  3172. const maxRounds = pollOverrides.maxRounds || VERIFICATION_POLL_MAX_ROUNDS;
  3173. for (let round = 1; round <= maxRounds; round++) {
  3174. if (round > 1) {
  3175. await requestVerificationCodeResend(step);
  3176. }
  3177. const payload = getVerificationPollPayload(step, state, {
  3178. ...pollOverrides,
  3179. filterAfterTimestamp,
  3180. excludeCodes: [...rejectedCodes],
  3181. });
  3182. try {
  3183. const result = await sendToMailContentScriptResilient(
  3184. mail,
  3185. {
  3186. type: 'POLL_EMAIL',
  3187. step,
  3188. source: 'background',
  3189. payload,
  3190. },
  3191. {
  3192. timeoutMs: 45000,
  3193. maxRecoveryAttempts: 2,
  3194. }
  3195. );
  3196. if (result && result.error) {
  3197. throw new Error(result.error);
  3198. }
  3199. if (!result || !result.code) {
  3200. throw new Error(`步骤 ${step}:邮箱轮询结束,但未获取到验证码。`);
  3201. }
  3202. if (rejectedCodes.has(result.code)) {
  3203. throw new Error(`步骤 ${step}:再次收到了相同的${getVerificationCodeLabel(step)}验证码:${result.code}`);
  3204. }
  3205. return result;
  3206. } catch (err) {
  3207. lastError = err;
  3208. await addLog(`步骤 ${step}:${err.message}`, 'warn');
  3209. if (round < maxRounds) {
  3210. await addLog(`步骤 ${step}:将重新发送验证码后重试(${round + 1}/${maxRounds})...`, 'warn');
  3211. }
  3212. }
  3213. }
  3214. throw lastError || new Error(`步骤 ${step}:无法获取新的${getVerificationCodeLabel(step)}验证码。`);
  3215. }
  3216. async function submitVerificationCode(step, code) {
  3217. const signupTabId = await getTabId('signup-page');
  3218. if (!signupTabId) {
  3219. throw new Error('认证页面标签页已关闭,无法填写验证码。');
  3220. }
  3221. await chrome.tabs.update(signupTabId, { active: true });
  3222. const result = await sendToContentScript('signup-page', {
  3223. type: 'FILL_CODE',
  3224. step,
  3225. source: 'background',
  3226. payload: { code },
  3227. });
  3228. if (step === 7) {
  3229. const restartError = getStep7RestartFromStep6Error(result);
  3230. if (restartError) {
  3231. throw restartError;
  3232. }
  3233. }
  3234. if (result && result.error) {
  3235. throw new Error(result.error);
  3236. }
  3237. return result || {};
  3238. }
  3239. async function resolveVerificationStep(step, state, mail, options = {}) {
  3240. const stateKey = getVerificationCodeStateKey(step);
  3241. const rejectedCodes = new Set();
  3242. const hotmailPollConfig = mail.provider === HOTMAIL_PROVIDER
  3243. ? getHotmailVerificationPollConfig(step)
  3244. : null;
  3245. const ignorePersistedLastCode = Boolean(hotmailPollConfig?.ignorePersistedLastCode);
  3246. if (state[stateKey] && !ignorePersistedLastCode) {
  3247. rejectedCodes.add(state[stateKey]);
  3248. }
  3249. const nextFilterAfterTimestamp = options.filterAfterTimestamp ?? null;
  3250. const requestFreshCodeFirst = options.requestFreshCodeFirst !== undefined
  3251. ? Boolean(options.requestFreshCodeFirst)
  3252. : (hotmailPollConfig?.requestFreshCodeFirst ?? false);
  3253. const maxSubmitAttempts = 3;
  3254. if (requestFreshCodeFirst) {
  3255. try {
  3256. await requestVerificationCodeResend(step);
  3257. await addLog(`步骤 ${step}:已先请求一封新的${getVerificationCodeLabel(step)}验证码,再开始轮询邮箱。`, 'warn');
  3258. } catch (err) {
  3259. if (step === 7 && isStep7RestartFromStep6Error(err)) {
  3260. throw err;
  3261. }
  3262. await addLog(`步骤 ${step}:首次重新获取验证码失败:${err.message},将继续使用当前时间窗口轮询。`, 'warn');
  3263. }
  3264. }
  3265. if (mail.provider === HOTMAIL_PROVIDER) {
  3266. const initialDelayMs = Number(options.initialDelayMs ?? hotmailPollConfig.initialDelayMs) || 0;
  3267. if (initialDelayMs > 0) {
  3268. await addLog(`步骤 ${step}:等待 ${Math.round(initialDelayMs / 1000)} 秒,让 Hotmail 验证码邮件先到达...`, 'info');
  3269. await sleepWithStop(initialDelayMs);
  3270. }
  3271. }
  3272. for (let attempt = 1; attempt <= maxSubmitAttempts; attempt++) {
  3273. const result = await pollFreshVerificationCode(step, state, mail, {
  3274. excludeCodes: [...rejectedCodes],
  3275. filterAfterTimestamp: nextFilterAfterTimestamp ?? undefined,
  3276. });
  3277. await addLog(`步骤 ${step}:已获取${getVerificationCodeLabel(step)}验证码:${result.code}`);
  3278. const submitResult = await submitVerificationCode(step, result.code);
  3279. if (submitResult.invalidCode) {
  3280. rejectedCodes.add(result.code);
  3281. await addLog(`步骤 ${step}:验证码被页面拒绝:${submitResult.errorText || result.code}`, 'warn');
  3282. if (attempt >= maxSubmitAttempts) {
  3283. throw new Error(`步骤 ${step}:验证码连续失败,已达到 ${maxSubmitAttempts} 次重试上限。`);
  3284. }
  3285. await requestVerificationCodeResend(step);
  3286. await addLog(`步骤 ${step}:提交失败后已请求新验证码(${attempt + 1}/${maxSubmitAttempts})...`, 'warn');
  3287. continue;
  3288. }
  3289. await setState({
  3290. lastEmailTimestamp: result.emailTimestamp,
  3291. [stateKey]: result.code,
  3292. });
  3293. await completeStepFromBackground(step, {
  3294. emailTimestamp: result.emailTimestamp,
  3295. code: result.code,
  3296. });
  3297. return;
  3298. }
  3299. }
  3300. async function executeStep4(state) {
  3301. const mail = getMailConfig(state);
  3302. if (mail.error) throw new Error(mail.error);
  3303. const stepStartedAt = Date.now();
  3304. const signupTabId = await getTabId('signup-page');
  3305. if (!signupTabId) {
  3306. throw new Error('认证页面标签页已关闭,无法继续步骤 4。');
  3307. }
  3308. await chrome.tabs.update(signupTabId, { active: true });
  3309. await addLog('步骤 4:正在确认注册验证码页面是否就绪,必要时自动恢复密码页超时报错...');
  3310. const prepareResult = await sendToContentScriptResilient(
  3311. 'signup-page',
  3312. {
  3313. type: 'PREPARE_SIGNUP_VERIFICATION',
  3314. step: 4,
  3315. source: 'background',
  3316. payload: { password: state.password || state.customPassword || '' },
  3317. },
  3318. {
  3319. timeoutMs: 30000,
  3320. retryDelayMs: 700,
  3321. logMessage: '步骤 4:认证页正在切换,等待页面重新就绪后继续检测...',
  3322. }
  3323. );
  3324. if (prepareResult && prepareResult.error) {
  3325. throw new Error(prepareResult.error);
  3326. }
  3327. if (prepareResult?.verificationRequestedAt) {
  3328. await setState({ loginVerificationRequestedAt: prepareResult.verificationRequestedAt });
  3329. }
  3330. if (prepareResult?.alreadyVerified) {
  3331. await completeStepFromBackground(4, {});
  3332. return;
  3333. }
  3334. if (mail.provider === HOTMAIL_PROVIDER) {
  3335. await addLog(`步骤 4:正在通过 ${mail.label} 轮询验证码...`);
  3336. } else {
  3337. await addLog(`步骤 4:正在打开${mail.label}...`);
  3338. // For mail tabs, only create if not alive — don't navigate (preserves login session)
  3339. const alive = await isTabAlive(mail.source);
  3340. if (alive) {
  3341. if (mail.navigateOnReuse) {
  3342. await reuseOrCreateTab(mail.source, mail.url, {
  3343. inject: mail.inject,
  3344. injectSource: mail.injectSource,
  3345. });
  3346. } else {
  3347. const tabId = await getTabId(mail.source);
  3348. await chrome.tabs.update(tabId, { active: true });
  3349. }
  3350. } else {
  3351. await reuseOrCreateTab(mail.source, mail.url, {
  3352. inject: mail.inject,
  3353. injectSource: mail.injectSource,
  3354. });
  3355. }
  3356. }
  3357. await resolveVerificationStep(4, state, mail, {
  3358. filterAfterTimestamp: mail.provider === HOTMAIL_PROVIDER ? undefined : stepStartedAt,
  3359. requestFreshCodeFirst: mail.provider === HOTMAIL_PROVIDER ? false : true,
  3360. });
  3361. return;
  3362. }
  3363. // ============================================================
  3364. // Step 5: Fill Name & Birthday (via signup-page.js)
  3365. // ============================================================
  3366. async function executeStep5(state) {
  3367. const { firstName, lastName } = generateRandomName();
  3368. const { year, month, day } = generateRandomBirthday();
  3369. await addLog(`步骤 5:已生成姓名 ${firstName} ${lastName},生日 ${year}-${month}-${day}`);
  3370. await sendToContentScript('signup-page', {
  3371. type: 'EXECUTE_STEP',
  3372. step: 5,
  3373. source: 'background',
  3374. payload: { firstName, lastName, year, month, day },
  3375. });
  3376. }
  3377. // ============================================================
  3378. // Step 6: Login ChatGPT (Background opens tab, chatgpt.js handles login)
  3379. // ============================================================
  3380. async function refreshOAuthUrlBeforeStep6(state) {
  3381. await addLog(`步骤 6:正在刷新登录用的 ${getPanelModeLabel(state)} OAuth 链接...`);
  3382. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] preparing fresh OAuth via step 1');
  3383. const waitForFreshOAuth = waitForStepComplete(1, 120000);
  3384. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] executing step 1 for fresh OAuth');
  3385. await executeStep1(state);
  3386. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] step 1 execute returned, waiting for completion signal');
  3387. await waitForFreshOAuth;
  3388. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] step 1 completion signal received');
  3389. const latestState = await getState();
  3390. if (!latestState.oauthUrl) {
  3391. throw new Error('刷新 OAuth 链接后仍未拿到可用链接。');
  3392. }
  3393. return latestState.oauthUrl;
  3394. }
  3395. async function executeStep6(state) {
  3396. if (!state.email) {
  3397. throw new Error('缺少邮箱地址,请先完成步骤 3。');
  3398. }
  3399. const oauthUrl = await refreshOAuthUrlBeforeStep6(state);
  3400. await addLog('步骤 6:正在打开最新 OAuth 链接并登录...');
  3401. // Reuse the signup-page tab — navigate it to the OAuth URL
  3402. await reuseOrCreateTab('signup-page', oauthUrl);
  3403. // signup-page.js will inject (same auth.openai.com domain) and handle login
  3404. await sendToContentScript('signup-page', {
  3405. type: 'EXECUTE_STEP',
  3406. step: 6,
  3407. source: 'background',
  3408. payload: { email: state.email, password: state.password },
  3409. });
  3410. }
  3411. // ============================================================
  3412. // Step 7: Get Login Verification Code (qq-mail.js polls, then fills in chatgpt.js)
  3413. // ============================================================
  3414. async function runStep7Attempt(state) {
  3415. const mail = getMailConfig(state);
  3416. if (mail.error) throw new Error(mail.error);
  3417. const stepStartedAt = Date.now();
  3418. const authTabId = await getTabId('signup-page');
  3419. if (authTabId) {
  3420. await chrome.tabs.update(authTabId, { active: true });
  3421. } else {
  3422. if (!state.oauthUrl) {
  3423. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  3424. }
  3425. await reuseOrCreateTab('signup-page', state.oauthUrl);
  3426. }
  3427. await addLog('步骤 7:正在准备认证页,必要时切换到一次性验证码登录...');
  3428. const prepareResult = await sendToContentScript('signup-page', {
  3429. type: 'PREPARE_LOGIN_CODE',
  3430. step: 7,
  3431. source: 'background',
  3432. payload: {},
  3433. });
  3434. const restartError = getStep7RestartFromStep6Error(prepareResult);
  3435. if (restartError) {
  3436. throw restartError;
  3437. }
  3438. if (prepareResult && prepareResult.error) {
  3439. throw new Error(prepareResult.error);
  3440. }
  3441. if (mail.provider === HOTMAIL_PROVIDER) {
  3442. await addLog(`步骤 7:正在通过 ${mail.label} 轮询验证码...`);
  3443. } else {
  3444. await addLog(`步骤 7:正在打开${mail.label}...`);
  3445. const alive = await isTabAlive(mail.source);
  3446. if (alive) {
  3447. if (mail.navigateOnReuse) {
  3448. await reuseOrCreateTab(mail.source, mail.url, {
  3449. inject: mail.inject,
  3450. injectSource: mail.injectSource,
  3451. });
  3452. } else {
  3453. const tabId = await getTabId(mail.source);
  3454. await chrome.tabs.update(tabId, { active: true });
  3455. }
  3456. } else {
  3457. await reuseOrCreateTab(mail.source, mail.url, {
  3458. inject: mail.inject,
  3459. injectSource: mail.injectSource,
  3460. });
  3461. }
  3462. }
  3463. await resolveVerificationStep(7, state, mail, {
  3464. filterAfterTimestamp: mail.provider === HOTMAIL_PROVIDER ? undefined : stepStartedAt,
  3465. requestFreshCodeFirst: mail.provider === HOTMAIL_PROVIDER ? false : true,
  3466. });
  3467. }
  3468. async function rerunStep6ForStep7Recovery() {
  3469. const currentState = await getState();
  3470. const waitForStep6 = waitForStepComplete(6, 120000);
  3471. await addLog('步骤 7:正在回到步骤 6,重新发起登录验证码流程...', 'warn');
  3472. await executeStep6(currentState);
  3473. await waitForStep6;
  3474. await sleepWithStop(3000);
  3475. }
  3476. async function executeStep7(state) {
  3477. let lastError = null;
  3478. for (let round = 1; round <= STEP7_RESTART_MAX_ROUNDS; round++) {
  3479. const currentState = round === 1 ? state : await getState();
  3480. try {
  3481. if (round > 1) {
  3482. await addLog(`步骤 7:正在进行第 ${round}/${STEP7_RESTART_MAX_ROUNDS} 轮登录验证码恢复尝试。`, 'warn');
  3483. }
  3484. await runStep7Attempt(currentState);
  3485. return;
  3486. } catch (err) {
  3487. lastError = err;
  3488. if (!isStep7RecoverableError(err)) {
  3489. throw err;
  3490. }
  3491. if (round >= STEP7_RESTART_MAX_ROUNDS) {
  3492. break;
  3493. }
  3494. await addLog(
  3495. isStep7RestartFromStep6Error(err)
  3496. ? `步骤 7:检测到登录页超时报错,准备从步骤 6 重新开始(${round + 1}/${STEP7_RESTART_MAX_ROUNDS})...`
  3497. : `步骤 7:检测到邮箱轮询类失败,准备从步骤 6 重新开始(${round + 1}/${STEP7_RESTART_MAX_ROUNDS})...`,
  3498. 'warn'
  3499. );
  3500. await rerunStep6ForStep7Recovery();
  3501. }
  3502. }
  3503. if (lastError && isStep7RecoverableError(lastError)) {
  3504. throw new Error(`步骤 7:登录验证码流程在 ${STEP7_RESTART_MAX_ROUNDS} 轮恢复后仍未成功。最后一次原因:${lastError.message}`);
  3505. }
  3506. throw lastError || new Error(`步骤 7:登录验证码流程在 ${STEP7_RESTART_MAX_ROUNDS} 轮后仍未成功。`);
  3507. }
  3508. // ============================================================
  3509. // Step 8: 完成 OAuth(自动点击 + localhost 回调监听)
  3510. // ============================================================
  3511. let webNavListener = null;
  3512. let webNavCommittedListener = null;
  3513. let step8TabUpdatedListener = null;
  3514. let step8PendingReject = null;
  3515. const STEP8_CLICK_EFFECT_TIMEOUT_MS = 10000;
  3516. const STEP8_CLICK_RETRY_DELAY_MS = 500;
  3517. const STEP8_READY_WAIT_TIMEOUT_MS = 30000;
  3518. const STEP8_MAX_ROUNDS = 5;
  3519. const STEP8_SIGNUP_PAGE_INJECT_FILES = ['content/utils.js', 'content/signup-page.js'];
  3520. const STEP8_STRATEGIES = [
  3521. { mode: 'content', strategy: 'requestSubmit', label: 'form.requestSubmit' },
  3522. { mode: 'debugger', label: 'debugger click' },
  3523. { mode: 'content', strategy: 'nativeClick', label: 'element.click' },
  3524. { mode: 'content', strategy: 'dispatchClick', label: 'dispatch click' },
  3525. { mode: 'debugger', label: 'debugger click retry' },
  3526. ];
  3527. function cleanupStep8NavigationListeners() {
  3528. if (webNavListener) {
  3529. chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
  3530. webNavListener = null;
  3531. }
  3532. if (webNavCommittedListener) {
  3533. chrome.webNavigation.onCommitted.removeListener(webNavCommittedListener);
  3534. webNavCommittedListener = null;
  3535. }
  3536. if (step8TabUpdatedListener) {
  3537. chrome.tabs.onUpdated.removeListener(step8TabUpdatedListener);
  3538. step8TabUpdatedListener = null;
  3539. }
  3540. }
  3541. function rejectPendingStep8(error) {
  3542. if (!step8PendingReject) return;
  3543. const reject = step8PendingReject;
  3544. step8PendingReject = null;
  3545. reject(error);
  3546. }
  3547. function throwIfStep8SettledOrStopped(isSettled = false) {
  3548. if (isSettled || stopRequested) {
  3549. throw new Error(STOP_ERROR_MESSAGE);
  3550. }
  3551. }
  3552. async function ensureStep8SignupPageReady(tabId, options = {}) {
  3553. await ensureContentScriptReadyOnTab('signup-page', tabId, {
  3554. inject: STEP8_SIGNUP_PAGE_INJECT_FILES,
  3555. injectSource: 'signup-page',
  3556. timeoutMs: options.timeoutMs ?? 15000,
  3557. retryDelayMs: options.retryDelayMs ?? 600,
  3558. logMessage: options.logMessage || '',
  3559. });
  3560. }
  3561. async function getStep8PageState(tabId, responseTimeoutMs = 1500) {
  3562. try {
  3563. const result = await sendTabMessageWithTimeout(tabId, 'signup-page', {
  3564. type: 'STEP8_GET_STATE',
  3565. source: 'background',
  3566. payload: {},
  3567. }, responseTimeoutMs);
  3568. if (result?.error) {
  3569. throw new Error(result.error);
  3570. }
  3571. return result;
  3572. } catch (err) {
  3573. if (isRetryableContentScriptTransportError(err)) {
  3574. return null;
  3575. }
  3576. throw err;
  3577. }
  3578. }
  3579. async function waitForStep8Ready(tabId, timeoutMs = STEP8_READY_WAIT_TIMEOUT_MS) {
  3580. const start = Date.now();
  3581. let recovered = false;
  3582. while (Date.now() - start < timeoutMs) {
  3583. throwIfStopped();
  3584. const pageState = await getStep8PageState(tabId);
  3585. if (pageState?.addPhonePage) {
  3586. throw new Error('步骤 8:认证页进入了手机号页面,当前不是 OAuth 同意页,无法继续自动授权。');
  3587. }
  3588. if (pageState?.consentReady) {
  3589. return pageState;
  3590. }
  3591. if (pageState === null && !recovered) {
  3592. recovered = true;
  3593. await ensureStep8SignupPageReady(tabId, {
  3594. timeoutMs: Math.min(10000, timeoutMs),
  3595. logMessage: '步骤 8:认证页内容脚本已失联,正在等待页面重新就绪...',
  3596. });
  3597. continue;
  3598. }
  3599. recovered = false;
  3600. await sleepWithStop(250);
  3601. }
  3602. throw new Error('步骤 8:长时间未进入 OAuth 同意页,无法定位“继续”按钮。');
  3603. }
  3604. async function prepareStep8DebuggerClick(tabId) {
  3605. await ensureStep8SignupPageReady(tabId, {
  3606. timeoutMs: 15000,
  3607. logMessage: '步骤 8:认证页内容脚本已失联,正在恢复后继续定位按钮...',
  3608. });
  3609. const result = await sendToContentScriptResilient('signup-page', {
  3610. type: 'STEP8_FIND_AND_CLICK',
  3611. source: 'background',
  3612. payload: {},
  3613. }, {
  3614. timeoutMs: 15000,
  3615. retryDelayMs: 600,
  3616. logMessage: '步骤 8:认证页正在切换,等待 OAuth 同意页按钮重新就绪...',
  3617. });
  3618. if (result?.error) {
  3619. throw new Error(result.error);
  3620. }
  3621. return result;
  3622. }
  3623. async function triggerStep8ContentStrategy(tabId, strategy) {
  3624. await ensureStep8SignupPageReady(tabId, {
  3625. timeoutMs: 15000,
  3626. logMessage: '步骤 8:认证页内容脚本已失联,正在恢复后继续点击“继续”按钮...',
  3627. });
  3628. const result = await sendToContentScriptResilient('signup-page', {
  3629. type: 'STEP8_TRIGGER_CONTINUE',
  3630. source: 'background',
  3631. payload: {
  3632. strategy,
  3633. findTimeoutMs: 4000,
  3634. enabledTimeoutMs: 3000,
  3635. },
  3636. }, {
  3637. timeoutMs: 15000,
  3638. retryDelayMs: 600,
  3639. logMessage: '步骤 8:认证页正在切换,等待“继续”按钮重新就绪...',
  3640. });
  3641. if (result?.error) {
  3642. throw new Error(result.error);
  3643. }
  3644. return result;
  3645. }
  3646. async function reloadStep8ConsentPage(tabId, timeoutMs = 30000) {
  3647. if (!Number.isInteger(tabId)) {
  3648. throw new Error('步骤 8:缺少有效的认证页标签页,无法刷新后重试。');
  3649. }
  3650. await chrome.tabs.update(tabId, { active: true }).catch(() => { });
  3651. await new Promise((resolve, reject) => {
  3652. let settled = false;
  3653. const timer = setTimeout(() => {
  3654. if (settled) return;
  3655. settled = true;
  3656. chrome.tabs.onUpdated.removeListener(listener);
  3657. reject(new Error('步骤 8:刷新认证页后等待页面完成加载超时。'));
  3658. }, timeoutMs);
  3659. const listener = (updatedTabId, changeInfo) => {
  3660. if (updatedTabId !== tabId) return;
  3661. if (changeInfo.status !== 'complete') return;
  3662. if (settled) return;
  3663. settled = true;
  3664. clearTimeout(timer);
  3665. chrome.tabs.onUpdated.removeListener(listener);
  3666. resolve();
  3667. };
  3668. chrome.tabs.onUpdated.addListener(listener);
  3669. chrome.tabs.reload(tabId, { bypassCache: false }).catch((err) => {
  3670. if (settled) return;
  3671. settled = true;
  3672. clearTimeout(timer);
  3673. chrome.tabs.onUpdated.removeListener(listener);
  3674. reject(err);
  3675. });
  3676. });
  3677. await ensureStep8SignupPageReady(tabId, {
  3678. timeoutMs: Math.min(15000, timeoutMs),
  3679. logMessage: '步骤 8:认证页刷新后内容脚本尚未就绪,正在等待页面恢复...',
  3680. });
  3681. }
  3682. async function waitForStep8ClickEffect(tabId, baselineUrl, timeoutMs = STEP8_CLICK_EFFECT_TIMEOUT_MS) {
  3683. const start = Date.now();
  3684. let recovered = false;
  3685. while (Date.now() - start < timeoutMs) {
  3686. throwIfStopped();
  3687. const tab = await chrome.tabs.get(tabId).catch(() => null);
  3688. if (!tab) {
  3689. throw new Error('步骤 8:认证页面标签页已关闭,无法继续自动授权。');
  3690. }
  3691. if (baselineUrl && typeof tab.url === 'string' && tab.url !== baselineUrl) {
  3692. return { progressed: true, reason: 'url_changed', url: tab.url };
  3693. }
  3694. const pageState = await getStep8PageState(tabId);
  3695. if (pageState?.addPhonePage) {
  3696. throw new Error('步骤 8:点击“继续”后页面跳到了手机号页面,当前流程无法继续自动授权。');
  3697. }
  3698. if (pageState === null) {
  3699. if (!recovered) {
  3700. recovered = true;
  3701. await ensureStep8SignupPageReady(tabId, {
  3702. timeoutMs: Math.max(3000, Math.min(8000, timeoutMs)),
  3703. logMessage: '步骤 8:点击后认证页正在重载,正在等待内容脚本重新就绪...',
  3704. }).catch(() => null);
  3705. continue;
  3706. }
  3707. await sleepWithStop(200);
  3708. continue;
  3709. }
  3710. recovered = false;
  3711. await sleepWithStop(200);
  3712. }
  3713. return { progressed: false, reason: 'no_effect' };
  3714. }
  3715. function getStep8EffectLabel(effect) {
  3716. switch (effect?.reason) {
  3717. case 'url_changed':
  3718. return `URL 已变化:${effect.url}`;
  3719. case 'page_reloading':
  3720. return '页面正在跳转或重载';
  3721. case 'left_consent_page':
  3722. return `页面已离开 OAuth 同意页:${effect.url || 'unknown'}`;
  3723. default:
  3724. return '页面仍停留在 OAuth 同意页';
  3725. }
  3726. }
  3727. async function executeStep8(state) {
  3728. if (!state.oauthUrl) {
  3729. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  3730. }
  3731. await addLog('步骤 8:正在监听 localhost 回调地址...');
  3732. return new Promise((resolve, reject) => {
  3733. let resolved = false;
  3734. let signupTabId = null;
  3735. const cleanupListener = () => {
  3736. cleanupStep8NavigationListeners();
  3737. step8PendingReject = null;
  3738. };
  3739. const rejectStep8 = (error) => {
  3740. if (resolved) return;
  3741. resolved = true;
  3742. clearTimeout(timeout);
  3743. cleanupListener();
  3744. reject(error);
  3745. };
  3746. const finalizeStep8Callback = (callbackUrl) => {
  3747. if (resolved || !callbackUrl) return;
  3748. resolved = true;
  3749. cleanupListener();
  3750. clearTimeout(timeout);
  3751. addLog(`步骤 8:已捕获 localhost 地址:${callbackUrl}`, 'ok').then(() => {
  3752. return completeStepFromBackground(8, { localhostUrl: callbackUrl });
  3753. }).then(() => {
  3754. resolve();
  3755. }).catch((err) => {
  3756. reject(err);
  3757. });
  3758. };
  3759. const timeout = setTimeout(() => {
  3760. rejectStep8(new Error('120 秒内未捕获到 localhost 回调跳转,步骤 8 的点击可能被拦截了。'));
  3761. }, 120000);
  3762. step8PendingReject = (error) => {
  3763. rejectStep8(error);
  3764. };
  3765. webNavListener = (details) => {
  3766. const callbackUrl = getStep8CallbackUrlFromNavigation(details, signupTabId);
  3767. finalizeStep8Callback(callbackUrl);
  3768. };
  3769. webNavCommittedListener = (details) => {
  3770. const callbackUrl = getStep8CallbackUrlFromNavigation(details, signupTabId);
  3771. finalizeStep8Callback(callbackUrl);
  3772. };
  3773. step8TabUpdatedListener = (tabId, changeInfo, tab) => {
  3774. const callbackUrl = getStep8CallbackUrlFromTabUpdate(tabId, changeInfo, tab, signupTabId);
  3775. finalizeStep8Callback(callbackUrl);
  3776. };
  3777. (async () => {
  3778. try {
  3779. throwIfStep8SettledOrStopped(resolved);
  3780. signupTabId = await getTabId('signup-page');
  3781. throwIfStep8SettledOrStopped(resolved);
  3782. if (signupTabId && await isTabAlive('signup-page')) {
  3783. await chrome.tabs.update(signupTabId, { active: true });
  3784. await addLog('步骤 8:已切回认证页,正在准备调试器点击...');
  3785. } else {
  3786. signupTabId = await reuseOrCreateTab('signup-page', state.oauthUrl);
  3787. await addLog('步骤 8:已重新打开认证页,正在准备调试器点击...');
  3788. }
  3789. throwIfStep8SettledOrStopped(resolved);
  3790. chrome.webNavigation.onBeforeNavigate.addListener(webNavListener);
  3791. chrome.webNavigation.onCommitted.addListener(webNavCommittedListener);
  3792. chrome.tabs.onUpdated.addListener(step8TabUpdatedListener);
  3793. await ensureStep8SignupPageReady(signupTabId, {
  3794. timeoutMs: 15000,
  3795. logMessage: '步骤 8:认证页内容脚本尚未就绪,正在等待页面恢复...',
  3796. });
  3797. for (let round = 1; round <= STEP8_MAX_ROUNDS && !resolved; round++) {
  3798. throwIfStep8SettledOrStopped(resolved);
  3799. const pageState = await waitForStep8Ready(signupTabId);
  3800. if (!pageState?.consentReady) {
  3801. await sleepWithStop(STEP8_CLICK_RETRY_DELAY_MS);
  3802. continue;
  3803. }
  3804. const strategy = STEP8_STRATEGIES[Math.min(round - 1, STEP8_STRATEGIES.length - 1)];
  3805. await addLog(`步骤 8:第 ${round}/${STEP8_MAX_ROUNDS} 轮尝试点击“继续”(${strategy.label})...`);
  3806. if (strategy.mode === 'debugger') {
  3807. const clickTarget = await prepareStep8DebuggerClick(signupTabId);
  3808. throwIfStep8SettledOrStopped(resolved);
  3809. await clickWithDebugger(signupTabId, clickTarget?.rect);
  3810. } else {
  3811. await triggerStep8ContentStrategy(signupTabId, strategy.strategy);
  3812. }
  3813. if (resolved) {
  3814. return;
  3815. }
  3816. const effect = await waitForStep8ClickEffect(signupTabId, pageState.url);
  3817. if (resolved) {
  3818. return;
  3819. }
  3820. if (effect.progressed) {
  3821. await addLog(`步骤 8:检测到本次点击已生效,${getStep8EffectLabel(effect)},继续等待 localhost 回调...`, 'info');
  3822. break;
  3823. }
  3824. if (round >= STEP8_MAX_ROUNDS) {
  3825. throw new Error(`步骤 8:连续 ${STEP8_MAX_ROUNDS} 轮点击“继续”后页面仍无反应。`);
  3826. }
  3827. await addLog(`步骤 8:${strategy.label} 本轮点击后页面无反应,正在刷新认证页后重试(下一轮 ${round + 1}/${STEP8_MAX_ROUNDS})...`, 'warn');
  3828. await reloadStep8ConsentPage(signupTabId);
  3829. await sleepWithStop(STEP8_CLICK_RETRY_DELAY_MS);
  3830. }
  3831. } catch (err) {
  3832. rejectStep8(err);
  3833. }
  3834. })();
  3835. });
  3836. }
  3837. // ============================================================
  3838. // Step 9: 平台回调验证
  3839. // ============================================================
  3840. async function executeStep9(state) {
  3841. if (getPanelMode(state) === 'sub2api') {
  3842. return executeSub2ApiStep9(state);
  3843. }
  3844. return executeCpaStep9(state);
  3845. }
  3846. async function executeCpaStep9(state) {
  3847. if (state.localhostUrl && !isLocalhostOAuthCallbackUrl(state.localhostUrl)) {
  3848. throw new Error('步骤 8 捕获到的 localhost OAuth 回调地址无效,请重新执行步骤 8。');
  3849. }
  3850. if (!state.localhostUrl) {
  3851. throw new Error('缺少 localhost 回调地址,请先完成步骤 8。');
  3852. }
  3853. if (!state.vpsUrl) {
  3854. throw new Error('尚未填写 CPA 地址,请先在侧边栏输入。');
  3855. }
  3856. if (shouldBypassStep9ForLocalCpa(state)) {
  3857. await addLog('步骤 9:检测到本地 CPA,步骤 8 完成后已自动添加,无需重复提交回调地址。', 'info');
  3858. await completeStepFromBackground(9, {
  3859. localhostUrl: state.localhostUrl,
  3860. verifiedStatus: 'local-auto',
  3861. });
  3862. return;
  3863. }
  3864. await addLog('步骤 9:正在打开 CPA 面板...');
  3865. const injectFiles = ['content/activation-utils.js', 'content/utils.js', 'content/vps-panel.js'];
  3866. let tabId = await getTabId('vps-panel');
  3867. const alive = tabId && await isTabAlive('vps-panel');
  3868. if (!alive) {
  3869. tabId = await reuseOrCreateTab('vps-panel', state.vpsUrl, {
  3870. inject: injectFiles,
  3871. reloadIfSameUrl: true,
  3872. });
  3873. } else {
  3874. await closeConflictingTabsForSource('vps-panel', state.vpsUrl, { excludeTabIds: [tabId] });
  3875. await chrome.tabs.update(tabId, { active: true });
  3876. await rememberSourceLastUrl('vps-panel', state.vpsUrl);
  3877. }
  3878. await ensureContentScriptReadyOnTab('vps-panel', tabId, {
  3879. inject: injectFiles,
  3880. timeoutMs: 45000,
  3881. retryDelayMs: 900,
  3882. logMessage: '姝ラ 9锛欳PA 闈㈡澘浠嶅湪鍔犺浇锛屾鍦ㄩ噸璇曡繛鎺ュ唴瀹硅剼鏈?..',
  3883. });
  3884. await addLog('步骤 9:正在填写回调地址...');
  3885. const result = await sendToContentScriptResilient('vps-panel', {
  3886. type: 'EXECUTE_STEP',
  3887. step: 9,
  3888. source: 'background',
  3889. payload: { localhostUrl: state.localhostUrl, vpsPassword: state.vpsPassword },
  3890. }, {
  3891. timeoutMs: 30000,
  3892. retryDelayMs: 700,
  3893. logMessage: '步骤 9:CPA 面板通信未就绪,正在等待页面恢复...',
  3894. });
  3895. if (result?.error) {
  3896. throw new Error(result.error);
  3897. }
  3898. }
  3899. async function executeSub2ApiStep9(state) {
  3900. if (state.localhostUrl && !isLocalhostOAuthCallbackUrl(state.localhostUrl)) {
  3901. throw new Error('步骤 8 捕获到的 localhost OAuth 回调地址无效,请重新执行步骤 8。');
  3902. }
  3903. if (!state.localhostUrl) {
  3904. throw new Error('缺少 localhost 回调地址,请先完成步骤 8。');
  3905. }
  3906. if (!state.sub2apiSessionId) {
  3907. throw new Error('缺少 SUB2API 会话信息,请重新执行步骤 1。');
  3908. }
  3909. if (!state.sub2apiEmail) {
  3910. throw new Error('尚未配置 SUB2API 登录邮箱,请先在侧边栏填写。');
  3911. }
  3912. if (!state.sub2apiPassword) {
  3913. throw new Error('尚未配置 SUB2API 登录密码,请先在侧边栏填写。');
  3914. }
  3915. const sub2apiUrl = normalizeSub2ApiUrl(state.sub2apiUrl);
  3916. const injectFiles = ['content/utils.js', 'content/sub2api-panel.js'];
  3917. await addLog('步骤 9:正在打开 SUB2API 后台...');
  3918. let tabId = await getTabId('sub2api-panel');
  3919. const alive = tabId && await isTabAlive('sub2api-panel');
  3920. if (!alive) {
  3921. tabId = await reuseOrCreateTab('sub2api-panel', sub2apiUrl, {
  3922. inject: injectFiles,
  3923. injectSource: 'sub2api-panel',
  3924. reloadIfSameUrl: true,
  3925. });
  3926. } else {
  3927. await closeConflictingTabsForSource('sub2api-panel', sub2apiUrl, { excludeTabIds: [tabId] });
  3928. await chrome.tabs.update(tabId, { active: true });
  3929. await rememberSourceLastUrl('sub2api-panel', sub2apiUrl);
  3930. }
  3931. await ensureContentScriptReadyOnTab('sub2api-panel', tabId, {
  3932. inject: injectFiles,
  3933. injectSource: 'sub2api-panel',
  3934. });
  3935. await addLog('步骤 9:正在向 SUB2API 提交回调并创建账号...');
  3936. const result = await sendToContentScript('sub2api-panel', {
  3937. type: 'EXECUTE_STEP',
  3938. step: 9,
  3939. source: 'background',
  3940. payload: {
  3941. localhostUrl: state.localhostUrl,
  3942. sub2apiUrl,
  3943. sub2apiEmail: state.sub2apiEmail,
  3944. sub2apiPassword: state.sub2apiPassword,
  3945. sub2apiGroupName: state.sub2apiGroupName,
  3946. sub2apiSessionId: state.sub2apiSessionId,
  3947. sub2apiOAuthState: state.sub2apiOAuthState,
  3948. sub2apiGroupId: state.sub2apiGroupId,
  3949. sub2apiDraftName: state.sub2apiDraftName,
  3950. },
  3951. }, {
  3952. responseTimeoutMs: SUB2API_STEP9_RESPONSE_TIMEOUT_MS,
  3953. });
  3954. if (result?.error) {
  3955. throw new Error(result.error);
  3956. }
  3957. }
  3958. // ============================================================
  3959. // Open Side Panel on extension icon click
  3960. // ============================================================
  3961. chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });
  3962. chrome.alarms.onAlarm.addListener((alarm) => {
  3963. if (alarm.name !== AUTO_RUN_ALARM_NAME) {
  3964. return;
  3965. }
  3966. launchScheduledAutoRun('alarm').catch((err) => {
  3967. console.error(LOG_PREFIX, 'Failed to launch scheduled auto run from alarm:', err);
  3968. });
  3969. });
  3970. chrome.runtime.onStartup.addListener(() => {
  3971. restoreScheduledAutoRunIfNeeded().catch((err) => {
  3972. console.error(LOG_PREFIX, 'Failed to restore scheduled auto run on startup:', err);
  3973. });
  3974. });
  3975. chrome.runtime.onInstalled.addListener(() => {
  3976. restoreScheduledAutoRunIfNeeded().catch((err) => {
  3977. console.error(LOG_PREFIX, 'Failed to restore scheduled auto run on install/update:', err);
  3978. });
  3979. });
  3980. restoreScheduledAutoRunIfNeeded().catch((err) => {
  3981. console.error(LOG_PREFIX, 'Failed to restore scheduled auto run:', err);
  3982. });