background.js 195 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885
  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. buildHotmailMailApiLatestUrl,
  5. extractVerificationCodeFromMessage,
  6. filterHotmailAccountsByUsage,
  7. getLatestHotmailMessage,
  8. getHotmailMailApiRequestConfig,
  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 LOG_PREFIX = '[MultiPage:bg]';
  22. const DUCK_AUTOFILL_URL = 'https://duckduckgo.com/email/settings/autofill';
  23. const HOTMAIL_PROVIDER = 'hotmail-api';
  24. const HOTMAIL_MAILBOXES = ['INBOX', 'Junk'];
  25. const STOP_ERROR_MESSAGE = '流程已被用户停止。';
  26. const HUMAN_STEP_DELAY_MIN = 700;
  27. const HUMAN_STEP_DELAY_MAX = 2200;
  28. const STEP7_MAIL_POLLING_RECOVERY_MAX_ATTEMPTS = 8;
  29. const SUB2API_STEP1_RESPONSE_TIMEOUT_MS = 90000;
  30. const SUB2API_STEP9_RESPONSE_TIMEOUT_MS = 120000;
  31. const DEFAULT_SUB2API_URL = 'https://sub2api.hisence.fun/admin/accounts';
  32. const DEFAULT_SUB2API_GROUP_NAME = 'codex';
  33. const DEFAULT_SUB2API_REDIRECT_URI = 'http://localhost:1455/auth/callback';
  34. const AUTO_RUN_ALARM_NAME = 'scheduled-auto-run';
  35. const AUTO_RUN_DELAY_MIN_MINUTES = 1;
  36. const AUTO_RUN_DELAY_MAX_MINUTES = 1440;
  37. const AUTO_RUN_RETRY_DELAY_MS = 3000;
  38. const AUTO_RUN_MAX_RETRIES_PER_ROUND = 3;
  39. const AUTO_STEP_DELAY_MIN_ALLOWED_SECONDS = 0;
  40. const AUTO_STEP_DELAY_MAX_ALLOWED_SECONDS = 600;
  41. const LEGACY_AUTO_STEP_DELAY_KEYS = ['autoStepRandomDelayMinSeconds', 'autoStepRandomDelayMaxSeconds'];
  42. const DEFAULT_LOCAL_CPA_STEP9_MODE = 'submit';
  43. const HOTMAIL_SERVICE_MODE_REMOTE = 'remote';
  44. const HOTMAIL_SERVICE_MODE_LOCAL = 'local';
  45. const DEFAULT_HOTMAIL_REMOTE_BASE_URL = '';
  46. const DEFAULT_HOTMAIL_LOCAL_BASE_URL = 'http://127.0.0.1:17373';
  47. const HOTMAIL_LOCAL_HELPER_TIMEOUT_MS = 45000;
  48. const DISPLAY_TIMEZONE = 'Asia/Shanghai';
  49. initializeSessionStorageAccess();
  50. // ============================================================
  51. // 状态管理(chrome.storage.session + chrome.storage.local)
  52. // ============================================================
  53. const PERSISTED_SETTING_DEFAULTS = {
  54. panelMode: 'cpa',
  55. vpsUrl: '',
  56. vpsPassword: '',
  57. localCpaStep9Mode: DEFAULT_LOCAL_CPA_STEP9_MODE,
  58. sub2apiUrl: DEFAULT_SUB2API_URL,
  59. sub2apiEmail: '',
  60. sub2apiPassword: '',
  61. sub2apiGroupName: DEFAULT_SUB2API_GROUP_NAME,
  62. customPassword: '',
  63. autoRunSkipFailures: false,
  64. autoRunFallbackThreadIntervalMinutes: 0,
  65. autoRunDelayEnabled: false,
  66. autoRunDelayMinutes: 30,
  67. autoStepDelaySeconds: null,
  68. mailProvider: '163',
  69. emailGenerator: 'duck',
  70. emailPrefix: '',
  71. inbucketHost: '',
  72. inbucketMailbox: '',
  73. hotmailServiceMode: HOTMAIL_SERVICE_MODE_LOCAL,
  74. hotmailRemoteBaseUrl: DEFAULT_HOTMAIL_REMOTE_BASE_URL,
  75. hotmailLocalBaseUrl: DEFAULT_HOTMAIL_LOCAL_BASE_URL,
  76. cloudflareDomain: '',
  77. cloudflareDomains: [],
  78. hotmailAccounts: [],
  79. };
  80. const PERSISTED_SETTING_KEYS = Object.keys(PERSISTED_SETTING_DEFAULTS);
  81. const SETTINGS_EXPORT_SCHEMA_VERSION = 1;
  82. const SETTINGS_EXPORT_FILENAME_PREFIX = 'multipage-settings';
  83. const DEFAULT_STATE = {
  84. currentStep: 0, // 当前流程执行到的步骤编号。
  85. stepStatuses: {
  86. 1: 'pending', 2: 'pending', 3: 'pending', 4: 'pending', 5: 'pending', // 运行时步骤状态映射,不要手动预填。
  87. 6: 'pending', 7: 'pending', 8: 'pending', 9: 'pending',
  88. },
  89. oauthUrl: null, // 运行时抓取到的 OAuth 地址,不要手动预填。
  90. email: null, // 运行时邮箱,由程序自动获取并写入,不能手动预填。
  91. password: null, // 运行时实际密码,由 customPassword 或程序自动生成后写入。
  92. accounts: [], // 已生成账号记录:{ email, password, createdAt }。
  93. lastEmailTimestamp: null, // 最近一次获取到邮箱数据的运行时时间戳。
  94. lastSignupCode: null, // 注册验证码,运行时由程序自动读取并写入。
  95. lastLoginCode: null, // 登录验证码,运行时由程序自动读取并写入。
  96. localhostUrl: null, // 运行时捕获到的 localhost 回调地址,不要手动预填。
  97. sub2apiSessionId: null, // SUB2API OpenAI Auth 会话 ID。
  98. sub2apiOAuthState: null, // SUB2API OpenAI Auth state。
  99. sub2apiGroupId: null, // SUB2API 目标分组 ID。
  100. sub2apiDraftName: null, // SUB2API 本轮预生成的账号名称。
  101. flowStartTime: null, // 当前流程开始时间。
  102. tabRegistry: {}, // 程序维护的标签页注册表。
  103. sourceLastUrls: {}, // 各来源页面最近一次打开的地址记录。
  104. logs: [], // 侧边栏展示的运行日志。
  105. ...PERSISTED_SETTING_DEFAULTS, // 合并 chrome.storage.local 中持久化保存的用户配置。
  106. autoRunning: false, // 当前是否处于自动运行中。
  107. autoRunPhase: 'idle', // 当前自动运行阶段。
  108. autoRunCurrentRun: 0, // 自动运行当前执行到第几轮。
  109. autoRunTotalRuns: 1, // 自动运行计划总轮数。
  110. autoRunAttemptRun: 0, // 当前轮次的重试序号。
  111. autoRunRoundSummaries: [], // 自动运行轮次摘要。
  112. scheduledAutoRunAt: null, // 自动运行计划启动时间戳。
  113. scheduledAutoRunPlan: null, // 自动运行计划参数快照。
  114. autoRunCountdownAt: null,
  115. autoRunCountdownTitle: '',
  116. autoRunCountdownNote: '',
  117. signupVerificationRequestedAt: null,
  118. loginVerificationRequestedAt: null,
  119. currentHotmailAccountId: null,
  120. };
  121. function normalizeAutoRunDelayMinutes(value) {
  122. const numeric = Number(value);
  123. if (!Number.isFinite(numeric)) {
  124. return PERSISTED_SETTING_DEFAULTS.autoRunDelayMinutes;
  125. }
  126. return Math.min(
  127. AUTO_RUN_DELAY_MAX_MINUTES,
  128. Math.max(AUTO_RUN_DELAY_MIN_MINUTES, Math.floor(numeric))
  129. );
  130. }
  131. function normalizeAutoRunFallbackThreadIntervalMinutes(value) {
  132. const rawValue = String(value ?? '').trim();
  133. if (!rawValue) {
  134. return 0;
  135. }
  136. const numeric = Number(rawValue);
  137. if (!Number.isFinite(numeric)) {
  138. return 0;
  139. }
  140. return Math.min(
  141. AUTO_RUN_DELAY_MAX_MINUTES,
  142. Math.max(0, Math.floor(numeric))
  143. );
  144. }
  145. function normalizeAutoStepDelaySeconds(value, fallback = null) {
  146. const rawValue = String(value ?? '').trim();
  147. if (!rawValue) {
  148. return fallback;
  149. }
  150. const numeric = Number(rawValue);
  151. if (!Number.isFinite(numeric)) {
  152. return fallback;
  153. }
  154. return Math.min(
  155. AUTO_STEP_DELAY_MAX_ALLOWED_SECONDS,
  156. Math.max(AUTO_STEP_DELAY_MIN_ALLOWED_SECONDS, Math.floor(numeric))
  157. );
  158. }
  159. function resolveLegacyAutoStepDelaySeconds(input = {}) {
  160. const hasLegacyMin = input.autoStepRandomDelayMinSeconds !== undefined;
  161. const hasLegacyMax = input.autoStepRandomDelayMaxSeconds !== undefined;
  162. if (!hasLegacyMin && !hasLegacyMax) {
  163. return undefined;
  164. }
  165. const minSeconds = normalizeAutoStepDelaySeconds(input.autoStepRandomDelayMinSeconds, null);
  166. const maxSeconds = normalizeAutoStepDelaySeconds(input.autoStepRandomDelayMaxSeconds, null);
  167. if (minSeconds === null && maxSeconds === null) {
  168. return null;
  169. }
  170. if (minSeconds === null) {
  171. return maxSeconds;
  172. }
  173. if (maxSeconds === null) {
  174. return minSeconds;
  175. }
  176. return Math.round((minSeconds + maxSeconds) / 2);
  177. }
  178. function normalizeRunCount(value) {
  179. const numeric = Number(value);
  180. if (!Number.isFinite(numeric)) {
  181. return 1;
  182. }
  183. return Math.min(50, Math.max(1, Math.floor(numeric)));
  184. }
  185. function normalizeScheduledAutoRunPlan(plan) {
  186. if (!plan || typeof plan !== 'object') {
  187. return null;
  188. }
  189. return {
  190. totalRuns: normalizeRunCount(plan.totalRuns),
  191. autoRunSkipFailures: Boolean(plan.autoRunSkipFailures),
  192. mode: plan.mode === 'continue' ? 'continue' : 'restart',
  193. };
  194. }
  195. function normalizeEmailGenerator(value = '') {
  196. const normalized = String(value || '').trim().toLowerCase();
  197. if (normalized === 'custom' || normalized === 'manual') {
  198. return 'custom';
  199. }
  200. if (normalized === 'cloudflare') {
  201. return 'cloudflare';
  202. }
  203. return 'duck';
  204. }
  205. function normalizePanelMode(value = '') {
  206. return String(value || '').trim().toLowerCase() === 'sub2api' ? 'sub2api' : 'cpa';
  207. }
  208. function normalizeMailProvider(value = '') {
  209. const normalized = String(value || '').trim().toLowerCase();
  210. switch (normalized) {
  211. case 'custom':
  212. case HOTMAIL_PROVIDER:
  213. case '163':
  214. case '163-vip':
  215. case 'qq':
  216. case 'inbucket':
  217. case '2925':
  218. return normalized;
  219. default:
  220. return PERSISTED_SETTING_DEFAULTS.mailProvider;
  221. }
  222. }
  223. function normalizeLocalCpaStep9Mode(value = '') {
  224. return String(value || '').trim().toLowerCase() === 'bypass'
  225. ? 'bypass'
  226. : DEFAULT_LOCAL_CPA_STEP9_MODE;
  227. }
  228. function normalizeCloudflareDomain(rawValue = '') {
  229. let value = String(rawValue || '').trim().toLowerCase();
  230. if (!value) return '';
  231. value = value.replace(/^@+/, '');
  232. value = value.replace(/^https?:\/\//, '');
  233. value = value.replace(/\/.*$/, '');
  234. if (!/^[a-z0-9.-]+\.[a-z]{2,}$/.test(value)) return '';
  235. return value;
  236. }
  237. function normalizeCloudflareDomains(values) {
  238. const normalizedDomains = [];
  239. const seen = new Set();
  240. for (const value of Array.isArray(values) ? values : []) {
  241. const normalized = normalizeCloudflareDomain(value);
  242. if (!normalized || seen.has(normalized)) continue;
  243. seen.add(normalized);
  244. normalizedDomains.push(normalized);
  245. }
  246. return normalizedDomains;
  247. }
  248. function normalizeHotmailServiceMode(rawValue = '') {
  249. return HOTMAIL_SERVICE_MODE_LOCAL;
  250. }
  251. function normalizeHotmailRemoteBaseUrl(rawValue = '') {
  252. const value = String(rawValue || '').trim();
  253. if (!value) return DEFAULT_HOTMAIL_REMOTE_BASE_URL;
  254. try {
  255. const parsed = new URL(value);
  256. if (!['http:', 'https:'].includes(parsed.protocol)) {
  257. return DEFAULT_HOTMAIL_REMOTE_BASE_URL;
  258. }
  259. if (parsed.pathname.endsWith('/api/mail-new') || parsed.pathname.endsWith('/api/mail-all') || parsed.pathname === '/api.html') {
  260. parsed.pathname = '';
  261. parsed.search = '';
  262. parsed.hash = '';
  263. }
  264. return parsed.toString().replace(/\/$/, '');
  265. } catch {
  266. return DEFAULT_HOTMAIL_REMOTE_BASE_URL;
  267. }
  268. }
  269. function normalizeHotmailLocalBaseUrl(rawValue = '') {
  270. const value = String(rawValue || '').trim();
  271. if (!value) return DEFAULT_HOTMAIL_LOCAL_BASE_URL;
  272. try {
  273. const parsed = new URL(value);
  274. if (!['http:', 'https:'].includes(parsed.protocol)) {
  275. return DEFAULT_HOTMAIL_LOCAL_BASE_URL;
  276. }
  277. if (['/messages', '/code', '/clear', '/token'].includes(parsed.pathname)) {
  278. parsed.pathname = '';
  279. parsed.search = '';
  280. parsed.hash = '';
  281. }
  282. return parsed.toString().replace(/\/$/, '');
  283. } catch {
  284. return DEFAULT_HOTMAIL_LOCAL_BASE_URL;
  285. }
  286. }
  287. function getHotmailServiceSettings(state = {}) {
  288. return {
  289. mode: normalizeHotmailServiceMode(state.hotmailServiceMode),
  290. remoteBaseUrl: normalizeHotmailRemoteBaseUrl(state.hotmailRemoteBaseUrl),
  291. localBaseUrl: normalizeHotmailLocalBaseUrl(state.hotmailLocalBaseUrl),
  292. };
  293. }
  294. function normalizePersistentSettingValue(key, value) {
  295. switch (key) {
  296. case 'panelMode':
  297. return normalizePanelMode(value);
  298. case 'vpsUrl':
  299. return String(value || '').trim();
  300. case 'vpsPassword':
  301. return String(value || '');
  302. case 'localCpaStep9Mode':
  303. return normalizeLocalCpaStep9Mode(value);
  304. case 'sub2apiUrl':
  305. return String(value || '').trim();
  306. case 'sub2apiEmail':
  307. return String(value || '').trim();
  308. case 'sub2apiPassword':
  309. return String(value || '');
  310. case 'sub2apiGroupName':
  311. return String(value || '').trim();
  312. case 'customPassword':
  313. return String(value || '');
  314. case 'autoRunSkipFailures':
  315. case 'autoRunDelayEnabled':
  316. return Boolean(value);
  317. case 'autoRunFallbackThreadIntervalMinutes':
  318. return normalizeAutoRunFallbackThreadIntervalMinutes(value);
  319. case 'autoRunDelayMinutes':
  320. return normalizeAutoRunDelayMinutes(value);
  321. case 'autoStepDelaySeconds':
  322. return normalizeAutoStepDelaySeconds(value, PERSISTED_SETTING_DEFAULTS.autoStepDelaySeconds);
  323. case 'mailProvider':
  324. return normalizeMailProvider(value);
  325. case 'emailGenerator':
  326. return normalizeEmailGenerator(value);
  327. case 'emailPrefix':
  328. return String(value || '').trim();
  329. case 'inbucketHost':
  330. return String(value || '').trim();
  331. case 'inbucketMailbox':
  332. return String(value || '').trim();
  333. case 'hotmailServiceMode':
  334. return normalizeHotmailServiceMode(value);
  335. case 'hotmailRemoteBaseUrl':
  336. return normalizeHotmailRemoteBaseUrl(value);
  337. case 'hotmailLocalBaseUrl':
  338. return normalizeHotmailLocalBaseUrl(value);
  339. case 'cloudflareDomain':
  340. return normalizeCloudflareDomain(value);
  341. case 'cloudflareDomains':
  342. return normalizeCloudflareDomains(value);
  343. case 'hotmailAccounts':
  344. return normalizeHotmailAccounts(value);
  345. default:
  346. return value;
  347. }
  348. }
  349. function buildPersistentSettingsPayload(input = {}, options = {}) {
  350. const { fillDefaults = false, requireKnownKeys = false } = options;
  351. if (!input || typeof input !== 'object' || Array.isArray(input)) {
  352. throw new Error('\u914d\u7f6e\u5185\u5bb9\u683c\u5f0f\u65e0\u6548\u3002');
  353. }
  354. const normalizedInput = { ...input };
  355. if (normalizedInput.autoStepDelaySeconds === undefined) {
  356. const legacyAutoStepDelaySeconds = resolveLegacyAutoStepDelaySeconds(normalizedInput);
  357. if (legacyAutoStepDelaySeconds !== undefined) {
  358. normalizedInput.autoStepDelaySeconds = legacyAutoStepDelaySeconds;
  359. }
  360. }
  361. const payload = {};
  362. let matchedKeyCount = 0;
  363. for (const key of PERSISTED_SETTING_KEYS) {
  364. if (normalizedInput[key] !== undefined) {
  365. payload[key] = normalizePersistentSettingValue(key, normalizedInput[key]);
  366. matchedKeyCount += 1;
  367. } else if (fillDefaults) {
  368. payload[key] = normalizePersistentSettingValue(key, PERSISTED_SETTING_DEFAULTS[key]);
  369. }
  370. }
  371. if (requireKnownKeys && matchedKeyCount === 0) {
  372. throw new Error('\u914d\u7f6e\u6587\u4ef6\u4e2d\u6ca1\u6709\u53ef\u8bc6\u522b\u7684\u914d\u7f6e\u5185\u5bb9\u3002');
  373. }
  374. if (payload.cloudflareDomains) {
  375. const domains = normalizeCloudflareDomains(payload.cloudflareDomains);
  376. if (payload.cloudflareDomain && !domains.includes(payload.cloudflareDomain)) {
  377. domains.unshift(payload.cloudflareDomain);
  378. }
  379. payload.cloudflareDomains = domains;
  380. }
  381. return payload;
  382. }
  383. async function getPersistedSettings() {
  384. const stored = await chrome.storage.local.get([...PERSISTED_SETTING_KEYS, ...LEGACY_AUTO_STEP_DELAY_KEYS]);
  385. return buildPersistentSettingsPayload(stored, { fillDefaults: true });
  386. }
  387. async function getState() {
  388. const [state, persistedSettings] = await Promise.all([
  389. chrome.storage.session.get(null),
  390. getPersistedSettings(),
  391. ]);
  392. return { ...DEFAULT_STATE, ...persistedSettings, ...state };
  393. }
  394. async function initializeSessionStorageAccess() {
  395. try {
  396. if (chrome.storage?.session?.setAccessLevel) {
  397. await chrome.storage.session.setAccessLevel({
  398. accessLevel: 'TRUSTED_AND_UNTRUSTED_CONTEXTS',
  399. });
  400. console.log(LOG_PREFIX, 'Enabled storage.session for content scripts');
  401. }
  402. } catch (err) {
  403. console.warn(LOG_PREFIX, 'Failed to enable storage.session for content scripts:', err?.message || err);
  404. }
  405. }
  406. async function setState(updates) {
  407. console.log(LOG_PREFIX, 'storage.set:', JSON.stringify(updates).slice(0, 200));
  408. if (Object.keys(updates || {}).length > 0) {
  409. await chrome.storage.session.set(updates);
  410. }
  411. }
  412. async function setPersistentSettings(updates) {
  413. const persistedUpdates = buildPersistentSettingsPayload(updates);
  414. if (Object.keys(persistedUpdates).length > 0) {
  415. await chrome.storage.local.set(persistedUpdates);
  416. }
  417. }
  418. function buildSettingsExportFilename(date = new Date()) {
  419. const pad = (value) => String(value).padStart(2, '0');
  420. return `${SETTINGS_EXPORT_FILENAME_PREFIX}-${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}-${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}.json`;
  421. }
  422. async function exportSettingsBundle() {
  423. const settings = await getPersistedSettings();
  424. const bundle = {
  425. schemaVersion: SETTINGS_EXPORT_SCHEMA_VERSION,
  426. exportedAt: new Date().toISOString(),
  427. extensionVersion: chrome.runtime.getManifest().version,
  428. settings,
  429. };
  430. return {
  431. fileName: buildSettingsExportFilename(),
  432. fileContent: JSON.stringify(bundle, null, 2),
  433. };
  434. }
  435. async function importSettingsBundle(configBundle) {
  436. const state = await ensureManualInteractionAllowed('\u5bfc\u5165\u914d\u7f6e');
  437. if (Object.values(state.stepStatuses || {}).some((status) => status === 'running')) {
  438. throw new Error('\u5f53\u524d\u6709\u6b65\u9aa4\u6b63\u5728\u6267\u884c\uff0c\u65e0\u6cd5\u5bfc\u5165\u914d\u7f6e\u3002');
  439. }
  440. if (!configBundle || typeof configBundle !== 'object' || Array.isArray(configBundle)) {
  441. throw new Error('\u914d\u7f6e\u6587\u4ef6\u5185\u5bb9\u65e0\u6548\u3002');
  442. }
  443. const schemaVersion = Number(configBundle.schemaVersion);
  444. if (schemaVersion !== SETTINGS_EXPORT_SCHEMA_VERSION) {
  445. throw new Error(`\u4ec5\u652f\u6301\u5bfc\u5165 schemaVersion=${SETTINGS_EXPORT_SCHEMA_VERSION} \u7684\u914d\u7f6e\u6587\u4ef6\u3002`);
  446. }
  447. if (!configBundle.settings || typeof configBundle.settings !== 'object' || Array.isArray(configBundle.settings)) {
  448. throw new Error('\u914d\u7f6e\u6587\u4ef6\u7f3a\u5c11 settings \u914d\u7f6e\u6bb5\u3002');
  449. }
  450. const importedSettings = buildPersistentSettingsPayload(configBundle.settings, {
  451. fillDefaults: true,
  452. requireKnownKeys: true,
  453. });
  454. await setPersistentSettings(importedSettings);
  455. const sessionUpdates = {
  456. ...importedSettings,
  457. currentHotmailAccountId: null,
  458. email: null,
  459. };
  460. await setState(sessionUpdates);
  461. broadcastDataUpdate({
  462. ...importedSettings,
  463. currentHotmailAccountId: null,
  464. ...(sessionUpdates.email !== undefined ? { email: sessionUpdates.email } : {}),
  465. });
  466. return getState();
  467. }
  468. function broadcastDataUpdate(payload) {
  469. chrome.runtime.sendMessage({
  470. type: 'DATA_UPDATED',
  471. payload,
  472. }).catch(() => { });
  473. }
  474. async function setEmailStateSilently(email) {
  475. await setState({ email });
  476. broadcastDataUpdate({ email });
  477. }
  478. async function setEmailState(email) {
  479. await setEmailStateSilently(email);
  480. if (email) {
  481. await resumeAutoRunIfWaitingForEmail();
  482. }
  483. }
  484. async function setPasswordState(password) {
  485. await setState({ password });
  486. broadcastDataUpdate({ password });
  487. }
  488. async function resetState() {
  489. console.log(LOG_PREFIX, 'Resetting all state');
  490. // Preserve settings and persistent data across resets
  491. const [prev, persistedSettings] = await Promise.all([
  492. chrome.storage.session.get([
  493. 'seenCodes',
  494. 'seenInbucketMailIds',
  495. 'accounts',
  496. 'tabRegistry',
  497. 'sourceLastUrls',
  498. ]),
  499. getPersistedSettings(),
  500. ]);
  501. await chrome.storage.session.clear();
  502. await chrome.storage.session.set({
  503. ...DEFAULT_STATE,
  504. ...persistedSettings,
  505. seenCodes: prev.seenCodes || [],
  506. seenInbucketMailIds: prev.seenInbucketMailIds || [],
  507. accounts: prev.accounts || [],
  508. tabRegistry: prev.tabRegistry || {},
  509. sourceLastUrls: prev.sourceLastUrls || {},
  510. });
  511. }
  512. /**
  513. * Generate a random password: 14 chars, mix of uppercase, lowercase, digits, symbols.
  514. */
  515. function generatePassword() {
  516. const upper = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
  517. const lower = 'abcdefghjkmnpqrstuvwxyz';
  518. const digits = '23456789';
  519. const symbols = '!@#$%&*?';
  520. const all = upper + lower + digits + symbols;
  521. // Ensure at least one of each type
  522. let pw = '';
  523. pw += upper[Math.floor(Math.random() * upper.length)];
  524. pw += lower[Math.floor(Math.random() * lower.length)];
  525. pw += digits[Math.floor(Math.random() * digits.length)];
  526. pw += symbols[Math.floor(Math.random() * symbols.length)];
  527. // Fill remaining 10 chars
  528. for (let i = 0; i < 10; i++) {
  529. pw += all[Math.floor(Math.random() * all.length)];
  530. }
  531. // Shuffle
  532. return pw.split('').sort(() => Math.random() - 0.5).join('');
  533. }
  534. function normalizeHotmailAccount(account = {}) {
  535. const normalizedLastAuthAt = Number.isFinite(Number(account.lastAuthAt)) ? Number(account.lastAuthAt) : 0;
  536. const normalizedStatus = String(
  537. account.status
  538. || (normalizedLastAuthAt > 0 ? 'authorized' : 'pending')
  539. );
  540. return {
  541. id: String(account.id || crypto.randomUUID()),
  542. email: String(account.email || '').trim(),
  543. password: String(account.password || ''),
  544. clientId: String(account.clientId || '').trim(),
  545. refreshToken: String(account.refreshToken || ''),
  546. status: normalizedStatus,
  547. enabled: account.enabled !== undefined ? Boolean(account.enabled) : true,
  548. used: Boolean(account.used),
  549. lastUsedAt: Number.isFinite(Number(account.lastUsedAt)) ? Number(account.lastUsedAt) : 0,
  550. lastAuthAt: normalizedLastAuthAt,
  551. lastError: String(account.lastError || ''),
  552. };
  553. }
  554. function normalizeHotmailAccounts(accounts) {
  555. if (!Array.isArray(accounts)) return [];
  556. const deduped = new Map();
  557. for (const account of accounts) {
  558. const normalized = normalizeHotmailAccount(account);
  559. if (!normalized.email && !normalized.id) continue;
  560. deduped.set(normalized.id, normalized);
  561. }
  562. return [...deduped.values()];
  563. }
  564. function findHotmailAccount(accounts, accountId) {
  565. return normalizeHotmailAccounts(accounts).find((account) => account.id === accountId) || null;
  566. }
  567. function isHotmailProvider(stateOrProvider) {
  568. const provider = typeof stateOrProvider === 'string'
  569. ? stateOrProvider
  570. : stateOrProvider?.mailProvider;
  571. return provider === HOTMAIL_PROVIDER;
  572. }
  573. function isCustomMailProvider(stateOrProvider) {
  574. const provider = typeof stateOrProvider === 'string'
  575. ? stateOrProvider
  576. : stateOrProvider?.mailProvider;
  577. return provider === 'custom';
  578. }
  579. async function syncHotmailAccounts(accounts) {
  580. const normalized = normalizeHotmailAccounts(accounts);
  581. await setPersistentSettings({ hotmailAccounts: normalized });
  582. await setState({ hotmailAccounts: normalized });
  583. broadcastDataUpdate({ hotmailAccounts: normalized });
  584. return normalized;
  585. }
  586. async function upsertHotmailAccount(input) {
  587. const state = await getState();
  588. const accounts = normalizeHotmailAccounts(state.hotmailAccounts);
  589. const normalizedEmail = String(input?.email || '').trim().toLowerCase();
  590. const existing = input?.id
  591. ? findHotmailAccount(accounts, input.id)
  592. : accounts.find((account) => account.email.toLowerCase() === normalizedEmail) || null;
  593. const credentialsChanged = !existing
  594. || (input?.clientId !== undefined && String(input.clientId).trim() !== existing.clientId)
  595. || (input?.refreshToken !== undefined && String(input.refreshToken).trim() !== existing.refreshToken)
  596. || (input?.email !== undefined && String(input.email).trim().toLowerCase() !== existing.email.toLowerCase());
  597. const normalized = normalizeHotmailAccount({
  598. ...(existing || {}),
  599. ...(credentialsChanged ? {
  600. status: 'pending',
  601. lastAuthAt: 0,
  602. lastError: '',
  603. } : {}),
  604. ...input,
  605. id: input?.id || existing?.id || crypto.randomUUID(),
  606. });
  607. const nextAccounts = existing
  608. ? accounts.map((account) => (account.id === normalized.id ? normalized : account))
  609. : [...accounts, normalized];
  610. await syncHotmailAccounts(nextAccounts);
  611. return normalized;
  612. }
  613. async function deleteHotmailAccount(accountId) {
  614. const state = await getState();
  615. const accounts = normalizeHotmailAccounts(state.hotmailAccounts);
  616. const nextAccounts = accounts.filter((account) => account.id !== accountId);
  617. await syncHotmailAccounts(nextAccounts);
  618. if (state.currentHotmailAccountId === accountId) {
  619. await setState({ currentHotmailAccountId: null });
  620. if (isHotmailProvider(state)) {
  621. await setEmailState(null);
  622. }
  623. broadcastDataUpdate({ currentHotmailAccountId: null });
  624. }
  625. }
  626. async function deleteHotmailAccounts(mode = 'all') {
  627. const state = await getState();
  628. const accounts = normalizeHotmailAccounts(state.hotmailAccounts);
  629. const targets = filterHotmailAccountsByUsage(accounts, mode);
  630. const targetIds = new Set(targets.map((account) => account.id));
  631. const nextAccounts = mode === 'used'
  632. ? accounts.filter((account) => !targetIds.has(account.id))
  633. : [];
  634. await syncHotmailAccounts(nextAccounts);
  635. if (state.currentHotmailAccountId && targetIds.has(state.currentHotmailAccountId)) {
  636. await setState({ currentHotmailAccountId: null });
  637. if (isHotmailProvider(state)) {
  638. await setEmailState(null);
  639. }
  640. broadcastDataUpdate({ currentHotmailAccountId: null });
  641. }
  642. return {
  643. deletedCount: targets.length,
  644. remainingCount: nextAccounts.length,
  645. };
  646. }
  647. async function patchHotmailAccount(accountId, updates = {}) {
  648. const state = await getState();
  649. const accounts = normalizeHotmailAccounts(state.hotmailAccounts);
  650. const account = findHotmailAccount(accounts, accountId);
  651. if (!account) {
  652. throw new Error('未找到对应的 Hotmail 账号。');
  653. }
  654. const nextAccount = normalizeHotmailAccount({
  655. ...account,
  656. ...updates,
  657. id: account.id,
  658. });
  659. await syncHotmailAccounts(accounts.map((item) => (item.id === account.id ? nextAccount : item)));
  660. if (state.currentHotmailAccountId === account.id && shouldClearHotmailCurrentSelection(nextAccount)) {
  661. await setState({ currentHotmailAccountId: null });
  662. broadcastDataUpdate({ currentHotmailAccountId: null });
  663. if (isHotmailProvider(state)) {
  664. await setEmailState(null);
  665. }
  666. }
  667. return nextAccount;
  668. }
  669. async function setCurrentHotmailAccount(accountId, options = {}) {
  670. const { markUsed = false, syncEmail = true } = options;
  671. const state = await getState();
  672. const accounts = normalizeHotmailAccounts(state.hotmailAccounts);
  673. const account = findHotmailAccount(accounts, accountId);
  674. if (!account) {
  675. throw new Error('未找到对应的 Hotmail 账号。');
  676. }
  677. if (markUsed) {
  678. account.lastUsedAt = Date.now();
  679. await syncHotmailAccounts(accounts.map((item) => (item.id === account.id ? account : item)));
  680. }
  681. await setState({ currentHotmailAccountId: account.id });
  682. broadcastDataUpdate({ currentHotmailAccountId: account.id });
  683. if (syncEmail) {
  684. await setEmailState(account.email || null);
  685. }
  686. return account;
  687. }
  688. async function ensureHotmailAccountForFlow(options = {}) {
  689. const { allowAllocate = true, markUsed = false, preferredAccountId = null } = options;
  690. const state = await getState();
  691. const accounts = normalizeHotmailAccounts(state.hotmailAccounts);
  692. const isAccountAllocatable = (candidate) => Boolean(candidate)
  693. && candidate.status === 'authorized'
  694. && !candidate.used
  695. && Boolean(candidate.refreshToken);
  696. let account = null;
  697. if (preferredAccountId) {
  698. account = findHotmailAccount(accounts, preferredAccountId);
  699. }
  700. if (!account && state.currentHotmailAccountId) {
  701. account = findHotmailAccount(accounts, state.currentHotmailAccountId);
  702. }
  703. if ((!account || !isAccountAllocatable(account)) && allowAllocate) {
  704. account = pickHotmailAccountForRun(accounts, {});
  705. }
  706. if (!account) {
  707. throw new Error('没有可用的 Hotmail 账号。请先在侧边栏添加至少一个带刷新令牌(refresh token)的账号。');
  708. }
  709. if (!isAccountAllocatable(account)) {
  710. throw new Error(`Hotmail 账号 ${account.email || account.id} 尚未就绪,无法读取邮件。`);
  711. }
  712. return setCurrentHotmailAccount(account.id, { markUsed, syncEmail: true });
  713. }
  714. function buildHotmailRemoteEndpoint(baseUrl, path) {
  715. const normalizedBaseUrl = normalizeHotmailRemoteBaseUrl(baseUrl);
  716. return new URL(path, `${normalizedBaseUrl}/`).toString();
  717. }
  718. function buildHotmailLocalEndpoint(baseUrl, path) {
  719. const normalizedBaseUrl = normalizeHotmailLocalBaseUrl(baseUrl);
  720. return new URL(path, `${normalizedBaseUrl}/`).toString();
  721. }
  722. async function requestHotmailRemoteMailbox(account, mailbox = 'INBOX') {
  723. if (!account?.email) {
  724. throw new Error('Hotmail 账号缺少邮箱地址。');
  725. }
  726. if (!account?.clientId) {
  727. throw new Error(`Hotmail 账号 ${account.email || account.id} 缺少客户端 ID。`);
  728. }
  729. if (!account?.refreshToken) {
  730. throw new Error(`Hotmail 账号 ${account.email || account.id} 缺少刷新令牌(refresh token)。`);
  731. }
  732. const serviceSettings = getHotmailServiceSettings(await getState());
  733. const url = buildHotmailMailApiLatestUrl({
  734. apiUrl: buildHotmailRemoteEndpoint(serviceSettings.remoteBaseUrl, '/api/mail-new'),
  735. clientId: account.clientId,
  736. email: account.email,
  737. refreshToken: account.refreshToken,
  738. mailbox,
  739. responseType: 'json',
  740. });
  741. const { timeoutMs } = getHotmailMailApiRequestConfig();
  742. const controller = new AbortController();
  743. const timeoutId = setTimeout(() => controller.abort(new Error('timeout')), timeoutMs);
  744. let response;
  745. try {
  746. response = await fetch(url, { method: 'GET', signal: controller.signal });
  747. } catch (err) {
  748. if (err?.name === 'AbortError') {
  749. throw new Error(`Hotmail API 请求超时(>${Math.round(timeoutMs / 1000)} 秒):${mailbox}`);
  750. }
  751. throw new Error(`Hotmail API 请求失败:${err.message}`);
  752. } finally {
  753. clearTimeout(timeoutId);
  754. }
  755. const text = await response.text();
  756. let payload = {};
  757. try {
  758. payload = text ? JSON.parse(text) : {};
  759. } catch {
  760. payload = { raw: text };
  761. }
  762. if (!response.ok) {
  763. const errorText = payload?.message || payload?.error || payload?.msg || text || `HTTP ${response.status}`;
  764. throw new Error(`Hotmail API 请求失败:${errorText}`);
  765. }
  766. if (payload && payload.success === false) {
  767. const errorText = payload?.message || payload?.msg || payload?.error || '未知错误';
  768. throw new Error(`Hotmail API 返回失败:${errorText}`);
  769. }
  770. return {
  771. mailbox,
  772. payload,
  773. messages: normalizeHotmailMailApiMessages(payload?.data),
  774. nextRefreshToken: String(payload?.new_refresh_token || payload?.newRefreshToken || '').trim(),
  775. };
  776. }
  777. function applyHotmailApiResultToAccount(account, apiResult) {
  778. const nextRefreshToken = String(apiResult?.nextRefreshToken || '').trim();
  779. return {
  780. ...account,
  781. refreshToken: nextRefreshToken || account.refreshToken,
  782. status: 'authorized',
  783. lastAuthAt: Date.now(),
  784. lastError: '',
  785. };
  786. }
  787. function buildHotmailMailApiFailureAccount(account, errorMessage) {
  788. return normalizeHotmailAccount({
  789. ...account,
  790. status: 'error',
  791. lastError: String(errorMessage || ''),
  792. });
  793. }
  794. async function fetchHotmailMailboxMessagesFromRemoteService(account, mailboxes = HOTMAIL_MAILBOXES) {
  795. let workingAccount = normalizeHotmailAccount(account);
  796. const mailboxResults = [];
  797. try {
  798. for (const mailbox of mailboxes) {
  799. const result = await requestHotmailRemoteMailbox(workingAccount, mailbox);
  800. workingAccount = applyHotmailApiResultToAccount(workingAccount, result);
  801. mailboxResults.push({
  802. mailbox,
  803. count: result.messages.length,
  804. messages: result.messages.map((message) => ({ ...message, mailbox })),
  805. });
  806. }
  807. } catch (err) {
  808. const failedAccount = buildHotmailMailApiFailureAccount(workingAccount, err.message);
  809. await upsertHotmailAccount(failedAccount);
  810. throw err;
  811. }
  812. const savedAccount = await upsertHotmailAccount(workingAccount);
  813. return {
  814. account: savedAccount,
  815. mailboxResults,
  816. messages: mailboxResults.flatMap((item) => item.messages),
  817. };
  818. }
  819. async function requestHotmailLocalMessages(account, mailboxes = HOTMAIL_MAILBOXES) {
  820. if (!account?.email) {
  821. throw new Error('Hotmail 账号缺少邮箱地址。');
  822. }
  823. if (!account?.clientId) {
  824. throw new Error(`Hotmail 账号 ${account.email || account.id} 缺少客户端 ID。`);
  825. }
  826. if (!account?.refreshToken) {
  827. throw new Error(`Hotmail 账号 ${account.email || account.id} 缺少刷新令牌(refresh token)。`);
  828. }
  829. const serviceSettings = getHotmailServiceSettings(await getState());
  830. const { timeoutMs } = getHotmailMailApiRequestConfig();
  831. const requestTimeoutMs = Math.max(timeoutMs, HOTMAIL_LOCAL_HELPER_TIMEOUT_MS);
  832. const controller = new AbortController();
  833. const timeoutId = setTimeout(() => controller.abort(new Error('timeout')), requestTimeoutMs);
  834. let response;
  835. try {
  836. response = await fetch(buildHotmailLocalEndpoint(serviceSettings.localBaseUrl, '/messages'), {
  837. method: 'POST',
  838. headers: {
  839. 'Content-Type': 'application/json',
  840. Accept: 'application/json',
  841. },
  842. body: JSON.stringify({
  843. email: account.email,
  844. clientId: account.clientId,
  845. refreshToken: account.refreshToken,
  846. mailboxes,
  847. top: 5,
  848. }),
  849. signal: controller.signal,
  850. });
  851. } catch (err) {
  852. if (err?.name === 'AbortError') {
  853. throw new Error(`Hotmail 本地助手请求超时(>${Math.round(requestTimeoutMs / 1000)} 秒)`);
  854. }
  855. throw new Error(`Hotmail 本地助手请求失败:${err.message}`);
  856. } finally {
  857. clearTimeout(timeoutId);
  858. }
  859. const text = await response.text();
  860. let payload = {};
  861. try {
  862. payload = text ? JSON.parse(text) : {};
  863. } catch {
  864. payload = { raw: text };
  865. }
  866. if (!response.ok || payload?.ok === false) {
  867. const errorText = payload?.error || payload?.message || text || `HTTP ${response.status}`;
  868. throw new Error(`Hotmail 本地助手返回失败:${errorText}`);
  869. }
  870. const rawMessages = Array.isArray(payload?.messages) ? payload.messages : [];
  871. const normalizedMessages = normalizeHotmailMailApiMessages(rawMessages).map((message, index) => ({
  872. ...message,
  873. mailbox: rawMessages[index]?.mailbox || 'INBOX',
  874. receivedTimestamp: Number(rawMessages[index]?.receivedTimestamp || 0) || 0,
  875. }));
  876. const mailboxResults = Array.isArray(payload?.mailboxResults)
  877. ? payload.mailboxResults.map((item) => ({
  878. mailbox: String(item?.mailbox || 'INBOX'),
  879. count: Number(item?.count || 0),
  880. messages: normalizedMessages.filter((message) => String(message.mailbox || 'INBOX') === String(item?.mailbox || 'INBOX')),
  881. }))
  882. : mailboxes.map((mailbox) => ({
  883. mailbox,
  884. count: normalizedMessages.filter((message) => String(message.mailbox || 'INBOX') === mailbox).length,
  885. messages: normalizedMessages.filter((message) => String(message.mailbox || 'INBOX') === mailbox),
  886. }));
  887. const nextAccount = applyHotmailApiResultToAccount(account, {
  888. nextRefreshToken: String(payload?.nextRefreshToken || '').trim(),
  889. });
  890. const savedAccount = await upsertHotmailAccount(nextAccount);
  891. return {
  892. account: savedAccount,
  893. mailboxResults,
  894. messages: normalizedMessages,
  895. };
  896. }
  897. async function requestHotmailLocalCode(account, pollPayload = {}) {
  898. if (!account?.email) {
  899. throw new Error('Hotmail 账号缺少邮箱地址。');
  900. }
  901. if (!account?.clientId) {
  902. throw new Error(`Hotmail 账号 ${account.email || account.id} 缺少客户端 ID。`);
  903. }
  904. if (!account?.refreshToken) {
  905. throw new Error(`Hotmail 账号 ${account.email || account.id} 缺少刷新令牌(refresh token)。`);
  906. }
  907. const serviceSettings = getHotmailServiceSettings(await getState());
  908. const { timeoutMs } = getHotmailMailApiRequestConfig();
  909. const requestTimeoutMs = Math.max(timeoutMs, HOTMAIL_LOCAL_HELPER_TIMEOUT_MS);
  910. const controller = new AbortController();
  911. const timeoutId = setTimeout(() => controller.abort(new Error('timeout')), requestTimeoutMs);
  912. let response;
  913. try {
  914. response = await fetch(buildHotmailLocalEndpoint(serviceSettings.localBaseUrl, '/code'), {
  915. method: 'POST',
  916. headers: {
  917. 'Content-Type': 'application/json',
  918. Accept: 'application/json',
  919. },
  920. body: JSON.stringify({
  921. email: account.email,
  922. clientId: account.clientId,
  923. refreshToken: account.refreshToken,
  924. mailboxes: HOTMAIL_MAILBOXES,
  925. top: 5,
  926. senderFilters: pollPayload.senderFilters || [],
  927. subjectFilters: pollPayload.subjectFilters || [],
  928. excludeCodes: pollPayload.excludeCodes || [],
  929. filterAfterTimestamp: Number(pollPayload.filterAfterTimestamp || 0) || 0,
  930. }),
  931. signal: controller.signal,
  932. });
  933. } catch (err) {
  934. if (err?.name === 'AbortError') {
  935. throw new Error(`Hotmail 本地助手请求超时(>${Math.round(requestTimeoutMs / 1000)} 秒)`);
  936. }
  937. throw new Error(`Hotmail 本地助手请求失败:${err.message}`);
  938. } finally {
  939. clearTimeout(timeoutId);
  940. }
  941. const text = await response.text();
  942. let payload = {};
  943. try {
  944. payload = text ? JSON.parse(text) : {};
  945. } catch {
  946. payload = { raw: text };
  947. }
  948. if (!response.ok || payload?.ok === false) {
  949. const errorText = payload?.error || payload?.message || text || `HTTP ${response.status}`;
  950. throw new Error(`Hotmail 本地助手返回失败:${errorText}`);
  951. }
  952. const normalizedMessage = payload?.message
  953. ? {
  954. ...normalizeHotmailMailApiMessages([payload.message])[0],
  955. mailbox: payload?.message?.mailbox || 'INBOX',
  956. receivedTimestamp: Number(payload?.message?.receivedTimestamp || 0) || 0,
  957. }
  958. : null;
  959. const nextAccount = applyHotmailApiResultToAccount(account, {
  960. nextRefreshToken: String(payload?.nextRefreshToken || '').trim(),
  961. });
  962. const savedAccount = await upsertHotmailAccount(nextAccount);
  963. return {
  964. account: savedAccount,
  965. code: String(payload?.code || ''),
  966. message: normalizedMessage,
  967. usedTimeFallback: Boolean(payload?.usedTimeFallback),
  968. selectionSource: String(payload?.selectionSource || ''),
  969. };
  970. }
  971. async function pollHotmailVerificationCodeViaLocalHelper(step, account, pollPayload = {}) {
  972. const maxAttempts = Number(pollPayload.maxAttempts) || 5;
  973. const intervalMs = Number(pollPayload.intervalMs) || 3000;
  974. let workingAccount = account;
  975. let lastError = null;
  976. for (let attempt = 1; attempt <= maxAttempts; attempt++) {
  977. throwIfStopped();
  978. try {
  979. await addLog(`步骤 ${step}:正在通过本地助手轮询 Hotmail 验证码(${attempt}/${maxAttempts})...`, 'info');
  980. const fetchResult = await requestHotmailLocalCode(workingAccount, pollPayload);
  981. workingAccount = fetchResult.account;
  982. if (fetchResult.code) {
  983. const mailboxLabel = fetchResult.message?.mailbox || 'INBOX';
  984. if (fetchResult.usedTimeFallback) {
  985. await addLog(`步骤 ${step}:本地助手使用时间回退后命中 Hotmail ${mailboxLabel} 验证码。`, 'warn');
  986. }
  987. await addLog(`步骤 ${step}:已通过本地助手在 Hotmail ${mailboxLabel} 中找到验证码:${fetchResult.code}`, 'ok');
  988. return {
  989. ok: true,
  990. code: fetchResult.code,
  991. emailTimestamp: fetchResult.message?.receivedTimestamp || Date.now(),
  992. mailId: fetchResult.message?.id || '',
  993. };
  994. }
  995. lastError = new Error(`步骤 ${step}:本地助手暂未返回匹配验证码(${attempt}/${maxAttempts})。`);
  996. await addLog(lastError.message, attempt === maxAttempts ? 'warn' : 'info');
  997. } catch (err) {
  998. lastError = err;
  999. await addLog(`步骤 ${step}:本地助手轮询 Hotmail 失败:${err.message}`, 'warn');
  1000. }
  1001. if (attempt < maxAttempts) {
  1002. await sleepWithStop(intervalMs);
  1003. }
  1004. }
  1005. throw lastError || new Error(`步骤 ${step}:本地助手未返回新的匹配验证码。`);
  1006. }
  1007. async function fetchHotmailMailboxMessages(account, mailboxes = HOTMAIL_MAILBOXES) {
  1008. const serviceSettings = getHotmailServiceSettings(await getState());
  1009. if (serviceSettings.mode === HOTMAIL_SERVICE_MODE_LOCAL) {
  1010. return requestHotmailLocalMessages(account, mailboxes);
  1011. }
  1012. return fetchHotmailMailboxMessagesFromRemoteService(account, mailboxes);
  1013. }
  1014. async function verifyHotmailAccount(accountId) {
  1015. const state = await getState();
  1016. const account = findHotmailAccount(state.hotmailAccounts, accountId);
  1017. if (!account) {
  1018. throw new Error('未找到需要校验的 Hotmail 账号。');
  1019. }
  1020. const result = await fetchHotmailMailboxMessages(account, ['INBOX']);
  1021. return {
  1022. account: result.account,
  1023. messageCount: result.mailboxResults[0]?.count || 0,
  1024. };
  1025. }
  1026. async function testHotmailAccountMailAccess(accountId) {
  1027. const state = await getState();
  1028. const account = findHotmailAccount(state.hotmailAccounts, accountId);
  1029. if (!account) {
  1030. throw new Error('未找到需要测试的 Hotmail 账号。');
  1031. }
  1032. const result = await fetchHotmailMailboxMessages(account, HOTMAIL_MAILBOXES);
  1033. const latestMessage = getLatestHotmailMessage(result.messages);
  1034. const latestCode = latestMessage ? extractVerificationCodeFromMessage(latestMessage) : null;
  1035. return {
  1036. account: result.account,
  1037. accountId: result.account.id,
  1038. email: result.account.email,
  1039. messageCount: result.messages.length,
  1040. latestSubject: latestMessage?.subject || '',
  1041. latestMailbox: latestMessage?.mailbox || '',
  1042. latestCode: latestCode || '',
  1043. inboxCount: result.mailboxResults.find((item) => item.mailbox === 'INBOX')?.count || 0,
  1044. junkCount: result.mailboxResults.find((item) => item.mailbox === 'Junk')?.count || 0,
  1045. };
  1046. }
  1047. async function pollHotmailVerificationCode(step, state, pollPayload = {}) {
  1048. await addLog(`步骤 ${step}:正在确定 Hotmail 收信账号...`, 'info');
  1049. let account = await ensureHotmailAccountForFlow({
  1050. allowAllocate: true,
  1051. markUsed: false,
  1052. preferredAccountId: state.currentHotmailAccountId || null,
  1053. });
  1054. await addLog(`步骤 ${step}:当前使用 Hotmail 账号 ${account.email} 轮询收件箱。`, 'info');
  1055. const serviceSettings = getHotmailServiceSettings(state);
  1056. if (serviceSettings.mode === HOTMAIL_SERVICE_MODE_LOCAL) {
  1057. return pollHotmailVerificationCodeViaLocalHelper(step, account, pollPayload);
  1058. }
  1059. const maxAttempts = Number(pollPayload.maxAttempts) || 5;
  1060. const intervalMs = Number(pollPayload.intervalMs) || 3000;
  1061. let lastError = null;
  1062. function summarizeMessagesForLog(messages) {
  1063. return (messages || [])
  1064. .slice()
  1065. .sort((left, right) => {
  1066. const leftTime = Date.parse(left.receivedDateTime || '') || 0;
  1067. const rightTime = Date.parse(right.receivedDateTime || '') || 0;
  1068. return rightTime - leftTime;
  1069. })
  1070. .slice(0, 3)
  1071. .map((message) => {
  1072. const receivedAt = message?.receivedDateTime || '未知时间';
  1073. const sender = message?.from?.emailAddress?.address || '未知发件人';
  1074. const subject = message?.subject || '(无主题)';
  1075. const preview = String(message?.bodyPreview || '').replace(/\s+/g, ' ').trim().slice(0, 80);
  1076. return `[${message.mailbox || 'INBOX'}] ${receivedAt} | ${sender} | ${subject} | ${preview}`;
  1077. })
  1078. .join(' || ');
  1079. }
  1080. for (let attempt = 1; attempt <= maxAttempts; attempt++) {
  1081. throwIfStopped();
  1082. try {
  1083. await addLog(`步骤 ${step}:正在轮询 Hotmail 邮件(${attempt}/${maxAttempts})...`, 'info');
  1084. const fetchResult = await fetchHotmailMailboxMessages(account, HOTMAIL_MAILBOXES);
  1085. account = fetchResult.account;
  1086. const matchResult = pickVerificationMessageWithTimeFallback(fetchResult.messages, {
  1087. afterTimestamp: pollPayload.filterAfterTimestamp || 0,
  1088. senderFilters: pollPayload.senderFilters || [],
  1089. subjectFilters: pollPayload.subjectFilters || [],
  1090. excludeCodes: pollPayload.excludeCodes || [],
  1091. });
  1092. const match = matchResult.match;
  1093. if (match?.code) {
  1094. const mailboxLabel = match.message?.mailbox || 'INBOX';
  1095. if (matchResult.usedRelaxedFilters) {
  1096. const fallbackLabel = matchResult.usedTimeFallback ? '宽松匹配 + 时间回退' : '宽松匹配';
  1097. await addLog(`步骤 ${step}:严格规则未命中,已改用 ${fallbackLabel} 并命中 Hotmail ${mailboxLabel} 验证码。`, 'warn');
  1098. }
  1099. await addLog(`步骤 ${step}:已在 Hotmail ${mailboxLabel} 中找到验证码:${match.code}`, 'ok');
  1100. return {
  1101. ok: true,
  1102. code: match.code,
  1103. emailTimestamp: match.receivedAt || Date.now(),
  1104. mailId: match.message?.id || '',
  1105. };
  1106. }
  1107. lastError = new Error(`步骤 ${step}:暂未在 Hotmail 收件箱中找到匹配验证码(${attempt}/${maxAttempts})。`);
  1108. await addLog(lastError.message, attempt === maxAttempts ? 'warn' : 'info');
  1109. const mailSummary = summarizeMessagesForLog(fetchResult.messages);
  1110. if (mailSummary) {
  1111. await addLog(`步骤 ${step}:最近邮件样本:${mailSummary}`, 'info');
  1112. }
  1113. } catch (err) {
  1114. lastError = err;
  1115. await addLog(`步骤 ${step}:Hotmail 收件箱轮询失败:${err.message}`, 'warn');
  1116. }
  1117. if (attempt < maxAttempts) {
  1118. await sleepWithStop(intervalMs);
  1119. }
  1120. }
  1121. throw lastError || new Error(`步骤 ${step}:未在 Hotmail 收件箱中找到新的匹配验证码。`);
  1122. }
  1123. function generateRandomSuffix(length = 6) {
  1124. const chars = 'abcdefghjkmnpqrstuvwxyz23456789';
  1125. let suffix = '';
  1126. for (let i = 0; i < length; i++) {
  1127. suffix += chars[Math.floor(Math.random() * chars.length)];
  1128. }
  1129. return suffix;
  1130. }
  1131. function isGeneratedAliasProvider(provider) {
  1132. return provider === '2925';
  1133. }
  1134. function shouldUseCustomRegistrationEmail(state = {}) {
  1135. return isCustomMailProvider(state)
  1136. || (!isHotmailProvider(state)
  1137. && !isGeneratedAliasProvider(state.mailProvider)
  1138. && normalizeEmailGenerator(state.emailGenerator) === 'custom');
  1139. }
  1140. function buildGeneratedAliasEmail(state) {
  1141. const provider = state.mailProvider || '163';
  1142. const emailPrefix = (state.emailPrefix || '').trim();
  1143. if (!emailPrefix) {
  1144. throw new Error('2925 邮箱前缀未设置,请先在侧边栏填写。');
  1145. }
  1146. if (provider === '2925') {
  1147. return `${emailPrefix}${generateRandomSuffix(6)}@2925.com`;
  1148. }
  1149. throw new Error(`未支持的别名邮箱类型:${provider}`);
  1150. }
  1151. // ============================================================
  1152. // Tab Registry
  1153. // ============================================================
  1154. async function getTabRegistry() {
  1155. const state = await getState();
  1156. return state.tabRegistry || {};
  1157. }
  1158. async function registerTab(source, tabId) {
  1159. const registry = await getTabRegistry();
  1160. registry[source] = { tabId, ready: true };
  1161. await setState({ tabRegistry: registry });
  1162. console.log(LOG_PREFIX, `Tab registered: ${source} -> ${tabId}`);
  1163. }
  1164. async function isTabAlive(source) {
  1165. const registry = await getTabRegistry();
  1166. const entry = registry[source];
  1167. if (!entry) return false;
  1168. try {
  1169. await chrome.tabs.get(entry.tabId);
  1170. return true;
  1171. } catch {
  1172. // Tab no longer exists — clean up registry
  1173. registry[source] = null;
  1174. await setState({ tabRegistry: registry });
  1175. return false;
  1176. }
  1177. }
  1178. async function getTabId(source) {
  1179. const registry = await getTabRegistry();
  1180. return registry[source]?.tabId || null;
  1181. }
  1182. function parseUrlSafely(rawUrl) {
  1183. if (!rawUrl) return null;
  1184. try {
  1185. return new URL(rawUrl);
  1186. } catch {
  1187. return null;
  1188. }
  1189. }
  1190. function normalizeSub2ApiUrl(rawUrl) {
  1191. const input = (rawUrl || '').trim() || DEFAULT_SUB2API_URL;
  1192. const withProtocol = /^https?:\/\//i.test(input) ? input : `https://${input}`;
  1193. const parsed = new URL(withProtocol);
  1194. if (!parsed.pathname || parsed.pathname === '/') {
  1195. parsed.pathname = '/admin/accounts';
  1196. }
  1197. parsed.hash = '';
  1198. return parsed.toString();
  1199. }
  1200. function getPanelMode(state = {}) {
  1201. return state.panelMode === 'sub2api' ? 'sub2api' : 'cpa';
  1202. }
  1203. function getPanelModeLabel(modeOrState) {
  1204. const mode = typeof modeOrState === 'string' ? modeOrState : getPanelMode(modeOrState);
  1205. return mode === 'sub2api' ? 'SUB2API' : 'CPA';
  1206. }
  1207. function isSignupPageHost(hostname = '') {
  1208. return ['auth0.openai.com', 'auth.openai.com', 'accounts.openai.com'].includes(hostname);
  1209. }
  1210. function is163MailHost(hostname = '') {
  1211. return hostname === 'mail.163.com'
  1212. || hostname.endsWith('.mail.163.com')
  1213. || hostname === 'webmail.vip.163.com';
  1214. }
  1215. function isLocalhostOAuthCallbackUrl(rawUrl) {
  1216. const parsed = parseUrlSafely(rawUrl);
  1217. if (!parsed) return false;
  1218. if (!['http:', 'https:'].includes(parsed.protocol)) return false;
  1219. if (!['localhost', '127.0.0.1'].includes(parsed.hostname)) return false;
  1220. if (!['/auth/callback', '/codex/callback'].includes(parsed.pathname)) return false;
  1221. const code = (parsed.searchParams.get('code') || '').trim();
  1222. const state = (parsed.searchParams.get('state') || '').trim();
  1223. return Boolean(code && state);
  1224. }
  1225. function isLocalCpaUrl(rawUrl) {
  1226. const parsed = parseUrlSafely(rawUrl);
  1227. if (!parsed) return false;
  1228. if (!['http:', 'https:'].includes(parsed.protocol)) return false;
  1229. return ['localhost', '127.0.0.1'].includes(parsed.hostname);
  1230. }
  1231. function shouldBypassStep9ForLocalCpa(state) {
  1232. return normalizeLocalCpaStep9Mode(state?.localCpaStep9Mode) === 'bypass'
  1233. && Boolean(state?.localhostUrl)
  1234. && isLocalCpaUrl(state?.vpsUrl);
  1235. }
  1236. function matchesSourceUrlFamily(source, candidateUrl, referenceUrl) {
  1237. const candidate = parseUrlSafely(candidateUrl);
  1238. if (!candidate) return false;
  1239. const reference = parseUrlSafely(referenceUrl);
  1240. switch (source) {
  1241. case 'signup-page':
  1242. return isSignupPageHost(candidate.hostname);
  1243. case 'duck-mail':
  1244. return candidate.hostname === 'duckduckgo.com' && candidate.pathname.startsWith('/email/');
  1245. case 'qq-mail':
  1246. return candidate.hostname === 'mail.qq.com' || candidate.hostname === 'wx.mail.qq.com';
  1247. case 'mail-163':
  1248. return is163MailHost(candidate.hostname);
  1249. case 'inbucket-mail':
  1250. return Boolean(reference)
  1251. && candidate.origin === reference.origin
  1252. && candidate.pathname.startsWith('/m/');
  1253. case 'mail-2925':
  1254. return candidate.hostname === '2925.com' || candidate.hostname === 'www.2925.com';
  1255. case 'vps-panel':
  1256. return Boolean(reference)
  1257. && candidate.origin === reference.origin
  1258. && candidate.pathname === reference.pathname;
  1259. case 'sub2api-panel':
  1260. return Boolean(reference)
  1261. && candidate.origin === reference.origin
  1262. && (
  1263. candidate.pathname.startsWith('/admin/accounts')
  1264. || candidate.pathname.startsWith('/login')
  1265. || candidate.pathname === '/'
  1266. );
  1267. default:
  1268. return false;
  1269. }
  1270. }
  1271. async function rememberSourceLastUrl(source, url) {
  1272. if (!source || !url) return;
  1273. const state = await getState();
  1274. const sourceLastUrls = { ...(state.sourceLastUrls || {}) };
  1275. sourceLastUrls[source] = url;
  1276. await setState({ sourceLastUrls });
  1277. }
  1278. async function closeConflictingTabsForSource(source, currentUrl, options = {}) {
  1279. const { excludeTabIds = [] } = options;
  1280. const excluded = new Set(excludeTabIds.filter(id => Number.isInteger(id)));
  1281. const state = await getState();
  1282. const lastUrl = state.sourceLastUrls?.[source];
  1283. const referenceUrls = [currentUrl, lastUrl].filter(Boolean);
  1284. if (!referenceUrls.length) return;
  1285. const tabs = await chrome.tabs.query({});
  1286. const matchedIds = tabs
  1287. .filter((tab) => Number.isInteger(tab.id) && !excluded.has(tab.id))
  1288. .filter((tab) => referenceUrls.some((refUrl) => matchesSourceUrlFamily(source, tab.url, refUrl)))
  1289. .map(tab => tab.id);
  1290. if (!matchedIds.length) return;
  1291. await chrome.tabs.remove(matchedIds).catch(() => { });
  1292. const registry = await getTabRegistry();
  1293. if (registry[source]?.tabId && matchedIds.includes(registry[source].tabId)) {
  1294. registry[source] = null;
  1295. await setState({ tabRegistry: registry });
  1296. }
  1297. await addLog(`已关闭 ${matchedIds.length} 个旧的${getSourceLabel(source)}标签页。`, 'info');
  1298. }
  1299. function isLocalhostOAuthCallbackTabMatch(callbackUrl, candidateUrl) {
  1300. if (!isLocalhostOAuthCallbackUrl(callbackUrl) || !isLocalhostOAuthCallbackUrl(candidateUrl)) {
  1301. return false;
  1302. }
  1303. const callback = parseUrlSafely(callbackUrl);
  1304. const candidate = parseUrlSafely(candidateUrl);
  1305. if (!callback || !candidate) return false;
  1306. return callback.origin === candidate.origin
  1307. && callback.pathname === candidate.pathname
  1308. && callback.searchParams.get('code') === candidate.searchParams.get('code')
  1309. && callback.searchParams.get('state') === candidate.searchParams.get('state');
  1310. }
  1311. async function closeLocalhostCallbackTabs(callbackUrl, options = {}) {
  1312. if (!isLocalhostOAuthCallbackUrl(callbackUrl)) return 0;
  1313. const { excludeTabIds = [] } = options;
  1314. const excluded = new Set(excludeTabIds.filter(id => Number.isInteger(id)));
  1315. const tabs = await chrome.tabs.query({});
  1316. const matchedIds = tabs
  1317. .filter((tab) => Number.isInteger(tab.id) && !excluded.has(tab.id))
  1318. .filter((tab) => isLocalhostOAuthCallbackTabMatch(callbackUrl, tab.url))
  1319. .map((tab) => tab.id);
  1320. if (!matchedIds.length) return 0;
  1321. await chrome.tabs.remove(matchedIds).catch(() => { });
  1322. const registry = await getTabRegistry();
  1323. if (registry['signup-page']?.tabId && matchedIds.includes(registry['signup-page'].tabId)) {
  1324. registry['signup-page'] = null;
  1325. await setState({ tabRegistry: registry });
  1326. }
  1327. await addLog(`已关闭 ${matchedIds.length} 个匹配当前 OAuth callback 的 localhost 残留标签页。`, 'info');
  1328. return matchedIds.length;
  1329. }
  1330. function buildLocalhostCleanupPrefix(rawUrl) {
  1331. if (!isLocalhostOAuthCallbackUrl(rawUrl)) return '';
  1332. const parsed = parseUrlSafely(rawUrl);
  1333. if (!parsed) return '';
  1334. const segments = parsed.pathname.split('/').filter(Boolean);
  1335. if (!segments.length) {
  1336. return parsed.origin;
  1337. }
  1338. return `${parsed.origin}/${segments[0]}`;
  1339. }
  1340. async function closeTabsByUrlPrefix(prefix, options = {}) {
  1341. if (!prefix) return 0;
  1342. const { excludeTabIds = [] } = options;
  1343. const excluded = new Set(excludeTabIds.filter(id => Number.isInteger(id)));
  1344. const tabs = await chrome.tabs.query({});
  1345. const matchedIds = tabs
  1346. .filter((tab) => Number.isInteger(tab.id) && !excluded.has(tab.id))
  1347. .filter((tab) => typeof tab.url === 'string' && tab.url.startsWith(prefix))
  1348. .map((tab) => tab.id);
  1349. if (!matchedIds.length) return 0;
  1350. await chrome.tabs.remove(matchedIds).catch(() => { });
  1351. await addLog(`已关闭 ${matchedIds.length} 个匹配 ${prefix} 的 localhost 残留标签页。`, 'info');
  1352. return matchedIds.length;
  1353. }
  1354. async function pingContentScriptOnTab(tabId) {
  1355. if (!Number.isInteger(tabId)) return null;
  1356. try {
  1357. return await chrome.tabs.sendMessage(tabId, {
  1358. type: 'PING',
  1359. source: 'background',
  1360. payload: {},
  1361. });
  1362. } catch {
  1363. return null;
  1364. }
  1365. }
  1366. async function waitForTabUrlFamily(source, tabId, referenceUrl, options = {}) {
  1367. const { timeoutMs = 15000, retryDelayMs = 400 } = options;
  1368. const start = Date.now();
  1369. while (Date.now() - start < timeoutMs) {
  1370. try {
  1371. const tab = await chrome.tabs.get(tabId);
  1372. if (matchesSourceUrlFamily(source, tab.url, referenceUrl)) {
  1373. return tab;
  1374. }
  1375. } catch {
  1376. return null;
  1377. }
  1378. await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
  1379. }
  1380. return null;
  1381. }
  1382. async function ensureContentScriptReadyOnTab(source, tabId, options = {}) {
  1383. const {
  1384. inject = null,
  1385. injectSource = null,
  1386. timeoutMs = 30000,
  1387. retryDelayMs = 700,
  1388. logMessage = '',
  1389. } = options;
  1390. const start = Date.now();
  1391. let lastError = null;
  1392. let logged = false;
  1393. let attempt = 0;
  1394. console.log(
  1395. LOG_PREFIX,
  1396. `[ensureContentScriptReadyOnTab] start ${source} tab=${tabId}, timeout=${timeoutMs}ms, inject=${Array.isArray(inject) ? inject.join(',') : 'none'}`
  1397. );
  1398. while (Date.now() - start < timeoutMs) {
  1399. attempt += 1;
  1400. const pong = await pingContentScriptOnTab(tabId);
  1401. if (pong?.ok && (!pong.source || pong.source === source)) {
  1402. console.log(
  1403. LOG_PREFIX,
  1404. `[ensureContentScriptReadyOnTab] ready ${source} tab=${tabId} on attempt ${attempt} after ${Date.now() - start}ms`
  1405. );
  1406. await registerTab(source, tabId);
  1407. return;
  1408. }
  1409. if (!inject || !inject.length) {
  1410. throw new Error(`${getSourceLabel(source)} 内容脚本未就绪,且未提供可用的注入文件。`);
  1411. }
  1412. const registry = await getTabRegistry();
  1413. if (registry[source]) {
  1414. registry[source].ready = false;
  1415. await setState({ tabRegistry: registry });
  1416. }
  1417. try {
  1418. if (injectSource) {
  1419. await chrome.scripting.executeScript({
  1420. target: { tabId },
  1421. func: (injectedSource) => {
  1422. window.__MULTIPAGE_SOURCE = injectedSource;
  1423. },
  1424. args: [injectSource],
  1425. });
  1426. }
  1427. await chrome.scripting.executeScript({
  1428. target: { tabId },
  1429. files: inject,
  1430. });
  1431. } catch (err) {
  1432. lastError = err;
  1433. console.warn(
  1434. LOG_PREFIX,
  1435. `[ensureContentScriptReadyOnTab] inject attempt ${attempt} failed for ${source} tab=${tabId}: ${err?.message || err}`
  1436. );
  1437. }
  1438. const pongAfterInject = await pingContentScriptOnTab(tabId);
  1439. if (pongAfterInject?.ok && (!pongAfterInject.source || pongAfterInject.source === source)) {
  1440. console.log(
  1441. LOG_PREFIX,
  1442. `[ensureContentScriptReadyOnTab] ready after inject ${source} tab=${tabId} on attempt ${attempt} after ${Date.now() - start}ms`
  1443. );
  1444. await registerTab(source, tabId);
  1445. return;
  1446. }
  1447. if (logMessage && !logged) {
  1448. console.warn(
  1449. LOG_PREFIX,
  1450. `[ensureContentScriptReadyOnTab] ${source} tab=${tabId} still not ready after ${Date.now() - start}ms`
  1451. );
  1452. await addLog(logMessage, 'warn');
  1453. logged = true;
  1454. }
  1455. await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
  1456. }
  1457. throw lastError || new Error(`${getSourceLabel(source)} 内容脚本长时间未就绪。`);
  1458. }
  1459. // ============================================================
  1460. // Command Queue (for content scripts not yet ready)
  1461. // ============================================================
  1462. const pendingCommands = new Map(); // source -> { message, resolve, reject, timer }
  1463. function getContentScriptResponseTimeoutMs(message) {
  1464. if (!message || typeof message !== 'object') {
  1465. return 30000;
  1466. }
  1467. if (message.type === 'POLL_EMAIL') {
  1468. const maxAttempts = Math.max(1, Number(message.payload?.maxAttempts) || 1);
  1469. const intervalMs = Math.max(0, Number(message.payload?.intervalMs) || 0);
  1470. return Math.max(45000, maxAttempts * intervalMs + 25000);
  1471. }
  1472. if (message.type === 'FILL_CODE') {
  1473. return Number(message.step) === 7 ? 45000 : 30000;
  1474. }
  1475. if (message.type === 'PREPARE_SIGNUP_VERIFICATION') {
  1476. return 45000;
  1477. }
  1478. return 30000;
  1479. }
  1480. function getMessageDebugLabel(source, message, tabId = null) {
  1481. const parts = [source || 'unknown', message?.type || 'UNKNOWN'];
  1482. if (Number.isInteger(message?.step)) {
  1483. parts.push(`step=${message.step}`);
  1484. }
  1485. if (Number.isInteger(tabId)) {
  1486. parts.push(`tab=${tabId}`);
  1487. }
  1488. return parts.join(' ');
  1489. }
  1490. function summarizeMessageResultForDebug(result) {
  1491. if (result === undefined) return 'undefined';
  1492. if (result === null) return 'null';
  1493. if (typeof result !== 'object') return JSON.stringify(result);
  1494. const summary = {};
  1495. for (const key of ['ok', 'error', 'stopped', 'source', 'step']) {
  1496. if (key in result) summary[key] = result[key];
  1497. }
  1498. if (result.payload && typeof result.payload === 'object') {
  1499. summary.payloadKeys = Object.keys(result.payload);
  1500. }
  1501. return JSON.stringify(summary);
  1502. }
  1503. function sendTabMessageWithTimeout(tabId, source, message, responseTimeoutMs = getContentScriptResponseTimeoutMs(message)) {
  1504. return new Promise((resolve, reject) => {
  1505. let settled = false;
  1506. const startedAt = Date.now();
  1507. const debugLabel = getMessageDebugLabel(source, message, tabId);
  1508. console.log(LOG_PREFIX, `[sendTabMessageWithTimeout] dispatch ${debugLabel}, timeout=${responseTimeoutMs}ms`);
  1509. const timer = setTimeout(() => {
  1510. if (settled) return;
  1511. settled = true;
  1512. const seconds = Math.ceil(responseTimeoutMs / 1000);
  1513. console.warn(LOG_PREFIX, `[sendTabMessageWithTimeout] timeout ${debugLabel} after ${Date.now() - startedAt}ms`);
  1514. reject(new Error(`Content script on ${source} did not respond in ${seconds}s. Try refreshing the tab and retry.`));
  1515. }, responseTimeoutMs);
  1516. chrome.tabs.sendMessage(tabId, message)
  1517. .then((value) => {
  1518. const elapsed = Date.now() - startedAt;
  1519. if (settled) {
  1520. console.warn(
  1521. LOG_PREFIX,
  1522. `[sendTabMessageWithTimeout] late response ignored for ${debugLabel} after ${elapsed}ms: ${summarizeMessageResultForDebug(value)}`
  1523. );
  1524. return;
  1525. }
  1526. settled = true;
  1527. clearTimeout(timer);
  1528. console.log(
  1529. LOG_PREFIX,
  1530. `[sendTabMessageWithTimeout] response ${debugLabel} after ${elapsed}ms: ${summarizeMessageResultForDebug(value)}`
  1531. );
  1532. resolve(value);
  1533. })
  1534. .catch((error) => {
  1535. const elapsed = Date.now() - startedAt;
  1536. const errorMessage = error?.message || String(error);
  1537. if (settled) {
  1538. console.warn(
  1539. LOG_PREFIX,
  1540. `[sendTabMessageWithTimeout] late rejection ignored for ${debugLabel} after ${elapsed}ms: ${errorMessage}`
  1541. );
  1542. return;
  1543. }
  1544. settled = true;
  1545. clearTimeout(timer);
  1546. console.warn(
  1547. LOG_PREFIX,
  1548. `[sendTabMessageWithTimeout] rejection ${debugLabel} after ${elapsed}ms: ${errorMessage}`
  1549. );
  1550. reject(error);
  1551. });
  1552. });
  1553. }
  1554. function queueCommand(source, message, timeout = 15000) {
  1555. return new Promise((resolve, reject) => {
  1556. const timer = setTimeout(() => {
  1557. pendingCommands.delete(source);
  1558. const err = `Content script on ${source} did not respond in ${timeout / 1000}s. Try refreshing the tab and retry.`;
  1559. console.error(LOG_PREFIX, err);
  1560. reject(new Error(err));
  1561. }, timeout);
  1562. pendingCommands.set(source, { message, resolve, reject, timer });
  1563. console.log(LOG_PREFIX, `Command queued for ${source} (waiting for ready)`);
  1564. });
  1565. }
  1566. function flushCommand(source, tabId) {
  1567. const pending = pendingCommands.get(source);
  1568. if (pending) {
  1569. clearTimeout(pending.timer);
  1570. pendingCommands.delete(source);
  1571. sendTabMessageWithTimeout(tabId, source, pending.message).then(pending.resolve).catch(pending.reject);
  1572. console.log(LOG_PREFIX, `Flushed queued command to ${source} (tab ${tabId})`);
  1573. }
  1574. }
  1575. function cancelPendingCommands(reason = STOP_ERROR_MESSAGE) {
  1576. for (const [source, pending] of pendingCommands.entries()) {
  1577. clearTimeout(pending.timer);
  1578. pending.reject(new Error(reason));
  1579. pendingCommands.delete(source);
  1580. console.log(LOG_PREFIX, `Cancelled queued command for ${source}`);
  1581. }
  1582. }
  1583. // ============================================================
  1584. // Reuse or create tab
  1585. // ============================================================
  1586. async function reuseOrCreateTab(source, url, options = {}) {
  1587. const alive = await isTabAlive(source);
  1588. if (alive) {
  1589. const tabId = await getTabId(source);
  1590. await closeConflictingTabsForSource(source, url, { excludeTabIds: [tabId] });
  1591. const currentTab = await chrome.tabs.get(tabId);
  1592. const sameUrl = currentTab.url === url;
  1593. const shouldReloadOnReuse = sameUrl && options.reloadIfSameUrl;
  1594. const registry = await getTabRegistry();
  1595. if (sameUrl) {
  1596. await chrome.tabs.update(tabId, { active: true });
  1597. console.log(LOG_PREFIX, `Reused tab ${source} (${tabId}) on same URL`);
  1598. if (shouldReloadOnReuse) {
  1599. if (registry[source]) registry[source].ready = false;
  1600. await setState({ tabRegistry: registry });
  1601. await chrome.tabs.reload(tabId);
  1602. await new Promise((resolve) => {
  1603. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  1604. const listener = (tid, info) => {
  1605. if (tid === tabId && info.status === 'complete') {
  1606. chrome.tabs.onUpdated.removeListener(listener);
  1607. clearTimeout(timer);
  1608. resolve();
  1609. }
  1610. };
  1611. chrome.tabs.onUpdated.addListener(listener);
  1612. });
  1613. }
  1614. // For dynamically injected pages like the VPS panel, re-inject immediately.
  1615. if (options.inject) {
  1616. if (registry[source]) registry[source].ready = false;
  1617. await setState({ tabRegistry: registry });
  1618. if (options.injectSource) {
  1619. await chrome.scripting.executeScript({
  1620. target: { tabId },
  1621. func: (injectedSource) => {
  1622. window.__MULTIPAGE_SOURCE = injectedSource;
  1623. },
  1624. args: [options.injectSource],
  1625. });
  1626. }
  1627. await chrome.scripting.executeScript({
  1628. target: { tabId },
  1629. files: options.inject,
  1630. });
  1631. await new Promise(r => setTimeout(r, 500));
  1632. }
  1633. await rememberSourceLastUrl(source, url);
  1634. return tabId;
  1635. }
  1636. // Mark as not ready BEFORE navigating — so READY signal from new page is captured correctly
  1637. if (registry[source]) registry[source].ready = false;
  1638. await setState({ tabRegistry: registry });
  1639. // Navigate existing tab to new URL
  1640. await chrome.tabs.update(tabId, { url, active: true });
  1641. console.log(LOG_PREFIX, `Reused tab ${source} (${tabId}), navigated to ${url.slice(0, 60)}`);
  1642. // Wait for page load complete (with 30s timeout)
  1643. await new Promise((resolve) => {
  1644. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  1645. const listener = (tid, info) => {
  1646. if (tid === tabId && info.status === 'complete') {
  1647. chrome.tabs.onUpdated.removeListener(listener);
  1648. clearTimeout(timer);
  1649. resolve();
  1650. }
  1651. };
  1652. chrome.tabs.onUpdated.addListener(listener);
  1653. });
  1654. // If dynamic injection needed (VPS panel), re-inject after navigation
  1655. if (options.inject) {
  1656. if (options.injectSource) {
  1657. await chrome.scripting.executeScript({
  1658. target: { tabId },
  1659. func: (injectedSource) => {
  1660. window.__MULTIPAGE_SOURCE = injectedSource;
  1661. },
  1662. args: [options.injectSource],
  1663. });
  1664. }
  1665. await chrome.scripting.executeScript({
  1666. target: { tabId },
  1667. files: options.inject,
  1668. });
  1669. }
  1670. // Wait a bit for content script to inject and send READY
  1671. await new Promise(r => setTimeout(r, 500));
  1672. await rememberSourceLastUrl(source, url);
  1673. return tabId;
  1674. }
  1675. // Create new tab
  1676. await closeConflictingTabsForSource(source, url);
  1677. const tab = await chrome.tabs.create({ url, active: true });
  1678. console.log(LOG_PREFIX, `Created new tab ${source} (${tab.id})`);
  1679. // If dynamic injection needed (VPS panel), inject scripts after load
  1680. if (options.inject) {
  1681. await new Promise((resolve) => {
  1682. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  1683. const listener = (tabId, info) => {
  1684. if (tabId === tab.id && info.status === 'complete') {
  1685. chrome.tabs.onUpdated.removeListener(listener);
  1686. clearTimeout(timer);
  1687. resolve();
  1688. }
  1689. };
  1690. chrome.tabs.onUpdated.addListener(listener);
  1691. });
  1692. if (options.injectSource) {
  1693. await chrome.scripting.executeScript({
  1694. target: { tabId: tab.id },
  1695. func: (injectedSource) => {
  1696. window.__MULTIPAGE_SOURCE = injectedSource;
  1697. },
  1698. args: [options.injectSource],
  1699. });
  1700. }
  1701. await chrome.scripting.executeScript({
  1702. target: { tabId: tab.id },
  1703. files: options.inject,
  1704. });
  1705. }
  1706. await rememberSourceLastUrl(source, url);
  1707. return tab.id;
  1708. }
  1709. // ============================================================
  1710. // Send command to content script (with readiness check)
  1711. // ============================================================
  1712. async function sendToContentScript(source, message, options = {}) {
  1713. throwIfStopped();
  1714. const { responseTimeoutMs = getContentScriptResponseTimeoutMs(message) } = options;
  1715. const registry = await getTabRegistry();
  1716. const entry = registry[source];
  1717. if (!entry || !entry.ready) {
  1718. throwIfStopped();
  1719. console.log(LOG_PREFIX, `${source} not ready, queuing command`);
  1720. return queueCommand(source, message);
  1721. }
  1722. // Verify tab is still alive
  1723. const alive = await isTabAlive(source);
  1724. throwIfStopped();
  1725. if (!alive) {
  1726. // Tab was closed — queue the command, it will be sent when tab is reopened
  1727. console.log(LOG_PREFIX, `${source} tab was closed, queuing command`);
  1728. return queueCommand(source, message);
  1729. }
  1730. throwIfStopped();
  1731. console.log(LOG_PREFIX, `Sending to ${source} (tab ${entry.tabId}):`, message.type);
  1732. return sendTabMessageWithTimeout(entry.tabId, source, message, responseTimeoutMs);
  1733. }
  1734. async function sendToContentScriptResilient(source, message, options = {}) {
  1735. const { timeoutMs = 30000, retryDelayMs = 600, logMessage = '' } = options;
  1736. const start = Date.now();
  1737. let lastError = null;
  1738. let logged = false;
  1739. let attempt = 0;
  1740. const debugLabel = getMessageDebugLabel(source, message);
  1741. console.log(
  1742. LOG_PREFIX,
  1743. `[sendToContentScriptResilient] start ${debugLabel}, totalTimeout=${timeoutMs}ms, retryDelay=${retryDelayMs}ms`
  1744. );
  1745. while (Date.now() - start < timeoutMs) {
  1746. throwIfStopped();
  1747. attempt += 1;
  1748. try {
  1749. console.log(
  1750. LOG_PREFIX,
  1751. `[sendToContentScriptResilient] attempt ${attempt} -> ${debugLabel}, elapsed=${Date.now() - start}ms`
  1752. );
  1753. const result = await sendToContentScript(source, message);
  1754. console.log(
  1755. LOG_PREFIX,
  1756. `[sendToContentScriptResilient] success ${debugLabel} on attempt ${attempt} after ${Date.now() - start}ms`
  1757. );
  1758. return result;
  1759. } catch (err) {
  1760. const retryable = isRetryableContentScriptTransportError(err);
  1761. console.warn(
  1762. LOG_PREFIX,
  1763. `[sendToContentScriptResilient] attempt ${attempt} failed for ${debugLabel}, retryable=${retryable}, elapsed=${Date.now() - start}ms: ${err?.message || err}`
  1764. );
  1765. if (!retryable) {
  1766. throw err;
  1767. }
  1768. lastError = err;
  1769. if (logMessage && !logged) {
  1770. await addLog(logMessage, 'warn');
  1771. logged = true;
  1772. }
  1773. await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
  1774. }
  1775. }
  1776. throw lastError || new Error(`等待 ${getSourceLabel(source)} 重新就绪超时。`);
  1777. }
  1778. async function sendToMailContentScriptResilient(mail, message, options = {}) {
  1779. const { timeoutMs = 45000, maxRecoveryAttempts = 2 } = options;
  1780. const start = Date.now();
  1781. let lastError = null;
  1782. let recoveries = 0;
  1783. let logged = false;
  1784. while (Date.now() - start < timeoutMs) {
  1785. throwIfStopped();
  1786. try {
  1787. return await sendToContentScript(mail.source, message);
  1788. } catch (err) {
  1789. if (!isRetryableContentScriptTransportError(err)) {
  1790. throw err;
  1791. }
  1792. lastError = err;
  1793. if (!logged) {
  1794. await addLog(`步骤 ${message.step}:${mail.label} 页面通信异常,正在尝试让邮箱页重新就绪...`, 'warn');
  1795. logged = true;
  1796. }
  1797. if (recoveries >= maxRecoveryAttempts) {
  1798. break;
  1799. }
  1800. recoveries += 1;
  1801. await reuseOrCreateTab(mail.source, mail.url, {
  1802. inject: mail.inject,
  1803. injectSource: mail.injectSource,
  1804. reloadIfSameUrl: true,
  1805. });
  1806. await new Promise((resolve) => setTimeout(resolve, 800));
  1807. }
  1808. }
  1809. throw lastError || new Error(`${mail.label} 页面未能重新就绪。`);
  1810. }
  1811. // ============================================================
  1812. // Logging
  1813. // ============================================================
  1814. async function addLog(message, level = 'info') {
  1815. const state = await getState();
  1816. const logs = state.logs || [];
  1817. const entry = { message, level, timestamp: Date.now() };
  1818. logs.push(entry);
  1819. // Keep last 500 logs
  1820. if (logs.length > 500) logs.splice(0, logs.length - 500);
  1821. await setState({ logs });
  1822. // Broadcast to side panel
  1823. chrome.runtime.sendMessage({ type: 'LOG_ENTRY', payload: entry }).catch(() => { });
  1824. }
  1825. function getStep8CallbackUrlFromNavigation(details, signupTabId) {
  1826. if (!Number.isInteger(signupTabId) || !details) return '';
  1827. if (details.tabId !== signupTabId) return '';
  1828. if (details.frameId !== 0) return '';
  1829. return isLocalhostOAuthCallbackUrl(details.url) ? details.url : '';
  1830. }
  1831. function getStep8CallbackUrlFromTabUpdate(tabId, changeInfo, tab, signupTabId) {
  1832. if (!Number.isInteger(signupTabId) || tabId !== signupTabId) return '';
  1833. const candidates = [changeInfo?.url, tab?.url];
  1834. for (const candidate of candidates) {
  1835. if (isLocalhostOAuthCallbackUrl(candidate)) {
  1836. return candidate;
  1837. }
  1838. }
  1839. return '';
  1840. }
  1841. function getSourceLabel(source) {
  1842. const labels = {
  1843. 'sidepanel': '侧边栏',
  1844. 'signup-page': '认证页',
  1845. 'vps-panel': 'CPA 面板',
  1846. 'sub2api-panel': 'SUB2API 后台',
  1847. 'qq-mail': 'QQ 邮箱',
  1848. 'mail-163': '163 邮箱',
  1849. 'mail-2925': '2925 邮箱',
  1850. 'inbucket-mail': 'Inbucket 邮箱',
  1851. 'duck-mail': 'Duck 邮箱',
  1852. 'hotmail-api': 'Hotmail(远程/本地)',
  1853. };
  1854. return labels[source] || source || '未知来源';
  1855. }
  1856. // ============================================================
  1857. // Step Status Management
  1858. // ============================================================
  1859. async function setStepStatus(step, status) {
  1860. const state = await getState();
  1861. const statuses = { ...state.stepStatuses };
  1862. statuses[step] = status;
  1863. await setState({ stepStatuses: statuses, currentStep: step });
  1864. // Broadcast to side panel
  1865. chrome.runtime.sendMessage({
  1866. type: 'STEP_STATUS_CHANGED',
  1867. payload: { step, status },
  1868. }).catch(() => { });
  1869. }
  1870. function isStopError(error) {
  1871. const message = typeof error === 'string' ? error : error?.message;
  1872. return message === STOP_ERROR_MESSAGE;
  1873. }
  1874. function isRetryableContentScriptTransportError(error) {
  1875. const message = String(typeof error === 'string' ? error : error?.message || '');
  1876. 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);
  1877. }
  1878. function getErrorMessage(error) {
  1879. return String(typeof error === 'string' ? error : error?.message || '');
  1880. }
  1881. function isVerificationMailPollingError(error) {
  1882. const message = getErrorMessage(error);
  1883. return /未在 .*邮箱中找到新的匹配邮件|未在 Hotmail 收件箱中找到新的匹配验证码|邮箱轮询结束,但未获取到验证码|无法获取新的(?:注册|登录)验证码|页面未能重新就绪|页面通信异常|did not respond in \d+s/i.test(message);
  1884. }
  1885. const STEP7_RESTART_FROM_STEP6_ERROR_CODE = 'STEP7_RESTART_FROM_STEP6';
  1886. const STEP7_RESTART_FROM_STEP6_MARKER_PATTERN = /^STEP7_RESTART_FROM_STEP6::([^:]+)::(.*)$/;
  1887. function createStep7RestartFromStep6Error(details = {}) {
  1888. const { reason = 'unknown', url = '' } = details || {};
  1889. const reasonLabel = reason === 'login_timeout_error_page'
  1890. ? '检测到登录页超时报错'
  1891. : '步骤 7 请求回到步骤 6';
  1892. const error = new Error(`步骤 7:${reasonLabel}。${url ? `URL: ${url}` : ''}`.trim());
  1893. error.code = STEP7_RESTART_FROM_STEP6_ERROR_CODE;
  1894. error.restartReason = reason;
  1895. error.restartUrl = url;
  1896. return error;
  1897. }
  1898. function parseStep7RestartFromStep6Marker(message) {
  1899. const normalized = getErrorMessage(message);
  1900. const match = normalized.match(STEP7_RESTART_FROM_STEP6_MARKER_PATTERN);
  1901. if (!match) {
  1902. return null;
  1903. }
  1904. return {
  1905. reason: match[1] || 'unknown',
  1906. url: match[2] || '',
  1907. };
  1908. }
  1909. function getStep7RestartFromStep6Error(result) {
  1910. if (result?.restartFromStep6) {
  1911. return createStep7RestartFromStep6Error(result);
  1912. }
  1913. const parsed = parseStep7RestartFromStep6Marker(result?.error);
  1914. if (!parsed) {
  1915. return null;
  1916. }
  1917. return createStep7RestartFromStep6Error(parsed);
  1918. }
  1919. function isStep7RestartFromStep6Error(error) {
  1920. return error?.code === STEP7_RESTART_FROM_STEP6_ERROR_CODE
  1921. || Boolean(parseStep7RestartFromStep6Marker(error));
  1922. }
  1923. function isRestartCurrentAttemptError(error) {
  1924. const message = String(typeof error === 'string' ? error : error?.message || '');
  1925. return /当前邮箱已存在,需要重新开始新一轮/.test(message);
  1926. }
  1927. function isStep9RecoverableAuthError(error) {
  1928. const message = String(typeof error === 'string' ? error : error?.message || '');
  1929. return /STEP9_OAUTH_RETRY::/i.test(message)
  1930. || isRecoverableStep9AuthFailure(message);
  1931. }
  1932. function isLegacyStep9RecoverableAuthError(error) {
  1933. const message = String(typeof error === 'string' ? error : error?.message || '');
  1934. return /STEP9_OAUTH_TIMEOUT::|认证失败:\s*Timeout waiting for OAuth callback/i.test(message);
  1935. }
  1936. function isStepDoneStatus(status) {
  1937. return status === 'completed' || status === 'manual_completed' || status === 'skipped';
  1938. }
  1939. function getFirstUnfinishedStep(statuses = {}) {
  1940. for (let step = 1; step <= 9; step++) {
  1941. if (!isStepDoneStatus(statuses[step] || 'pending')) {
  1942. return step;
  1943. }
  1944. }
  1945. return null;
  1946. }
  1947. function hasSavedProgress(statuses = {}) {
  1948. return Object.values({ ...DEFAULT_STATE.stepStatuses, ...statuses }).some((status) => status !== 'pending');
  1949. }
  1950. function getDownstreamStateResets(step) {
  1951. if (step <= 1) {
  1952. return {
  1953. oauthUrl: null,
  1954. sub2apiSessionId: null,
  1955. sub2apiOAuthState: null,
  1956. sub2apiGroupId: null,
  1957. sub2apiDraftName: null,
  1958. flowStartTime: null,
  1959. password: null,
  1960. lastEmailTimestamp: null,
  1961. signupVerificationRequestedAt: null,
  1962. loginVerificationRequestedAt: null,
  1963. lastSignupCode: null,
  1964. lastLoginCode: null,
  1965. localhostUrl: null,
  1966. };
  1967. }
  1968. if (step === 2) {
  1969. return {
  1970. password: null,
  1971. lastEmailTimestamp: null,
  1972. signupVerificationRequestedAt: null,
  1973. loginVerificationRequestedAt: null,
  1974. lastSignupCode: null,
  1975. lastLoginCode: null,
  1976. localhostUrl: null,
  1977. };
  1978. }
  1979. if (step === 3 || step === 4) {
  1980. return {
  1981. lastEmailTimestamp: null,
  1982. signupVerificationRequestedAt: null,
  1983. loginVerificationRequestedAt: null,
  1984. lastSignupCode: null,
  1985. lastLoginCode: null,
  1986. localhostUrl: null,
  1987. };
  1988. }
  1989. if (step === 5 || step === 6 || step === 7) {
  1990. return {
  1991. lastLoginCode: null,
  1992. loginVerificationRequestedAt: null,
  1993. localhostUrl: null,
  1994. };
  1995. }
  1996. if (step === 8) {
  1997. return {
  1998. localhostUrl: null,
  1999. };
  2000. }
  2001. return {};
  2002. }
  2003. async function invalidateDownstreamAfterStepRestart(step, options = {}) {
  2004. const { logLabel = `步骤 ${step} 重新执行` } = options;
  2005. const state = await getState();
  2006. const statuses = { ...(state.stepStatuses || {}) };
  2007. const changedSteps = [];
  2008. for (let downstream = step + 1; downstream <= 9; downstream++) {
  2009. if (statuses[downstream] !== 'pending') {
  2010. statuses[downstream] = 'pending';
  2011. changedSteps.push(downstream);
  2012. }
  2013. }
  2014. if (changedSteps.length) {
  2015. await setState({ stepStatuses: statuses });
  2016. for (const downstream of changedSteps) {
  2017. chrome.runtime.sendMessage({
  2018. type: 'STEP_STATUS_CHANGED',
  2019. payload: { step: downstream, status: 'pending' },
  2020. }).catch(() => { });
  2021. }
  2022. await addLog(`${logLabel},已重置后续步骤状态:${changedSteps.join(', ')}`, 'warn');
  2023. }
  2024. const resets = getDownstreamStateResets(step);
  2025. if (Object.keys(resets).length) {
  2026. await setState(resets);
  2027. broadcastDataUpdate(resets);
  2028. }
  2029. }
  2030. function clearStopRequest() {
  2031. stopRequested = false;
  2032. autoRunCountdownSkipRequested = false;
  2033. }
  2034. function getRunningSteps(statuses = {}) {
  2035. return Object.entries({ ...DEFAULT_STATE.stepStatuses, ...statuses })
  2036. .filter(([, status]) => status === 'running')
  2037. .map(([step]) => Number(step))
  2038. .sort((a, b) => a - b);
  2039. }
  2040. function getAutoRunStatusPayload(phase, payload = {}) {
  2041. const currentRun = payload.currentRun ?? autoRunCurrentRun;
  2042. const totalRuns = payload.totalRuns ?? autoRunTotalRuns;
  2043. const attemptRun = payload.attemptRun ?? autoRunAttemptRun;
  2044. const rawScheduledAt = phase === 'scheduled'
  2045. ? (payload.scheduledAt ?? payload.scheduledAutoRunAt ?? null)
  2046. : null;
  2047. const scheduledAt = rawScheduledAt === null ? null : Number(rawScheduledAt);
  2048. const rawCountdownAt = payload.countdownAt ?? payload.autoRunCountdownAt ?? null;
  2049. const countdownAt = rawCountdownAt === null ? null : Number(rawCountdownAt);
  2050. const countdownTitle = payload.countdownTitle === undefined
  2051. ? ''
  2052. : String(payload.countdownTitle || '');
  2053. const countdownNote = payload.countdownNote === undefined
  2054. ? ''
  2055. : String(payload.countdownNote || '');
  2056. const autoRunning = phase === 'scheduled'
  2057. || phase === 'running'
  2058. || phase === 'waiting_step'
  2059. || phase === 'waiting_email'
  2060. || phase === 'retrying'
  2061. || phase === 'waiting_interval';
  2062. return {
  2063. autoRunning,
  2064. autoRunPhase: phase,
  2065. autoRunCurrentRun: currentRun,
  2066. autoRunTotalRuns: totalRuns,
  2067. autoRunAttemptRun: attemptRun,
  2068. scheduledAutoRunAt: Number.isFinite(scheduledAt) ? scheduledAt : null,
  2069. autoRunCountdownAt: Number.isFinite(countdownAt) ? countdownAt : null,
  2070. autoRunCountdownTitle: countdownTitle,
  2071. autoRunCountdownNote: countdownNote,
  2072. };
  2073. }
  2074. async function broadcastAutoRunStatus(phase, payload = {}, extraState = {}) {
  2075. const rawScheduledAt = phase === 'scheduled'
  2076. ? (payload.scheduledAt ?? payload.scheduledAutoRunAt ?? null)
  2077. : null;
  2078. const rawCountdownAt = payload.countdownAt ?? payload.autoRunCountdownAt ?? null;
  2079. const statusPayload = {
  2080. phase,
  2081. currentRun: payload.currentRun ?? autoRunCurrentRun,
  2082. totalRuns: payload.totalRuns ?? autoRunTotalRuns,
  2083. attemptRun: payload.attemptRun ?? autoRunAttemptRun,
  2084. scheduledAt: rawScheduledAt === null ? null : Number(rawScheduledAt),
  2085. countdownAt: rawCountdownAt === null ? null : Number(rawCountdownAt),
  2086. countdownTitle: payload.countdownTitle === undefined ? '' : String(payload.countdownTitle || ''),
  2087. countdownNote: payload.countdownNote === undefined ? '' : String(payload.countdownNote || ''),
  2088. };
  2089. await setState({
  2090. ...extraState,
  2091. ...getAutoRunStatusPayload(phase, statusPayload),
  2092. });
  2093. chrome.runtime.sendMessage({
  2094. type: 'AUTO_RUN_STATUS',
  2095. payload: statusPayload,
  2096. }).catch(() => { });
  2097. }
  2098. function isAutoRunLockedState(state) {
  2099. return Boolean(state.autoRunning)
  2100. && (
  2101. state.autoRunPhase === 'running'
  2102. || state.autoRunPhase === 'waiting_step'
  2103. || state.autoRunPhase === 'retrying'
  2104. || state.autoRunPhase === 'waiting_interval'
  2105. );
  2106. }
  2107. function isAutoRunPausedState(state) {
  2108. return Boolean(state.autoRunning) && state.autoRunPhase === 'waiting_email';
  2109. }
  2110. function isAutoRunScheduledState(state) {
  2111. const scheduledAt = state.scheduledAutoRunAt === null ? null : Number(state.scheduledAutoRunAt);
  2112. return Boolean(state.autoRunning)
  2113. && state.autoRunPhase === 'scheduled'
  2114. && Number.isFinite(scheduledAt)
  2115. && Boolean(normalizeScheduledAutoRunPlan(state.scheduledAutoRunPlan));
  2116. }
  2117. function formatAutoRunScheduleTime(timestamp) {
  2118. return new Date(timestamp).toLocaleString('zh-CN', {
  2119. hour12: false,
  2120. timeZone: DISPLAY_TIMEZONE,
  2121. month: '2-digit',
  2122. day: '2-digit',
  2123. hour: '2-digit',
  2124. minute: '2-digit',
  2125. second: '2-digit',
  2126. });
  2127. }
  2128. async function setAutoRunDelayEnabledState(enabled) {
  2129. const normalized = Boolean(enabled);
  2130. await setPersistentSettings({ autoRunDelayEnabled: normalized });
  2131. await setState({ autoRunDelayEnabled: normalized });
  2132. broadcastDataUpdate({ autoRunDelayEnabled: normalized });
  2133. }
  2134. async function ensureScheduledAutoRunAlarm(scheduledAt) {
  2135. if (!Number.isFinite(scheduledAt) || scheduledAt <= Date.now()) {
  2136. return false;
  2137. }
  2138. const existingAlarm = await chrome.alarms.get(AUTO_RUN_ALARM_NAME);
  2139. if (!existingAlarm || Math.abs((existingAlarm.scheduledTime || 0) - scheduledAt) > 1000) {
  2140. await chrome.alarms.clear(AUTO_RUN_ALARM_NAME);
  2141. await chrome.alarms.create(AUTO_RUN_ALARM_NAME, { when: scheduledAt });
  2142. }
  2143. return true;
  2144. }
  2145. async function clearScheduledAutoRunAlarm() {
  2146. await chrome.alarms.clear(AUTO_RUN_ALARM_NAME);
  2147. }
  2148. async function scheduleAutoRun(totalRuns, options = {}) {
  2149. const state = await getState();
  2150. if (isAutoRunLockedState(state) || isAutoRunPausedState(state) || autoRunActive) {
  2151. throw new Error('自动运行已在进行中,请先停止后再重新计划。');
  2152. }
  2153. if (isAutoRunScheduledState(state)) {
  2154. throw new Error('已有自动运行倒计时计划,请先取消或立即开始。');
  2155. }
  2156. const delayMinutes = normalizeAutoRunDelayMinutes(options.delayMinutes);
  2157. const plan = normalizeScheduledAutoRunPlan({
  2158. totalRuns,
  2159. autoRunSkipFailures: options.autoRunSkipFailures,
  2160. mode: options.mode,
  2161. });
  2162. const scheduledAt = Date.now() + delayMinutes * 60 * 1000;
  2163. autoRunCurrentRun = 0;
  2164. autoRunTotalRuns = plan.totalRuns;
  2165. autoRunAttemptRun = 0;
  2166. await ensureScheduledAutoRunAlarm(scheduledAt);
  2167. await broadcastAutoRunStatus(
  2168. 'scheduled',
  2169. {
  2170. currentRun: 0,
  2171. totalRuns: plan.totalRuns,
  2172. attemptRun: 0,
  2173. scheduledAt,
  2174. countdownAt: scheduledAt,
  2175. countdownTitle: '已计划自动运行',
  2176. countdownNote: `计划于 ${formatAutoRunScheduleTime(scheduledAt)} 开始`,
  2177. },
  2178. {
  2179. autoRunSkipFailures: plan.autoRunSkipFailures,
  2180. scheduledAutoRunPlan: plan,
  2181. }
  2182. );
  2183. await addLog(
  2184. `自动运行已计划:${delayMinutes} 分钟后启动(${formatAutoRunScheduleTime(scheduledAt)}),目标 ${plan.totalRuns} 轮。`,
  2185. 'info'
  2186. );
  2187. return { ok: true, scheduledAt };
  2188. }
  2189. let scheduledAutoRunLaunching = false;
  2190. async function launchScheduledAutoRun(trigger = 'alarm') {
  2191. if (scheduledAutoRunLaunching) {
  2192. return false;
  2193. }
  2194. scheduledAutoRunLaunching = true;
  2195. try {
  2196. const state = await getState();
  2197. if (!isAutoRunScheduledState(state)) {
  2198. return false;
  2199. }
  2200. if (autoRunActive) {
  2201. return false;
  2202. }
  2203. const plan = normalizeScheduledAutoRunPlan(state.scheduledAutoRunPlan);
  2204. if (!plan) {
  2205. await clearScheduledAutoRunAlarm();
  2206. await broadcastAutoRunStatus('idle', {
  2207. currentRun: 0,
  2208. totalRuns: 1,
  2209. attemptRun: 0,
  2210. }, {
  2211. scheduledAutoRunPlan: null,
  2212. });
  2213. return false;
  2214. }
  2215. await clearScheduledAutoRunAlarm();
  2216. if (trigger !== 'manual' && state.autoRunDelayEnabled) {
  2217. await setAutoRunDelayEnabledState(false);
  2218. }
  2219. await broadcastAutoRunStatus(
  2220. 'running',
  2221. {
  2222. currentRun: 0,
  2223. totalRuns: plan.totalRuns,
  2224. attemptRun: 0,
  2225. },
  2226. {
  2227. autoRunSkipFailures: plan.autoRunSkipFailures,
  2228. scheduledAutoRunPlan: null,
  2229. }
  2230. );
  2231. clearStopRequest();
  2232. await addLog(
  2233. trigger === 'manual'
  2234. ? '已手动跳过倒计时,自动运行立即开始。'
  2235. : '倒计时结束,自动运行开始执行。',
  2236. 'info'
  2237. );
  2238. startAutoRunLoop(plan.totalRuns, {
  2239. autoRunSkipFailures: Boolean(plan.autoRunSkipFailures),
  2240. mode: plan.mode,
  2241. });
  2242. return true;
  2243. } finally {
  2244. scheduledAutoRunLaunching = false;
  2245. }
  2246. }
  2247. async function cancelScheduledAutoRun(options = {}) {
  2248. const state = await getState();
  2249. if (!isAutoRunScheduledState(state)) {
  2250. return false;
  2251. }
  2252. const plan = normalizeScheduledAutoRunPlan(state.scheduledAutoRunPlan);
  2253. await clearScheduledAutoRunAlarm();
  2254. autoRunCurrentRun = 0;
  2255. autoRunTotalRuns = plan?.totalRuns || 1;
  2256. autoRunAttemptRun = 0;
  2257. await broadcastAutoRunStatus(
  2258. 'idle',
  2259. {
  2260. currentRun: 0,
  2261. totalRuns: plan?.totalRuns || 1,
  2262. attemptRun: 0,
  2263. },
  2264. {
  2265. scheduledAutoRunPlan: null,
  2266. }
  2267. );
  2268. if (options.logMessage !== false) {
  2269. await addLog(options.logMessage || '已取消自动运行倒计时计划。', 'warn');
  2270. }
  2271. return true;
  2272. }
  2273. async function restoreScheduledAutoRunIfNeeded() {
  2274. const state = await getState();
  2275. if (state.autoRunPhase !== 'scheduled') {
  2276. return;
  2277. }
  2278. const plan = normalizeScheduledAutoRunPlan(state.scheduledAutoRunPlan);
  2279. const scheduledAt = state.scheduledAutoRunAt === null ? null : Number(state.scheduledAutoRunAt);
  2280. if (!plan || !Number.isFinite(scheduledAt)) {
  2281. await clearScheduledAutoRunAlarm();
  2282. await broadcastAutoRunStatus('idle', {
  2283. currentRun: 0,
  2284. totalRuns: 1,
  2285. attemptRun: 0,
  2286. }, {
  2287. scheduledAutoRunPlan: null,
  2288. });
  2289. return;
  2290. }
  2291. if (scheduledAt <= Date.now()) {
  2292. await launchScheduledAutoRun('restore');
  2293. return;
  2294. }
  2295. await ensureScheduledAutoRunAlarm(scheduledAt);
  2296. }
  2297. async function ensureManualInteractionAllowed(actionLabel) {
  2298. const state = await getState();
  2299. if (isAutoRunLockedState(state)) {
  2300. throw new Error(`自动流程运行中,请先停止后再${actionLabel}。`);
  2301. }
  2302. if (isAutoRunPausedState(state)) {
  2303. throw new Error(`自动流程当前已暂停。请点击“继续”,或先确认接管自动流程后再${actionLabel}。`);
  2304. }
  2305. if (isAutoRunScheduledState(state)) {
  2306. throw new Error(`自动流程已计划启动。请先取消计划,或立即开始后再${actionLabel}。`);
  2307. }
  2308. return state;
  2309. }
  2310. async function skipStep(step) {
  2311. const state = await ensureManualInteractionAllowed('跳过步骤');
  2312. if (!Number.isInteger(step) || step < 1 || step > 9) {
  2313. throw new Error(`无效步骤:${step}`);
  2314. }
  2315. const statuses = { ...(state.stepStatuses || {}) };
  2316. const currentStatus = statuses[step];
  2317. if (currentStatus === 'running') {
  2318. throw new Error(`步骤 ${step} 正在运行中,不能跳过。`);
  2319. }
  2320. if (isStepDoneStatus(currentStatus)) {
  2321. throw new Error(`步骤 ${step} 已完成,无需再跳过。`);
  2322. }
  2323. if (step > 1) {
  2324. const prevStatus = statuses[step - 1];
  2325. if (!isStepDoneStatus(prevStatus)) {
  2326. throw new Error(`请先完成步骤 ${step - 1},再跳过步骤 ${step}。`);
  2327. }
  2328. }
  2329. await setStepStatus(step, 'skipped');
  2330. await addLog(`步骤 ${step} 已跳过`, 'warn');
  2331. if (step === 1) {
  2332. const latestState = await getState();
  2333. const step2Status = latestState.stepStatuses?.[2];
  2334. if (!isStepDoneStatus(step2Status) && step2Status !== 'running') {
  2335. await setStepStatus(2, 'skipped');
  2336. await addLog('步骤 1 已跳过,步骤 2 也已同时跳过。', 'warn');
  2337. }
  2338. }
  2339. return { ok: true, step, status: 'skipped' };
  2340. }
  2341. function throwIfStopped() {
  2342. if (stopRequested) {
  2343. throw new Error(STOP_ERROR_MESSAGE);
  2344. }
  2345. }
  2346. async function sleepWithStop(ms) {
  2347. const start = Date.now();
  2348. while (Date.now() - start < ms) {
  2349. throwIfStopped();
  2350. await new Promise(r => setTimeout(r, Math.min(100, ms - (Date.now() - start))));
  2351. }
  2352. }
  2353. async function humanStepDelay(min = HUMAN_STEP_DELAY_MIN, max = HUMAN_STEP_DELAY_MAX) {
  2354. const duration = Math.floor(Math.random() * (max - min + 1)) + min;
  2355. await sleepWithStop(duration);
  2356. }
  2357. async function clickWithDebugger(tabId, rect) {
  2358. throwIfStopped();
  2359. if (!tabId) {
  2360. throw new Error('未找到用于调试点击的认证页面标签页。');
  2361. }
  2362. if (!rect || !Number.isFinite(rect.centerX) || !Number.isFinite(rect.centerY)) {
  2363. throw new Error('步骤 8 的调试器兜底点击需要有效的按钮坐标。');
  2364. }
  2365. const target = { tabId };
  2366. try {
  2367. await chrome.debugger.attach(target, '1.3');
  2368. } catch (err) {
  2369. throw new Error(
  2370. `步骤 8 的调试器兜底点击附加失败:${err.message}。` +
  2371. '如果认证页标签已打开 DevTools,请先关闭后重试。'
  2372. );
  2373. }
  2374. try {
  2375. throwIfStopped();
  2376. const x = Math.round(rect.centerX);
  2377. const y = Math.round(rect.centerY);
  2378. await chrome.debugger.sendCommand(target, 'Page.bringToFront');
  2379. throwIfStopped();
  2380. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  2381. type: 'mouseMoved',
  2382. x,
  2383. y,
  2384. button: 'none',
  2385. buttons: 0,
  2386. clickCount: 0,
  2387. });
  2388. throwIfStopped();
  2389. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  2390. type: 'mousePressed',
  2391. x,
  2392. y,
  2393. button: 'left',
  2394. buttons: 1,
  2395. clickCount: 1,
  2396. });
  2397. throwIfStopped();
  2398. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  2399. type: 'mouseReleased',
  2400. x,
  2401. y,
  2402. button: 'left',
  2403. buttons: 0,
  2404. clickCount: 1,
  2405. });
  2406. } finally {
  2407. await chrome.debugger.detach(target).catch(() => { });
  2408. }
  2409. }
  2410. async function broadcastStopToContentScripts() {
  2411. const registry = await getTabRegistry();
  2412. for (const entry of Object.values(registry)) {
  2413. if (!entry?.tabId) continue;
  2414. try {
  2415. await chrome.tabs.sendMessage(entry.tabId, {
  2416. type: 'STOP_FLOW',
  2417. source: 'background',
  2418. payload: {},
  2419. });
  2420. } catch { }
  2421. }
  2422. }
  2423. let stopRequested = false;
  2424. let autoRunCountdownSkipRequested = false;
  2425. // ============================================================
  2426. // Message Handler (central router)
  2427. // ============================================================
  2428. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  2429. console.log(LOG_PREFIX, `Received: ${message.type} from ${message.source || 'sidepanel'}`, message);
  2430. handleMessage(message, sender).then(response => {
  2431. sendResponse(response);
  2432. }).catch(err => {
  2433. console.error(LOG_PREFIX, 'Handler error:', err);
  2434. sendResponse({ error: err.message });
  2435. });
  2436. return true; // async response
  2437. });
  2438. async function handleMessage(message, sender) {
  2439. switch (message.type) {
  2440. case 'CONTENT_SCRIPT_READY': {
  2441. const tabId = sender.tab?.id;
  2442. if (tabId && message.source) {
  2443. await registerTab(message.source, tabId);
  2444. flushCommand(message.source, tabId);
  2445. await addLog(`内容脚本已就绪:${getSourceLabel(message.source)}(标签页 ${tabId})`);
  2446. }
  2447. return { ok: true };
  2448. }
  2449. case 'LOG': {
  2450. const { message: msg, level } = message.payload;
  2451. await addLog(`[${getSourceLabel(message.source)}] ${msg}`, level);
  2452. return { ok: true };
  2453. }
  2454. case 'STEP_COMPLETE': {
  2455. if (stopRequested) {
  2456. await setStepStatus(message.step, 'stopped');
  2457. notifyStepError(message.step, STOP_ERROR_MESSAGE);
  2458. return { ok: true };
  2459. }
  2460. await setStepStatus(message.step, 'completed');
  2461. await addLog(`步骤 ${message.step} 已完成`, 'ok');
  2462. await handleStepData(message.step, message.payload);
  2463. notifyStepComplete(message.step, message.payload);
  2464. return { ok: true };
  2465. }
  2466. case 'STEP_ERROR': {
  2467. if (isStopError(message.error)) {
  2468. await setStepStatus(message.step, 'stopped');
  2469. await addLog(`步骤 ${message.step} 已被用户停止`, 'warn');
  2470. notifyStepError(message.step, message.error);
  2471. } else {
  2472. await setStepStatus(message.step, 'failed');
  2473. await addLog(`步骤 ${message.step} 失败:${message.error}`, 'error');
  2474. notifyStepError(message.step, message.error);
  2475. }
  2476. return { ok: true };
  2477. }
  2478. case 'GET_STATE': {
  2479. return await getState();
  2480. }
  2481. case 'RESET': {
  2482. clearStopRequest();
  2483. await clearScheduledAutoRunAlarm();
  2484. await resetState();
  2485. await addLog('流程已重置', 'info');
  2486. return { ok: true };
  2487. }
  2488. case 'EXECUTE_STEP': {
  2489. clearStopRequest();
  2490. if (message.source === 'sidepanel') {
  2491. await ensureManualInteractionAllowed('手动执行步骤');
  2492. }
  2493. const step = message.payload.step;
  2494. if (message.source === 'sidepanel') {
  2495. await invalidateDownstreamAfterStepRestart(step, { logLabel: `步骤 ${step} 重新执行` });
  2496. }
  2497. // Save email if provided (from side panel step 3)
  2498. if (message.payload.email) {
  2499. await setEmailState(message.payload.email);
  2500. }
  2501. if (message.payload.emailPrefix !== undefined) {
  2502. await setPersistentSettings({ emailPrefix: message.payload.emailPrefix });
  2503. await setState({ emailPrefix: message.payload.emailPrefix });
  2504. }
  2505. if (doesStepUseCompletionSignal(step)) {
  2506. await executeStepViaCompletionSignal(step);
  2507. } else {
  2508. await executeStep(step);
  2509. }
  2510. return { ok: true };
  2511. }
  2512. case 'AUTO_RUN': {
  2513. clearStopRequest();
  2514. const state = await getState();
  2515. if (isAutoRunScheduledState(state)) {
  2516. throw new Error('已有自动运行倒计时计划,请先取消或立即开始。');
  2517. }
  2518. const totalRuns = normalizeRunCount(message.payload?.totalRuns || 1);
  2519. const autoRunSkipFailures = Boolean(message.payload?.autoRunSkipFailures);
  2520. const mode = message.payload?.mode === 'continue' ? 'continue' : 'restart';
  2521. await setState({ autoRunSkipFailures });
  2522. startAutoRunLoop(totalRuns, { autoRunSkipFailures, mode });
  2523. return { ok: true };
  2524. }
  2525. case 'SCHEDULE_AUTO_RUN': {
  2526. clearStopRequest();
  2527. const totalRuns = normalizeRunCount(message.payload?.totalRuns || 1);
  2528. return await scheduleAutoRun(totalRuns, {
  2529. delayMinutes: message.payload?.delayMinutes,
  2530. autoRunSkipFailures: Boolean(message.payload?.autoRunSkipFailures),
  2531. mode: message.payload?.mode,
  2532. });
  2533. }
  2534. case 'START_SCHEDULED_AUTO_RUN_NOW': {
  2535. clearStopRequest();
  2536. const started = await launchScheduledAutoRun('manual');
  2537. if (!started) {
  2538. throw new Error('当前没有可立即开始的倒计时计划。');
  2539. }
  2540. return { ok: true };
  2541. }
  2542. case 'CANCEL_SCHEDULED_AUTO_RUN': {
  2543. const cancelled = await cancelScheduledAutoRun();
  2544. if (!cancelled) {
  2545. throw new Error('当前没有可取消的倒计时计划。');
  2546. }
  2547. return { ok: true };
  2548. }
  2549. case 'SKIP_AUTO_RUN_COUNTDOWN': {
  2550. clearStopRequest();
  2551. const skipped = await skipAutoRunCountdown();
  2552. if (!skipped) {
  2553. throw new Error('当前没有可立即开始的倒计时。');
  2554. }
  2555. return { ok: true };
  2556. }
  2557. case 'RESUME_AUTO_RUN': {
  2558. clearStopRequest();
  2559. if (message.payload.email) {
  2560. await setEmailState(message.payload.email);
  2561. }
  2562. resumeAutoRun().catch((error) => {
  2563. handleAutoRunLoopUnhandledError(error).catch((handlerError) => {
  2564. console.error(LOG_PREFIX, 'Failed to finalize resume error:', handlerError);
  2565. });
  2566. });
  2567. return { ok: true };
  2568. }
  2569. case 'TAKEOVER_AUTO_RUN': {
  2570. await requestStop({ logMessage: '已确认手动接管,正在停止自动流程并切换为手动控制...' });
  2571. await addLog('自动流程已切换为手动控制。', 'warn');
  2572. return { ok: true };
  2573. }
  2574. case 'SKIP_STEP': {
  2575. const step = Number(message.payload?.step);
  2576. return await skipStep(step);
  2577. }
  2578. case 'SAVE_SETTING': {
  2579. const updates = buildPersistentSettingsPayload(message.payload || {});
  2580. await setPersistentSettings(updates);
  2581. await setState(updates);
  2582. return { ok: true, state: await getState() };
  2583. }
  2584. case 'EXPORT_SETTINGS': {
  2585. return { ok: true, ...(await exportSettingsBundle()) };
  2586. }
  2587. case 'IMPORT_SETTINGS': {
  2588. const state = await importSettingsBundle(message.payload?.config || null);
  2589. return { ok: true, state };
  2590. }
  2591. case 'UPSERT_HOTMAIL_ACCOUNT': {
  2592. const account = await upsertHotmailAccount(message.payload || {});
  2593. return { ok: true, account };
  2594. }
  2595. case 'DELETE_HOTMAIL_ACCOUNT': {
  2596. await deleteHotmailAccount(String(message.payload?.accountId || ''));
  2597. return { ok: true };
  2598. }
  2599. case 'DELETE_HOTMAIL_ACCOUNTS': {
  2600. const result = await deleteHotmailAccounts(String(message.payload?.mode || 'all'));
  2601. return { ok: true, ...result };
  2602. }
  2603. case 'SELECT_HOTMAIL_ACCOUNT': {
  2604. const account = await setCurrentHotmailAccount(String(message.payload?.accountId || ''), {
  2605. markUsed: false,
  2606. syncEmail: true,
  2607. });
  2608. return { ok: true, account };
  2609. }
  2610. case 'PATCH_HOTMAIL_ACCOUNT': {
  2611. const account = await patchHotmailAccount(
  2612. String(message.payload?.accountId || ''),
  2613. message.payload?.updates || {}
  2614. );
  2615. return { ok: true, account };
  2616. }
  2617. case 'VERIFY_HOTMAIL_ACCOUNT':
  2618. case 'AUTHORIZE_HOTMAIL_ACCOUNT': {
  2619. const accountId = String(message.payload?.accountId || '');
  2620. try {
  2621. const result = await verifyHotmailAccount(accountId);
  2622. await setCurrentHotmailAccount(result.account.id, { markUsed: false, syncEmail: true });
  2623. await addLog(`Hotmail 账号 ${result.account.email} 校验通过,可直接用于收信。`, 'ok');
  2624. return { ok: true, account: result.account, messageCount: result.messageCount };
  2625. } catch (err) {
  2626. const state = await getState();
  2627. const accounts = normalizeHotmailAccounts(state.hotmailAccounts);
  2628. const target = findHotmailAccount(accounts, accountId);
  2629. if (target) {
  2630. target.status = 'error';
  2631. target.lastError = err.message;
  2632. await syncHotmailAccounts(accounts.map((item) => (item.id === target.id ? target : item)));
  2633. }
  2634. throw err;
  2635. }
  2636. }
  2637. case 'TEST_HOTMAIL_ACCOUNT': {
  2638. const result = await testHotmailAccountMailAccess(String(message.payload?.accountId || ''));
  2639. return { ok: true, ...result };
  2640. }
  2641. // Side panel data updates
  2642. case 'SET_EMAIL_STATE': {
  2643. const state = await getState();
  2644. if (isAutoRunLockedState(state)) {
  2645. throw new Error('自动流程运行中,当前不能手动修改邮箱。');
  2646. }
  2647. const email = String(message.payload?.email || '').trim() || null;
  2648. await setEmailStateSilently(email);
  2649. return { ok: true, email };
  2650. }
  2651. case 'SAVE_EMAIL': {
  2652. const state = await getState();
  2653. if (isAutoRunLockedState(state)) {
  2654. throw new Error('自动流程运行中,当前不能手动修改邮箱。');
  2655. }
  2656. await setEmailState(message.payload.email);
  2657. await resumeAutoRun();
  2658. return { ok: true, email: message.payload.email };
  2659. }
  2660. case 'FETCH_GENERATED_EMAIL': {
  2661. clearStopRequest();
  2662. const state = await getState();
  2663. if (isAutoRunLockedState(state)) {
  2664. throw new Error('自动流程运行中,当前不能手动获取邮箱。');
  2665. }
  2666. const email = await fetchGeneratedEmail(state, message.payload || {});
  2667. await resumeAutoRun();
  2668. return { ok: true, email };
  2669. }
  2670. case 'FETCH_DUCK_EMAIL': {
  2671. clearStopRequest();
  2672. const state = await getState();
  2673. if (isAutoRunLockedState(state)) {
  2674. throw new Error('自动流程运行中,当前不能手动获取邮箱。');
  2675. }
  2676. const email = await fetchGeneratedEmail(state, { ...(message.payload || {}), generator: 'duck' });
  2677. await resumeAutoRun();
  2678. return { ok: true, email };
  2679. }
  2680. case 'STOP_FLOW': {
  2681. await requestStop();
  2682. return { ok: true };
  2683. }
  2684. default:
  2685. console.warn(LOG_PREFIX, `Unknown message type: ${message.type}`);
  2686. return { error: `Unknown message type: ${message.type}` };
  2687. }
  2688. }
  2689. // ============================================================
  2690. // Step Data Handlers
  2691. // ============================================================
  2692. async function handleStepData(step, payload) {
  2693. switch (step) {
  2694. case 1: {
  2695. const updates = {};
  2696. if (payload.oauthUrl) {
  2697. updates.oauthUrl = payload.oauthUrl;
  2698. broadcastDataUpdate({ oauthUrl: payload.oauthUrl });
  2699. }
  2700. if (payload.sub2apiSessionId !== undefined) updates.sub2apiSessionId = payload.sub2apiSessionId || null;
  2701. if (payload.sub2apiOAuthState !== undefined) updates.sub2apiOAuthState = payload.sub2apiOAuthState || null;
  2702. if (payload.sub2apiGroupId !== undefined) updates.sub2apiGroupId = payload.sub2apiGroupId || null;
  2703. if (payload.sub2apiDraftName !== undefined) updates.sub2apiDraftName = payload.sub2apiDraftName || null;
  2704. if (Object.keys(updates).length) {
  2705. await setState(updates);
  2706. }
  2707. break;
  2708. }
  2709. case 3:
  2710. if (payload.email) await setEmailState(payload.email);
  2711. if (payload.signupVerificationRequestedAt) {
  2712. await setState({ signupVerificationRequestedAt: payload.signupVerificationRequestedAt });
  2713. }
  2714. if (payload.loginVerificationRequestedAt) {
  2715. await setState({ loginVerificationRequestedAt: payload.loginVerificationRequestedAt });
  2716. }
  2717. break;
  2718. case 6:
  2719. if (payload.loginVerificationRequestedAt) {
  2720. await setState({ loginVerificationRequestedAt: payload.loginVerificationRequestedAt });
  2721. }
  2722. break;
  2723. case 4:
  2724. await setState({
  2725. lastEmailTimestamp: payload.emailTimestamp || null,
  2726. signupVerificationRequestedAt: null,
  2727. });
  2728. break;
  2729. case 7:
  2730. await setState({
  2731. lastEmailTimestamp: payload.emailTimestamp || null,
  2732. loginVerificationRequestedAt: null,
  2733. });
  2734. break;
  2735. case 8:
  2736. if (payload.localhostUrl) {
  2737. if (!isLocalhostOAuthCallbackUrl(payload.localhostUrl)) {
  2738. throw new Error('步骤 8 返回了无效的 localhost OAuth 回调地址。');
  2739. }
  2740. await setState({ localhostUrl: payload.localhostUrl });
  2741. broadcastDataUpdate({ localhostUrl: payload.localhostUrl });
  2742. }
  2743. break;
  2744. case 9: {
  2745. if (payload.localhostUrl) {
  2746. await closeLocalhostCallbackTabs(payload.localhostUrl);
  2747. }
  2748. const latestState = await getState();
  2749. if (latestState.currentHotmailAccountId && isHotmailProvider(latestState)) {
  2750. await patchHotmailAccount(latestState.currentHotmailAccountId, {
  2751. used: true,
  2752. lastUsedAt: Date.now(),
  2753. });
  2754. await addLog('当前 Hotmail 账号已自动标记为已用。', 'ok');
  2755. }
  2756. const localhostPrefix = buildLocalhostCleanupPrefix(payload.localhostUrl);
  2757. if (localhostPrefix) {
  2758. await closeTabsByUrlPrefix(localhostPrefix);
  2759. }
  2760. if (shouldUseCustomRegistrationEmail(latestState) && latestState.email) {
  2761. await setEmailStateSilently(null);
  2762. }
  2763. break;
  2764. }
  2765. }
  2766. }
  2767. // ============================================================
  2768. // Step Completion Waiting
  2769. // ============================================================
  2770. // Map of step -> { resolve, reject } for waiting on step completion
  2771. const stepWaiters = new Map();
  2772. let resumeWaiter = null;
  2773. const AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS = 120000;
  2774. const AUTO_RUN_BACKGROUND_COMPLETED_STEPS = new Set([4, 7, 8]);
  2775. const STEP_COMPLETION_SIGNAL_STEPS = new Set([1, 2, 3, 5, 6, 9]);
  2776. function waitForStepComplete(step, timeoutMs = 120000) {
  2777. return new Promise((resolve, reject) => {
  2778. throwIfStopped();
  2779. if (stepWaiters.has(step)) {
  2780. console.warn(LOG_PREFIX, `[waitForStepComplete] replacing existing waiter for step ${step}`);
  2781. }
  2782. console.log(LOG_PREFIX, `[waitForStepComplete] register step ${step}, timeout=${timeoutMs}ms`);
  2783. const timer = setTimeout(() => {
  2784. stepWaiters.delete(step);
  2785. console.warn(LOG_PREFIX, `[waitForStepComplete] timeout for step ${step} after ${timeoutMs}ms`);
  2786. reject(new Error(`步骤 ${step} 等待超时(>${timeoutMs / 1000} 秒)`));
  2787. }, timeoutMs);
  2788. stepWaiters.set(step, {
  2789. resolve: (data) => { clearTimeout(timer); stepWaiters.delete(step); resolve(data); },
  2790. reject: (err) => { clearTimeout(timer); stepWaiters.delete(step); reject(err); },
  2791. });
  2792. });
  2793. }
  2794. function doesStepUseCompletionSignal(step) {
  2795. return STEP_COMPLETION_SIGNAL_STEPS.has(step);
  2796. }
  2797. function notifyStepComplete(step, payload) {
  2798. const waiter = stepWaiters.get(step);
  2799. console.log(LOG_PREFIX, `[notifyStepComplete] step ${step}, hasWaiter=${Boolean(waiter)}`);
  2800. if (waiter) waiter.resolve(payload);
  2801. }
  2802. function notifyStepError(step, error) {
  2803. const waiter = stepWaiters.get(step);
  2804. console.warn(LOG_PREFIX, `[notifyStepError] step ${step}, hasWaiter=${Boolean(waiter)}, error=${error}`);
  2805. if (waiter) waiter.reject(new Error(error));
  2806. }
  2807. async function completeStepFromBackground(step, payload = {}) {
  2808. if (stopRequested) {
  2809. await setStepStatus(step, 'stopped');
  2810. notifyStepError(step, STOP_ERROR_MESSAGE);
  2811. return;
  2812. }
  2813. await setStepStatus(step, 'completed');
  2814. await addLog(`步骤 ${step} 已完成`, 'ok');
  2815. await handleStepData(step, payload);
  2816. notifyStepComplete(step, payload);
  2817. }
  2818. async function finalizeDeferredStepExecutionError(step, error) {
  2819. const latestState = await getState();
  2820. const currentStatus = latestState.stepStatuses?.[step];
  2821. if (currentStatus === 'completed' || currentStatus === 'failed' || currentStatus === 'stopped') {
  2822. return;
  2823. }
  2824. if (isStopError(error)) {
  2825. await setStepStatus(step, 'stopped');
  2826. await addLog(`步骤 ${step} 已被用户停止`, 'warn');
  2827. return;
  2828. }
  2829. await setStepStatus(step, 'failed');
  2830. await addLog(`步骤 ${step} 失败:${getErrorMessage(error)}`, 'error');
  2831. }
  2832. async function executeStepViaCompletionSignal(step, timeoutMs = AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS) {
  2833. const completionResultPromise = waitForStepComplete(step, timeoutMs).then(
  2834. payload => ({ ok: true, payload }),
  2835. error => ({ ok: false, error }),
  2836. );
  2837. let executeError = null;
  2838. try {
  2839. await executeStep(step, { deferRetryableTransportError: true });
  2840. } catch (err) {
  2841. executeError = err;
  2842. if (isStopError(err) || !isRetryableContentScriptTransportError(err)) {
  2843. notifyStepError(step, getErrorMessage(err));
  2844. }
  2845. }
  2846. const completionResult = await completionResultPromise;
  2847. if (completionResult.ok) {
  2848. if (executeError) {
  2849. console.warn(
  2850. LOG_PREFIX,
  2851. `[executeStepViaCompletionSignal] step ${step} completed after deferred execute error: ${getErrorMessage(executeError)}`
  2852. );
  2853. }
  2854. return completionResult.payload;
  2855. }
  2856. if (executeError && isRetryableContentScriptTransportError(executeError)) {
  2857. const completionMessage = getErrorMessage(completionResult.error);
  2858. if (/等待超时/.test(completionMessage)) {
  2859. await finalizeDeferredStepExecutionError(step, executeError);
  2860. throw executeError;
  2861. }
  2862. throw completionResult.error;
  2863. }
  2864. if (executeError) {
  2865. throw executeError;
  2866. }
  2867. throw completionResult.error;
  2868. }
  2869. async function waitForRunningStepsToFinish(payload = {}) {
  2870. let currentState = await getState();
  2871. let runningSteps = getRunningSteps(currentState.stepStatuses);
  2872. if (!runningSteps.length) {
  2873. return currentState;
  2874. }
  2875. await addLog(`自动继续:检测到步骤 ${runningSteps.join(', ')} 正在运行,等待完成后再继续自动流程...`, 'info');
  2876. await broadcastAutoRunStatus('waiting_step', payload);
  2877. while (runningSteps.length) {
  2878. await sleepWithStop(250);
  2879. currentState = await getState();
  2880. runningSteps = getRunningSteps(currentState.stepStatuses);
  2881. }
  2882. await addLog('自动继续:当前运行步骤已结束,准备按最新进度继续自动流程...', 'info');
  2883. return currentState;
  2884. }
  2885. async function markRunningStepsStopped() {
  2886. const state = await getState();
  2887. const runningSteps = getRunningSteps(state.stepStatuses);
  2888. for (const step of runningSteps) {
  2889. await setStepStatus(step, 'stopped');
  2890. }
  2891. }
  2892. async function requestStop(options = {}) {
  2893. const { logMessage = '已收到停止请求,正在取消当前操作...' } = options;
  2894. const state = await getState();
  2895. if (isAutoRunScheduledState(state) && !autoRunActive) {
  2896. await cancelScheduledAutoRun({
  2897. logMessage: options.logMessage === false
  2898. ? false
  2899. : (options.logMessage || '已取消自动运行倒计时计划。'),
  2900. });
  2901. return;
  2902. }
  2903. if (stopRequested) return;
  2904. stopRequested = true;
  2905. cancelPendingCommands();
  2906. cleanupStep8NavigationListeners();
  2907. rejectPendingStep8(new Error(STOP_ERROR_MESSAGE));
  2908. await addLog(logMessage, 'warn');
  2909. await broadcastStopToContentScripts();
  2910. for (const waiter of stepWaiters.values()) {
  2911. waiter.reject(new Error(STOP_ERROR_MESSAGE));
  2912. }
  2913. stepWaiters.clear();
  2914. if (resumeWaiter) {
  2915. resumeWaiter.reject(new Error(STOP_ERROR_MESSAGE));
  2916. resumeWaiter = null;
  2917. }
  2918. await markRunningStepsStopped();
  2919. autoRunActive = false;
  2920. await broadcastAutoRunStatus('stopped', {
  2921. currentRun: autoRunCurrentRun,
  2922. totalRuns: autoRunTotalRuns,
  2923. attemptRun: autoRunAttemptRun,
  2924. });
  2925. }
  2926. // ============================================================
  2927. // Step Execution
  2928. // ============================================================
  2929. async function executeStep(step, options = {}) {
  2930. const { deferRetryableTransportError = false } = options;
  2931. console.log(LOG_PREFIX, `Executing step ${step}`);
  2932. throwIfStopped();
  2933. await setStepStatus(step, 'running');
  2934. await addLog(`步骤 ${step} 开始执行`);
  2935. await humanStepDelay();
  2936. const state = await getState();
  2937. // Set flow start time on first step
  2938. if (step === 1 && !state.flowStartTime) {
  2939. await setState({ flowStartTime: Date.now() });
  2940. }
  2941. try {
  2942. switch (step) {
  2943. case 1: await executeStep1(state); break;
  2944. case 2: await executeStep2(state); break;
  2945. case 3: await executeStep3(state); break;
  2946. case 4: await executeStep4(state); break;
  2947. case 5: await executeStep5(state); break;
  2948. case 6: await executeStep6(state); break;
  2949. case 7: await executeStep7(state); break;
  2950. case 8: await executeStep8(state); break;
  2951. case 9: await executeStep9(state); break;
  2952. default:
  2953. throw new Error(`未知步骤:${step}`);
  2954. }
  2955. } catch (err) {
  2956. if (isStopError(err)) {
  2957. await setStepStatus(step, 'stopped');
  2958. await addLog(`步骤 ${step} 已被用户停止`, 'warn');
  2959. throw err;
  2960. }
  2961. if (!(deferRetryableTransportError && doesStepUseCompletionSignal(step) && isRetryableContentScriptTransportError(err))) {
  2962. await setStepStatus(step, 'failed');
  2963. await addLog(`步骤 ${step} 失败:${err.message}`, 'error');
  2964. } else {
  2965. console.warn(
  2966. LOG_PREFIX,
  2967. `[executeStep] deferring retryable transport error for step ${step}: ${getErrorMessage(err)}`
  2968. );
  2969. }
  2970. throw err;
  2971. }
  2972. }
  2973. /**
  2974. * Execute a step and wait for it to complete before returning.
  2975. * @param {number} step
  2976. * @param {number} delayAfter - ms to wait after completion (for page transitions)
  2977. */
  2978. async function executeStepAndWait(step, delayAfter = 2000) {
  2979. throwIfStopped();
  2980. const delaySeconds = normalizeAutoStepDelaySeconds((await getState()).autoStepDelaySeconds, null);
  2981. if (delaySeconds > 0) {
  2982. await addLog(
  2983. `自动运行:步骤 ${step} 执行前额外等待 ${delaySeconds} 秒,避免节奏过快。`,
  2984. 'info'
  2985. );
  2986. await sleepWithStop(delaySeconds * 1000);
  2987. }
  2988. if (AUTO_RUN_BACKGROUND_COMPLETED_STEPS.has(step)) {
  2989. await addLog(`自动运行:步骤 ${step} 由后台流程负责收尾,执行函数返回后将直接进入下一步。`, 'info');
  2990. await executeStep(step);
  2991. const latestState = await getState();
  2992. await addLog(`自动运行:步骤 ${step} 已执行返回,当前状态为 ${latestState.stepStatuses?.[step] || 'pending'},准备继续后续步骤。`, 'info');
  2993. } else if (doesStepUseCompletionSignal(step)) {
  2994. await addLog(`自动运行:步骤 ${step} 已发起,正在等待完成信号(超时 ${AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS / 1000} 秒)。`, 'info');
  2995. await executeStepViaCompletionSignal(step, AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS);
  2996. await addLog(`自动运行:步骤 ${step} 已收到完成信号,准备继续后续步骤。`, 'info');
  2997. } else {
  2998. await executeStep(step);
  2999. }
  3000. // Extra delay for page transitions / DOM updates
  3001. if (delayAfter > 0) {
  3002. await sleepWithStop(delayAfter + Math.floor(Math.random() * 1200));
  3003. }
  3004. }
  3005. function getEmailGeneratorLabel(generator) {
  3006. if (generator === 'custom') {
  3007. return '自定义邮箱';
  3008. }
  3009. return generator === 'cloudflare' ? 'Cloudflare 邮箱' : 'Duck 邮箱';
  3010. }
  3011. function generateCloudflareAliasLocalPart() {
  3012. const letters = 'abcdefghijklmnopqrstuvwxyz';
  3013. const digits = '0123456789';
  3014. const chars = [];
  3015. for (let i = 0; i < 6; i++) {
  3016. chars.push(letters[Math.floor(Math.random() * letters.length)]);
  3017. }
  3018. for (let i = 0; i < 4; i++) {
  3019. chars.push(digits[Math.floor(Math.random() * digits.length)]);
  3020. }
  3021. for (let i = chars.length - 1; i > 0; i--) {
  3022. const j = Math.floor(Math.random() * (i + 1));
  3023. [chars[i], chars[j]] = [chars[j], chars[i]];
  3024. }
  3025. return chars.join('');
  3026. }
  3027. async function fetchCloudflareEmail(state, options = {}) {
  3028. throwIfStopped();
  3029. const latestState = state || await getState();
  3030. const domain = normalizeCloudflareDomain(latestState.cloudflareDomain);
  3031. if (!domain) {
  3032. throw new Error('Cloudflare 域名为空或格式无效。');
  3033. }
  3034. const localPart = String(options.localPart || '').trim().toLowerCase() || generateCloudflareAliasLocalPart();
  3035. const aliasEmail = `${localPart}@${domain}`;
  3036. await setEmailState(aliasEmail);
  3037. await addLog(`Cloudflare 邮箱:已生成 ${aliasEmail}`, 'ok');
  3038. return aliasEmail;
  3039. }
  3040. async function fetchDuckEmail(options = {}) {
  3041. throwIfStopped();
  3042. const { generateNew = true } = options;
  3043. await addLog(`Duck 邮箱:正在打开自动填充设置(${generateNew ? '生成新地址' : '复用当前地址'})...`);
  3044. await reuseOrCreateTab('duck-mail', DUCK_AUTOFILL_URL);
  3045. const result = await sendToContentScript('duck-mail', {
  3046. type: 'FETCH_DUCK_EMAIL',
  3047. source: 'background',
  3048. payload: { generateNew },
  3049. });
  3050. if (result?.error) {
  3051. throw new Error(result.error);
  3052. }
  3053. if (!result?.email) {
  3054. throw new Error('未返回 Duck 邮箱地址。');
  3055. }
  3056. await setEmailState(result.email);
  3057. await addLog(`Duck 邮箱:${result.generated ? '已生成' : '已读取'} ${result.email}`, 'ok');
  3058. return result.email;
  3059. }
  3060. async function fetchGeneratedEmail(state, options = {}) {
  3061. const currentState = state || await getState();
  3062. const generator = normalizeEmailGenerator(options.generator ?? currentState.emailGenerator);
  3063. if (generator === 'custom') {
  3064. throw new Error('当前邮箱生成方式为自定义邮箱,请直接填写注册邮箱。');
  3065. }
  3066. if (generator === 'cloudflare') {
  3067. return fetchCloudflareEmail(currentState, options);
  3068. }
  3069. return fetchDuckEmail(options);
  3070. }
  3071. // ============================================================
  3072. // Auto Run Flow
  3073. // ============================================================
  3074. let autoRunActive = false;
  3075. let autoRunCurrentRun = 0;
  3076. let autoRunTotalRuns = 1;
  3077. let autoRunAttemptRun = 0;
  3078. const EMAIL_FETCH_MAX_ATTEMPTS = 5;
  3079. const VERIFICATION_POLL_MAX_ROUNDS = 5;
  3080. const AUTO_STEP_DELAYS = {
  3081. 1: 2000,
  3082. 2: 2000,
  3083. 3: 3000,
  3084. 4: 2000,
  3085. 5: 3000,
  3086. 6: 3000,
  3087. 7: 2000,
  3088. 8: 2000,
  3089. 9: 1000,
  3090. };
  3091. async function resumeAutoRunIfWaitingForEmail(options = {}) {
  3092. const { silent = false } = options;
  3093. const state = await getState();
  3094. if (!state.email || !isAutoRunPausedState(state)) {
  3095. return false;
  3096. }
  3097. if (resumeWaiter) {
  3098. if (!silent) {
  3099. await addLog('邮箱已就绪,自动继续后续步骤...', 'info');
  3100. }
  3101. resumeWaiter.resolve();
  3102. resumeWaiter = null;
  3103. return true;
  3104. }
  3105. return false;
  3106. }
  3107. async function ensureAutoEmailReady(targetRun, totalRuns, attemptRuns) {
  3108. const currentState = await getState();
  3109. if (isHotmailProvider(currentState)) {
  3110. const account = await ensureHotmailAccountForFlow({
  3111. allowAllocate: true,
  3112. markUsed: true,
  3113. preferredAccountId: null,
  3114. });
  3115. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:已分配 Hotmail 账号 ${account.email}(第 ${attemptRuns} 次尝试)===`, 'ok');
  3116. return account.email;
  3117. }
  3118. if (isGeneratedAliasProvider(currentState.mailProvider)) {
  3119. if (!currentState.emailPrefix) {
  3120. throw new Error('2925 邮箱前缀未设置,请先在侧边栏填写。');
  3121. }
  3122. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:2925 模式已启用,将在步骤 3 自动生成邮箱(第 ${attemptRuns} 次尝试)===`, 'info');
  3123. return null;
  3124. }
  3125. if (currentState.email) {
  3126. return currentState.email;
  3127. }
  3128. if (shouldUseCustomRegistrationEmail(currentState)) {
  3129. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮已暂停:请先填写自定义注册邮箱,然后继续 ===`, 'warn');
  3130. await broadcastAutoRunStatus('waiting_email', {
  3131. currentRun: targetRun,
  3132. totalRuns,
  3133. attemptRun: attemptRuns,
  3134. });
  3135. await waitForResume();
  3136. const resumedState = await getState();
  3137. if (!resumedState.email) {
  3138. throw new Error('无法继续:当前没有注册邮箱。');
  3139. }
  3140. return resumedState.email;
  3141. }
  3142. const generator = normalizeEmailGenerator(currentState.emailGenerator);
  3143. const generatorLabel = getEmailGeneratorLabel(generator);
  3144. let lastError = null;
  3145. for (let attempt = 1; attempt <= EMAIL_FETCH_MAX_ATTEMPTS; attempt++) {
  3146. try {
  3147. if (attempt > 1) {
  3148. await addLog(`${generatorLabel}:正在进行第 ${attempt}/${EMAIL_FETCH_MAX_ATTEMPTS} 次自动获取重试...`, 'warn');
  3149. }
  3150. const generatedEmail = await fetchGeneratedEmail(currentState, { generateNew: true, generator });
  3151. await addLog(
  3152. `=== 目标 ${targetRun}/${totalRuns} 轮:${generatorLabel}已就绪:${generatedEmail}(第 ${attemptRuns} 次尝试,第 ${attempt}/${EMAIL_FETCH_MAX_ATTEMPTS} 次获取)===`,
  3153. 'ok'
  3154. );
  3155. return generatedEmail;
  3156. } catch (err) {
  3157. lastError = err;
  3158. await addLog(`${generatorLabel}自动获取失败(${attempt}/${EMAIL_FETCH_MAX_ATTEMPTS}):${err.message}`, 'warn');
  3159. if (generator === 'cloudflare' && /域名/.test(String(err.message || ''))) {
  3160. break;
  3161. }
  3162. }
  3163. }
  3164. await addLog(`${generatorLabel}自动获取已连续失败 ${EMAIL_FETCH_MAX_ATTEMPTS} 次:${lastError?.message || '未知错误'}`, 'error');
  3165. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮已暂停:请先自动获取邮箱或手动粘贴邮箱,然后继续 ===`, 'warn');
  3166. await broadcastAutoRunStatus('waiting_email', {
  3167. currentRun: targetRun,
  3168. totalRuns,
  3169. attemptRun: attemptRuns,
  3170. });
  3171. await waitForResume();
  3172. const resumedState = await getState();
  3173. if (!resumedState.email) {
  3174. throw new Error('无法继续:当前没有邮箱地址。');
  3175. }
  3176. return resumedState.email;
  3177. }
  3178. async function runAutoSequenceFromStep(startStep, context = {}) {
  3179. const { targetRun, totalRuns, attemptRuns, continued = false } = context;
  3180. const maxStep9RestartAttempts = 5;
  3181. let step9RestartAttempts = 0;
  3182. if (continued) {
  3183. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:继续当前进度,从步骤 ${startStep} 开始(第 ${attemptRuns} 次尝试)===`, 'info');
  3184. } else {
  3185. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:第 ${attemptRuns} 次尝试,阶段 1,获取 OAuth 链接并打开注册页 ===`, 'info');
  3186. }
  3187. if (startStep <= 2) {
  3188. for (const step of [1, 2]) {
  3189. if (step < startStep) continue;
  3190. await executeStepAndWait(step, AUTO_STEP_DELAYS[step]);
  3191. }
  3192. }
  3193. if (startStep <= 3) {
  3194. await ensureAutoEmailReady(targetRun, totalRuns, attemptRuns);
  3195. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:阶段 2,注册、验证、登录并完成授权(第 ${attemptRuns} 次尝试)===`, 'info');
  3196. await broadcastAutoRunStatus('running', {
  3197. currentRun: targetRun,
  3198. totalRuns,
  3199. attemptRun: attemptRuns,
  3200. });
  3201. await executeStepAndWait(3, AUTO_STEP_DELAYS[3]);
  3202. } else {
  3203. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:继续执行剩余流程(第 ${attemptRuns} 次尝试)===`, 'info');
  3204. }
  3205. const signupTabId = await getTabId('signup-page');
  3206. if (signupTabId) {
  3207. await chrome.tabs.update(signupTabId, { active: true });
  3208. }
  3209. let step = Math.max(startStep, 4);
  3210. while (step <= 9) {
  3211. try {
  3212. await executeStepAndWait(step, AUTO_STEP_DELAYS[step]);
  3213. step += 1;
  3214. } catch (err) {
  3215. const latestState = await getState();
  3216. const currentMail = getMailConfig(latestState);
  3217. const shouldRetryStep9 = step === 9
  3218. && (
  3219. isLegacyStep9RecoverableAuthError(err)
  3220. || (currentMail.provider === HOTMAIL_PROVIDER && isStep9RecoverableAuthError(err))
  3221. )
  3222. && step9RestartAttempts < maxStep9RestartAttempts;
  3223. if (shouldRetryStep9) {
  3224. step9RestartAttempts += 1;
  3225. await addLog(
  3226. `步骤 9:检测到 CPA 认证失败,正在回到步骤 6 重新开始授权流程(${step9RestartAttempts}/${maxStep9RestartAttempts})...`,
  3227. 'warn'
  3228. );
  3229. await invalidateDownstreamAfterStepRestart(6, {
  3230. logLabel: `步骤 9 认证失败后准备回到步骤 6 重试(${step9RestartAttempts}/${maxStep9RestartAttempts})`,
  3231. });
  3232. step = 6;
  3233. continue;
  3234. }
  3235. throw err;
  3236. }
  3237. }
  3238. }
  3239. // Outer loop: keep retrying until the target number of successful runs is reached.
  3240. async function legacyAutoRunLoop(totalRuns, options = {}) {
  3241. if (autoRunActive) {
  3242. await addLog('自动运行已在进行中', 'warn');
  3243. return;
  3244. }
  3245. clearStopRequest();
  3246. autoRunActive = true;
  3247. autoRunTotalRuns = totalRuns;
  3248. autoRunCurrentRun = 0;
  3249. autoRunAttemptRun = 0;
  3250. const autoRunSkipFailures = Boolean(options.autoRunSkipFailures);
  3251. const initialMode = options.mode === 'continue' ? 'continue' : 'restart';
  3252. const resumeCurrentRun = Number.isInteger(options.resumeCurrentRun) ? options.resumeCurrentRun : 0;
  3253. const resumeSuccessfulRuns = Number.isInteger(options.resumeSuccessfulRuns) ? options.resumeSuccessfulRuns : 0;
  3254. const resumeAttemptRunsProcessed = Number.isInteger(options.resumeAttemptRunsProcessed) ? options.resumeAttemptRunsProcessed : 0;
  3255. let maxAttempts = autoRunSkipFailures ? Math.max(totalRuns * 10, totalRuns + 20) : totalRuns;
  3256. const forcedRetryCap = Math.max(totalRuns * 10, totalRuns + 20);
  3257. let successfulRuns = Math.max(0, resumeSuccessfulRuns);
  3258. let attemptRuns = Math.max(0, resumeAttemptRunsProcessed);
  3259. let forceFreshTabsNextRun = false;
  3260. let continueCurrentOnFirstAttempt = initialMode === 'continue';
  3261. const initialState = await getState();
  3262. const initialPhase = continueCurrentOnFirstAttempt && getRunningSteps(initialState.stepStatuses).length
  3263. ? 'waiting_step'
  3264. : 'running';
  3265. await setState({
  3266. autoRunSkipFailures,
  3267. ...getAutoRunStatusPayload(initialPhase, {
  3268. currentRun: resumeCurrentRun,
  3269. totalRuns,
  3270. attemptRun: resumeAttemptRunsProcessed,
  3271. }),
  3272. });
  3273. while (successfulRuns < totalRuns && attemptRuns < maxAttempts) {
  3274. attemptRuns += 1;
  3275. const targetRun = successfulRuns + 1;
  3276. autoRunCurrentRun = targetRun;
  3277. autoRunAttemptRun = attemptRuns;
  3278. let startStep = 1;
  3279. let useExistingProgress = false;
  3280. if (continueCurrentOnFirstAttempt) {
  3281. let currentState = await getState();
  3282. if (getRunningSteps(currentState.stepStatuses).length) {
  3283. currentState = await waitForRunningStepsToFinish({
  3284. currentRun: targetRun,
  3285. totalRuns,
  3286. attemptRun: attemptRuns,
  3287. });
  3288. }
  3289. const resumeStep = getFirstUnfinishedStep(currentState.stepStatuses);
  3290. if (resumeStep && hasSavedProgress(currentState.stepStatuses)) {
  3291. startStep = resumeStep;
  3292. useExistingProgress = true;
  3293. } else if (hasSavedProgress(currentState.stepStatuses)) {
  3294. await addLog('当前流程已全部处理,将按“重新开始”新开一轮自动运行。', 'info');
  3295. }
  3296. continueCurrentOnFirstAttempt = false;
  3297. }
  3298. if (!useExistingProgress) {
  3299. // Reset everything at the start of each fresh attempt (keep user settings).
  3300. const prevState = await getState();
  3301. const keepSettings = {
  3302. vpsUrl: prevState.vpsUrl,
  3303. vpsPassword: prevState.vpsPassword,
  3304. customPassword: prevState.customPassword,
  3305. autoRunSkipFailures: prevState.autoRunSkipFailures,
  3306. autoRunFallbackThreadIntervalMinutes: prevState.autoRunFallbackThreadIntervalMinutes,
  3307. autoRunDelayEnabled: prevState.autoRunDelayEnabled,
  3308. autoRunDelayMinutes: prevState.autoRunDelayMinutes,
  3309. autoStepDelaySeconds: prevState.autoStepDelaySeconds,
  3310. mailProvider: prevState.mailProvider,
  3311. emailGenerator: prevState.emailGenerator,
  3312. emailPrefix: prevState.emailPrefix,
  3313. inbucketHost: prevState.inbucketHost,
  3314. inbucketMailbox: prevState.inbucketMailbox,
  3315. cloudflareDomain: prevState.cloudflareDomain,
  3316. cloudflareDomains: prevState.cloudflareDomains,
  3317. // Fresh attempts must drop stale tab/url runtime state from the prior run.
  3318. tabRegistry: {},
  3319. sourceLastUrls: {},
  3320. ...getAutoRunStatusPayload('running', { currentRun: targetRun, totalRuns, attemptRun: attemptRuns }),
  3321. };
  3322. await resetState();
  3323. await setState(keepSettings);
  3324. chrome.runtime.sendMessage({ type: 'AUTO_RUN_RESET' }).catch(() => { });
  3325. await sleepWithStop(500);
  3326. } else {
  3327. await setState({
  3328. autoRunSkipFailures,
  3329. ...getAutoRunStatusPayload('running', { currentRun: targetRun, totalRuns, attemptRun: attemptRuns }),
  3330. });
  3331. }
  3332. if (forceFreshTabsNextRun) {
  3333. await addLog(`兜底模式:上一轮已放弃,当前开始第 ${attemptRuns} 次尝试,将使用新线程继续补足第 ${targetRun}/${totalRuns} 轮。`, 'warn');
  3334. forceFreshTabsNextRun = false;
  3335. }
  3336. try {
  3337. throwIfStopped();
  3338. await broadcastAutoRunStatus('running', {
  3339. currentRun: targetRun,
  3340. totalRuns,
  3341. attemptRun: attemptRuns,
  3342. });
  3343. await runAutoSequenceFromStep(startStep, {
  3344. targetRun,
  3345. totalRuns,
  3346. attemptRuns,
  3347. continued: useExistingProgress,
  3348. });
  3349. successfulRuns += 1;
  3350. autoRunCurrentRun = successfulRuns;
  3351. await addLog(`=== 目标 ${successfulRuns}/${totalRuns} 轮已完成(第 ${attemptRuns} 次尝试成功)===`, 'ok');
  3352. const fallbackThreadIntervalMinutes = normalizeAutoRunFallbackThreadIntervalMinutes(
  3353. (await getState()).autoRunFallbackThreadIntervalMinutes
  3354. );
  3355. if (autoRunSkipFailures && totalRuns > 1 && successfulRuns < totalRuns && fallbackThreadIntervalMinutes > 0) {
  3356. await addLog(
  3357. `兜底模式:第 ${successfulRuns}/${totalRuns} 轮已完成,等待 ${fallbackThreadIntervalMinutes} 分钟后再启动下一轮新线程。`,
  3358. 'info'
  3359. );
  3360. await sleepWithStop(fallbackThreadIntervalMinutes * 60 * 1000);
  3361. }
  3362. continue;
  3363. } catch (err) {
  3364. if (isStopError(err)) {
  3365. await addLog(`目标 ${targetRun}/${totalRuns} 轮已被用户停止`, 'warn');
  3366. await broadcastAutoRunStatus('stopped', {
  3367. currentRun: targetRun,
  3368. totalRuns,
  3369. attemptRun: attemptRuns,
  3370. });
  3371. break;
  3372. }
  3373. if (isRestartCurrentAttemptError(err)) {
  3374. await addLog(`目标 ${targetRun}/${totalRuns} 轮检测到当前邮箱已存在,当前线程已放弃,将重新开始新一轮。`, 'warn');
  3375. cancelPendingCommands('当前线程因邮箱已存在而放弃。');
  3376. await broadcastStopToContentScripts();
  3377. await broadcastAutoRunStatus('retrying', {
  3378. currentRun: targetRun,
  3379. totalRuns,
  3380. attemptRun: attemptRuns,
  3381. });
  3382. forceFreshTabsNextRun = true;
  3383. maxAttempts = Math.max(maxAttempts, Math.min(forcedRetryCap, attemptRuns + 1));
  3384. continue;
  3385. }
  3386. if (!autoRunSkipFailures) {
  3387. await addLog(`目标 ${targetRun}/${totalRuns} 轮失败:${err.message}`, 'error');
  3388. await broadcastAutoRunStatus('stopped', {
  3389. currentRun: targetRun,
  3390. totalRuns,
  3391. attemptRun: attemptRuns,
  3392. });
  3393. break;
  3394. }
  3395. await addLog(`目标 ${targetRun}/${totalRuns} 轮的第 ${attemptRuns} 次尝试失败:${err.message}`, 'error');
  3396. await addLog('兜底开关已开启:将放弃当前线程,重新开一轮继续补足目标次数。', 'warn');
  3397. cancelPendingCommands('当前尝试已放弃。');
  3398. await broadcastStopToContentScripts();
  3399. await broadcastAutoRunStatus('retrying', {
  3400. currentRun: targetRun,
  3401. totalRuns,
  3402. attemptRun: attemptRuns,
  3403. });
  3404. forceFreshTabsNextRun = true;
  3405. }
  3406. }
  3407. if (!stopRequested && autoRunSkipFailures && successfulRuns < totalRuns && attemptRuns >= maxAttempts) {
  3408. await addLog(`已达到安全重试上限(${attemptRuns} 次尝试),当前仅完成 ${successfulRuns}/${totalRuns} 轮。`, 'error');
  3409. await broadcastAutoRunStatus('stopped', {
  3410. currentRun: successfulRuns,
  3411. totalRuns: autoRunTotalRuns,
  3412. attemptRun: attemptRuns,
  3413. });
  3414. } else if (stopRequested) {
  3415. await addLog(`=== 已停止,完成 ${successfulRuns}/${autoRunTotalRuns} 轮,共尝试 ${attemptRuns} 次 ===`, 'warn');
  3416. await broadcastAutoRunStatus('stopped', {
  3417. currentRun: successfulRuns,
  3418. totalRuns: autoRunTotalRuns,
  3419. attemptRun: attemptRuns,
  3420. });
  3421. } else if (successfulRuns >= autoRunTotalRuns) {
  3422. await addLog(`=== 全部 ${autoRunTotalRuns} 轮均已成功完成,共尝试 ${attemptRuns} 次 ===`, 'ok');
  3423. await broadcastAutoRunStatus('complete', {
  3424. currentRun: successfulRuns,
  3425. totalRuns: autoRunTotalRuns,
  3426. attemptRun: attemptRuns,
  3427. });
  3428. } else {
  3429. await addLog(`=== 已停止,完成 ${successfulRuns}/${autoRunTotalRuns} 轮,共尝试 ${attemptRuns} 次 ===`, 'warn');
  3430. await broadcastAutoRunStatus('stopped', {
  3431. currentRun: successfulRuns,
  3432. totalRuns: autoRunTotalRuns,
  3433. attemptRun: attemptRuns,
  3434. });
  3435. }
  3436. autoRunActive = false;
  3437. autoRunAttemptRun = attemptRuns;
  3438. await setState(getAutoRunStatusPayload(stopRequested ? 'stopped' : (successfulRuns >= autoRunTotalRuns ? 'complete' : 'stopped'), {
  3439. currentRun: successfulRuns,
  3440. totalRuns: autoRunTotalRuns,
  3441. attemptRun: attemptRuns,
  3442. }));
  3443. clearStopRequest();
  3444. }
  3445. async function waitForResume() {
  3446. throwIfStopped();
  3447. const state = await getState();
  3448. if (state.email) {
  3449. await addLog('邮箱已就绪,自动继续后续步骤...', 'info');
  3450. return;
  3451. }
  3452. return new Promise((resolve, reject) => {
  3453. resumeWaiter = { resolve, reject };
  3454. });
  3455. }
  3456. async function legacyResumeAutoRun() {
  3457. throwIfStopped();
  3458. const state = await getState();
  3459. if (!state.email) {
  3460. await addLog('无法继续:当前没有邮箱地址,请先在侧边栏填写邮箱。', 'error');
  3461. return false;
  3462. }
  3463. const resumedInMemory = await resumeAutoRunIfWaitingForEmail({ silent: true });
  3464. if (resumedInMemory) {
  3465. return true;
  3466. }
  3467. if (!isAutoRunPausedState(state)) {
  3468. return false;
  3469. }
  3470. if (autoRunActive) {
  3471. return false;
  3472. }
  3473. const totalRuns = state.autoRunTotalRuns || 1;
  3474. const currentRun = state.autoRunCurrentRun || 1;
  3475. const attemptRun = state.autoRunAttemptRun || 1;
  3476. const successfulRuns = Math.max(0, currentRun - 1);
  3477. await addLog('检测到自动流程暂停上下文已丢失,正在从当前进度恢复自动运行...', 'warn');
  3478. autoRunLoop(totalRuns, {
  3479. autoRunSkipFailures: Boolean(state.autoRunSkipFailures),
  3480. mode: 'continue',
  3481. resumeCurrentRun: currentRun,
  3482. resumeSuccessfulRuns: successfulRuns,
  3483. resumeAttemptRunsProcessed: Math.max(0, attemptRun - 1),
  3484. });
  3485. return true;
  3486. }
  3487. function createAutoRunRoundSummary(round) {
  3488. return {
  3489. round,
  3490. status: 'pending',
  3491. attempts: 0,
  3492. failureReasons: [],
  3493. finalFailureReason: '',
  3494. };
  3495. }
  3496. function normalizeAutoRunRoundSummary(summary, round) {
  3497. const base = createAutoRunRoundSummary(round);
  3498. if (!summary || typeof summary !== 'object') {
  3499. return base;
  3500. }
  3501. const status = String(summary.status || '').trim().toLowerCase();
  3502. return {
  3503. round,
  3504. status: ['pending', 'success', 'failed'].includes(status) ? status : base.status,
  3505. attempts: Math.max(0, Math.floor(Number(summary.attempts) || 0)),
  3506. failureReasons: Array.isArray(summary.failureReasons)
  3507. ? summary.failureReasons.map((item) => String(item || '').trim()).filter(Boolean)
  3508. : [],
  3509. finalFailureReason: String(summary.finalFailureReason || '').trim(),
  3510. };
  3511. }
  3512. function buildAutoRunRoundSummaries(totalRuns, rawSummaries = []) {
  3513. return Array.from({ length: totalRuns }, (_, index) => {
  3514. return normalizeAutoRunRoundSummary(rawSummaries[index], index + 1);
  3515. });
  3516. }
  3517. function serializeAutoRunRoundSummaries(totalRuns, roundSummaries = []) {
  3518. return buildAutoRunRoundSummaries(totalRuns, roundSummaries).map((summary) => ({
  3519. ...summary,
  3520. failureReasons: [...summary.failureReasons],
  3521. }));
  3522. }
  3523. function getAutoRunRoundRetryCount(summary) {
  3524. return Math.max(0, Number(summary?.attempts || 0) - 1);
  3525. }
  3526. function formatAutoRunFailureReasons(reasons = []) {
  3527. if (!Array.isArray(reasons) || !reasons.length) {
  3528. return '未知错误';
  3529. }
  3530. const counts = new Map();
  3531. for (const reason of reasons) {
  3532. const normalized = String(reason || '').trim() || '未知错误';
  3533. counts.set(normalized, (counts.get(normalized) || 0) + 1);
  3534. }
  3535. return Array.from(counts.entries())
  3536. .map(([reason, count]) => (count > 1 ? `${reason}(${count}次)` : reason))
  3537. .join(';');
  3538. }
  3539. async function logAutoRunFinalSummary(totalRuns, roundSummaries = []) {
  3540. const summaries = buildAutoRunRoundSummaries(totalRuns, roundSummaries);
  3541. const successRounds = summaries.filter((item) => item.status === 'success');
  3542. const failedRounds = summaries.filter((item) => item.status === 'failed');
  3543. const pendingRounds = summaries.filter((item) => item.status === 'pending');
  3544. await addLog('=== 自动运行汇总 ===', failedRounds.length ? 'warn' : 'ok');
  3545. await addLog(
  3546. `总轮数:${totalRuns};成功:${successRounds.length};失败:${failedRounds.length};未完成:${pendingRounds.length}`,
  3547. failedRounds.length ? 'warn' : 'ok'
  3548. );
  3549. if (successRounds.length) {
  3550. await addLog(
  3551. `成功轮次:${successRounds
  3552. .map((item) => `第 ${item.round} 轮(重试 ${getAutoRunRoundRetryCount(item)} 次)`)
  3553. .join(';')}`,
  3554. 'ok'
  3555. );
  3556. }
  3557. if (failedRounds.length) {
  3558. await addLog(
  3559. `失败轮次:${failedRounds
  3560. .map((item) => {
  3561. const retryCount = getAutoRunRoundRetryCount(item);
  3562. const finalReason = item.finalFailureReason || item.failureReasons[item.failureReasons.length - 1] || '未知错误';
  3563. const reasonSummary = formatAutoRunFailureReasons(item.failureReasons);
  3564. return `第 ${item.round} 轮(重试 ${retryCount} 次,最终原因:${finalReason};失败记录:${reasonSummary})`;
  3565. })
  3566. .join(';')}`,
  3567. 'error'
  3568. );
  3569. }
  3570. if (pendingRounds.length) {
  3571. await addLog(
  3572. `未完成轮次:${pendingRounds.map((item) => `第 ${item.round} 轮`).join(';')}`,
  3573. 'warn'
  3574. );
  3575. }
  3576. }
  3577. async function sleepWithAutoRunCountdown(waitMs, payload = {}) {
  3578. if (!Number.isFinite(waitMs) || waitMs <= 0) {
  3579. return;
  3580. }
  3581. autoRunCountdownSkipRequested = false;
  3582. const countdownPayload = {
  3583. ...payload,
  3584. countdownAt: Date.now() + waitMs,
  3585. };
  3586. await broadcastAutoRunStatus('waiting_interval', countdownPayload);
  3587. const start = Date.now();
  3588. try {
  3589. while (Date.now() - start < waitMs) {
  3590. throwIfStopped();
  3591. if (autoRunCountdownSkipRequested) {
  3592. autoRunCountdownSkipRequested = false;
  3593. return;
  3594. }
  3595. await new Promise((resolve) => setTimeout(resolve, Math.min(100, waitMs - (Date.now() - start))));
  3596. }
  3597. } finally {
  3598. if (!stopRequested) {
  3599. await broadcastAutoRunStatus('waiting_interval', {
  3600. ...payload,
  3601. countdownAt: null,
  3602. countdownTitle: '',
  3603. countdownNote: '',
  3604. });
  3605. }
  3606. }
  3607. }
  3608. async function skipAutoRunCountdown() {
  3609. const state = await getState();
  3610. if (!autoRunActive || state.autoRunPhase !== 'waiting_interval') {
  3611. return false;
  3612. }
  3613. autoRunCountdownSkipRequested = true;
  3614. await addLog('已手动跳过当前倒计时,自动流程将立即继续。', 'info');
  3615. await broadcastAutoRunStatus('waiting_interval', {
  3616. currentRun: state.autoRunCurrentRun,
  3617. totalRuns: state.autoRunTotalRuns,
  3618. attemptRun: state.autoRunAttemptRun,
  3619. countdownAt: null,
  3620. countdownTitle: '',
  3621. countdownNote: '',
  3622. });
  3623. return true;
  3624. }
  3625. async function waitBetweenAutoRunRounds(targetRun, totalRuns, roundSummary) {
  3626. if (totalRuns <= 1 || targetRun >= totalRuns) {
  3627. return;
  3628. }
  3629. const fallbackThreadIntervalMinutes = normalizeAutoRunFallbackThreadIntervalMinutes(
  3630. (await getState()).autoRunFallbackThreadIntervalMinutes
  3631. );
  3632. if (fallbackThreadIntervalMinutes <= 0) {
  3633. return;
  3634. }
  3635. const statusLabel = roundSummary?.status === 'failed' ? '失败' : '完成';
  3636. await addLog(
  3637. `线程间隔:第 ${targetRun}/${totalRuns} 轮已${statusLabel},等待 ${fallbackThreadIntervalMinutes} 分钟后开始下一轮。`,
  3638. 'info'
  3639. );
  3640. await sleepWithAutoRunCountdown(fallbackThreadIntervalMinutes * 60 * 1000, {
  3641. currentRun: targetRun,
  3642. totalRuns,
  3643. attemptRun: autoRunAttemptRun,
  3644. countdownTitle: '线程间隔中',
  3645. countdownNote: `第 ${Math.min(targetRun + 1, totalRuns)}/${totalRuns} 轮即将开始`,
  3646. });
  3647. }
  3648. async function waitBeforeAutoRunRetry(targetRun, totalRuns, nextAttemptRun) {
  3649. const fallbackThreadIntervalMinutes = normalizeAutoRunFallbackThreadIntervalMinutes(
  3650. (await getState()).autoRunFallbackThreadIntervalMinutes
  3651. );
  3652. if (fallbackThreadIntervalMinutes <= 0) {
  3653. return;
  3654. }
  3655. await addLog(
  3656. `线程间隔:等待 ${fallbackThreadIntervalMinutes} 分钟后开始第 ${targetRun}/${totalRuns} 轮第 ${nextAttemptRun} 次尝试。`,
  3657. 'info'
  3658. );
  3659. await sleepWithAutoRunCountdown(fallbackThreadIntervalMinutes * 60 * 1000, {
  3660. currentRun: targetRun,
  3661. totalRuns,
  3662. attemptRun: nextAttemptRun,
  3663. countdownTitle: '线程间隔中',
  3664. countdownNote: `第 ${targetRun}/${totalRuns} 轮第 ${nextAttemptRun} 次尝试即将开始`,
  3665. });
  3666. }
  3667. async function handleAutoRunLoopUnhandledError(error) {
  3668. console.error(LOG_PREFIX, 'Auto run loop crashed:', error);
  3669. if (!isStopError(error)) {
  3670. await addLog(`自动运行异常终止:${getErrorMessage(error) || '未知错误'}`, 'error');
  3671. }
  3672. autoRunActive = false;
  3673. await broadcastAutoRunStatus('stopped', {
  3674. currentRun: autoRunCurrentRun,
  3675. totalRuns: autoRunTotalRuns,
  3676. attemptRun: autoRunAttemptRun,
  3677. });
  3678. clearStopRequest();
  3679. }
  3680. function startAutoRunLoop(totalRuns, options = {}) {
  3681. autoRunLoop(totalRuns, options).catch((error) => {
  3682. handleAutoRunLoopUnhandledError(error).catch((handlerError) => {
  3683. console.error(LOG_PREFIX, 'Failed to finalize auto run error:', handlerError);
  3684. });
  3685. });
  3686. }
  3687. async function autoRunLoop(totalRuns, options = {}) {
  3688. if (autoRunActive) {
  3689. await addLog('自动运行已在进行中', 'warn');
  3690. return;
  3691. }
  3692. clearStopRequest();
  3693. autoRunActive = true;
  3694. autoRunTotalRuns = totalRuns;
  3695. autoRunCurrentRun = 0;
  3696. autoRunAttemptRun = 0;
  3697. const autoRunSkipFailures = Boolean(options.autoRunSkipFailures);
  3698. const initialMode = options.mode === 'continue' ? 'continue' : 'restart';
  3699. const resumeCurrentRun = Number.isInteger(options.resumeCurrentRun) && options.resumeCurrentRun > 0
  3700. ? Math.min(totalRuns, options.resumeCurrentRun)
  3701. : 1;
  3702. const resumeAttemptRun = Number.isInteger(options.resumeAttemptRun) && options.resumeAttemptRun > 0
  3703. ? Math.min(AUTO_RUN_MAX_RETRIES_PER_ROUND + 1, options.resumeAttemptRun)
  3704. : 1;
  3705. let continueCurrentOnFirstAttempt = initialMode === 'continue';
  3706. let forceFreshTabsNextRun = false;
  3707. let stoppedEarly = false;
  3708. const roundSummaries = buildAutoRunRoundSummaries(totalRuns, options.resumeRoundSummaries);
  3709. if (continueCurrentOnFirstAttempt && resumeCurrentRun > 1) {
  3710. for (let round = 1; round < resumeCurrentRun; round += 1) {
  3711. const summary = roundSummaries[round - 1];
  3712. if (summary.status === 'pending') {
  3713. summary.status = 'success';
  3714. if (!summary.attempts) {
  3715. summary.attempts = 1;
  3716. }
  3717. }
  3718. }
  3719. }
  3720. let successfulRuns = roundSummaries.filter((item) => item.status === 'success').length;
  3721. const initialState = await getState();
  3722. const initialPhase = continueCurrentOnFirstAttempt && getRunningSteps(initialState.stepStatuses).length
  3723. ? 'waiting_step'
  3724. : 'running';
  3725. await setState({
  3726. autoRunSkipFailures,
  3727. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  3728. ...getAutoRunStatusPayload(initialPhase, {
  3729. currentRun: continueCurrentOnFirstAttempt ? resumeCurrentRun : 0,
  3730. totalRuns,
  3731. attemptRun: continueCurrentOnFirstAttempt ? resumeAttemptRun : 0,
  3732. }),
  3733. });
  3734. for (let targetRun = resumeCurrentRun; targetRun <= totalRuns; targetRun += 1) {
  3735. const roundSummary = roundSummaries[targetRun - 1];
  3736. const resumingCurrentRound = continueCurrentOnFirstAttempt && targetRun === resumeCurrentRun;
  3737. let attemptRun = resumingCurrentRound ? resumeAttemptRun : 1;
  3738. let reuseExistingProgress = resumingCurrentRound;
  3739. const maxAttemptsForRound = autoRunSkipFailures
  3740. ? AUTO_RUN_MAX_RETRIES_PER_ROUND + 1
  3741. : Math.max(1, attemptRun);
  3742. while (attemptRun <= maxAttemptsForRound) {
  3743. autoRunCurrentRun = targetRun;
  3744. autoRunAttemptRun = attemptRun;
  3745. roundSummary.attempts = attemptRun;
  3746. let startStep = 1;
  3747. let useExistingProgress = false;
  3748. if (reuseExistingProgress) {
  3749. let currentState = await getState();
  3750. if (getRunningSteps(currentState.stepStatuses).length) {
  3751. currentState = await waitForRunningStepsToFinish({
  3752. currentRun: targetRun,
  3753. totalRuns,
  3754. attemptRun,
  3755. });
  3756. }
  3757. const resumeStep = getFirstUnfinishedStep(currentState.stepStatuses);
  3758. if (resumeStep && hasSavedProgress(currentState.stepStatuses)) {
  3759. startStep = resumeStep;
  3760. useExistingProgress = true;
  3761. } else if (hasSavedProgress(currentState.stepStatuses)) {
  3762. await addLog('检测到当前流程已处理完成,本轮将改为从步骤 1 重新开始。', 'info');
  3763. }
  3764. }
  3765. if (!useExistingProgress) {
  3766. const prevState = await getState();
  3767. const keepSettings = {
  3768. vpsUrl: prevState.vpsUrl,
  3769. vpsPassword: prevState.vpsPassword,
  3770. customPassword: prevState.customPassword,
  3771. autoRunSkipFailures: prevState.autoRunSkipFailures,
  3772. autoRunFallbackThreadIntervalMinutes: prevState.autoRunFallbackThreadIntervalMinutes,
  3773. autoRunDelayEnabled: prevState.autoRunDelayEnabled,
  3774. autoRunDelayMinutes: prevState.autoRunDelayMinutes,
  3775. autoStepDelaySeconds: prevState.autoStepDelaySeconds,
  3776. mailProvider: prevState.mailProvider,
  3777. emailGenerator: prevState.emailGenerator,
  3778. emailPrefix: prevState.emailPrefix,
  3779. inbucketHost: prevState.inbucketHost,
  3780. inbucketMailbox: prevState.inbucketMailbox,
  3781. cloudflareDomain: prevState.cloudflareDomain,
  3782. cloudflareDomains: prevState.cloudflareDomains,
  3783. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  3784. tabRegistry: {},
  3785. sourceLastUrls: {},
  3786. ...getAutoRunStatusPayload('running', { currentRun: targetRun, totalRuns, attemptRun }),
  3787. };
  3788. await resetState();
  3789. await setState(keepSettings);
  3790. chrome.runtime.sendMessage({ type: 'AUTO_RUN_RESET' }).catch(() => { });
  3791. await sleepWithStop(500);
  3792. } else {
  3793. await setState({
  3794. autoRunSkipFailures,
  3795. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  3796. ...getAutoRunStatusPayload('running', { currentRun: targetRun, totalRuns, attemptRun }),
  3797. });
  3798. }
  3799. if (forceFreshTabsNextRun) {
  3800. await addLog(`上一轮尝试已放弃,当前开始第 ${targetRun}/${totalRuns} 轮第 ${attemptRun} 次尝试。`, 'warn');
  3801. forceFreshTabsNextRun = false;
  3802. }
  3803. try {
  3804. throwIfStopped();
  3805. await broadcastAutoRunStatus('running', {
  3806. currentRun: targetRun,
  3807. totalRuns,
  3808. attemptRun,
  3809. });
  3810. await runAutoSequenceFromStep(startStep, {
  3811. targetRun,
  3812. totalRuns,
  3813. attemptRuns: attemptRun,
  3814. continued: useExistingProgress,
  3815. });
  3816. roundSummary.status = 'success';
  3817. roundSummary.finalFailureReason = '';
  3818. successfulRuns += 1;
  3819. await setState({
  3820. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  3821. });
  3822. await addLog(`=== 第 ${targetRun}/${totalRuns} 轮完成(第 ${attemptRun} 次尝试成功)===`, 'ok');
  3823. break;
  3824. } catch (err) {
  3825. if (isStopError(err)) {
  3826. stoppedEarly = true;
  3827. await addLog(`第 ${targetRun}/${totalRuns} 轮已被用户停止`, 'warn');
  3828. await broadcastAutoRunStatus('stopped', {
  3829. currentRun: targetRun,
  3830. totalRuns,
  3831. attemptRun,
  3832. });
  3833. break;
  3834. }
  3835. const reason = getErrorMessage(err);
  3836. roundSummary.failureReasons.push(reason);
  3837. const canRetry = autoRunSkipFailures && attemptRun < maxAttemptsForRound;
  3838. await setState({
  3839. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  3840. });
  3841. if (canRetry) {
  3842. const retryIndex = attemptRun;
  3843. if (isRestartCurrentAttemptError(err)) {
  3844. await addLog(`第 ${targetRun}/${totalRuns} 轮第 ${attemptRun} 次尝试需要整轮重开:${reason}`, 'warn');
  3845. } else {
  3846. await addLog(`第 ${targetRun}/${totalRuns} 轮第 ${attemptRun} 次尝试失败:${reason}`, 'error');
  3847. }
  3848. cancelPendingCommands('当前尝试已放弃。');
  3849. await broadcastStopToContentScripts();
  3850. await broadcastAutoRunStatus('retrying', {
  3851. currentRun: targetRun,
  3852. totalRuns,
  3853. attemptRun,
  3854. });
  3855. forceFreshTabsNextRun = true;
  3856. await addLog(
  3857. `自动重试:${Math.round(AUTO_RUN_RETRY_DELAY_MS / 1000)} 秒后开始第 ${targetRun}/${totalRuns} 轮第 ${attemptRun + 1} 次尝试(第 ${retryIndex}/${AUTO_RUN_MAX_RETRIES_PER_ROUND} 次重试)。`,
  3858. 'warn'
  3859. );
  3860. try {
  3861. await sleepWithStop(AUTO_RUN_RETRY_DELAY_MS);
  3862. } catch (sleepError) {
  3863. if (isStopError(sleepError)) {
  3864. stoppedEarly = true;
  3865. await addLog(`第 ${targetRun}/${totalRuns} 轮已被用户停止`, 'warn');
  3866. await broadcastAutoRunStatus('stopped', {
  3867. currentRun: targetRun,
  3868. totalRuns,
  3869. attemptRun,
  3870. });
  3871. break;
  3872. }
  3873. throw sleepError;
  3874. }
  3875. try {
  3876. await waitBeforeAutoRunRetry(targetRun, totalRuns, attemptRun + 1);
  3877. } catch (sleepError) {
  3878. if (isStopError(sleepError)) {
  3879. stoppedEarly = true;
  3880. await addLog(`第 ${targetRun}/${totalRuns} 轮已被用户停止`, 'warn');
  3881. await broadcastAutoRunStatus('stopped', {
  3882. currentRun: targetRun,
  3883. totalRuns,
  3884. attemptRun,
  3885. });
  3886. break;
  3887. }
  3888. throw sleepError;
  3889. }
  3890. attemptRun += 1;
  3891. reuseExistingProgress = false;
  3892. continue;
  3893. }
  3894. roundSummary.status = 'failed';
  3895. roundSummary.finalFailureReason = reason;
  3896. await setState({
  3897. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  3898. });
  3899. if (!autoRunSkipFailures) {
  3900. cancelPendingCommands('当前轮执行失败。');
  3901. await broadcastStopToContentScripts();
  3902. await addLog('自动重试未开启,自动运行将在当前失败后停止。', 'warn');
  3903. stoppedEarly = true;
  3904. await broadcastAutoRunStatus('stopped', {
  3905. currentRun: targetRun,
  3906. totalRuns,
  3907. attemptRun,
  3908. });
  3909. break;
  3910. }
  3911. await addLog(`第 ${targetRun}/${totalRuns} 轮最终失败:${reason}`, 'error');
  3912. await addLog(
  3913. targetRun < totalRuns
  3914. ? `第 ${targetRun}/${totalRuns} 轮已达到 ${AUTO_RUN_MAX_RETRIES_PER_ROUND} 次重试上限,继续下一轮。`
  3915. : `第 ${targetRun}/${totalRuns} 轮已达到 ${AUTO_RUN_MAX_RETRIES_PER_ROUND} 次重试上限,本次自动运行结束。`,
  3916. 'warn'
  3917. );
  3918. cancelPendingCommands('当前轮已达到重试上限。');
  3919. await broadcastStopToContentScripts();
  3920. forceFreshTabsNextRun = true;
  3921. break;
  3922. } finally {
  3923. reuseExistingProgress = false;
  3924. continueCurrentOnFirstAttempt = false;
  3925. }
  3926. }
  3927. if (stoppedEarly) {
  3928. break;
  3929. }
  3930. try {
  3931. await waitBetweenAutoRunRounds(targetRun, totalRuns, roundSummary);
  3932. } catch (sleepError) {
  3933. if (isStopError(sleepError)) {
  3934. stoppedEarly = true;
  3935. await addLog(`第 ${targetRun}/${totalRuns} 轮已被用户停止`, 'warn');
  3936. await broadcastAutoRunStatus('stopped', {
  3937. currentRun: targetRun,
  3938. totalRuns,
  3939. attemptRun: autoRunAttemptRun,
  3940. });
  3941. break;
  3942. }
  3943. throw sleepError;
  3944. }
  3945. }
  3946. await setState({
  3947. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  3948. });
  3949. await logAutoRunFinalSummary(totalRuns, roundSummaries);
  3950. if (stopRequested || stoppedEarly) {
  3951. await addLog(`=== 已停止,完成 ${successfulRuns}/${autoRunTotalRuns} 轮 ===`, 'warn');
  3952. await broadcastAutoRunStatus('stopped', {
  3953. currentRun: autoRunCurrentRun,
  3954. totalRuns: autoRunTotalRuns,
  3955. attemptRun: autoRunAttemptRun,
  3956. });
  3957. } else {
  3958. await addLog(`=== 全部 ${autoRunTotalRuns} 轮已执行完成,成功 ${successfulRuns} 轮 ===`, 'ok');
  3959. await broadcastAutoRunStatus('complete', {
  3960. currentRun: autoRunTotalRuns,
  3961. totalRuns: autoRunTotalRuns,
  3962. attemptRun: autoRunAttemptRun,
  3963. });
  3964. }
  3965. autoRunActive = false;
  3966. await setState({
  3967. autoRunRoundSummaries: serializeAutoRunRoundSummaries(totalRuns, roundSummaries),
  3968. ...getAutoRunStatusPayload(stopRequested || stoppedEarly ? 'stopped' : 'complete', {
  3969. currentRun: stopRequested || stoppedEarly ? autoRunCurrentRun : autoRunTotalRuns,
  3970. totalRuns: autoRunTotalRuns,
  3971. attemptRun: autoRunAttemptRun,
  3972. }),
  3973. });
  3974. clearStopRequest();
  3975. }
  3976. async function resumeAutoRun() {
  3977. throwIfStopped();
  3978. const state = await getState();
  3979. if (!state.email) {
  3980. await addLog('无法继续:当前没有邮箱地址,请先在侧边栏填写邮箱。', 'error');
  3981. return false;
  3982. }
  3983. const resumedInMemory = await resumeAutoRunIfWaitingForEmail({ silent: true });
  3984. if (resumedInMemory) {
  3985. return true;
  3986. }
  3987. if (!isAutoRunPausedState(state)) {
  3988. return false;
  3989. }
  3990. if (autoRunActive) {
  3991. return false;
  3992. }
  3993. const totalRuns = state.autoRunTotalRuns || 1;
  3994. const currentRun = state.autoRunCurrentRun || 1;
  3995. const attemptRun = state.autoRunAttemptRun || 1;
  3996. await addLog('检测到自动流程暂停上下文已丢失,正在从当前进度恢复自动运行...', 'warn');
  3997. startAutoRunLoop(totalRuns, {
  3998. autoRunSkipFailures: Boolean(state.autoRunSkipFailures),
  3999. mode: 'continue',
  4000. resumeCurrentRun: currentRun,
  4001. resumeAttemptRun: attemptRun,
  4002. resumeRoundSummaries: state.autoRunRoundSummaries,
  4003. });
  4004. return true;
  4005. }
  4006. // ============================================================
  4007. // Step 1: Get OAuth Link
  4008. // ============================================================
  4009. async function executeStep1(state) {
  4010. if (getPanelMode(state) === 'sub2api') {
  4011. return executeSub2ApiStep1(state);
  4012. }
  4013. return executeCpaStep1(state);
  4014. }
  4015. async function executeCpaStep1(state) {
  4016. if (!state.vpsUrl) {
  4017. throw new Error('尚未配置 CPA 地址,请先在侧边栏填写。');
  4018. }
  4019. await addLog('步骤 1:正在打开 CPA 面板...');
  4020. const injectFiles = ['content/activation-utils.js', 'content/utils.js', 'content/vps-panel.js'];
  4021. await closeConflictingTabsForSource('vps-panel', state.vpsUrl);
  4022. const tab = await chrome.tabs.create({ url: state.vpsUrl, active: true });
  4023. const tabId = tab.id;
  4024. await rememberSourceLastUrl('vps-panel', state.vpsUrl);
  4025. await addLog('步骤 1:CPA 面板已打开,正在等待页面进入目标地址...');
  4026. const matchedTab = await waitForTabUrlFamily('vps-panel', tabId, state.vpsUrl, {
  4027. timeoutMs: 15000,
  4028. retryDelayMs: 400,
  4029. });
  4030. if (!matchedTab) {
  4031. await addLog('步骤 1:CPA 页面尚未完全进入目标地址,继续尝试连接内容脚本...', 'warn');
  4032. }
  4033. await ensureContentScriptReadyOnTab('vps-panel', tabId, {
  4034. inject: injectFiles,
  4035. timeoutMs: 45000,
  4036. retryDelayMs: 900,
  4037. logMessage: '步骤 1:CPA 面板仍在加载,正在重试连接内容脚本...',
  4038. });
  4039. const result = await sendToContentScriptResilient('vps-panel', {
  4040. type: 'EXECUTE_STEP',
  4041. step: 1,
  4042. source: 'background',
  4043. payload: { vpsPassword: state.vpsPassword },
  4044. }, {
  4045. timeoutMs: 30000,
  4046. retryDelayMs: 700,
  4047. logMessage: '步骤 1:CPA 面板通信未就绪,正在等待页面恢复...',
  4048. });
  4049. if (result?.error) {
  4050. throw new Error(result.error);
  4051. }
  4052. }
  4053. async function executeSub2ApiStep1(state) {
  4054. const sub2apiUrl = normalizeSub2ApiUrl(state.sub2apiUrl);
  4055. const groupName = (state.sub2apiGroupName || DEFAULT_SUB2API_GROUP_NAME).trim() || DEFAULT_SUB2API_GROUP_NAME;
  4056. if (!state.sub2apiEmail) {
  4057. throw new Error('尚未配置 SUB2API 登录邮箱,请先在侧边栏填写。');
  4058. }
  4059. if (!state.sub2apiPassword) {
  4060. throw new Error('尚未配置 SUB2API 登录密码,请先在侧边栏填写。');
  4061. }
  4062. await addLog('步骤 1:正在打开 SUB2API 后台...');
  4063. const injectFiles = ['content/utils.js', 'content/sub2api-panel.js'];
  4064. await closeConflictingTabsForSource('sub2api-panel', sub2apiUrl);
  4065. const tab = await chrome.tabs.create({ url: sub2apiUrl, active: true });
  4066. const tabId = tab.id;
  4067. await rememberSourceLastUrl('sub2api-panel', sub2apiUrl);
  4068. await addLog('步骤 1:SUB2API 页面已打开,正在等待页面进入目标地址...');
  4069. const matchedTab = await waitForTabUrlFamily('sub2api-panel', tabId, sub2apiUrl, {
  4070. timeoutMs: 15000,
  4071. retryDelayMs: 400,
  4072. });
  4073. if (!matchedTab) {
  4074. await addLog('步骤 1:SUB2API 页面尚未稳定,继续尝试连接内容脚本...', 'warn');
  4075. }
  4076. await ensureContentScriptReadyOnTab('sub2api-panel', tabId, {
  4077. inject: injectFiles,
  4078. injectSource: 'sub2api-panel',
  4079. timeoutMs: 45000,
  4080. retryDelayMs: 900,
  4081. logMessage: '步骤 1:SUB2API 页面仍在加载,正在重试连接内容脚本...',
  4082. });
  4083. const result = await sendToContentScript('sub2api-panel', {
  4084. type: 'EXECUTE_STEP',
  4085. step: 1,
  4086. source: 'background',
  4087. payload: {
  4088. sub2apiUrl,
  4089. sub2apiEmail: state.sub2apiEmail,
  4090. sub2apiPassword: state.sub2apiPassword,
  4091. sub2apiGroupName: groupName,
  4092. },
  4093. }, {
  4094. responseTimeoutMs: SUB2API_STEP1_RESPONSE_TIMEOUT_MS,
  4095. });
  4096. if (result?.error) {
  4097. throw new Error(result.error);
  4098. }
  4099. }
  4100. // ============================================================
  4101. // Step 2: Open Signup Page (Background opens tab, signup-page.js clicks Register)
  4102. // ============================================================
  4103. async function executeStep2(state) {
  4104. if (!state.oauthUrl) {
  4105. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  4106. }
  4107. await addLog('步骤 2:正在打开认证链接...');
  4108. await reuseOrCreateTab('signup-page', state.oauthUrl);
  4109. await sendToContentScript('signup-page', {
  4110. type: 'EXECUTE_STEP',
  4111. step: 2,
  4112. source: 'background',
  4113. payload: {},
  4114. });
  4115. }
  4116. // ============================================================
  4117. // Step 3: Fill Email & Password (via signup-page.js)
  4118. // ============================================================
  4119. async function executeStep3(state) {
  4120. let resolvedEmail = state.email;
  4121. if (isHotmailProvider(state)) {
  4122. const account = await ensureHotmailAccountForFlow({
  4123. allowAllocate: true,
  4124. markUsed: true,
  4125. preferredAccountId: state.currentHotmailAccountId || null,
  4126. });
  4127. resolvedEmail = account.email;
  4128. } else if (isGeneratedAliasProvider(state.mailProvider)) {
  4129. resolvedEmail = buildGeneratedAliasEmail(state);
  4130. }
  4131. if (!resolvedEmail) {
  4132. throw new Error('缺少邮箱地址,请先在侧边栏粘贴邮箱。');
  4133. }
  4134. const password = state.customPassword || generatePassword();
  4135. if (resolvedEmail !== state.email) {
  4136. await setEmailState(resolvedEmail);
  4137. }
  4138. await setPasswordState(password);
  4139. // Save account record
  4140. const accounts = state.accounts || [];
  4141. accounts.push({ email: resolvedEmail, password, createdAt: new Date().toISOString() });
  4142. await setState({ accounts });
  4143. await addLog(
  4144. `步骤 3:正在填写邮箱 ${resolvedEmail},密码为${state.customPassword ? '自定义' : '自动生成'}(${password.length} 位)`
  4145. );
  4146. await sendToContentScript('signup-page', {
  4147. type: 'EXECUTE_STEP',
  4148. step: 3,
  4149. source: 'background',
  4150. payload: { email: resolvedEmail, password },
  4151. });
  4152. }
  4153. // ============================================================
  4154. // Step 4: Get Signup Verification Code (qq-mail.js polls, then fills in signup-page.js)
  4155. // ============================================================
  4156. function getMailConfig(state) {
  4157. const provider = state.mailProvider || 'qq';
  4158. if (provider === 'custom') {
  4159. return { provider: 'custom', label: '自定义邮箱' };
  4160. }
  4161. if (provider === HOTMAIL_PROVIDER) {
  4162. return { provider: HOTMAIL_PROVIDER, label: 'Hotmail(远程/本地)' };
  4163. }
  4164. if (provider === '163') {
  4165. 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 邮箱' };
  4166. }
  4167. if (provider === '163-vip') {
  4168. 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 邮箱' };
  4169. }
  4170. if (provider === 'inbucket') {
  4171. const host = normalizeInbucketOrigin(state.inbucketHost);
  4172. const mailbox = (state.inbucketMailbox || '').trim();
  4173. if (!host) {
  4174. return { error: 'Inbucket 主机地址为空或无效。' };
  4175. }
  4176. if (!mailbox) {
  4177. return { error: 'Inbucket 邮箱名称为空。' };
  4178. }
  4179. return {
  4180. source: 'inbucket-mail',
  4181. url: `${host}/m/${encodeURIComponent(mailbox)}/`,
  4182. label: `Inbucket 邮箱(${mailbox})`,
  4183. navigateOnReuse: true,
  4184. inject: ['content/activation-utils.js', 'content/utils.js', 'content/inbucket-mail.js'],
  4185. injectSource: 'inbucket-mail',
  4186. };
  4187. }
  4188. if (provider === '2925') {
  4189. return {
  4190. source: 'mail-2925',
  4191. url: 'https://2925.com/#/mailList',
  4192. label: '2925 邮箱',
  4193. inject: ['content/utils.js', 'content/mail-2925.js'],
  4194. injectSource: 'mail-2925',
  4195. };
  4196. }
  4197. return { source: 'qq-mail', url: 'https://wx.mail.qq.com/', label: 'QQ 邮箱' };
  4198. }
  4199. function normalizeInbucketOrigin(rawValue) {
  4200. const value = (rawValue || '').trim();
  4201. if (!value) return '';
  4202. const candidate = /^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(value) ? value : `https://${value}`;
  4203. try {
  4204. const parsed = new URL(candidate);
  4205. return parsed.origin;
  4206. } catch {
  4207. return '';
  4208. }
  4209. }
  4210. function getVerificationCodeStateKey(step) {
  4211. return step === 4 ? 'lastSignupCode' : 'lastLoginCode';
  4212. }
  4213. function getVerificationCodeLabel(step) {
  4214. return step === 4 ? '注册' : '登录';
  4215. }
  4216. async function confirmCustomVerificationStepBypass(step) {
  4217. const verificationLabel = getVerificationCodeLabel(step);
  4218. await addLog(`步骤 ${step}:当前为自定义邮箱模式,请手动在页面中输入${verificationLabel}验证码并进入下一页面。`, 'warn');
  4219. let response = null;
  4220. try {
  4221. response = await chrome.runtime.sendMessage({
  4222. type: 'REQUEST_CUSTOM_VERIFICATION_BYPASS_CONFIRMATION',
  4223. payload: { step },
  4224. });
  4225. } catch {
  4226. throw new Error(`步骤 ${step}:无法打开确认弹窗,请先保持侧边栏打开后重试。`);
  4227. }
  4228. if (response?.error) {
  4229. throw new Error(response.error);
  4230. }
  4231. if (!response?.confirmed) {
  4232. throw new Error(`步骤 ${step}:已取消手动${verificationLabel}验证码确认。`);
  4233. }
  4234. await setState({
  4235. lastEmailTimestamp: null,
  4236. signupVerificationRequestedAt: null,
  4237. loginVerificationRequestedAt: null,
  4238. });
  4239. await setStepStatus(step, 'skipped');
  4240. await addLog(`步骤 ${step}:已确认手动完成${verificationLabel}验证码输入,当前步骤已跳过。`, 'warn');
  4241. }
  4242. function getVerificationPollPayload(step, state, overrides = {}) {
  4243. if (step === 4) {
  4244. return {
  4245. filterAfterTimestamp: getHotmailVerificationRequestTimestamp(4, state),
  4246. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'duckduckgo', 'forward'],
  4247. subjectFilters: ['verify', 'verification', 'code', '楠岃瘉', 'confirm'],
  4248. targetEmail: state.email,
  4249. maxAttempts: 5,
  4250. intervalMs: 3000,
  4251. ...overrides,
  4252. };
  4253. }
  4254. return {
  4255. filterAfterTimestamp: getHotmailVerificationRequestTimestamp(7, state),
  4256. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'chatgpt', 'duckduckgo', 'forward'],
  4257. subjectFilters: ['verify', 'verification', 'code', '楠岃瘉', 'confirm', 'login'],
  4258. targetEmail: state.email,
  4259. maxAttempts: 5,
  4260. intervalMs: 3000,
  4261. ...overrides,
  4262. };
  4263. }
  4264. async function requestVerificationCodeResend(step) {
  4265. throwIfStopped();
  4266. const signupTabId = await getTabId('signup-page');
  4267. if (!signupTabId) {
  4268. throw new Error('认证页面标签页已关闭,无法重新请求验证码。');
  4269. }
  4270. throwIfStopped();
  4271. await chrome.tabs.update(signupTabId, { active: true });
  4272. throwIfStopped();
  4273. await addLog(`步骤 ${step}:正在请求新的${getVerificationCodeLabel(step)}验证码...`, 'warn');
  4274. throwIfStopped();
  4275. const result = await sendToContentScript('signup-page', {
  4276. type: 'RESEND_VERIFICATION_CODE',
  4277. step,
  4278. source: 'background',
  4279. payload: {},
  4280. });
  4281. if (step === 7) {
  4282. const restartError = getStep7RestartFromStep6Error(result);
  4283. if (restartError) {
  4284. throw restartError;
  4285. }
  4286. }
  4287. if (result && result.error) {
  4288. throw new Error(result.error);
  4289. }
  4290. const currentState = await getState();
  4291. if (currentState.mailProvider === '2925') {
  4292. const mailTabId = await getTabId('mail-2925');
  4293. if (mailTabId) {
  4294. await chrome.tabs.update(mailTabId, { active: true });
  4295. await addLog(`步骤 ${step}:已切换到 2925 邮箱标签页等待新邮件。`, 'info');
  4296. }
  4297. }
  4298. return Date.now();
  4299. }
  4300. async function pollFreshVerificationCode(step, state, mail, pollOverrides = {}) {
  4301. if (mail.provider === HOTMAIL_PROVIDER) {
  4302. const hotmailPollConfig = getHotmailVerificationPollConfig(step);
  4303. return pollHotmailVerificationCode(step, state, {
  4304. ...getVerificationPollPayload(step, state),
  4305. ...hotmailPollConfig,
  4306. ...pollOverrides,
  4307. });
  4308. }
  4309. const stateKey = getVerificationCodeStateKey(step);
  4310. const rejectedCodes = new Set();
  4311. if (state[stateKey]) {
  4312. rejectedCodes.add(state[stateKey]);
  4313. }
  4314. for (const code of (pollOverrides.excludeCodes || [])) {
  4315. if (code) rejectedCodes.add(code);
  4316. }
  4317. let lastError = null;
  4318. const filterAfterTimestamp = pollOverrides.filterAfterTimestamp ?? getVerificationPollPayload(step, state).filterAfterTimestamp;
  4319. const maxRounds = pollOverrides.maxRounds || VERIFICATION_POLL_MAX_ROUNDS;
  4320. for (let round = 1; round <= maxRounds; round++) {
  4321. throwIfStopped();
  4322. if (round > 1) {
  4323. await requestVerificationCodeResend(step);
  4324. }
  4325. const payload = getVerificationPollPayload(step, state, {
  4326. ...pollOverrides,
  4327. filterAfterTimestamp,
  4328. excludeCodes: [...rejectedCodes],
  4329. });
  4330. try {
  4331. const result = await sendToMailContentScriptResilient(
  4332. mail,
  4333. {
  4334. type: 'POLL_EMAIL',
  4335. step,
  4336. source: 'background',
  4337. payload,
  4338. },
  4339. {
  4340. timeoutMs: 45000,
  4341. maxRecoveryAttempts: 2,
  4342. }
  4343. );
  4344. if (result && result.error) {
  4345. throw new Error(result.error);
  4346. }
  4347. if (!result || !result.code) {
  4348. throw new Error(`步骤 ${step}:邮箱轮询结束,但未获取到验证码。`);
  4349. }
  4350. if (rejectedCodes.has(result.code)) {
  4351. throw new Error(`步骤 ${step}:再次收到了相同的${getVerificationCodeLabel(step)}验证码:${result.code}`);
  4352. }
  4353. return result;
  4354. } catch (err) {
  4355. if (isStopError(err)) {
  4356. throw err;
  4357. }
  4358. lastError = err;
  4359. await addLog(`步骤 ${step}:${err.message}`, 'warn');
  4360. if (round < maxRounds) {
  4361. await addLog(`步骤 ${step}:将重新发送验证码后重试(${round + 1}/${maxRounds})...`, 'warn');
  4362. }
  4363. }
  4364. }
  4365. throw lastError || new Error(`步骤 ${step}:无法获取新的${getVerificationCodeLabel(step)}验证码。`);
  4366. }
  4367. async function submitVerificationCode(step, code) {
  4368. const signupTabId = await getTabId('signup-page');
  4369. if (!signupTabId) {
  4370. throw new Error('认证页面标签页已关闭,无法填写验证码。');
  4371. }
  4372. await chrome.tabs.update(signupTabId, { active: true });
  4373. const result = await sendToContentScript('signup-page', {
  4374. type: 'FILL_CODE',
  4375. step,
  4376. source: 'background',
  4377. payload: { code },
  4378. });
  4379. if (step === 7) {
  4380. const restartError = getStep7RestartFromStep6Error(result);
  4381. if (restartError) {
  4382. throw restartError;
  4383. }
  4384. }
  4385. if (result && result.error) {
  4386. throw new Error(result.error);
  4387. }
  4388. return result || {};
  4389. }
  4390. async function resolveVerificationStep(step, state, mail, options = {}) {
  4391. const stateKey = getVerificationCodeStateKey(step);
  4392. const rejectedCodes = new Set();
  4393. const hotmailPollConfig = mail.provider === HOTMAIL_PROVIDER
  4394. ? getHotmailVerificationPollConfig(step)
  4395. : null;
  4396. const ignorePersistedLastCode = Boolean(hotmailPollConfig?.ignorePersistedLastCode);
  4397. if (state[stateKey] && !ignorePersistedLastCode) {
  4398. rejectedCodes.add(state[stateKey]);
  4399. }
  4400. const nextFilterAfterTimestamp = options.filterAfterTimestamp ?? null;
  4401. const requestFreshCodeFirst = options.requestFreshCodeFirst !== undefined
  4402. ? Boolean(options.requestFreshCodeFirst)
  4403. : (hotmailPollConfig?.requestFreshCodeFirst ?? false);
  4404. const maxSubmitAttempts = 3;
  4405. if (requestFreshCodeFirst) {
  4406. try {
  4407. await requestVerificationCodeResend(step);
  4408. await addLog(`步骤 ${step}:已先请求一封新的${getVerificationCodeLabel(step)}验证码,再开始轮询邮箱。`, 'warn');
  4409. } catch (err) {
  4410. if (isStopError(err) || (step === 7 && isStep7RestartFromStep6Error(err))) {
  4411. throw err;
  4412. }
  4413. await addLog(`步骤 ${step}:首次重新获取验证码失败:${err.message},将继续使用当前时间窗口轮询。`, 'warn');
  4414. }
  4415. }
  4416. if (mail.provider === HOTMAIL_PROVIDER) {
  4417. const initialDelayMs = Number(options.initialDelayMs ?? hotmailPollConfig.initialDelayMs) || 0;
  4418. if (initialDelayMs > 0) {
  4419. await addLog(`步骤 ${step}:等待 ${Math.round(initialDelayMs / 1000)} 秒,让 Hotmail 验证码邮件先到达...`, 'info');
  4420. await sleepWithStop(initialDelayMs);
  4421. }
  4422. }
  4423. for (let attempt = 1; attempt <= maxSubmitAttempts; attempt++) {
  4424. const result = await pollFreshVerificationCode(step, state, mail, {
  4425. excludeCodes: [...rejectedCodes],
  4426. filterAfterTimestamp: nextFilterAfterTimestamp ?? undefined,
  4427. });
  4428. throwIfStopped();
  4429. await addLog(`步骤 ${step}:已获取${getVerificationCodeLabel(step)}验证码:${result.code}`);
  4430. throwIfStopped();
  4431. const submitResult = await submitVerificationCode(step, result.code);
  4432. if (submitResult.invalidCode) {
  4433. rejectedCodes.add(result.code);
  4434. await addLog(`步骤 ${step}:验证码被页面拒绝:${submitResult.errorText || result.code}`, 'warn');
  4435. if (attempt >= maxSubmitAttempts) {
  4436. throw new Error(`步骤 ${step}:验证码连续失败,已达到 ${maxSubmitAttempts} 次重试上限。`);
  4437. }
  4438. await requestVerificationCodeResend(step);
  4439. await addLog(`步骤 ${step}:提交失败后已请求新验证码(${attempt + 1}/${maxSubmitAttempts})...`, 'warn');
  4440. continue;
  4441. }
  4442. await setState({
  4443. lastEmailTimestamp: result.emailTimestamp,
  4444. [stateKey]: result.code,
  4445. });
  4446. await completeStepFromBackground(step, {
  4447. emailTimestamp: result.emailTimestamp,
  4448. code: result.code,
  4449. });
  4450. return;
  4451. }
  4452. }
  4453. async function executeStep4(state) {
  4454. const mail = getMailConfig(state);
  4455. if (mail.error) throw new Error(mail.error);
  4456. const stepStartedAt = Date.now();
  4457. const signupTabId = await getTabId('signup-page');
  4458. if (!signupTabId) {
  4459. throw new Error('认证页面标签页已关闭,无法继续步骤 4。');
  4460. }
  4461. await chrome.tabs.update(signupTabId, { active: true });
  4462. throwIfStopped();
  4463. await addLog('步骤 4:正在确认注册验证码页面是否就绪,必要时自动恢复密码页超时报错...');
  4464. const prepareResult = await sendToContentScriptResilient(
  4465. 'signup-page',
  4466. {
  4467. type: 'PREPARE_SIGNUP_VERIFICATION',
  4468. step: 4,
  4469. source: 'background',
  4470. payload: { password: state.password || state.customPassword || '' },
  4471. },
  4472. {
  4473. timeoutMs: 30000,
  4474. retryDelayMs: 700,
  4475. logMessage: '步骤 4:认证页正在切换,等待页面重新就绪后继续检测...',
  4476. }
  4477. );
  4478. if (prepareResult && prepareResult.error) {
  4479. throw new Error(prepareResult.error);
  4480. }
  4481. if (prepareResult?.verificationRequestedAt) {
  4482. await setState({ loginVerificationRequestedAt: prepareResult.verificationRequestedAt });
  4483. }
  4484. if (prepareResult?.alreadyVerified) {
  4485. await completeStepFromBackground(4, {});
  4486. return;
  4487. }
  4488. if (shouldUseCustomRegistrationEmail(state)) {
  4489. await confirmCustomVerificationStepBypass(4);
  4490. return;
  4491. }
  4492. throwIfStopped();
  4493. if (mail.provider === HOTMAIL_PROVIDER) {
  4494. await addLog(`步骤 4:正在通过 ${mail.label} 轮询验证码...`);
  4495. } else {
  4496. await addLog(`步骤 4:正在打开${mail.label}...`);
  4497. // For mail tabs, only create if not alive — don't navigate (preserves login session)
  4498. const alive = await isTabAlive(mail.source);
  4499. if (alive) {
  4500. if (mail.navigateOnReuse) {
  4501. await reuseOrCreateTab(mail.source, mail.url, {
  4502. inject: mail.inject,
  4503. injectSource: mail.injectSource,
  4504. });
  4505. } else {
  4506. const tabId = await getTabId(mail.source);
  4507. await chrome.tabs.update(tabId, { active: true });
  4508. }
  4509. } else {
  4510. await reuseOrCreateTab(mail.source, mail.url, {
  4511. inject: mail.inject,
  4512. injectSource: mail.injectSource,
  4513. });
  4514. }
  4515. }
  4516. await resolveVerificationStep(4, state, mail, {
  4517. filterAfterTimestamp: mail.provider === HOTMAIL_PROVIDER ? undefined : stepStartedAt,
  4518. requestFreshCodeFirst: mail.provider === HOTMAIL_PROVIDER ? false : true,
  4519. });
  4520. return;
  4521. }
  4522. // ============================================================
  4523. // Step 5: Fill Name & Birthday (via signup-page.js)
  4524. // ============================================================
  4525. async function executeStep5(state) {
  4526. const { firstName, lastName } = generateRandomName();
  4527. const { year, month, day } = generateRandomBirthday();
  4528. await addLog(`步骤 5:已生成姓名 ${firstName} ${lastName},生日 ${year}-${month}-${day}`);
  4529. await sendToContentScript('signup-page', {
  4530. type: 'EXECUTE_STEP',
  4531. step: 5,
  4532. source: 'background',
  4533. payload: { firstName, lastName, year, month, day },
  4534. });
  4535. }
  4536. // ============================================================
  4537. // Step 6: Login ChatGPT (Background opens tab, chatgpt.js handles login)
  4538. // ============================================================
  4539. async function refreshOAuthUrlBeforeStep6(state) {
  4540. await addLog(`步骤 6:正在刷新登录用的 ${getPanelModeLabel(state)} OAuth 链接...`);
  4541. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] preparing fresh OAuth via step 1');
  4542. const waitForFreshOAuth = waitForStepComplete(1, 120000);
  4543. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] executing step 1 for fresh OAuth');
  4544. await executeStep1(state);
  4545. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] step 1 execute returned, waiting for completion signal');
  4546. await waitForFreshOAuth;
  4547. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] step 1 completion signal received');
  4548. const latestState = await getState();
  4549. if (!latestState.oauthUrl) {
  4550. throw new Error('刷新 OAuth 链接后仍未拿到可用链接。');
  4551. }
  4552. return latestState.oauthUrl;
  4553. }
  4554. async function executeStep6(state) {
  4555. if (!state.email) {
  4556. throw new Error('缺少邮箱地址,请先完成步骤 3。');
  4557. }
  4558. const oauthUrl = await refreshOAuthUrlBeforeStep6(state);
  4559. await addLog('步骤 6:正在打开最新 OAuth 链接并登录...');
  4560. // Reuse the signup-page tab — navigate it to the OAuth URL
  4561. await reuseOrCreateTab('signup-page', oauthUrl);
  4562. // signup-page.js will inject (same auth.openai.com domain) and handle login
  4563. await sendToContentScript('signup-page', {
  4564. type: 'EXECUTE_STEP',
  4565. step: 6,
  4566. source: 'background',
  4567. payload: { email: state.email, password: state.password },
  4568. });
  4569. }
  4570. // ============================================================
  4571. // Step 7: Get Login Verification Code (qq-mail.js polls, then fills in chatgpt.js)
  4572. // ============================================================
  4573. async function runStep7Attempt(state) {
  4574. const mail = getMailConfig(state);
  4575. if (mail.error) throw new Error(mail.error);
  4576. const stepStartedAt = Date.now();
  4577. const authTabId = await getTabId('signup-page');
  4578. if (authTabId) {
  4579. await chrome.tabs.update(authTabId, { active: true });
  4580. } else {
  4581. if (!state.oauthUrl) {
  4582. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  4583. }
  4584. await reuseOrCreateTab('signup-page', state.oauthUrl);
  4585. }
  4586. throwIfStopped();
  4587. await addLog('步骤 7:正在准备认证页,必要时切换到一次性验证码登录...');
  4588. const prepareResult = await sendToContentScript('signup-page', {
  4589. type: 'PREPARE_LOGIN_CODE',
  4590. step: 7,
  4591. source: 'background',
  4592. payload: {},
  4593. });
  4594. const restartError = getStep7RestartFromStep6Error(prepareResult);
  4595. if (restartError) {
  4596. throw restartError;
  4597. }
  4598. if (prepareResult && prepareResult.error) {
  4599. throw new Error(prepareResult.error);
  4600. }
  4601. if (shouldUseCustomRegistrationEmail(state)) {
  4602. await confirmCustomVerificationStepBypass(7);
  4603. return;
  4604. }
  4605. throwIfStopped();
  4606. if (mail.provider === HOTMAIL_PROVIDER) {
  4607. await addLog(`步骤 7:正在通过 ${mail.label} 轮询验证码...`);
  4608. } else {
  4609. await addLog(`步骤 7:正在打开${mail.label}...`);
  4610. const alive = await isTabAlive(mail.source);
  4611. if (alive) {
  4612. if (mail.navigateOnReuse) {
  4613. await reuseOrCreateTab(mail.source, mail.url, {
  4614. inject: mail.inject,
  4615. injectSource: mail.injectSource,
  4616. });
  4617. } else {
  4618. const tabId = await getTabId(mail.source);
  4619. await chrome.tabs.update(tabId, { active: true });
  4620. }
  4621. } else {
  4622. await reuseOrCreateTab(mail.source, mail.url, {
  4623. inject: mail.inject,
  4624. injectSource: mail.injectSource,
  4625. });
  4626. }
  4627. }
  4628. await resolveVerificationStep(7, state, mail, {
  4629. filterAfterTimestamp: mail.provider === HOTMAIL_PROVIDER ? undefined : stepStartedAt,
  4630. requestFreshCodeFirst: mail.provider === HOTMAIL_PROVIDER ? false : true,
  4631. });
  4632. }
  4633. async function rerunStep6ForStep7Recovery() {
  4634. const currentState = await getState();
  4635. const waitForStep6 = waitForStepComplete(6, 120000);
  4636. await addLog('步骤 7:正在回到步骤 6,重新发起登录验证码流程...', 'warn');
  4637. await executeStep6(currentState);
  4638. await waitForStep6;
  4639. await sleepWithStop(3000);
  4640. }
  4641. async function executeStep7(state) {
  4642. let currentState = state;
  4643. let mailPollingAttempt = 1;
  4644. let lastMailPollingError = null;
  4645. while (true) {
  4646. try {
  4647. await runStep7Attempt(currentState);
  4648. return;
  4649. } catch (err) {
  4650. if (isStep7RestartFromStep6Error(err)) {
  4651. await addLog('步骤 7:检测到登录页超时报错,准备从步骤 6 重新开始...', 'warn');
  4652. await rerunStep6ForStep7Recovery();
  4653. currentState = await getState();
  4654. continue;
  4655. }
  4656. if (!isVerificationMailPollingError(err)) {
  4657. throw err;
  4658. }
  4659. lastMailPollingError = err;
  4660. if (mailPollingAttempt >= STEP7_MAIL_POLLING_RECOVERY_MAX_ATTEMPTS) {
  4661. break;
  4662. }
  4663. mailPollingAttempt += 1;
  4664. await addLog(
  4665. `步骤 7:检测到邮箱轮询类失败,准备从步骤 6 重新开始(${mailPollingAttempt}/${STEP7_MAIL_POLLING_RECOVERY_MAX_ATTEMPTS})...`,
  4666. 'warn'
  4667. );
  4668. await rerunStep6ForStep7Recovery();
  4669. currentState = await getState();
  4670. }
  4671. }
  4672. if (lastMailPollingError) {
  4673. throw new Error(
  4674. `步骤 7:登录验证码流程在 ${STEP7_MAIL_POLLING_RECOVERY_MAX_ATTEMPTS} 轮邮箱轮询恢复后仍未成功。最后一次原因:${lastMailPollingError.message}`
  4675. );
  4676. }
  4677. throw new Error('步骤 7:登录验证码流程未成功完成。');
  4678. }
  4679. // ============================================================
  4680. // Step 8: 完成 OAuth(自动点击 + localhost 回调监听)
  4681. // ============================================================
  4682. let webNavListener = null;
  4683. let webNavCommittedListener = null;
  4684. let step8TabUpdatedListener = null;
  4685. let step8PendingReject = null;
  4686. const STEP8_CLICK_EFFECT_TIMEOUT_MS = 15000;
  4687. const STEP8_CLICK_RETRY_DELAY_MS = 500;
  4688. const STEP8_READY_WAIT_TIMEOUT_MS = 30000;
  4689. const STEP8_MAX_ROUNDS = 5;
  4690. const STEP8_SIGNUP_PAGE_INJECT_FILES = ['content/utils.js', 'content/signup-page.js'];
  4691. const STEP8_STRATEGIES = [
  4692. { mode: 'content', strategy: 'requestSubmit', label: 'form.requestSubmit' },
  4693. { mode: 'debugger', label: 'debugger click' },
  4694. { mode: 'content', strategy: 'nativeClick', label: 'element.click' },
  4695. { mode: 'content', strategy: 'dispatchClick', label: 'dispatch click' },
  4696. { mode: 'debugger', label: 'debugger click retry' },
  4697. ];
  4698. function cleanupStep8NavigationListeners() {
  4699. if (webNavListener) {
  4700. chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
  4701. webNavListener = null;
  4702. }
  4703. if (webNavCommittedListener) {
  4704. chrome.webNavigation.onCommitted.removeListener(webNavCommittedListener);
  4705. webNavCommittedListener = null;
  4706. }
  4707. if (step8TabUpdatedListener) {
  4708. chrome.tabs.onUpdated.removeListener(step8TabUpdatedListener);
  4709. step8TabUpdatedListener = null;
  4710. }
  4711. }
  4712. function rejectPendingStep8(error) {
  4713. if (!step8PendingReject) return;
  4714. const reject = step8PendingReject;
  4715. step8PendingReject = null;
  4716. reject(error);
  4717. }
  4718. function throwIfStep8SettledOrStopped(isSettled = false) {
  4719. if (isSettled || stopRequested) {
  4720. throw new Error(STOP_ERROR_MESSAGE);
  4721. }
  4722. }
  4723. async function ensureStep8SignupPageReady(tabId, options = {}) {
  4724. await ensureContentScriptReadyOnTab('signup-page', tabId, {
  4725. inject: STEP8_SIGNUP_PAGE_INJECT_FILES,
  4726. injectSource: 'signup-page',
  4727. timeoutMs: options.timeoutMs ?? 15000,
  4728. retryDelayMs: options.retryDelayMs ?? 600,
  4729. logMessage: options.logMessage || '',
  4730. });
  4731. }
  4732. async function getStep8PageState(tabId, responseTimeoutMs = 1500) {
  4733. try {
  4734. const result = await sendTabMessageWithTimeout(tabId, 'signup-page', {
  4735. type: 'STEP8_GET_STATE',
  4736. source: 'background',
  4737. payload: {},
  4738. }, responseTimeoutMs);
  4739. if (result?.error) {
  4740. throw new Error(result.error);
  4741. }
  4742. return result;
  4743. } catch (err) {
  4744. if (isRetryableContentScriptTransportError(err)) {
  4745. return null;
  4746. }
  4747. throw err;
  4748. }
  4749. }
  4750. async function waitForStep8Ready(tabId, timeoutMs = STEP8_READY_WAIT_TIMEOUT_MS) {
  4751. const start = Date.now();
  4752. let recovered = false;
  4753. while (Date.now() - start < timeoutMs) {
  4754. throwIfStopped();
  4755. const pageState = await getStep8PageState(tabId);
  4756. if (pageState?.addPhonePage) {
  4757. throw new Error('步骤 8:认证页进入了手机号页面,当前不是 OAuth 同意页,无法继续自动授权。');
  4758. }
  4759. if (pageState?.consentReady) {
  4760. return pageState;
  4761. }
  4762. if (pageState === null && !recovered) {
  4763. recovered = true;
  4764. await ensureStep8SignupPageReady(tabId, {
  4765. timeoutMs: Math.min(10000, timeoutMs),
  4766. logMessage: '步骤 8:认证页内容脚本已失联,正在等待页面重新就绪...',
  4767. });
  4768. continue;
  4769. }
  4770. recovered = false;
  4771. await sleepWithStop(250);
  4772. }
  4773. throw new Error('步骤 8:长时间未进入 OAuth 同意页,无法定位“继续”按钮。');
  4774. }
  4775. async function prepareStep8DebuggerClick(tabId) {
  4776. await ensureStep8SignupPageReady(tabId, {
  4777. timeoutMs: 15000,
  4778. logMessage: '步骤 8:认证页内容脚本已失联,正在恢复后继续定位按钮...',
  4779. });
  4780. const result = await sendToContentScriptResilient('signup-page', {
  4781. type: 'STEP8_FIND_AND_CLICK',
  4782. source: 'background',
  4783. payload: {},
  4784. }, {
  4785. timeoutMs: 15000,
  4786. retryDelayMs: 600,
  4787. logMessage: '步骤 8:认证页正在切换,等待 OAuth 同意页按钮重新就绪...',
  4788. });
  4789. if (result?.error) {
  4790. throw new Error(result.error);
  4791. }
  4792. return result;
  4793. }
  4794. async function triggerStep8ContentStrategy(tabId, strategy) {
  4795. await ensureStep8SignupPageReady(tabId, {
  4796. timeoutMs: 15000,
  4797. logMessage: '步骤 8:认证页内容脚本已失联,正在恢复后继续点击“继续”按钮...',
  4798. });
  4799. const result = await sendToContentScriptResilient('signup-page', {
  4800. type: 'STEP8_TRIGGER_CONTINUE',
  4801. source: 'background',
  4802. payload: {
  4803. strategy,
  4804. findTimeoutMs: 4000,
  4805. enabledTimeoutMs: 3000,
  4806. },
  4807. }, {
  4808. timeoutMs: 15000,
  4809. retryDelayMs: 600,
  4810. logMessage: '步骤 8:认证页正在切换,等待“继续”按钮重新就绪...',
  4811. });
  4812. if (result?.error) {
  4813. throw new Error(result.error);
  4814. }
  4815. return result;
  4816. }
  4817. async function reloadStep8ConsentPage(tabId, timeoutMs = 30000) {
  4818. if (!Number.isInteger(tabId)) {
  4819. throw new Error('步骤 8:缺少有效的认证页标签页,无法刷新后重试。');
  4820. }
  4821. await chrome.tabs.update(tabId, { active: true }).catch(() => { });
  4822. await new Promise((resolve, reject) => {
  4823. let settled = false;
  4824. const timer = setTimeout(() => {
  4825. if (settled) return;
  4826. settled = true;
  4827. chrome.tabs.onUpdated.removeListener(listener);
  4828. reject(new Error('步骤 8:刷新认证页后等待页面完成加载超时。'));
  4829. }, timeoutMs);
  4830. const listener = (updatedTabId, changeInfo) => {
  4831. if (updatedTabId !== tabId) return;
  4832. if (changeInfo.status !== 'complete') return;
  4833. if (settled) return;
  4834. settled = true;
  4835. clearTimeout(timer);
  4836. chrome.tabs.onUpdated.removeListener(listener);
  4837. resolve();
  4838. };
  4839. chrome.tabs.onUpdated.addListener(listener);
  4840. chrome.tabs.reload(tabId, { bypassCache: false }).catch((err) => {
  4841. if (settled) return;
  4842. settled = true;
  4843. clearTimeout(timer);
  4844. chrome.tabs.onUpdated.removeListener(listener);
  4845. reject(err);
  4846. });
  4847. });
  4848. await ensureStep8SignupPageReady(tabId, {
  4849. timeoutMs: Math.min(15000, timeoutMs),
  4850. logMessage: '步骤 8:认证页刷新后内容脚本尚未就绪,正在等待页面恢复...',
  4851. });
  4852. }
  4853. async function waitForStep8ClickEffect(tabId, baselineUrl, timeoutMs = STEP8_CLICK_EFFECT_TIMEOUT_MS) {
  4854. const start = Date.now();
  4855. let recovered = false;
  4856. while (Date.now() - start < timeoutMs) {
  4857. throwIfStopped();
  4858. const tab = await chrome.tabs.get(tabId).catch(() => null);
  4859. if (!tab) {
  4860. throw new Error('步骤 8:认证页面标签页已关闭,无法继续自动授权。');
  4861. }
  4862. if (baselineUrl && typeof tab.url === 'string' && tab.url !== baselineUrl) {
  4863. return { progressed: true, reason: 'url_changed', url: tab.url };
  4864. }
  4865. const pageState = await getStep8PageState(tabId);
  4866. if (pageState?.addPhonePage) {
  4867. throw new Error('步骤 8:点击“继续”后页面跳到了手机号页面,当前流程无法继续自动授权。');
  4868. }
  4869. if (pageState === null) {
  4870. if (!recovered) {
  4871. recovered = true;
  4872. await ensureStep8SignupPageReady(tabId, {
  4873. timeoutMs: Math.max(3000, Math.min(8000, timeoutMs)),
  4874. logMessage: '步骤 8:点击后认证页正在重载,正在等待内容脚本重新就绪...',
  4875. }).catch(() => null);
  4876. continue;
  4877. }
  4878. await sleepWithStop(200);
  4879. continue;
  4880. }
  4881. recovered = false;
  4882. await sleepWithStop(200);
  4883. }
  4884. return { progressed: false, reason: 'no_effect' };
  4885. }
  4886. function getStep8EffectLabel(effect) {
  4887. switch (effect?.reason) {
  4888. case 'url_changed':
  4889. return `URL 已变化:${effect.url}`;
  4890. case 'page_reloading':
  4891. return '页面正在跳转或重载';
  4892. case 'left_consent_page':
  4893. return `页面已离开 OAuth 同意页:${effect.url || 'unknown'}`;
  4894. default:
  4895. return '页面仍停留在 OAuth 同意页';
  4896. }
  4897. }
  4898. async function executeStep8(state) {
  4899. if (!state.oauthUrl) {
  4900. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  4901. }
  4902. await addLog('步骤 8:正在监听 localhost 回调地址...');
  4903. return new Promise((resolve, reject) => {
  4904. let resolved = false;
  4905. let signupTabId = null;
  4906. const cleanupListener = () => {
  4907. cleanupStep8NavigationListeners();
  4908. step8PendingReject = null;
  4909. };
  4910. const rejectStep8 = (error) => {
  4911. if (resolved) return;
  4912. resolved = true;
  4913. clearTimeout(timeout);
  4914. cleanupListener();
  4915. reject(error);
  4916. };
  4917. const finalizeStep8Callback = (callbackUrl) => {
  4918. if (resolved || !callbackUrl) return;
  4919. resolved = true;
  4920. cleanupListener();
  4921. clearTimeout(timeout);
  4922. addLog(`步骤 8:已捕获 localhost 地址:${callbackUrl}`, 'ok').then(() => {
  4923. return completeStepFromBackground(8, { localhostUrl: callbackUrl });
  4924. }).then(() => {
  4925. resolve();
  4926. }).catch((err) => {
  4927. reject(err);
  4928. });
  4929. };
  4930. const timeout = setTimeout(() => {
  4931. rejectStep8(new Error('120 秒内未捕获到 localhost 回调跳转,步骤 8 的点击可能被拦截了。'));
  4932. }, 120000);
  4933. step8PendingReject = (error) => {
  4934. rejectStep8(error);
  4935. };
  4936. webNavListener = (details) => {
  4937. const callbackUrl = getStep8CallbackUrlFromNavigation(details, signupTabId);
  4938. finalizeStep8Callback(callbackUrl);
  4939. };
  4940. webNavCommittedListener = (details) => {
  4941. const callbackUrl = getStep8CallbackUrlFromNavigation(details, signupTabId);
  4942. finalizeStep8Callback(callbackUrl);
  4943. };
  4944. step8TabUpdatedListener = (tabId, changeInfo, tab) => {
  4945. const callbackUrl = getStep8CallbackUrlFromTabUpdate(tabId, changeInfo, tab, signupTabId);
  4946. finalizeStep8Callback(callbackUrl);
  4947. };
  4948. (async () => {
  4949. try {
  4950. throwIfStep8SettledOrStopped(resolved);
  4951. signupTabId = await getTabId('signup-page');
  4952. throwIfStep8SettledOrStopped(resolved);
  4953. if (signupTabId && await isTabAlive('signup-page')) {
  4954. await chrome.tabs.update(signupTabId, { active: true });
  4955. await addLog('步骤 8:已切回认证页,正在准备调试器点击...');
  4956. } else {
  4957. signupTabId = await reuseOrCreateTab('signup-page', state.oauthUrl);
  4958. await addLog('步骤 8:已重新打开认证页,正在准备调试器点击...');
  4959. }
  4960. throwIfStep8SettledOrStopped(resolved);
  4961. chrome.webNavigation.onBeforeNavigate.addListener(webNavListener);
  4962. chrome.webNavigation.onCommitted.addListener(webNavCommittedListener);
  4963. chrome.tabs.onUpdated.addListener(step8TabUpdatedListener);
  4964. await ensureStep8SignupPageReady(signupTabId, {
  4965. timeoutMs: 15000,
  4966. logMessage: '步骤 8:认证页内容脚本尚未就绪,正在等待页面恢复...',
  4967. });
  4968. for (let round = 1; round <= STEP8_MAX_ROUNDS && !resolved; round++) {
  4969. throwIfStep8SettledOrStopped(resolved);
  4970. const pageState = await waitForStep8Ready(signupTabId);
  4971. if (!pageState?.consentReady) {
  4972. await sleepWithStop(STEP8_CLICK_RETRY_DELAY_MS);
  4973. continue;
  4974. }
  4975. const strategy = STEP8_STRATEGIES[Math.min(round - 1, STEP8_STRATEGIES.length - 1)];
  4976. await addLog(`步骤 8:第 ${round}/${STEP8_MAX_ROUNDS} 轮尝试点击“继续”(${strategy.label})...`);
  4977. if (strategy.mode === 'debugger') {
  4978. const clickTarget = await prepareStep8DebuggerClick(signupTabId);
  4979. throwIfStep8SettledOrStopped(resolved);
  4980. await clickWithDebugger(signupTabId, clickTarget?.rect);
  4981. } else {
  4982. await triggerStep8ContentStrategy(signupTabId, strategy.strategy);
  4983. }
  4984. if (resolved) {
  4985. return;
  4986. }
  4987. const effect = await waitForStep8ClickEffect(signupTabId, pageState.url);
  4988. if (resolved) {
  4989. return;
  4990. }
  4991. if (effect.progressed) {
  4992. await addLog(`步骤 8:检测到本次点击已生效,${getStep8EffectLabel(effect)},继续等待 localhost 回调...`, 'info');
  4993. break;
  4994. }
  4995. if (round >= STEP8_MAX_ROUNDS) {
  4996. throw new Error(`步骤 8:连续 ${STEP8_MAX_ROUNDS} 轮点击“继续”后页面仍无反应。`);
  4997. }
  4998. await addLog(`步骤 8:${strategy.label} 本轮点击后页面无反应,正在刷新认证页后重试(下一轮 ${round + 1}/${STEP8_MAX_ROUNDS})...`, 'warn');
  4999. await reloadStep8ConsentPage(signupTabId);
  5000. await sleepWithStop(STEP8_CLICK_RETRY_DELAY_MS);
  5001. }
  5002. } catch (err) {
  5003. rejectStep8(err);
  5004. }
  5005. })();
  5006. });
  5007. }
  5008. // ============================================================
  5009. // Step 9: 平台回调验证
  5010. // ============================================================
  5011. async function executeStep9(state) {
  5012. if (getPanelMode(state) === 'sub2api') {
  5013. return executeSub2ApiStep9(state);
  5014. }
  5015. return executeCpaStep9(state);
  5016. }
  5017. async function executeCpaStep9(state) {
  5018. if (state.localhostUrl && !isLocalhostOAuthCallbackUrl(state.localhostUrl)) {
  5019. throw new Error('步骤 8 捕获到的 localhost OAuth 回调地址无效,请重新执行步骤 8。');
  5020. }
  5021. if (!state.localhostUrl) {
  5022. throw new Error('缺少 localhost 回调地址,请先完成步骤 8。');
  5023. }
  5024. if (!state.vpsUrl) {
  5025. throw new Error('尚未填写 CPA 地址,请先在侧边栏输入。');
  5026. }
  5027. if (shouldBypassStep9ForLocalCpa(state)) {
  5028. await addLog('步骤 9:检测到本地 CPA,且当前策略为“跳过第9步”,本轮不再重复提交回调地址。', 'info');
  5029. await completeStepFromBackground(9, {
  5030. localhostUrl: state.localhostUrl,
  5031. verifiedStatus: 'local-auto',
  5032. });
  5033. return;
  5034. }
  5035. await addLog('步骤 9:正在打开 CPA 面板...');
  5036. const injectFiles = ['content/activation-utils.js', 'content/utils.js', 'content/vps-panel.js'];
  5037. let tabId = await getTabId('vps-panel');
  5038. const alive = tabId && await isTabAlive('vps-panel');
  5039. if (!alive) {
  5040. tabId = await reuseOrCreateTab('vps-panel', state.vpsUrl, {
  5041. inject: injectFiles,
  5042. reloadIfSameUrl: true,
  5043. });
  5044. } else {
  5045. await closeConflictingTabsForSource('vps-panel', state.vpsUrl, { excludeTabIds: [tabId] });
  5046. await chrome.tabs.update(tabId, { active: true });
  5047. await rememberSourceLastUrl('vps-panel', state.vpsUrl);
  5048. }
  5049. await ensureContentScriptReadyOnTab('vps-panel', tabId, {
  5050. inject: injectFiles,
  5051. timeoutMs: 45000,
  5052. retryDelayMs: 900,
  5053. logMessage: '姝ラ 9锛欳PA 闈㈡澘浠嶅湪鍔犺浇锛屾鍦ㄩ噸璇曡繛鎺ュ唴瀹硅剼鏈?..',
  5054. });
  5055. await addLog('步骤 9:正在填写回调地址...');
  5056. const result = await sendToContentScriptResilient('vps-panel', {
  5057. type: 'EXECUTE_STEP',
  5058. step: 9,
  5059. source: 'background',
  5060. payload: { localhostUrl: state.localhostUrl, vpsPassword: state.vpsPassword },
  5061. }, {
  5062. timeoutMs: 30000,
  5063. retryDelayMs: 700,
  5064. logMessage: '步骤 9:CPA 面板通信未就绪,正在等待页面恢复...',
  5065. });
  5066. if (result?.error) {
  5067. throw new Error(result.error);
  5068. }
  5069. }
  5070. async function executeSub2ApiStep9(state) {
  5071. if (state.localhostUrl && !isLocalhostOAuthCallbackUrl(state.localhostUrl)) {
  5072. throw new Error('步骤 8 捕获到的 localhost OAuth 回调地址无效,请重新执行步骤 8。');
  5073. }
  5074. if (!state.localhostUrl) {
  5075. throw new Error('缺少 localhost 回调地址,请先完成步骤 8。');
  5076. }
  5077. if (!state.sub2apiSessionId) {
  5078. throw new Error('缺少 SUB2API 会话信息,请重新执行步骤 1。');
  5079. }
  5080. if (!state.sub2apiEmail) {
  5081. throw new Error('尚未配置 SUB2API 登录邮箱,请先在侧边栏填写。');
  5082. }
  5083. if (!state.sub2apiPassword) {
  5084. throw new Error('尚未配置 SUB2API 登录密码,请先在侧边栏填写。');
  5085. }
  5086. const sub2apiUrl = normalizeSub2ApiUrl(state.sub2apiUrl);
  5087. const injectFiles = ['content/utils.js', 'content/sub2api-panel.js'];
  5088. await addLog('步骤 9:正在打开 SUB2API 后台...');
  5089. let tabId = await getTabId('sub2api-panel');
  5090. const alive = tabId && await isTabAlive('sub2api-panel');
  5091. if (!alive) {
  5092. tabId = await reuseOrCreateTab('sub2api-panel', sub2apiUrl, {
  5093. inject: injectFiles,
  5094. injectSource: 'sub2api-panel',
  5095. reloadIfSameUrl: true,
  5096. });
  5097. } else {
  5098. await closeConflictingTabsForSource('sub2api-panel', sub2apiUrl, { excludeTabIds: [tabId] });
  5099. await chrome.tabs.update(tabId, { active: true });
  5100. await rememberSourceLastUrl('sub2api-panel', sub2apiUrl);
  5101. }
  5102. await ensureContentScriptReadyOnTab('sub2api-panel', tabId, {
  5103. inject: injectFiles,
  5104. injectSource: 'sub2api-panel',
  5105. });
  5106. await addLog('步骤 9:正在向 SUB2API 提交回调并创建账号...');
  5107. const result = await sendToContentScript('sub2api-panel', {
  5108. type: 'EXECUTE_STEP',
  5109. step: 9,
  5110. source: 'background',
  5111. payload: {
  5112. localhostUrl: state.localhostUrl,
  5113. sub2apiUrl,
  5114. sub2apiEmail: state.sub2apiEmail,
  5115. sub2apiPassword: state.sub2apiPassword,
  5116. sub2apiGroupName: state.sub2apiGroupName,
  5117. sub2apiSessionId: state.sub2apiSessionId,
  5118. sub2apiOAuthState: state.sub2apiOAuthState,
  5119. sub2apiGroupId: state.sub2apiGroupId,
  5120. sub2apiDraftName: state.sub2apiDraftName,
  5121. },
  5122. }, {
  5123. responseTimeoutMs: SUB2API_STEP9_RESPONSE_TIMEOUT_MS,
  5124. });
  5125. if (result?.error) {
  5126. throw new Error(result.error);
  5127. }
  5128. }
  5129. // ============================================================
  5130. // Open Side Panel on extension icon click
  5131. // ============================================================
  5132. chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });
  5133. chrome.alarms.onAlarm.addListener((alarm) => {
  5134. if (alarm.name !== AUTO_RUN_ALARM_NAME) {
  5135. return;
  5136. }
  5137. launchScheduledAutoRun('alarm').catch((err) => {
  5138. console.error(LOG_PREFIX, 'Failed to launch scheduled auto run from alarm:', err);
  5139. });
  5140. });
  5141. chrome.runtime.onStartup.addListener(() => {
  5142. restoreScheduledAutoRunIfNeeded().catch((err) => {
  5143. console.error(LOG_PREFIX, 'Failed to restore scheduled auto run on startup:', err);
  5144. });
  5145. });
  5146. chrome.runtime.onInstalled.addListener(() => {
  5147. restoreScheduledAutoRunIfNeeded().catch((err) => {
  5148. console.error(LOG_PREFIX, 'Failed to restore scheduled auto run on install/update:', err);
  5149. });
  5150. });
  5151. restoreScheduledAutoRunIfNeeded().catch((err) => {
  5152. console.error(LOG_PREFIX, 'Failed to restore scheduled auto run:', err);
  5153. });