background.js 164 KB

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