background.js 163 KB

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