background.js 159 KB

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