background.js 164 KB

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