background.js 161 KB

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