background.js 166 KB

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