background.js 164 KB

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