background.js 162 KB

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