background.js 164 KB

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