background.js 155 KB

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