background.js 159 KB

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