background.js 156 KB

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