background.js 170 KB

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