background.js 172 KB

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