background.js 161 KB

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