background.js 116 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557
  1. // background.js — Service Worker: orchestration, state, tab management, message routing
  2. importScripts('data/names.js');
  3. const LOG_PREFIX = '[MultiPage:bg]';
  4. const DUCK_AUTOFILL_URL = 'https://duckduckgo.com/email/settings/autofill';
  5. const STOP_ERROR_MESSAGE = '流程已被用户停止。';
  6. const HUMAN_STEP_DELAY_MIN = 700;
  7. const HUMAN_STEP_DELAY_MAX = 2200;
  8. const STEP7_RESTART_MAX_ROUNDS = 8;
  9. const AUTO_RUN_ALARM_NAME = 'scheduled-auto-run';
  10. const AUTO_RUN_DELAY_MIN_MINUTES = 1;
  11. const AUTO_RUN_DELAY_MAX_MINUTES = 1440;
  12. initializeSessionStorageAccess();
  13. // ============================================================
  14. // 状态管理(chrome.storage.session + chrome.storage.local)
  15. // ============================================================
  16. const PERSISTED_SETTING_DEFAULTS = {
  17. vpsUrl: '', // VPS 面板地址,可手动填写。
  18. vpsPassword: '', // VPS 面板登录密码,可手动填写。
  19. customPassword: '', // 自定义账号密码;留空时由程序自动生成随机密码。
  20. autoRunSkipFailures: false, // 自动运行遇到失败步骤后,是否继续执行后续流程。
  21. autoRunDelayEnabled: false, // 自动运行是否启用启动前倒计时。
  22. autoRunDelayMinutes: 30, // 自动运行倒计时分钟数。
  23. mailProvider: '163', // 验证码邮箱来源(163 / 163-vip / qq / inbucket)。
  24. emailGenerator: 'duck', // 注册邮箱生成方式:duck / cloudflare。
  25. inbucketHost: '', // 仅当 mailProvider 为 inbucket 时填写 Inbucket 地址,其他情况保持为空。
  26. inbucketMailbox: '', // 仅当 mailProvider 为 inbucket 时填写邮箱名,其他情况保持为空。
  27. cloudflareDomain: '', // 仅当 emailGenerator=cloudflare 时填写自定义域名。
  28. cloudflareDomains: [], // Cloudflare 可选域名列表。
  29. };
  30. const PERSISTED_SETTING_KEYS = Object.keys(PERSISTED_SETTING_DEFAULTS);
  31. const DEFAULT_STATE = {
  32. currentStep: 0, // 当前流程执行到的步骤编号。
  33. stepStatuses: {
  34. 1: 'pending', 2: 'pending', 3: 'pending', 4: 'pending', 5: 'pending', // 运行时步骤状态映射,不要手动预填。
  35. 6: 'pending', 7: 'pending', 8: 'pending', 9: 'pending',
  36. },
  37. oauthUrl: null, // 运行时抓取到的 OAuth 地址,不要手动预填。
  38. email: null, // 运行时邮箱,由程序自动获取并写入,不能手动预填。
  39. password: null, // 运行时实际密码,由 customPassword 或程序自动生成后写入。
  40. accounts: [], // 已生成账号记录:{ email, password, createdAt }。
  41. lastEmailTimestamp: null, // 最近一次获取到邮箱数据的运行时时间戳。
  42. lastSignupCode: null, // 注册验证码,运行时由程序自动读取并写入。
  43. lastLoginCode: null, // 登录验证码,运行时由程序自动读取并写入。
  44. localhostUrl: null, // 运行时捕获到的 localhost 回调地址,不要手动预填。
  45. flowStartTime: null, // 当前流程开始时间。
  46. tabRegistry: {}, // 程序维护的标签页注册表。
  47. sourceLastUrls: {}, // 各来源页面最近一次打开的地址记录。
  48. logs: [], // 侧边栏展示的运行日志。
  49. ...PERSISTED_SETTING_DEFAULTS, // 合并 chrome.storage.local 中持久化保存的用户配置。
  50. autoRunning: false, // 当前是否处于自动运行中。
  51. autoRunPhase: 'idle', // 当前自动运行阶段。
  52. autoRunCurrentRun: 0, // 自动运行当前执行到第几轮。
  53. autoRunTotalRuns: 1, // 自动运行计划总轮数。
  54. autoRunAttemptRun: 0, // 当前轮次的重试序号。
  55. scheduledAutoRunAt: null, // 自动运行计划启动时间戳。
  56. scheduledAutoRunPlan: null, // 自动运行计划参数快照。
  57. };
  58. function normalizeAutoRunDelayMinutes(value) {
  59. const numeric = Number(value);
  60. if (!Number.isFinite(numeric)) {
  61. return PERSISTED_SETTING_DEFAULTS.autoRunDelayMinutes;
  62. }
  63. return Math.min(
  64. AUTO_RUN_DELAY_MAX_MINUTES,
  65. Math.max(AUTO_RUN_DELAY_MIN_MINUTES, Math.floor(numeric))
  66. );
  67. }
  68. function normalizeRunCount(value) {
  69. const numeric = Number(value);
  70. if (!Number.isFinite(numeric)) {
  71. return 1;
  72. }
  73. return Math.min(50, Math.max(1, Math.floor(numeric)));
  74. }
  75. function normalizeScheduledAutoRunPlan(plan) {
  76. if (!plan || typeof plan !== 'object') {
  77. return null;
  78. }
  79. return {
  80. totalRuns: normalizeRunCount(plan.totalRuns),
  81. autoRunSkipFailures: Boolean(plan.autoRunSkipFailures),
  82. mode: plan.mode === 'continue' ? 'continue' : 'restart',
  83. };
  84. }
  85. function normalizeEmailGenerator(value = '') {
  86. return String(value || '').trim().toLowerCase() === 'cloudflare' ? 'cloudflare' : 'duck';
  87. }
  88. function normalizeCloudflareDomain(rawValue = '') {
  89. let value = String(rawValue || '').trim().toLowerCase();
  90. if (!value) return '';
  91. value = value.replace(/^@+/, '');
  92. value = value.replace(/^https?:\/\//, '');
  93. value = value.replace(/\/.*$/, '');
  94. if (!/^[a-z0-9.-]+\.[a-z]{2,}$/.test(value)) return '';
  95. return value;
  96. }
  97. async function getPersistedSettings() {
  98. const stored = await chrome.storage.local.get(PERSISTED_SETTING_KEYS);
  99. return {
  100. ...PERSISTED_SETTING_DEFAULTS,
  101. ...stored,
  102. autoRunSkipFailures: Boolean(stored.autoRunSkipFailures ?? PERSISTED_SETTING_DEFAULTS.autoRunSkipFailures),
  103. autoRunDelayEnabled: Boolean(stored.autoRunDelayEnabled ?? PERSISTED_SETTING_DEFAULTS.autoRunDelayEnabled),
  104. autoRunDelayMinutes: normalizeAutoRunDelayMinutes(stored.autoRunDelayMinutes ?? PERSISTED_SETTING_DEFAULTS.autoRunDelayMinutes),
  105. emailGenerator: normalizeEmailGenerator(stored.emailGenerator ?? PERSISTED_SETTING_DEFAULTS.emailGenerator),
  106. };
  107. }
  108. async function getState() {
  109. const [state, persistedSettings] = await Promise.all([
  110. chrome.storage.session.get(null),
  111. getPersistedSettings(),
  112. ]);
  113. return { ...DEFAULT_STATE, ...persistedSettings, ...state };
  114. }
  115. async function initializeSessionStorageAccess() {
  116. try {
  117. if (chrome.storage?.session?.setAccessLevel) {
  118. await chrome.storage.session.setAccessLevel({
  119. accessLevel: 'TRUSTED_AND_UNTRUSTED_CONTEXTS',
  120. });
  121. console.log(LOG_PREFIX, 'Enabled storage.session for content scripts');
  122. }
  123. } catch (err) {
  124. console.warn(LOG_PREFIX, 'Failed to enable storage.session for content scripts:', err?.message || err);
  125. }
  126. }
  127. async function setState(updates) {
  128. console.log(LOG_PREFIX, 'storage.set:', JSON.stringify(updates).slice(0, 200));
  129. if (Object.keys(updates || {}).length > 0) {
  130. await chrome.storage.session.set(updates);
  131. }
  132. }
  133. async function setPersistentSettings(updates) {
  134. const persistedUpdates = {};
  135. for (const key of PERSISTED_SETTING_KEYS) {
  136. if (updates[key] !== undefined) {
  137. if (key === 'autoRunSkipFailures' || key === 'autoRunDelayEnabled') {
  138. persistedUpdates[key] = Boolean(updates[key]);
  139. } else if (key === 'autoRunDelayMinutes') {
  140. persistedUpdates[key] = normalizeAutoRunDelayMinutes(updates[key]);
  141. } else {
  142. persistedUpdates[key] = updates[key];
  143. }
  144. }
  145. }
  146. if (Object.keys(persistedUpdates).length > 0) {
  147. await chrome.storage.local.set(persistedUpdates);
  148. }
  149. }
  150. function broadcastDataUpdate(payload) {
  151. chrome.runtime.sendMessage({
  152. type: 'DATA_UPDATED',
  153. payload,
  154. }).catch(() => { });
  155. }
  156. async function setEmailState(email) {
  157. await setState({ email });
  158. broadcastDataUpdate({ email });
  159. if (email) {
  160. await resumeAutoRunIfWaitingForEmail();
  161. }
  162. }
  163. async function setPasswordState(password) {
  164. await setState({ password });
  165. broadcastDataUpdate({ password });
  166. }
  167. async function resetState() {
  168. console.log(LOG_PREFIX, 'Resetting all state');
  169. // Preserve settings and persistent data across resets
  170. const [prev, persistedSettings] = await Promise.all([
  171. chrome.storage.session.get([
  172. 'seenCodes',
  173. 'seenInbucketMailIds',
  174. 'accounts',
  175. 'tabRegistry',
  176. 'sourceLastUrls',
  177. ]),
  178. getPersistedSettings(),
  179. ]);
  180. await chrome.storage.session.clear();
  181. await chrome.storage.session.set({
  182. ...DEFAULT_STATE,
  183. ...persistedSettings,
  184. seenCodes: prev.seenCodes || [],
  185. seenInbucketMailIds: prev.seenInbucketMailIds || [],
  186. accounts: prev.accounts || [],
  187. tabRegistry: prev.tabRegistry || {},
  188. sourceLastUrls: prev.sourceLastUrls || {},
  189. });
  190. }
  191. /**
  192. * Generate a random password: 14 chars, mix of uppercase, lowercase, digits, symbols.
  193. */
  194. function generatePassword() {
  195. const upper = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
  196. const lower = 'abcdefghjkmnpqrstuvwxyz';
  197. const digits = '23456789';
  198. const symbols = '!@#$%&*?';
  199. const all = upper + lower + digits + symbols;
  200. // Ensure at least one of each type
  201. let pw = '';
  202. pw += upper[Math.floor(Math.random() * upper.length)];
  203. pw += lower[Math.floor(Math.random() * lower.length)];
  204. pw += digits[Math.floor(Math.random() * digits.length)];
  205. pw += symbols[Math.floor(Math.random() * symbols.length)];
  206. // Fill remaining 10 chars
  207. for (let i = 0; i < 10; i++) {
  208. pw += all[Math.floor(Math.random() * all.length)];
  209. }
  210. // Shuffle
  211. return pw.split('').sort(() => Math.random() - 0.5).join('');
  212. }
  213. // ============================================================
  214. // Tab Registry
  215. // ============================================================
  216. async function getTabRegistry() {
  217. const state = await getState();
  218. return state.tabRegistry || {};
  219. }
  220. async function registerTab(source, tabId) {
  221. const registry = await getTabRegistry();
  222. registry[source] = { tabId, ready: true };
  223. await setState({ tabRegistry: registry });
  224. console.log(LOG_PREFIX, `Tab registered: ${source} -> ${tabId}`);
  225. }
  226. async function isTabAlive(source) {
  227. const registry = await getTabRegistry();
  228. const entry = registry[source];
  229. if (!entry) return false;
  230. try {
  231. await chrome.tabs.get(entry.tabId);
  232. return true;
  233. } catch {
  234. // Tab no longer exists — clean up registry
  235. registry[source] = null;
  236. await setState({ tabRegistry: registry });
  237. return false;
  238. }
  239. }
  240. async function getTabId(source) {
  241. const registry = await getTabRegistry();
  242. return registry[source]?.tabId || null;
  243. }
  244. function parseUrlSafely(rawUrl) {
  245. if (!rawUrl) return null;
  246. try {
  247. return new URL(rawUrl);
  248. } catch {
  249. return null;
  250. }
  251. }
  252. function isSignupPageHost(hostname = '') {
  253. return ['auth0.openai.com', 'auth.openai.com', 'accounts.openai.com'].includes(hostname);
  254. }
  255. function is163MailHost(hostname = '') {
  256. return hostname === 'mail.163.com'
  257. || hostname.endsWith('.mail.163.com')
  258. || hostname === 'webmail.vip.163.com';
  259. }
  260. function isLocalhostOAuthCallbackUrl(rawUrl) {
  261. const parsed = parseUrlSafely(rawUrl);
  262. if (!parsed) return false;
  263. if (!['http:', 'https:'].includes(parsed.protocol)) return false;
  264. if (!['localhost', '127.0.0.1'].includes(parsed.hostname)) return false;
  265. if (!['/auth/callback', '/codex/callback'].includes(parsed.pathname)) return false;
  266. const code = (parsed.searchParams.get('code') || '').trim();
  267. const state = (parsed.searchParams.get('state') || '').trim();
  268. return Boolean(code && state);
  269. }
  270. function isLocalCpaUrl(rawUrl) {
  271. const parsed = parseUrlSafely(rawUrl);
  272. if (!parsed) return false;
  273. if (!['http:', 'https:'].includes(parsed.protocol)) return false;
  274. return ['localhost', '127.0.0.1'].includes(parsed.hostname);
  275. }
  276. function shouldBypassStep9ForLocalCpa(state) {
  277. return Boolean(state?.localhostUrl) && isLocalCpaUrl(state?.vpsUrl);
  278. }
  279. function matchesSourceUrlFamily(source, candidateUrl, referenceUrl) {
  280. const candidate = parseUrlSafely(candidateUrl);
  281. if (!candidate) return false;
  282. const reference = parseUrlSafely(referenceUrl);
  283. switch (source) {
  284. case 'signup-page':
  285. return isSignupPageHost(candidate.hostname);
  286. case 'duck-mail':
  287. return candidate.hostname === 'duckduckgo.com' && candidate.pathname.startsWith('/email/');
  288. case 'qq-mail':
  289. return candidate.hostname === 'mail.qq.com' || candidate.hostname === 'wx.mail.qq.com';
  290. case 'mail-163':
  291. return is163MailHost(candidate.hostname);
  292. case 'inbucket-mail':
  293. return Boolean(reference)
  294. && candidate.origin === reference.origin
  295. && candidate.pathname.startsWith('/m/');
  296. case 'vps-panel':
  297. return Boolean(reference)
  298. && candidate.origin === reference.origin
  299. && candidate.pathname === reference.pathname;
  300. default:
  301. return false;
  302. }
  303. }
  304. async function rememberSourceLastUrl(source, url) {
  305. if (!source || !url) return;
  306. const state = await getState();
  307. const sourceLastUrls = { ...(state.sourceLastUrls || {}) };
  308. sourceLastUrls[source] = url;
  309. await setState({ sourceLastUrls });
  310. }
  311. async function closeConflictingTabsForSource(source, currentUrl, options = {}) {
  312. const { excludeTabIds = [] } = options;
  313. const excluded = new Set(excludeTabIds.filter(id => Number.isInteger(id)));
  314. const state = await getState();
  315. const lastUrl = state.sourceLastUrls?.[source];
  316. const referenceUrls = [currentUrl, lastUrl].filter(Boolean);
  317. if (!referenceUrls.length) return;
  318. const tabs = await chrome.tabs.query({});
  319. const matchedIds = tabs
  320. .filter((tab) => Number.isInteger(tab.id) && !excluded.has(tab.id))
  321. .filter((tab) => referenceUrls.some((refUrl) => matchesSourceUrlFamily(source, tab.url, refUrl)))
  322. .map(tab => tab.id);
  323. if (!matchedIds.length) return;
  324. await chrome.tabs.remove(matchedIds).catch(() => { });
  325. const registry = await getTabRegistry();
  326. if (registry[source]?.tabId && matchedIds.includes(registry[source].tabId)) {
  327. registry[source] = null;
  328. await setState({ tabRegistry: registry });
  329. }
  330. await addLog(`已关闭 ${matchedIds.length} 个旧的${getSourceLabel(source)}标签页。`, 'info');
  331. }
  332. function isLocalhostOAuthCallbackTabMatch(callbackUrl, candidateUrl) {
  333. if (!isLocalhostOAuthCallbackUrl(callbackUrl) || !isLocalhostOAuthCallbackUrl(candidateUrl)) {
  334. return false;
  335. }
  336. const callback = parseUrlSafely(callbackUrl);
  337. const candidate = parseUrlSafely(candidateUrl);
  338. if (!callback || !candidate) return false;
  339. return callback.origin === candidate.origin
  340. && callback.pathname === candidate.pathname
  341. && callback.searchParams.get('code') === candidate.searchParams.get('code')
  342. && callback.searchParams.get('state') === candidate.searchParams.get('state');
  343. }
  344. async function closeLocalhostCallbackTabs(callbackUrl, options = {}) {
  345. if (!isLocalhostOAuthCallbackUrl(callbackUrl)) return 0;
  346. const { excludeTabIds = [] } = options;
  347. const excluded = new Set(excludeTabIds.filter(id => Number.isInteger(id)));
  348. const tabs = await chrome.tabs.query({});
  349. const matchedIds = tabs
  350. .filter((tab) => Number.isInteger(tab.id) && !excluded.has(tab.id))
  351. .filter((tab) => isLocalhostOAuthCallbackTabMatch(callbackUrl, tab.url))
  352. .map((tab) => tab.id);
  353. if (!matchedIds.length) return 0;
  354. await chrome.tabs.remove(matchedIds).catch(() => { });
  355. const registry = await getTabRegistry();
  356. if (registry['signup-page']?.tabId && matchedIds.includes(registry['signup-page'].tabId)) {
  357. registry['signup-page'] = null;
  358. await setState({ tabRegistry: registry });
  359. }
  360. await addLog(`已关闭 ${matchedIds.length} 个匹配当前 OAuth callback 的 localhost 残留标签页。`, 'info');
  361. return matchedIds.length;
  362. }
  363. async function pingContentScriptOnTab(tabId) {
  364. if (!Number.isInteger(tabId)) return null;
  365. try {
  366. return await chrome.tabs.sendMessage(tabId, {
  367. type: 'PING',
  368. source: 'background',
  369. payload: {},
  370. });
  371. } catch {
  372. return null;
  373. }
  374. }
  375. async function waitForTabUrlFamily(source, tabId, referenceUrl, options = {}) {
  376. const { timeoutMs = 15000, retryDelayMs = 400 } = options;
  377. const start = Date.now();
  378. while (Date.now() - start < timeoutMs) {
  379. try {
  380. const tab = await chrome.tabs.get(tabId);
  381. if (matchesSourceUrlFamily(source, tab.url, referenceUrl)) {
  382. return tab;
  383. }
  384. } catch {
  385. return null;
  386. }
  387. await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
  388. }
  389. return null;
  390. }
  391. async function ensureContentScriptReadyOnTab(source, tabId, options = {}) {
  392. const {
  393. inject = null,
  394. injectSource = null,
  395. timeoutMs = 30000,
  396. retryDelayMs = 700,
  397. logMessage = '',
  398. } = options;
  399. const start = Date.now();
  400. let lastError = null;
  401. let logged = false;
  402. let attempt = 0;
  403. console.log(
  404. LOG_PREFIX,
  405. `[ensureContentScriptReadyOnTab] start ${source} tab=${tabId}, timeout=${timeoutMs}ms, inject=${Array.isArray(inject) ? inject.join(',') : 'none'}`
  406. );
  407. while (Date.now() - start < timeoutMs) {
  408. attempt += 1;
  409. const pong = await pingContentScriptOnTab(tabId);
  410. if (pong?.ok && (!pong.source || pong.source === source)) {
  411. console.log(
  412. LOG_PREFIX,
  413. `[ensureContentScriptReadyOnTab] ready ${source} tab=${tabId} on attempt ${attempt} after ${Date.now() - start}ms`
  414. );
  415. await registerTab(source, tabId);
  416. return;
  417. }
  418. if (!inject || !inject.length) {
  419. throw new Error(`${getSourceLabel(source)} 内容脚本未就绪,且未提供可用的注入文件。`);
  420. }
  421. const registry = await getTabRegistry();
  422. if (registry[source]) {
  423. registry[source].ready = false;
  424. await setState({ tabRegistry: registry });
  425. }
  426. try {
  427. if (injectSource) {
  428. await chrome.scripting.executeScript({
  429. target: { tabId },
  430. func: (injectedSource) => {
  431. window.__MULTIPAGE_SOURCE = injectedSource;
  432. },
  433. args: [injectSource],
  434. });
  435. }
  436. await chrome.scripting.executeScript({
  437. target: { tabId },
  438. files: inject,
  439. });
  440. } catch (err) {
  441. lastError = err;
  442. console.warn(
  443. LOG_PREFIX,
  444. `[ensureContentScriptReadyOnTab] inject attempt ${attempt} failed for ${source} tab=${tabId}: ${err?.message || err}`
  445. );
  446. }
  447. const pongAfterInject = await pingContentScriptOnTab(tabId);
  448. if (pongAfterInject?.ok && (!pongAfterInject.source || pongAfterInject.source === source)) {
  449. console.log(
  450. LOG_PREFIX,
  451. `[ensureContentScriptReadyOnTab] ready after inject ${source} tab=${tabId} on attempt ${attempt} after ${Date.now() - start}ms`
  452. );
  453. await registerTab(source, tabId);
  454. return;
  455. }
  456. if (logMessage && !logged) {
  457. console.warn(
  458. LOG_PREFIX,
  459. `[ensureContentScriptReadyOnTab] ${source} tab=${tabId} still not ready after ${Date.now() - start}ms`
  460. );
  461. await addLog(logMessage, 'warn');
  462. logged = true;
  463. }
  464. await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
  465. }
  466. throw lastError || new Error(`${getSourceLabel(source)} 内容脚本长时间未就绪。`);
  467. }
  468. // ============================================================
  469. // Command Queue (for content scripts not yet ready)
  470. // ============================================================
  471. const pendingCommands = new Map(); // source -> { message, resolve, reject, timer }
  472. function getContentScriptResponseTimeoutMs(message) {
  473. if (!message || typeof message !== 'object') {
  474. return 30000;
  475. }
  476. if (message.type === 'POLL_EMAIL') {
  477. const maxAttempts = Math.max(1, Number(message.payload?.maxAttempts) || 1);
  478. const intervalMs = Math.max(0, Number(message.payload?.intervalMs) || 0);
  479. return Math.max(45000, maxAttempts * intervalMs + 25000);
  480. }
  481. if (message.type === 'FILL_CODE') {
  482. return Number(message.step) === 7 ? 45000 : 30000;
  483. }
  484. if (message.type === 'PREPARE_SIGNUP_VERIFICATION') {
  485. return 45000;
  486. }
  487. return 30000;
  488. }
  489. function getMessageDebugLabel(source, message, tabId = null) {
  490. const parts = [source || 'unknown', message?.type || 'UNKNOWN'];
  491. if (Number.isInteger(message?.step)) {
  492. parts.push(`step=${message.step}`);
  493. }
  494. if (Number.isInteger(tabId)) {
  495. parts.push(`tab=${tabId}`);
  496. }
  497. return parts.join(' ');
  498. }
  499. function summarizeMessageResultForDebug(result) {
  500. if (result === undefined) return 'undefined';
  501. if (result === null) return 'null';
  502. if (typeof result !== 'object') return JSON.stringify(result);
  503. const summary = {};
  504. for (const key of ['ok', 'error', 'stopped', 'source', 'step']) {
  505. if (key in result) summary[key] = result[key];
  506. }
  507. if (result.payload && typeof result.payload === 'object') {
  508. summary.payloadKeys = Object.keys(result.payload);
  509. }
  510. return JSON.stringify(summary);
  511. }
  512. function sendTabMessageWithTimeout(tabId, source, message, responseTimeoutMs = getContentScriptResponseTimeoutMs(message)) {
  513. return new Promise((resolve, reject) => {
  514. let settled = false;
  515. const startedAt = Date.now();
  516. const debugLabel = getMessageDebugLabel(source, message, tabId);
  517. console.log(LOG_PREFIX, `[sendTabMessageWithTimeout] dispatch ${debugLabel}, timeout=${responseTimeoutMs}ms`);
  518. const timer = setTimeout(() => {
  519. if (settled) return;
  520. settled = true;
  521. const seconds = Math.ceil(responseTimeoutMs / 1000);
  522. console.warn(LOG_PREFIX, `[sendTabMessageWithTimeout] timeout ${debugLabel} after ${Date.now() - startedAt}ms`);
  523. reject(new Error(`Content script on ${source} did not respond in ${seconds}s. Try refreshing the tab and retry.`));
  524. }, responseTimeoutMs);
  525. chrome.tabs.sendMessage(tabId, message)
  526. .then((value) => {
  527. const elapsed = Date.now() - startedAt;
  528. if (settled) {
  529. console.warn(
  530. LOG_PREFIX,
  531. `[sendTabMessageWithTimeout] late response ignored for ${debugLabel} after ${elapsed}ms: ${summarizeMessageResultForDebug(value)}`
  532. );
  533. return;
  534. }
  535. settled = true;
  536. clearTimeout(timer);
  537. console.log(
  538. LOG_PREFIX,
  539. `[sendTabMessageWithTimeout] response ${debugLabel} after ${elapsed}ms: ${summarizeMessageResultForDebug(value)}`
  540. );
  541. resolve(value);
  542. })
  543. .catch((error) => {
  544. const elapsed = Date.now() - startedAt;
  545. const errorMessage = error?.message || String(error);
  546. if (settled) {
  547. console.warn(
  548. LOG_PREFIX,
  549. `[sendTabMessageWithTimeout] late rejection ignored for ${debugLabel} after ${elapsed}ms: ${errorMessage}`
  550. );
  551. return;
  552. }
  553. settled = true;
  554. clearTimeout(timer);
  555. console.warn(
  556. LOG_PREFIX,
  557. `[sendTabMessageWithTimeout] rejection ${debugLabel} after ${elapsed}ms: ${errorMessage}`
  558. );
  559. reject(error);
  560. });
  561. });
  562. }
  563. function queueCommand(source, message, timeout = 15000) {
  564. return new Promise((resolve, reject) => {
  565. const timer = setTimeout(() => {
  566. pendingCommands.delete(source);
  567. const err = `Content script on ${source} did not respond in ${timeout / 1000}s. Try refreshing the tab and retry.`;
  568. console.error(LOG_PREFIX, err);
  569. reject(new Error(err));
  570. }, timeout);
  571. pendingCommands.set(source, { message, resolve, reject, timer });
  572. console.log(LOG_PREFIX, `Command queued for ${source} (waiting for ready)`);
  573. });
  574. }
  575. function flushCommand(source, tabId) {
  576. const pending = pendingCommands.get(source);
  577. if (pending) {
  578. clearTimeout(pending.timer);
  579. pendingCommands.delete(source);
  580. sendTabMessageWithTimeout(tabId, source, pending.message).then(pending.resolve).catch(pending.reject);
  581. console.log(LOG_PREFIX, `Flushed queued command to ${source} (tab ${tabId})`);
  582. }
  583. }
  584. function cancelPendingCommands(reason = STOP_ERROR_MESSAGE) {
  585. for (const [source, pending] of pendingCommands.entries()) {
  586. clearTimeout(pending.timer);
  587. pending.reject(new Error(reason));
  588. pendingCommands.delete(source);
  589. console.log(LOG_PREFIX, `Cancelled queued command for ${source}`);
  590. }
  591. }
  592. // ============================================================
  593. // Reuse or create tab
  594. // ============================================================
  595. async function reuseOrCreateTab(source, url, options = {}) {
  596. const alive = await isTabAlive(source);
  597. if (alive) {
  598. const tabId = await getTabId(source);
  599. await closeConflictingTabsForSource(source, url, { excludeTabIds: [tabId] });
  600. const currentTab = await chrome.tabs.get(tabId);
  601. const sameUrl = currentTab.url === url;
  602. const shouldReloadOnReuse = sameUrl && options.reloadIfSameUrl;
  603. const registry = await getTabRegistry();
  604. if (sameUrl) {
  605. await chrome.tabs.update(tabId, { active: true });
  606. console.log(LOG_PREFIX, `Reused tab ${source} (${tabId}) on same URL`);
  607. if (shouldReloadOnReuse) {
  608. if (registry[source]) registry[source].ready = false;
  609. await setState({ tabRegistry: registry });
  610. await chrome.tabs.reload(tabId);
  611. await new Promise((resolve) => {
  612. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  613. const listener = (tid, info) => {
  614. if (tid === tabId && info.status === 'complete') {
  615. chrome.tabs.onUpdated.removeListener(listener);
  616. clearTimeout(timer);
  617. resolve();
  618. }
  619. };
  620. chrome.tabs.onUpdated.addListener(listener);
  621. });
  622. }
  623. // For dynamically injected pages like the VPS panel, re-inject immediately.
  624. if (options.inject) {
  625. if (registry[source]) registry[source].ready = false;
  626. await setState({ tabRegistry: registry });
  627. if (options.injectSource) {
  628. await chrome.scripting.executeScript({
  629. target: { tabId },
  630. func: (injectedSource) => {
  631. window.__MULTIPAGE_SOURCE = injectedSource;
  632. },
  633. args: [options.injectSource],
  634. });
  635. }
  636. await chrome.scripting.executeScript({
  637. target: { tabId },
  638. files: options.inject,
  639. });
  640. await new Promise(r => setTimeout(r, 500));
  641. }
  642. await rememberSourceLastUrl(source, url);
  643. return tabId;
  644. }
  645. // Mark as not ready BEFORE navigating — so READY signal from new page is captured correctly
  646. if (registry[source]) registry[source].ready = false;
  647. await setState({ tabRegistry: registry });
  648. // Navigate existing tab to new URL
  649. await chrome.tabs.update(tabId, { url, active: true });
  650. console.log(LOG_PREFIX, `Reused tab ${source} (${tabId}), navigated to ${url.slice(0, 60)}`);
  651. // Wait for page load complete (with 30s timeout)
  652. await new Promise((resolve) => {
  653. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  654. const listener = (tid, info) => {
  655. if (tid === tabId && info.status === 'complete') {
  656. chrome.tabs.onUpdated.removeListener(listener);
  657. clearTimeout(timer);
  658. resolve();
  659. }
  660. };
  661. chrome.tabs.onUpdated.addListener(listener);
  662. });
  663. // If dynamic injection needed (VPS panel), re-inject after navigation
  664. if (options.inject) {
  665. if (options.injectSource) {
  666. await chrome.scripting.executeScript({
  667. target: { tabId },
  668. func: (injectedSource) => {
  669. window.__MULTIPAGE_SOURCE = injectedSource;
  670. },
  671. args: [options.injectSource],
  672. });
  673. }
  674. await chrome.scripting.executeScript({
  675. target: { tabId },
  676. files: options.inject,
  677. });
  678. }
  679. // Wait a bit for content script to inject and send READY
  680. await new Promise(r => setTimeout(r, 500));
  681. await rememberSourceLastUrl(source, url);
  682. return tabId;
  683. }
  684. // Create new tab
  685. await closeConflictingTabsForSource(source, url);
  686. const tab = await chrome.tabs.create({ url, active: true });
  687. console.log(LOG_PREFIX, `Created new tab ${source} (${tab.id})`);
  688. // If dynamic injection needed (VPS panel), inject scripts after load
  689. if (options.inject) {
  690. await new Promise((resolve) => {
  691. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  692. const listener = (tabId, info) => {
  693. if (tabId === tab.id && info.status === 'complete') {
  694. chrome.tabs.onUpdated.removeListener(listener);
  695. clearTimeout(timer);
  696. resolve();
  697. }
  698. };
  699. chrome.tabs.onUpdated.addListener(listener);
  700. });
  701. if (options.injectSource) {
  702. await chrome.scripting.executeScript({
  703. target: { tabId: tab.id },
  704. func: (injectedSource) => {
  705. window.__MULTIPAGE_SOURCE = injectedSource;
  706. },
  707. args: [options.injectSource],
  708. });
  709. }
  710. await chrome.scripting.executeScript({
  711. target: { tabId: tab.id },
  712. files: options.inject,
  713. });
  714. }
  715. await rememberSourceLastUrl(source, url);
  716. return tab.id;
  717. }
  718. // ============================================================
  719. // Send command to content script (with readiness check)
  720. // ============================================================
  721. async function sendToContentScript(source, message, options = {}) {
  722. const { responseTimeoutMs = getContentScriptResponseTimeoutMs(message) } = options;
  723. const registry = await getTabRegistry();
  724. const entry = registry[source];
  725. if (!entry || !entry.ready) {
  726. console.log(LOG_PREFIX, `${source} not ready, queuing command`);
  727. return queueCommand(source, message);
  728. }
  729. // Verify tab is still alive
  730. const alive = await isTabAlive(source);
  731. if (!alive) {
  732. // Tab was closed — queue the command, it will be sent when tab is reopened
  733. console.log(LOG_PREFIX, `${source} tab was closed, queuing command`);
  734. return queueCommand(source, message);
  735. }
  736. console.log(LOG_PREFIX, `Sending to ${source} (tab ${entry.tabId}):`, message.type);
  737. return sendTabMessageWithTimeout(entry.tabId, source, message, responseTimeoutMs);
  738. }
  739. async function sendToContentScriptResilient(source, message, options = {}) {
  740. const { timeoutMs = 30000, retryDelayMs = 600, logMessage = '' } = options;
  741. const start = Date.now();
  742. let lastError = null;
  743. let logged = false;
  744. let attempt = 0;
  745. const debugLabel = getMessageDebugLabel(source, message);
  746. console.log(
  747. LOG_PREFIX,
  748. `[sendToContentScriptResilient] start ${debugLabel}, totalTimeout=${timeoutMs}ms, retryDelay=${retryDelayMs}ms`
  749. );
  750. while (Date.now() - start < timeoutMs) {
  751. throwIfStopped();
  752. attempt += 1;
  753. try {
  754. console.log(
  755. LOG_PREFIX,
  756. `[sendToContentScriptResilient] attempt ${attempt} -> ${debugLabel}, elapsed=${Date.now() - start}ms`
  757. );
  758. const result = await sendToContentScript(source, message);
  759. console.log(
  760. LOG_PREFIX,
  761. `[sendToContentScriptResilient] success ${debugLabel} on attempt ${attempt} after ${Date.now() - start}ms`
  762. );
  763. return result;
  764. } catch (err) {
  765. const retryable = isRetryableContentScriptTransportError(err);
  766. console.warn(
  767. LOG_PREFIX,
  768. `[sendToContentScriptResilient] attempt ${attempt} failed for ${debugLabel}, retryable=${retryable}, elapsed=${Date.now() - start}ms: ${err?.message || err}`
  769. );
  770. if (!retryable) {
  771. throw err;
  772. }
  773. lastError = err;
  774. if (logMessage && !logged) {
  775. await addLog(logMessage, 'warn');
  776. logged = true;
  777. }
  778. await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
  779. }
  780. }
  781. throw lastError || new Error(`等待 ${getSourceLabel(source)} 重新就绪超时。`);
  782. }
  783. async function sendToMailContentScriptResilient(mail, message, options = {}) {
  784. const { timeoutMs = 45000, maxRecoveryAttempts = 2 } = options;
  785. const start = Date.now();
  786. let lastError = null;
  787. let recoveries = 0;
  788. let logged = false;
  789. while (Date.now() - start < timeoutMs) {
  790. throwIfStopped();
  791. try {
  792. return await sendToContentScript(mail.source, message);
  793. } catch (err) {
  794. if (!isRetryableContentScriptTransportError(err)) {
  795. throw err;
  796. }
  797. lastError = err;
  798. if (!logged) {
  799. await addLog(`步骤 ${message.step}:${mail.label} 页面通信异常,正在尝试让邮箱页重新就绪...`, 'warn');
  800. logged = true;
  801. }
  802. if (recoveries >= maxRecoveryAttempts) {
  803. break;
  804. }
  805. recoveries += 1;
  806. await reuseOrCreateTab(mail.source, mail.url, {
  807. inject: mail.inject,
  808. injectSource: mail.injectSource,
  809. reloadIfSameUrl: true,
  810. });
  811. await new Promise((resolve) => setTimeout(resolve, 800));
  812. }
  813. }
  814. throw lastError || new Error(`${mail.label} 页面未能重新就绪。`);
  815. }
  816. // ============================================================
  817. // Logging
  818. // ============================================================
  819. async function addLog(message, level = 'info') {
  820. const state = await getState();
  821. const logs = state.logs || [];
  822. const entry = { message, level, timestamp: Date.now() };
  823. logs.push(entry);
  824. // Keep last 500 logs
  825. if (logs.length > 500) logs.splice(0, logs.length - 500);
  826. await setState({ logs });
  827. // Broadcast to side panel
  828. chrome.runtime.sendMessage({ type: 'LOG_ENTRY', payload: entry }).catch(() => { });
  829. }
  830. function getStep8CallbackUrlFromNavigation(details, signupTabId) {
  831. if (!Number.isInteger(signupTabId) || !details) return '';
  832. if (details.tabId !== signupTabId) return '';
  833. if (details.frameId !== 0) return '';
  834. return isLocalhostOAuthCallbackUrl(details.url) ? details.url : '';
  835. }
  836. function getStep8CallbackUrlFromTabUpdate(tabId, changeInfo, tab, signupTabId) {
  837. if (!Number.isInteger(signupTabId) || tabId !== signupTabId) return '';
  838. const candidates = [changeInfo?.url, tab?.url];
  839. for (const candidate of candidates) {
  840. if (isLocalhostOAuthCallbackUrl(candidate)) {
  841. return candidate;
  842. }
  843. }
  844. return '';
  845. }
  846. function getSourceLabel(source) {
  847. const labels = {
  848. 'sidepanel': '侧边栏',
  849. 'signup-page': '认证页',
  850. 'vps-panel': 'CPA 面板',
  851. 'qq-mail': 'QQ 邮箱',
  852. 'mail-163': '163 邮箱',
  853. 'inbucket-mail': 'Inbucket 邮箱',
  854. 'duck-mail': 'Duck 邮箱',
  855. };
  856. return labels[source] || source || '未知来源';
  857. }
  858. // ============================================================
  859. // Step Status Management
  860. // ============================================================
  861. async function setStepStatus(step, status) {
  862. const state = await getState();
  863. const statuses = { ...state.stepStatuses };
  864. statuses[step] = status;
  865. await setState({ stepStatuses: statuses, currentStep: step });
  866. // Broadcast to side panel
  867. chrome.runtime.sendMessage({
  868. type: 'STEP_STATUS_CHANGED',
  869. payload: { step, status },
  870. }).catch(() => { });
  871. }
  872. function isStopError(error) {
  873. const message = typeof error === 'string' ? error : error?.message;
  874. return message === STOP_ERROR_MESSAGE;
  875. }
  876. function isRetryableContentScriptTransportError(error) {
  877. const message = String(typeof error === 'string' ? error : error?.message || '');
  878. 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);
  879. }
  880. function getErrorMessage(error) {
  881. return String(typeof error === 'string' ? error : error?.message || '');
  882. }
  883. function isVerificationMailPollingError(error) {
  884. const message = getErrorMessage(error);
  885. return /未在 .*邮箱中找到新的匹配邮件|邮箱轮询结束,但未获取到验证码|无法获取新的(?:注册|登录)验证码|页面未能重新就绪|页面通信异常|did not respond in \d+s/i.test(message);
  886. }
  887. const STEP7_RESTART_FROM_STEP6_ERROR_CODE = 'STEP7_RESTART_FROM_STEP6';
  888. const STEP7_RESTART_FROM_STEP6_MARKER_PATTERN = /^STEP7_RESTART_FROM_STEP6::([^:]+)::(.*)$/;
  889. function createStep7RestartFromStep6Error(details = {}) {
  890. const { reason = 'unknown', url = '' } = details || {};
  891. const reasonLabel = reason === 'login_timeout_error_page'
  892. ? '检测到登录页超时报错'
  893. : '步骤 7 请求回到步骤 6';
  894. const error = new Error(`步骤 7:${reasonLabel}。${url ? `URL: ${url}` : ''}`.trim());
  895. error.code = STEP7_RESTART_FROM_STEP6_ERROR_CODE;
  896. error.restartReason = reason;
  897. error.restartUrl = url;
  898. return error;
  899. }
  900. function parseStep7RestartFromStep6Marker(message) {
  901. const normalized = getErrorMessage(message);
  902. const match = normalized.match(STEP7_RESTART_FROM_STEP6_MARKER_PATTERN);
  903. if (!match) {
  904. return null;
  905. }
  906. return {
  907. reason: match[1] || 'unknown',
  908. url: match[2] || '',
  909. };
  910. }
  911. function getStep7RestartFromStep6Error(result) {
  912. if (result?.restartFromStep6) {
  913. return createStep7RestartFromStep6Error(result);
  914. }
  915. const parsed = parseStep7RestartFromStep6Marker(result?.error);
  916. if (!parsed) {
  917. return null;
  918. }
  919. return createStep7RestartFromStep6Error(parsed);
  920. }
  921. function isStep7RestartFromStep6Error(error) {
  922. return error?.code === STEP7_RESTART_FROM_STEP6_ERROR_CODE
  923. || Boolean(parseStep7RestartFromStep6Marker(error));
  924. }
  925. function isStep7RecoverableError(error) {
  926. return isVerificationMailPollingError(error) || isStep7RestartFromStep6Error(error);
  927. }
  928. function isRestartCurrentAttemptError(error) {
  929. const message = String(typeof error === 'string' ? error : error?.message || '');
  930. return /当前邮箱已存在,需要重新开始新一轮/.test(message);
  931. }
  932. function isStep9OAuthTimeoutError(error) {
  933. const message = String(typeof error === 'string' ? error : error?.message || '');
  934. return /STEP9_OAUTH_TIMEOUT::|认证失败:\s*Timeout waiting for OAuth callback/i.test(message);
  935. }
  936. function isStepDoneStatus(status) {
  937. return status === 'completed' || status === 'manual_completed' || status === 'skipped';
  938. }
  939. function getFirstUnfinishedStep(statuses = {}) {
  940. for (let step = 1; step <= 9; step++) {
  941. if (!isStepDoneStatus(statuses[step] || 'pending')) {
  942. return step;
  943. }
  944. }
  945. return null;
  946. }
  947. function hasSavedProgress(statuses = {}) {
  948. return Object.values({ ...DEFAULT_STATE.stepStatuses, ...statuses }).some((status) => status !== 'pending');
  949. }
  950. function getDownstreamStateResets(step) {
  951. if (step <= 1) {
  952. return {
  953. oauthUrl: null,
  954. flowStartTime: null,
  955. password: null,
  956. lastEmailTimestamp: null,
  957. lastSignupCode: null,
  958. lastLoginCode: null,
  959. localhostUrl: null,
  960. };
  961. }
  962. if (step === 2) {
  963. return {
  964. password: null,
  965. lastEmailTimestamp: null,
  966. lastSignupCode: null,
  967. lastLoginCode: null,
  968. localhostUrl: null,
  969. };
  970. }
  971. if (step === 3 || step === 4) {
  972. return {
  973. lastEmailTimestamp: null,
  974. lastSignupCode: null,
  975. lastLoginCode: null,
  976. localhostUrl: null,
  977. };
  978. }
  979. if (step === 5 || step === 6 || step === 7) {
  980. return {
  981. lastLoginCode: null,
  982. localhostUrl: null,
  983. };
  984. }
  985. if (step === 8) {
  986. return {
  987. localhostUrl: null,
  988. };
  989. }
  990. return {};
  991. }
  992. async function invalidateDownstreamAfterStepRestart(step, options = {}) {
  993. const { logLabel = `步骤 ${step} 重新执行` } = options;
  994. const state = await getState();
  995. const statuses = { ...(state.stepStatuses || {}) };
  996. const changedSteps = [];
  997. for (let downstream = step + 1; downstream <= 9; downstream++) {
  998. if (statuses[downstream] !== 'pending') {
  999. statuses[downstream] = 'pending';
  1000. changedSteps.push(downstream);
  1001. }
  1002. }
  1003. if (changedSteps.length) {
  1004. await setState({ stepStatuses: statuses });
  1005. for (const downstream of changedSteps) {
  1006. chrome.runtime.sendMessage({
  1007. type: 'STEP_STATUS_CHANGED',
  1008. payload: { step: downstream, status: 'pending' },
  1009. }).catch(() => { });
  1010. }
  1011. await addLog(`${logLabel},已重置后续步骤状态:${changedSteps.join(', ')}`, 'warn');
  1012. }
  1013. const resets = getDownstreamStateResets(step);
  1014. if (Object.keys(resets).length) {
  1015. await setState(resets);
  1016. broadcastDataUpdate(resets);
  1017. }
  1018. }
  1019. function clearStopRequest() {
  1020. stopRequested = false;
  1021. }
  1022. function getAutoRunStatusPayload(phase, payload = {}) {
  1023. const currentRun = payload.currentRun ?? autoRunCurrentRun;
  1024. const totalRuns = payload.totalRuns ?? autoRunTotalRuns;
  1025. const attemptRun = payload.attemptRun ?? autoRunAttemptRun;
  1026. const rawScheduledAt = phase === 'scheduled'
  1027. ? (payload.scheduledAt ?? payload.scheduledAutoRunAt ?? null)
  1028. : null;
  1029. const scheduledAt = rawScheduledAt === null ? null : Number(rawScheduledAt);
  1030. const autoRunning = phase === 'scheduled' || phase === 'running' || phase === 'waiting_email' || phase === 'retrying';
  1031. return {
  1032. autoRunning,
  1033. autoRunPhase: phase,
  1034. autoRunCurrentRun: currentRun,
  1035. autoRunTotalRuns: totalRuns,
  1036. autoRunAttemptRun: attemptRun,
  1037. scheduledAutoRunAt: Number.isFinite(scheduledAt) ? scheduledAt : null,
  1038. };
  1039. }
  1040. async function broadcastAutoRunStatus(phase, payload = {}, extraState = {}) {
  1041. const rawScheduledAt = phase === 'scheduled'
  1042. ? (payload.scheduledAt ?? payload.scheduledAutoRunAt ?? null)
  1043. : null;
  1044. const statusPayload = {
  1045. phase,
  1046. currentRun: payload.currentRun ?? autoRunCurrentRun,
  1047. totalRuns: payload.totalRuns ?? autoRunTotalRuns,
  1048. attemptRun: payload.attemptRun ?? autoRunAttemptRun,
  1049. scheduledAt: rawScheduledAt === null ? null : Number(rawScheduledAt),
  1050. };
  1051. await setState({
  1052. ...extraState,
  1053. ...getAutoRunStatusPayload(phase, statusPayload),
  1054. });
  1055. chrome.runtime.sendMessage({
  1056. type: 'AUTO_RUN_STATUS',
  1057. payload: statusPayload,
  1058. }).catch(() => { });
  1059. }
  1060. function isAutoRunLockedState(state) {
  1061. return Boolean(state.autoRunning) && (state.autoRunPhase === 'running' || state.autoRunPhase === 'retrying');
  1062. }
  1063. function isAutoRunPausedState(state) {
  1064. return Boolean(state.autoRunning) && state.autoRunPhase === 'waiting_email';
  1065. }
  1066. function isAutoRunScheduledState(state) {
  1067. const scheduledAt = state.scheduledAutoRunAt === null ? null : Number(state.scheduledAutoRunAt);
  1068. return Boolean(state.autoRunning)
  1069. && state.autoRunPhase === 'scheduled'
  1070. && Number.isFinite(scheduledAt)
  1071. && Boolean(normalizeScheduledAutoRunPlan(state.scheduledAutoRunPlan));
  1072. }
  1073. function formatAutoRunScheduleTime(timestamp) {
  1074. return new Date(timestamp).toLocaleString('zh-CN', {
  1075. hour12: false,
  1076. month: '2-digit',
  1077. day: '2-digit',
  1078. hour: '2-digit',
  1079. minute: '2-digit',
  1080. second: '2-digit',
  1081. });
  1082. }
  1083. async function setAutoRunDelayEnabledState(enabled) {
  1084. const normalized = Boolean(enabled);
  1085. await setPersistentSettings({ autoRunDelayEnabled: normalized });
  1086. await setState({ autoRunDelayEnabled: normalized });
  1087. broadcastDataUpdate({ autoRunDelayEnabled: normalized });
  1088. }
  1089. async function ensureScheduledAutoRunAlarm(scheduledAt) {
  1090. if (!Number.isFinite(scheduledAt) || scheduledAt <= Date.now()) {
  1091. return false;
  1092. }
  1093. const existingAlarm = await chrome.alarms.get(AUTO_RUN_ALARM_NAME);
  1094. if (!existingAlarm || Math.abs((existingAlarm.scheduledTime || 0) - scheduledAt) > 1000) {
  1095. await chrome.alarms.clear(AUTO_RUN_ALARM_NAME);
  1096. await chrome.alarms.create(AUTO_RUN_ALARM_NAME, { when: scheduledAt });
  1097. }
  1098. return true;
  1099. }
  1100. async function clearScheduledAutoRunAlarm() {
  1101. await chrome.alarms.clear(AUTO_RUN_ALARM_NAME);
  1102. }
  1103. async function scheduleAutoRun(totalRuns, options = {}) {
  1104. const state = await getState();
  1105. if (isAutoRunLockedState(state) || isAutoRunPausedState(state) || autoRunActive) {
  1106. throw new Error('自动运行已在进行中,请先停止后再重新计划。');
  1107. }
  1108. if (isAutoRunScheduledState(state)) {
  1109. throw new Error('已有自动运行倒计时计划,请先取消或立即开始。');
  1110. }
  1111. const delayMinutes = normalizeAutoRunDelayMinutes(options.delayMinutes);
  1112. const plan = normalizeScheduledAutoRunPlan({
  1113. totalRuns,
  1114. autoRunSkipFailures: options.autoRunSkipFailures,
  1115. mode: options.mode,
  1116. });
  1117. const scheduledAt = Date.now() + delayMinutes * 60 * 1000;
  1118. autoRunCurrentRun = 0;
  1119. autoRunTotalRuns = plan.totalRuns;
  1120. autoRunAttemptRun = 0;
  1121. await ensureScheduledAutoRunAlarm(scheduledAt);
  1122. await broadcastAutoRunStatus(
  1123. 'scheduled',
  1124. {
  1125. currentRun: 0,
  1126. totalRuns: plan.totalRuns,
  1127. attemptRun: 0,
  1128. scheduledAt,
  1129. },
  1130. {
  1131. autoRunSkipFailures: plan.autoRunSkipFailures,
  1132. scheduledAutoRunPlan: plan,
  1133. }
  1134. );
  1135. await addLog(
  1136. `自动运行已计划:${delayMinutes} 分钟后启动(${formatAutoRunScheduleTime(scheduledAt)}),目标 ${plan.totalRuns} 轮。`,
  1137. 'info'
  1138. );
  1139. return { ok: true, scheduledAt };
  1140. }
  1141. let scheduledAutoRunLaunching = false;
  1142. async function launchScheduledAutoRun(trigger = 'alarm') {
  1143. if (scheduledAutoRunLaunching) {
  1144. return false;
  1145. }
  1146. scheduledAutoRunLaunching = true;
  1147. try {
  1148. const state = await getState();
  1149. if (!isAutoRunScheduledState(state)) {
  1150. return false;
  1151. }
  1152. if (autoRunActive) {
  1153. return false;
  1154. }
  1155. const plan = normalizeScheduledAutoRunPlan(state.scheduledAutoRunPlan);
  1156. if (!plan) {
  1157. await clearScheduledAutoRunAlarm();
  1158. await broadcastAutoRunStatus('idle', {
  1159. currentRun: 0,
  1160. totalRuns: 1,
  1161. attemptRun: 0,
  1162. }, {
  1163. scheduledAutoRunPlan: null,
  1164. });
  1165. return false;
  1166. }
  1167. await clearScheduledAutoRunAlarm();
  1168. if (trigger !== 'manual' && state.autoRunDelayEnabled) {
  1169. await setAutoRunDelayEnabledState(false);
  1170. }
  1171. await broadcastAutoRunStatus(
  1172. 'running',
  1173. {
  1174. currentRun: 0,
  1175. totalRuns: plan.totalRuns,
  1176. attemptRun: 0,
  1177. },
  1178. {
  1179. autoRunSkipFailures: plan.autoRunSkipFailures,
  1180. scheduledAutoRunPlan: null,
  1181. }
  1182. );
  1183. clearStopRequest();
  1184. await addLog(
  1185. trigger === 'manual'
  1186. ? '已手动跳过倒计时,自动运行立即开始。'
  1187. : '倒计时结束,自动运行开始执行。',
  1188. 'info'
  1189. );
  1190. autoRunLoop(plan.totalRuns, {
  1191. autoRunSkipFailures: plan.autoRunSkipFailures,
  1192. mode: plan.mode,
  1193. });
  1194. return true;
  1195. } finally {
  1196. scheduledAutoRunLaunching = false;
  1197. }
  1198. }
  1199. async function cancelScheduledAutoRun(options = {}) {
  1200. const state = await getState();
  1201. if (!isAutoRunScheduledState(state)) {
  1202. return false;
  1203. }
  1204. const plan = normalizeScheduledAutoRunPlan(state.scheduledAutoRunPlan);
  1205. await clearScheduledAutoRunAlarm();
  1206. autoRunCurrentRun = 0;
  1207. autoRunTotalRuns = plan?.totalRuns || 1;
  1208. autoRunAttemptRun = 0;
  1209. await broadcastAutoRunStatus(
  1210. 'idle',
  1211. {
  1212. currentRun: 0,
  1213. totalRuns: plan?.totalRuns || 1,
  1214. attemptRun: 0,
  1215. },
  1216. {
  1217. scheduledAutoRunPlan: null,
  1218. }
  1219. );
  1220. if (options.logMessage !== false) {
  1221. await addLog(options.logMessage || '已取消自动运行倒计时计划。', 'warn');
  1222. }
  1223. return true;
  1224. }
  1225. async function restoreScheduledAutoRunIfNeeded() {
  1226. const state = await getState();
  1227. if (state.autoRunPhase !== 'scheduled') {
  1228. return;
  1229. }
  1230. const plan = normalizeScheduledAutoRunPlan(state.scheduledAutoRunPlan);
  1231. const scheduledAt = state.scheduledAutoRunAt === null ? null : Number(state.scheduledAutoRunAt);
  1232. if (!plan || !Number.isFinite(scheduledAt)) {
  1233. await clearScheduledAutoRunAlarm();
  1234. await broadcastAutoRunStatus('idle', {
  1235. currentRun: 0,
  1236. totalRuns: 1,
  1237. attemptRun: 0,
  1238. }, {
  1239. scheduledAutoRunPlan: null,
  1240. });
  1241. return;
  1242. }
  1243. if (scheduledAt <= Date.now()) {
  1244. await launchScheduledAutoRun('restore');
  1245. return;
  1246. }
  1247. await ensureScheduledAutoRunAlarm(scheduledAt);
  1248. }
  1249. async function ensureManualInteractionAllowed(actionLabel) {
  1250. const state = await getState();
  1251. if (isAutoRunLockedState(state)) {
  1252. throw new Error(`自动流程运行中,请先停止后再${actionLabel}。`);
  1253. }
  1254. if (isAutoRunPausedState(state)) {
  1255. throw new Error(`自动流程当前已暂停。请点击“继续”,或先确认接管自动流程后再${actionLabel}。`);
  1256. }
  1257. if (isAutoRunScheduledState(state)) {
  1258. throw new Error(`自动流程已计划启动。请先取消计划,或立即开始后再${actionLabel}。`);
  1259. }
  1260. return state;
  1261. }
  1262. async function skipStep(step) {
  1263. const state = await ensureManualInteractionAllowed('跳过步骤');
  1264. if (!Number.isInteger(step) || step < 1 || step > 9) {
  1265. throw new Error(`无效步骤:${step}`);
  1266. }
  1267. const statuses = { ...(state.stepStatuses || {}) };
  1268. const currentStatus = statuses[step];
  1269. if (currentStatus === 'running') {
  1270. throw new Error(`步骤 ${step} 正在运行中,不能跳过。`);
  1271. }
  1272. if (isStepDoneStatus(currentStatus)) {
  1273. throw new Error(`步骤 ${step} 已完成,无需再跳过。`);
  1274. }
  1275. if (step > 1) {
  1276. const prevStatus = statuses[step - 1];
  1277. if (!isStepDoneStatus(prevStatus)) {
  1278. throw new Error(`请先完成步骤 ${step - 1},再跳过步骤 ${step}。`);
  1279. }
  1280. }
  1281. await setStepStatus(step, 'skipped');
  1282. await addLog(`步骤 ${step} 已跳过`, 'warn');
  1283. if (step === 1) {
  1284. const latestState = await getState();
  1285. const step2Status = latestState.stepStatuses?.[2];
  1286. if (!isStepDoneStatus(step2Status) && step2Status !== 'running') {
  1287. await setStepStatus(2, 'skipped');
  1288. await addLog('步骤 1 已跳过,步骤 2 也已同时跳过。', 'warn');
  1289. }
  1290. }
  1291. return { ok: true, step, status: 'skipped' };
  1292. }
  1293. function throwIfStopped() {
  1294. if (stopRequested) {
  1295. throw new Error(STOP_ERROR_MESSAGE);
  1296. }
  1297. }
  1298. async function sleepWithStop(ms) {
  1299. const start = Date.now();
  1300. while (Date.now() - start < ms) {
  1301. throwIfStopped();
  1302. await new Promise(r => setTimeout(r, Math.min(100, ms - (Date.now() - start))));
  1303. }
  1304. }
  1305. async function humanStepDelay(min = HUMAN_STEP_DELAY_MIN, max = HUMAN_STEP_DELAY_MAX) {
  1306. const duration = Math.floor(Math.random() * (max - min + 1)) + min;
  1307. await sleepWithStop(duration);
  1308. }
  1309. async function clickWithDebugger(tabId, rect) {
  1310. if (!tabId) {
  1311. throw new Error('未找到用于调试点击的认证页面标签页。');
  1312. }
  1313. if (!rect || !Number.isFinite(rect.centerX) || !Number.isFinite(rect.centerY)) {
  1314. throw new Error('步骤 8 的调试器兜底点击需要有效的按钮坐标。');
  1315. }
  1316. const target = { tabId };
  1317. try {
  1318. await chrome.debugger.attach(target, '1.3');
  1319. } catch (err) {
  1320. throw new Error(
  1321. `步骤 8 的调试器兜底点击附加失败:${err.message}。` +
  1322. '如果认证页标签已打开 DevTools,请先关闭后重试。'
  1323. );
  1324. }
  1325. try {
  1326. const x = Math.round(rect.centerX);
  1327. const y = Math.round(rect.centerY);
  1328. await chrome.debugger.sendCommand(target, 'Page.bringToFront');
  1329. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  1330. type: 'mouseMoved',
  1331. x,
  1332. y,
  1333. button: 'none',
  1334. buttons: 0,
  1335. clickCount: 0,
  1336. });
  1337. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  1338. type: 'mousePressed',
  1339. x,
  1340. y,
  1341. button: 'left',
  1342. buttons: 1,
  1343. clickCount: 1,
  1344. });
  1345. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  1346. type: 'mouseReleased',
  1347. x,
  1348. y,
  1349. button: 'left',
  1350. buttons: 0,
  1351. clickCount: 1,
  1352. });
  1353. } finally {
  1354. await chrome.debugger.detach(target).catch(() => { });
  1355. }
  1356. }
  1357. async function broadcastStopToContentScripts() {
  1358. const registry = await getTabRegistry();
  1359. for (const entry of Object.values(registry)) {
  1360. if (!entry?.tabId) continue;
  1361. try {
  1362. await chrome.tabs.sendMessage(entry.tabId, {
  1363. type: 'STOP_FLOW',
  1364. source: 'background',
  1365. payload: {},
  1366. });
  1367. } catch { }
  1368. }
  1369. }
  1370. let stopRequested = false;
  1371. // ============================================================
  1372. // Message Handler (central router)
  1373. // ============================================================
  1374. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  1375. console.log(LOG_PREFIX, `Received: ${message.type} from ${message.source || 'sidepanel'}`, message);
  1376. handleMessage(message, sender).then(response => {
  1377. sendResponse(response);
  1378. }).catch(err => {
  1379. console.error(LOG_PREFIX, 'Handler error:', err);
  1380. sendResponse({ error: err.message });
  1381. });
  1382. return true; // async response
  1383. });
  1384. async function handleMessage(message, sender) {
  1385. switch (message.type) {
  1386. case 'CONTENT_SCRIPT_READY': {
  1387. const tabId = sender.tab?.id;
  1388. if (tabId && message.source) {
  1389. await registerTab(message.source, tabId);
  1390. flushCommand(message.source, tabId);
  1391. await addLog(`内容脚本已就绪:${getSourceLabel(message.source)}(标签页 ${tabId})`);
  1392. }
  1393. return { ok: true };
  1394. }
  1395. case 'LOG': {
  1396. const { message: msg, level } = message.payload;
  1397. await addLog(`[${getSourceLabel(message.source)}] ${msg}`, level);
  1398. return { ok: true };
  1399. }
  1400. case 'STEP_COMPLETE': {
  1401. if (stopRequested) {
  1402. await setStepStatus(message.step, 'stopped');
  1403. notifyStepError(message.step, STOP_ERROR_MESSAGE);
  1404. return { ok: true };
  1405. }
  1406. await setStepStatus(message.step, 'completed');
  1407. await addLog(`步骤 ${message.step} 已完成`, 'ok');
  1408. await handleStepData(message.step, message.payload);
  1409. notifyStepComplete(message.step, message.payload);
  1410. return { ok: true };
  1411. }
  1412. case 'STEP_ERROR': {
  1413. if (isStopError(message.error)) {
  1414. await setStepStatus(message.step, 'stopped');
  1415. await addLog(`步骤 ${message.step} 已被用户停止`, 'warn');
  1416. notifyStepError(message.step, message.error);
  1417. } else {
  1418. await setStepStatus(message.step, 'failed');
  1419. await addLog(`步骤 ${message.step} 失败:${message.error}`, 'error');
  1420. notifyStepError(message.step, message.error);
  1421. }
  1422. return { ok: true };
  1423. }
  1424. case 'GET_STATE': {
  1425. return await getState();
  1426. }
  1427. case 'RESET': {
  1428. clearStopRequest();
  1429. await clearScheduledAutoRunAlarm();
  1430. await resetState();
  1431. await addLog('流程已重置', 'info');
  1432. return { ok: true };
  1433. }
  1434. case 'EXECUTE_STEP': {
  1435. clearStopRequest();
  1436. if (message.source === 'sidepanel') {
  1437. await ensureManualInteractionAllowed('手动执行步骤');
  1438. }
  1439. const step = message.payload.step;
  1440. if (message.source === 'sidepanel') {
  1441. await invalidateDownstreamAfterStepRestart(step, { logLabel: `步骤 ${step} 重新执行` });
  1442. }
  1443. // Save email if provided (from side panel step 3)
  1444. if (message.payload.email) {
  1445. await setEmailState(message.payload.email);
  1446. }
  1447. await executeStep(step);
  1448. return { ok: true };
  1449. }
  1450. case 'AUTO_RUN': {
  1451. clearStopRequest();
  1452. const state = await getState();
  1453. if (isAutoRunScheduledState(state)) {
  1454. throw new Error('已有自动运行倒计时计划,请先取消或立即开始。');
  1455. }
  1456. const totalRuns = normalizeRunCount(message.payload?.totalRuns || 1);
  1457. const autoRunSkipFailures = Boolean(message.payload?.autoRunSkipFailures);
  1458. const mode = message.payload?.mode === 'continue' ? 'continue' : 'restart';
  1459. await setState({ autoRunSkipFailures });
  1460. autoRunLoop(totalRuns, { autoRunSkipFailures, mode }); // fire-and-forget
  1461. return { ok: true };
  1462. }
  1463. case 'SCHEDULE_AUTO_RUN': {
  1464. clearStopRequest();
  1465. const totalRuns = normalizeRunCount(message.payload?.totalRuns || 1);
  1466. return await scheduleAutoRun(totalRuns, {
  1467. delayMinutes: message.payload?.delayMinutes,
  1468. autoRunSkipFailures: Boolean(message.payload?.autoRunSkipFailures),
  1469. mode: message.payload?.mode,
  1470. });
  1471. }
  1472. case 'START_SCHEDULED_AUTO_RUN_NOW': {
  1473. clearStopRequest();
  1474. const started = await launchScheduledAutoRun('manual');
  1475. if (!started) {
  1476. throw new Error('当前没有可立即开始的倒计时计划。');
  1477. }
  1478. return { ok: true };
  1479. }
  1480. case 'CANCEL_SCHEDULED_AUTO_RUN': {
  1481. const cancelled = await cancelScheduledAutoRun();
  1482. if (!cancelled) {
  1483. throw new Error('当前没有可取消的倒计时计划。');
  1484. }
  1485. return { ok: true };
  1486. }
  1487. case 'RESUME_AUTO_RUN': {
  1488. clearStopRequest();
  1489. if (message.payload.email) {
  1490. await setEmailState(message.payload.email);
  1491. }
  1492. resumeAutoRun(); // fire-and-forget
  1493. return { ok: true };
  1494. }
  1495. case 'TAKEOVER_AUTO_RUN': {
  1496. await requestStop({ logMessage: '已确认手动接管,正在停止自动流程并切换为手动控制...' });
  1497. await addLog('自动流程已切换为手动控制。', 'warn');
  1498. return { ok: true };
  1499. }
  1500. case 'SKIP_STEP': {
  1501. const step = Number(message.payload?.step);
  1502. return await skipStep(step);
  1503. }
  1504. case 'SAVE_SETTING': {
  1505. const updates = {};
  1506. if (message.payload.vpsUrl !== undefined) updates.vpsUrl = message.payload.vpsUrl;
  1507. if (message.payload.vpsPassword !== undefined) updates.vpsPassword = message.payload.vpsPassword;
  1508. if (message.payload.customPassword !== undefined) updates.customPassword = message.payload.customPassword;
  1509. if (message.payload.autoRunSkipFailures !== undefined) updates.autoRunSkipFailures = Boolean(message.payload.autoRunSkipFailures);
  1510. if (message.payload.autoRunDelayEnabled !== undefined) updates.autoRunDelayEnabled = Boolean(message.payload.autoRunDelayEnabled);
  1511. if (message.payload.autoRunDelayMinutes !== undefined) updates.autoRunDelayMinutes = normalizeAutoRunDelayMinutes(message.payload.autoRunDelayMinutes);
  1512. if (message.payload.mailProvider !== undefined) updates.mailProvider = message.payload.mailProvider;
  1513. if (message.payload.emailGenerator !== undefined) updates.emailGenerator = normalizeEmailGenerator(message.payload.emailGenerator);
  1514. if (message.payload.inbucketHost !== undefined) updates.inbucketHost = message.payload.inbucketHost;
  1515. if (message.payload.inbucketMailbox !== undefined) updates.inbucketMailbox = message.payload.inbucketMailbox;
  1516. if (message.payload.cloudflareDomain !== undefined) updates.cloudflareDomain = normalizeCloudflareDomain(message.payload.cloudflareDomain);
  1517. if (message.payload.cloudflareDomains !== undefined) updates.cloudflareDomains = Array.isArray(message.payload.cloudflareDomains)
  1518. ? message.payload.cloudflareDomains.map(domain => normalizeCloudflareDomain(domain)).filter(Boolean)
  1519. : [];
  1520. await setPersistentSettings(updates);
  1521. await setState(updates);
  1522. return { ok: true };
  1523. }
  1524. // Side panel data updates
  1525. case 'SAVE_EMAIL': {
  1526. const state = await getState();
  1527. if (isAutoRunLockedState(state)) {
  1528. throw new Error('自动流程运行中,当前不能手动修改邮箱。');
  1529. }
  1530. await setEmailState(message.payload.email);
  1531. await resumeAutoRun();
  1532. return { ok: true, email: message.payload.email };
  1533. }
  1534. case 'FETCH_GENERATED_EMAIL': {
  1535. clearStopRequest();
  1536. const state = await getState();
  1537. if (isAutoRunLockedState(state)) {
  1538. throw new Error('自动流程运行中,当前不能手动获取邮箱。');
  1539. }
  1540. const email = await fetchGeneratedEmail(state, message.payload || {});
  1541. await resumeAutoRun();
  1542. return { ok: true, email };
  1543. }
  1544. case 'FETCH_DUCK_EMAIL': {
  1545. clearStopRequest();
  1546. const state = await getState();
  1547. if (isAutoRunLockedState(state)) {
  1548. throw new Error('自动流程运行中,当前不能手动获取邮箱。');
  1549. }
  1550. const email = await fetchGeneratedEmail(state, { ...(message.payload || {}), generator: 'duck' });
  1551. await resumeAutoRun();
  1552. return { ok: true, email };
  1553. }
  1554. case 'STOP_FLOW': {
  1555. await requestStop();
  1556. return { ok: true };
  1557. }
  1558. default:
  1559. console.warn(LOG_PREFIX, `Unknown message type: ${message.type}`);
  1560. return { error: `Unknown message type: ${message.type}` };
  1561. }
  1562. }
  1563. // ============================================================
  1564. // Step Data Handlers
  1565. // ============================================================
  1566. async function handleStepData(step, payload) {
  1567. switch (step) {
  1568. case 1:
  1569. if (payload.oauthUrl) {
  1570. await setState({ oauthUrl: payload.oauthUrl });
  1571. broadcastDataUpdate({ oauthUrl: payload.oauthUrl });
  1572. }
  1573. break;
  1574. case 3:
  1575. if (payload.email) await setEmailState(payload.email);
  1576. break;
  1577. case 4:
  1578. if (payload.emailTimestamp) await setState({ lastEmailTimestamp: payload.emailTimestamp });
  1579. break;
  1580. case 8:
  1581. if (payload.localhostUrl) {
  1582. if (!isLocalhostOAuthCallbackUrl(payload.localhostUrl)) {
  1583. throw new Error('步骤 8 返回了无效的 localhost OAuth 回调地址。');
  1584. }
  1585. await setState({ localhostUrl: payload.localhostUrl });
  1586. broadcastDataUpdate({ localhostUrl: payload.localhostUrl });
  1587. }
  1588. break;
  1589. case 9: {
  1590. if (payload.localhostUrl) {
  1591. await closeLocalhostCallbackTabs(payload.localhostUrl);
  1592. }
  1593. break;
  1594. }
  1595. }
  1596. }
  1597. // ============================================================
  1598. // Step Completion Waiting
  1599. // ============================================================
  1600. // Map of step -> { resolve, reject } for waiting on step completion
  1601. const stepWaiters = new Map();
  1602. let resumeWaiter = null;
  1603. const AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS = 120000;
  1604. const AUTO_RUN_BACKGROUND_COMPLETED_STEPS = new Set([4, 7, 8]);
  1605. function waitForStepComplete(step, timeoutMs = 120000) {
  1606. return new Promise((resolve, reject) => {
  1607. throwIfStopped();
  1608. if (stepWaiters.has(step)) {
  1609. console.warn(LOG_PREFIX, `[waitForStepComplete] replacing existing waiter for step ${step}`);
  1610. }
  1611. console.log(LOG_PREFIX, `[waitForStepComplete] register step ${step}, timeout=${timeoutMs}ms`);
  1612. const timer = setTimeout(() => {
  1613. stepWaiters.delete(step);
  1614. console.warn(LOG_PREFIX, `[waitForStepComplete] timeout for step ${step} after ${timeoutMs}ms`);
  1615. reject(new Error(`Step ${step} timed out after ${timeoutMs / 1000}s`));
  1616. }, timeoutMs);
  1617. stepWaiters.set(step, {
  1618. resolve: (data) => { clearTimeout(timer); stepWaiters.delete(step); resolve(data); },
  1619. reject: (err) => { clearTimeout(timer); stepWaiters.delete(step); reject(err); },
  1620. });
  1621. });
  1622. }
  1623. function notifyStepComplete(step, payload) {
  1624. const waiter = stepWaiters.get(step);
  1625. console.log(LOG_PREFIX, `[notifyStepComplete] step ${step}, hasWaiter=${Boolean(waiter)}`);
  1626. if (waiter) waiter.resolve(payload);
  1627. }
  1628. function notifyStepError(step, error) {
  1629. const waiter = stepWaiters.get(step);
  1630. console.warn(LOG_PREFIX, `[notifyStepError] step ${step}, hasWaiter=${Boolean(waiter)}, error=${error}`);
  1631. if (waiter) waiter.reject(new Error(error));
  1632. }
  1633. async function completeStepFromBackground(step, payload = {}) {
  1634. if (stopRequested) {
  1635. await setStepStatus(step, 'stopped');
  1636. notifyStepError(step, STOP_ERROR_MESSAGE);
  1637. return;
  1638. }
  1639. await setStepStatus(step, 'completed');
  1640. await addLog(`步骤 ${step} 已完成`, 'ok');
  1641. await handleStepData(step, payload);
  1642. notifyStepComplete(step, payload);
  1643. }
  1644. async function markRunningStepsStopped() {
  1645. const state = await getState();
  1646. const runningSteps = Object.entries(state.stepStatuses || {})
  1647. .filter(([, status]) => status === 'running')
  1648. .map(([step]) => Number(step));
  1649. for (const step of runningSteps) {
  1650. await setStepStatus(step, 'stopped');
  1651. }
  1652. }
  1653. async function requestStop(options = {}) {
  1654. const { logMessage = '已收到停止请求,正在取消当前操作...' } = options;
  1655. const state = await getState();
  1656. if (isAutoRunScheduledState(state) && !autoRunActive) {
  1657. await cancelScheduledAutoRun({
  1658. logMessage: options.logMessage === false
  1659. ? false
  1660. : (options.logMessage || '已取消自动运行倒计时计划。'),
  1661. });
  1662. return;
  1663. }
  1664. if (stopRequested) return;
  1665. stopRequested = true;
  1666. cancelPendingCommands();
  1667. cleanupStep8NavigationListeners();
  1668. rejectPendingStep8(new Error(STOP_ERROR_MESSAGE));
  1669. await addLog(logMessage, 'warn');
  1670. await broadcastStopToContentScripts();
  1671. for (const waiter of stepWaiters.values()) {
  1672. waiter.reject(new Error(STOP_ERROR_MESSAGE));
  1673. }
  1674. stepWaiters.clear();
  1675. if (resumeWaiter) {
  1676. resumeWaiter.reject(new Error(STOP_ERROR_MESSAGE));
  1677. resumeWaiter = null;
  1678. }
  1679. await markRunningStepsStopped();
  1680. autoRunActive = false;
  1681. await broadcastAutoRunStatus('stopped', {
  1682. currentRun: autoRunCurrentRun,
  1683. totalRuns: autoRunTotalRuns,
  1684. attemptRun: autoRunAttemptRun,
  1685. });
  1686. }
  1687. // ============================================================
  1688. // Step Execution
  1689. // ============================================================
  1690. async function executeStep(step) {
  1691. console.log(LOG_PREFIX, `Executing step ${step}`);
  1692. throwIfStopped();
  1693. await setStepStatus(step, 'running');
  1694. await addLog(`步骤 ${step} 开始执行`);
  1695. await humanStepDelay();
  1696. const state = await getState();
  1697. // Set flow start time on first step
  1698. if (step === 1 && !state.flowStartTime) {
  1699. await setState({ flowStartTime: Date.now() });
  1700. }
  1701. try {
  1702. switch (step) {
  1703. case 1: await executeStep1(state); break;
  1704. case 2: await executeStep2(state); break;
  1705. case 3: await executeStep3(state); break;
  1706. case 4: await executeStep4(state); break;
  1707. case 5: await executeStep5(state); break;
  1708. case 6: await executeStep6(state); break;
  1709. case 7: await executeStep7(state); break;
  1710. case 8: await executeStep8(state); break;
  1711. case 9: await executeStep9(state); break;
  1712. default:
  1713. throw new Error(`未知步骤:${step}`);
  1714. }
  1715. } catch (err) {
  1716. if (isStopError(err)) {
  1717. await setStepStatus(step, 'stopped');
  1718. await addLog(`步骤 ${step} 已被用户停止`, 'warn');
  1719. throw err;
  1720. }
  1721. await setStepStatus(step, 'failed');
  1722. await addLog(`步骤 ${step} 失败:${err.message}`, 'error');
  1723. throw err;
  1724. }
  1725. }
  1726. /**
  1727. * Execute a step and wait for it to complete before returning.
  1728. * @param {number} step
  1729. * @param {number} delayAfter - ms to wait after completion (for page transitions)
  1730. */
  1731. async function executeStepAndWait(step, delayAfter = 2000) {
  1732. throwIfStopped();
  1733. if (AUTO_RUN_BACKGROUND_COMPLETED_STEPS.has(step)) {
  1734. await addLog(`自动运行:步骤 ${step} 由后台流程负责收尾,执行函数返回后将直接进入下一步。`, 'info');
  1735. await executeStep(step);
  1736. const latestState = await getState();
  1737. await addLog(`自动运行:步骤 ${step} 已执行返回,当前状态为 ${latestState.stepStatuses?.[step] || 'pending'},准备继续后续步骤。`, 'info');
  1738. } else {
  1739. await addLog(`自动运行:步骤 ${step} 已发起,正在等待完成信号(超时 ${AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS / 1000} 秒)。`, 'info');
  1740. const completionResultPromise = waitForStepComplete(step, AUTO_RUN_SIGNAL_COMPLETION_TIMEOUT_MS).then(
  1741. payload => ({ ok: true, payload }),
  1742. error => ({ ok: false, error }),
  1743. );
  1744. try {
  1745. await executeStep(step);
  1746. } catch (err) {
  1747. notifyStepError(step, getErrorMessage(err));
  1748. await completionResultPromise;
  1749. throw err;
  1750. }
  1751. const completionResult = await completionResultPromise;
  1752. if (!completionResult.ok) {
  1753. throw completionResult.error;
  1754. }
  1755. await addLog(`自动运行:步骤 ${step} 已收到完成信号,准备继续后续步骤。`, 'info');
  1756. }
  1757. // Extra delay for page transitions / DOM updates
  1758. if (delayAfter > 0) {
  1759. await sleepWithStop(delayAfter + Math.floor(Math.random() * 1200));
  1760. }
  1761. }
  1762. function getEmailGeneratorLabel(generator) {
  1763. return generator === 'cloudflare' ? 'Cloudflare 邮箱' : 'Duck 邮箱';
  1764. }
  1765. function generateCloudflareAliasLocalPart() {
  1766. const now = new Date();
  1767. const stamp = [
  1768. now.getFullYear(),
  1769. String(now.getMonth() + 1).padStart(2, '0'),
  1770. String(now.getDate()).padStart(2, '0'),
  1771. String(now.getHours()).padStart(2, '0'),
  1772. String(now.getMinutes()).padStart(2, '0'),
  1773. String(now.getSeconds()).padStart(2, '0'),
  1774. ].join('');
  1775. const randomPart = String(Math.floor(Math.random() * 900) + 100);
  1776. return `user${stamp}${randomPart}`.toLowerCase();
  1777. }
  1778. async function fetchCloudflareEmail(state, options = {}) {
  1779. throwIfStopped();
  1780. const latestState = state || await getState();
  1781. const domain = normalizeCloudflareDomain(latestState.cloudflareDomain);
  1782. if (!domain) {
  1783. throw new Error('Cloudflare 域名为空或格式无效。');
  1784. }
  1785. const localPart = String(options.localPart || '').trim().toLowerCase() || generateCloudflareAliasLocalPart();
  1786. const aliasEmail = `${localPart}@${domain}`;
  1787. await setEmailState(aliasEmail);
  1788. await addLog(`Cloudflare 邮箱:已生成 ${aliasEmail}`, 'ok');
  1789. return aliasEmail;
  1790. }
  1791. async function fetchDuckEmail(options = {}) {
  1792. throwIfStopped();
  1793. const { generateNew = true } = options;
  1794. await addLog(`Duck 邮箱:正在打开自动填充设置(${generateNew ? '生成新地址' : '复用当前地址'})...`);
  1795. await reuseOrCreateTab('duck-mail', DUCK_AUTOFILL_URL);
  1796. const result = await sendToContentScript('duck-mail', {
  1797. type: 'FETCH_DUCK_EMAIL',
  1798. source: 'background',
  1799. payload: { generateNew },
  1800. });
  1801. if (result?.error) {
  1802. throw new Error(result.error);
  1803. }
  1804. if (!result?.email) {
  1805. throw new Error('未返回 Duck 邮箱地址。');
  1806. }
  1807. await setEmailState(result.email);
  1808. await addLog(`Duck 邮箱:${result.generated ? '已生成' : '已读取'} ${result.email}`, 'ok');
  1809. return result.email;
  1810. }
  1811. async function fetchGeneratedEmail(state, options = {}) {
  1812. const currentState = state || await getState();
  1813. const generator = normalizeEmailGenerator(options.generator ?? currentState.emailGenerator);
  1814. if (generator === 'cloudflare') {
  1815. return fetchCloudflareEmail(currentState, options);
  1816. }
  1817. return fetchDuckEmail(options);
  1818. }
  1819. // ============================================================
  1820. // Auto Run Flow
  1821. // ============================================================
  1822. let autoRunActive = false;
  1823. let autoRunCurrentRun = 0;
  1824. let autoRunTotalRuns = 1;
  1825. let autoRunAttemptRun = 0;
  1826. const EMAIL_FETCH_MAX_ATTEMPTS = 5;
  1827. const VERIFICATION_POLL_MAX_ROUNDS = 5;
  1828. const AUTO_STEP_DELAYS = {
  1829. 1: 2000,
  1830. 2: 2000,
  1831. 3: 3000,
  1832. 4: 2000,
  1833. 5: 3000,
  1834. 6: 3000,
  1835. 7: 2000,
  1836. 8: 2000,
  1837. 9: 1000,
  1838. };
  1839. async function resumeAutoRunIfWaitingForEmail(options = {}) {
  1840. const { silent = false } = options;
  1841. const state = await getState();
  1842. if (!state.email || !isAutoRunPausedState(state)) {
  1843. return false;
  1844. }
  1845. if (resumeWaiter) {
  1846. if (!silent) {
  1847. await addLog('邮箱已就绪,自动继续后续步骤...', 'info');
  1848. }
  1849. resumeWaiter.resolve();
  1850. resumeWaiter = null;
  1851. return true;
  1852. }
  1853. return false;
  1854. }
  1855. async function ensureAutoEmailReady(targetRun, totalRuns, attemptRuns) {
  1856. const currentState = await getState();
  1857. if (currentState.email) {
  1858. return currentState.email;
  1859. }
  1860. const generator = normalizeEmailGenerator(currentState.emailGenerator);
  1861. const generatorLabel = getEmailGeneratorLabel(generator);
  1862. let lastError = null;
  1863. for (let attempt = 1; attempt <= EMAIL_FETCH_MAX_ATTEMPTS; attempt++) {
  1864. try {
  1865. if (attempt > 1) {
  1866. await addLog(`${generatorLabel}:正在进行第 ${attempt}/${EMAIL_FETCH_MAX_ATTEMPTS} 次自动获取重试...`, 'warn');
  1867. }
  1868. const generatedEmail = await fetchGeneratedEmail(currentState, { generateNew: true, generator });
  1869. await addLog(
  1870. `=== 目标 ${targetRun}/${totalRuns} 轮:${generatorLabel}已就绪:${generatedEmail}(第 ${attemptRuns} 次尝试,第 ${attempt}/${EMAIL_FETCH_MAX_ATTEMPTS} 次获取)===`,
  1871. 'ok'
  1872. );
  1873. return generatedEmail;
  1874. } catch (err) {
  1875. lastError = err;
  1876. await addLog(`${generatorLabel}自动获取失败(${attempt}/${EMAIL_FETCH_MAX_ATTEMPTS}):${err.message}`, 'warn');
  1877. if (generator === 'cloudflare' && /域名/.test(String(err.message || ''))) {
  1878. break;
  1879. }
  1880. }
  1881. }
  1882. await addLog(`${generatorLabel}自动获取已连续失败 ${EMAIL_FETCH_MAX_ATTEMPTS} 次:${lastError?.message || '未知错误'}`, 'error');
  1883. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮已暂停:请先自动获取邮箱或手动粘贴邮箱,然后继续 ===`, 'warn');
  1884. await broadcastAutoRunStatus('waiting_email', {
  1885. currentRun: targetRun,
  1886. totalRuns,
  1887. attemptRun: attemptRuns,
  1888. });
  1889. await waitForResume();
  1890. const resumedState = await getState();
  1891. if (!resumedState.email) {
  1892. throw new Error('无法继续:当前没有邮箱地址。');
  1893. }
  1894. return resumedState.email;
  1895. }
  1896. async function runAutoSequenceFromStep(startStep, context = {}) {
  1897. const { targetRun, totalRuns, attemptRuns, continued = false } = context;
  1898. const maxStep9RestartAttempts = 5;
  1899. let step9RestartAttempts = 0;
  1900. if (continued) {
  1901. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:继续当前进度,从步骤 ${startStep} 开始(第 ${attemptRuns} 次尝试)===`, 'info');
  1902. } else {
  1903. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:第 ${attemptRuns} 次尝试,阶段 1,获取 OAuth 链接并打开注册页 ===`, 'info');
  1904. }
  1905. if (startStep <= 2) {
  1906. for (const step of [1, 2]) {
  1907. if (step < startStep) continue;
  1908. await executeStepAndWait(step, AUTO_STEP_DELAYS[step]);
  1909. }
  1910. }
  1911. if (startStep <= 3) {
  1912. await ensureAutoEmailReady(targetRun, totalRuns, attemptRuns);
  1913. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:阶段 2,注册、验证、登录并完成授权(第 ${attemptRuns} 次尝试)===`, 'info');
  1914. await broadcastAutoRunStatus('running', {
  1915. currentRun: targetRun,
  1916. totalRuns,
  1917. attemptRun: attemptRuns,
  1918. });
  1919. await executeStepAndWait(3, AUTO_STEP_DELAYS[3]);
  1920. } else {
  1921. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:继续执行剩余流程(第 ${attemptRuns} 次尝试)===`, 'info');
  1922. }
  1923. const signupTabId = await getTabId('signup-page');
  1924. if (signupTabId) {
  1925. await chrome.tabs.update(signupTabId, { active: true });
  1926. }
  1927. let step = Math.max(startStep, 4);
  1928. while (step <= 9) {
  1929. try {
  1930. await executeStepAndWait(step, AUTO_STEP_DELAYS[step]);
  1931. step += 1;
  1932. } catch (err) {
  1933. if (step === 9 && isStep9OAuthTimeoutError(err) && step9RestartAttempts < maxStep9RestartAttempts) {
  1934. step9RestartAttempts += 1;
  1935. await addLog(
  1936. `步骤 9:检测到 OAuth callback 超时,正在回到步骤 6 重新开始授权流程(${step9RestartAttempts}/${maxStep9RestartAttempts})...`,
  1937. 'warn'
  1938. );
  1939. await invalidateDownstreamAfterStepRestart(6, {
  1940. logLabel: `步骤 9 超时后准备回到步骤 6 重试(${step9RestartAttempts}/${maxStep9RestartAttempts})`,
  1941. });
  1942. step = 6;
  1943. continue;
  1944. }
  1945. throw err;
  1946. }
  1947. }
  1948. }
  1949. // Outer loop: keep retrying until the target number of successful runs is reached.
  1950. async function autoRunLoop(totalRuns, options = {}) {
  1951. if (autoRunActive) {
  1952. await addLog('自动运行已在进行中', 'warn');
  1953. return;
  1954. }
  1955. clearStopRequest();
  1956. autoRunActive = true;
  1957. autoRunTotalRuns = totalRuns;
  1958. autoRunCurrentRun = 0;
  1959. autoRunAttemptRun = 0;
  1960. const autoRunSkipFailures = Boolean(options.autoRunSkipFailures);
  1961. const initialMode = options.mode === 'continue' ? 'continue' : 'restart';
  1962. const resumeCurrentRun = Number.isInteger(options.resumeCurrentRun) ? options.resumeCurrentRun : 0;
  1963. const resumeSuccessfulRuns = Number.isInteger(options.resumeSuccessfulRuns) ? options.resumeSuccessfulRuns : 0;
  1964. const resumeAttemptRunsProcessed = Number.isInteger(options.resumeAttemptRunsProcessed) ? options.resumeAttemptRunsProcessed : 0;
  1965. let maxAttempts = autoRunSkipFailures ? Math.max(totalRuns * 10, totalRuns + 20) : totalRuns;
  1966. const forcedRetryCap = Math.max(totalRuns * 10, totalRuns + 20);
  1967. let successfulRuns = Math.max(0, resumeSuccessfulRuns);
  1968. let attemptRuns = Math.max(0, resumeAttemptRunsProcessed);
  1969. let forceFreshTabsNextRun = false;
  1970. let continueCurrentOnFirstAttempt = initialMode === 'continue';
  1971. await setState({
  1972. autoRunSkipFailures,
  1973. ...getAutoRunStatusPayload('running', {
  1974. currentRun: resumeCurrentRun,
  1975. totalRuns,
  1976. attemptRun: resumeAttemptRunsProcessed,
  1977. }),
  1978. });
  1979. while (successfulRuns < totalRuns && attemptRuns < maxAttempts) {
  1980. attemptRuns += 1;
  1981. const targetRun = successfulRuns + 1;
  1982. autoRunCurrentRun = targetRun;
  1983. autoRunAttemptRun = attemptRuns;
  1984. let startStep = 1;
  1985. let useExistingProgress = false;
  1986. if (continueCurrentOnFirstAttempt) {
  1987. const currentState = await getState();
  1988. const resumeStep = getFirstUnfinishedStep(currentState.stepStatuses);
  1989. if (resumeStep && hasSavedProgress(currentState.stepStatuses)) {
  1990. startStep = resumeStep;
  1991. useExistingProgress = true;
  1992. } else if (hasSavedProgress(currentState.stepStatuses)) {
  1993. await addLog('当前流程已全部处理,将按“重新开始”新开一轮自动运行。', 'info');
  1994. }
  1995. continueCurrentOnFirstAttempt = false;
  1996. }
  1997. if (!useExistingProgress) {
  1998. // Reset everything at the start of each fresh attempt (keep user settings).
  1999. const prevState = await getState();
  2000. const keepSettings = {
  2001. vpsUrl: prevState.vpsUrl,
  2002. vpsPassword: prevState.vpsPassword,
  2003. customPassword: prevState.customPassword,
  2004. autoRunSkipFailures: prevState.autoRunSkipFailures,
  2005. autoRunDelayEnabled: prevState.autoRunDelayEnabled,
  2006. autoRunDelayMinutes: prevState.autoRunDelayMinutes,
  2007. mailProvider: prevState.mailProvider,
  2008. emailGenerator: prevState.emailGenerator,
  2009. inbucketHost: prevState.inbucketHost,
  2010. inbucketMailbox: prevState.inbucketMailbox,
  2011. cloudflareDomain: prevState.cloudflareDomain,
  2012. cloudflareDomains: prevState.cloudflareDomains,
  2013. ...getAutoRunStatusPayload('running', { currentRun: targetRun, totalRuns, attemptRun: attemptRuns }),
  2014. ...(forceFreshTabsNextRun ? { tabRegistry: {} } : {}),
  2015. };
  2016. await resetState();
  2017. await setState(keepSettings);
  2018. chrome.runtime.sendMessage({ type: 'AUTO_RUN_RESET' }).catch(() => { });
  2019. await sleepWithStop(500);
  2020. } else {
  2021. await setState({
  2022. autoRunSkipFailures,
  2023. ...getAutoRunStatusPayload('running', { currentRun: targetRun, totalRuns, attemptRun: attemptRuns }),
  2024. });
  2025. }
  2026. if (forceFreshTabsNextRun) {
  2027. await addLog(`兜底模式:上一轮已放弃,当前开始第 ${attemptRuns} 次尝试,将使用新线程继续补足第 ${targetRun}/${totalRuns} 轮。`, 'warn');
  2028. forceFreshTabsNextRun = false;
  2029. }
  2030. try {
  2031. throwIfStopped();
  2032. await broadcastAutoRunStatus('running', {
  2033. currentRun: targetRun,
  2034. totalRuns,
  2035. attemptRun: attemptRuns,
  2036. });
  2037. await runAutoSequenceFromStep(startStep, {
  2038. targetRun,
  2039. totalRuns,
  2040. attemptRuns,
  2041. continued: useExistingProgress,
  2042. });
  2043. successfulRuns += 1;
  2044. autoRunCurrentRun = successfulRuns;
  2045. await addLog(`=== 目标 ${successfulRuns}/${totalRuns} 轮已完成(第 ${attemptRuns} 次尝试成功)===`, 'ok');
  2046. continue;
  2047. } catch (err) {
  2048. if (isStopError(err)) {
  2049. await addLog(`目标 ${targetRun}/${totalRuns} 轮已被用户停止`, 'warn');
  2050. await broadcastAutoRunStatus('stopped', {
  2051. currentRun: targetRun,
  2052. totalRuns,
  2053. attemptRun: attemptRuns,
  2054. });
  2055. break;
  2056. }
  2057. if (isRestartCurrentAttemptError(err)) {
  2058. await addLog(`目标 ${targetRun}/${totalRuns} 轮检测到当前邮箱已存在,当前线程已放弃,将重新开始新一轮。`, 'warn');
  2059. cancelPendingCommands('当前线程因邮箱已存在而放弃。');
  2060. await broadcastStopToContentScripts();
  2061. await broadcastAutoRunStatus('retrying', {
  2062. currentRun: targetRun,
  2063. totalRuns,
  2064. attemptRun: attemptRuns,
  2065. });
  2066. forceFreshTabsNextRun = true;
  2067. maxAttempts = Math.max(maxAttempts, Math.min(forcedRetryCap, attemptRuns + 1));
  2068. continue;
  2069. }
  2070. if (!autoRunSkipFailures) {
  2071. await addLog(`目标 ${targetRun}/${totalRuns} 轮失败:${err.message}`, 'error');
  2072. await broadcastAutoRunStatus('stopped', {
  2073. currentRun: targetRun,
  2074. totalRuns,
  2075. attemptRun: attemptRuns,
  2076. });
  2077. break;
  2078. }
  2079. await addLog(`目标 ${targetRun}/${totalRuns} 轮的第 ${attemptRuns} 次尝试失败:${err.message}`, 'error');
  2080. await addLog('兜底开关已开启:将放弃当前线程,重新开一轮继续补足目标次数。', 'warn');
  2081. cancelPendingCommands('当前尝试已放弃。');
  2082. await broadcastStopToContentScripts();
  2083. await broadcastAutoRunStatus('retrying', {
  2084. currentRun: targetRun,
  2085. totalRuns,
  2086. attemptRun: attemptRuns,
  2087. });
  2088. forceFreshTabsNextRun = true;
  2089. }
  2090. }
  2091. if (!stopRequested && autoRunSkipFailures && successfulRuns < totalRuns && attemptRuns >= maxAttempts) {
  2092. await addLog(`已达到安全重试上限(${attemptRuns} 次尝试),当前仅完成 ${successfulRuns}/${totalRuns} 轮。`, 'error');
  2093. await broadcastAutoRunStatus('stopped', {
  2094. currentRun: successfulRuns,
  2095. totalRuns: autoRunTotalRuns,
  2096. attemptRun: attemptRuns,
  2097. });
  2098. } else if (stopRequested) {
  2099. await addLog(`=== 已停止,完成 ${successfulRuns}/${autoRunTotalRuns} 轮,共尝试 ${attemptRuns} 次 ===`, 'warn');
  2100. await broadcastAutoRunStatus('stopped', {
  2101. currentRun: successfulRuns,
  2102. totalRuns: autoRunTotalRuns,
  2103. attemptRun: attemptRuns,
  2104. });
  2105. } else if (successfulRuns >= autoRunTotalRuns) {
  2106. await addLog(`=== 全部 ${autoRunTotalRuns} 轮均已成功完成,共尝试 ${attemptRuns} 次 ===`, 'ok');
  2107. await broadcastAutoRunStatus('complete', {
  2108. currentRun: successfulRuns,
  2109. totalRuns: autoRunTotalRuns,
  2110. attemptRun: attemptRuns,
  2111. });
  2112. } else {
  2113. await addLog(`=== 已停止,完成 ${successfulRuns}/${autoRunTotalRuns} 轮,共尝试 ${attemptRuns} 次 ===`, 'warn');
  2114. await broadcastAutoRunStatus('stopped', {
  2115. currentRun: successfulRuns,
  2116. totalRuns: autoRunTotalRuns,
  2117. attemptRun: attemptRuns,
  2118. });
  2119. }
  2120. autoRunActive = false;
  2121. autoRunAttemptRun = attemptRuns;
  2122. await setState(getAutoRunStatusPayload(stopRequested ? 'stopped' : (successfulRuns >= autoRunTotalRuns ? 'complete' : 'stopped'), {
  2123. currentRun: successfulRuns,
  2124. totalRuns: autoRunTotalRuns,
  2125. attemptRun: attemptRuns,
  2126. }));
  2127. clearStopRequest();
  2128. }
  2129. async function waitForResume() {
  2130. throwIfStopped();
  2131. const state = await getState();
  2132. if (state.email) {
  2133. await addLog('邮箱已就绪,自动继续后续步骤...', 'info');
  2134. return;
  2135. }
  2136. return new Promise((resolve, reject) => {
  2137. resumeWaiter = { resolve, reject };
  2138. });
  2139. }
  2140. async function resumeAutoRun() {
  2141. throwIfStopped();
  2142. const state = await getState();
  2143. if (!state.email) {
  2144. await addLog('无法继续:当前没有邮箱地址,请先在侧边栏填写邮箱。', 'error');
  2145. return false;
  2146. }
  2147. const resumedInMemory = await resumeAutoRunIfWaitingForEmail({ silent: true });
  2148. if (resumedInMemory) {
  2149. return true;
  2150. }
  2151. if (!isAutoRunPausedState(state)) {
  2152. return false;
  2153. }
  2154. if (autoRunActive) {
  2155. return false;
  2156. }
  2157. const totalRuns = state.autoRunTotalRuns || 1;
  2158. const currentRun = state.autoRunCurrentRun || 1;
  2159. const attemptRun = state.autoRunAttemptRun || 1;
  2160. const successfulRuns = Math.max(0, currentRun - 1);
  2161. await addLog('检测到自动流程暂停上下文已丢失,正在从当前进度恢复自动运行...', 'warn');
  2162. autoRunLoop(totalRuns, {
  2163. autoRunSkipFailures: Boolean(state.autoRunSkipFailures),
  2164. mode: 'continue',
  2165. resumeCurrentRun: currentRun,
  2166. resumeSuccessfulRuns: successfulRuns,
  2167. resumeAttemptRunsProcessed: Math.max(0, attemptRun - 1),
  2168. });
  2169. return true;
  2170. }
  2171. // ============================================================
  2172. // Step 1: Get OAuth Link (via vps-panel.js)
  2173. // ============================================================
  2174. async function executeStep1(state) {
  2175. if (!state.vpsUrl) {
  2176. throw new Error('尚未配置 CPA 地址,请先在侧边栏填写。');
  2177. }
  2178. await addLog('步骤 1:正在打开 CPA 面板...');
  2179. const injectFiles = ['content/utils.js', 'content/vps-panel.js'];
  2180. await closeConflictingTabsForSource('vps-panel', state.vpsUrl);
  2181. const tab = await chrome.tabs.create({ url: state.vpsUrl, active: true });
  2182. const tabId = tab.id;
  2183. await rememberSourceLastUrl('vps-panel', state.vpsUrl);
  2184. await addLog('步骤 1:CPA 面板已打开,正在等待页面进入目标地址...');
  2185. const matchedTab = await waitForTabUrlFamily('vps-panel', tabId, state.vpsUrl, {
  2186. timeoutMs: 15000,
  2187. retryDelayMs: 400,
  2188. });
  2189. if (!matchedTab) {
  2190. await addLog('步骤 1:CPA 页面尚未完全进入目标地址,继续尝试连接内容脚本...', 'warn');
  2191. }
  2192. await ensureContentScriptReadyOnTab('vps-panel', tabId, {
  2193. inject: injectFiles,
  2194. timeoutMs: 45000,
  2195. retryDelayMs: 900,
  2196. logMessage: '步骤 1:CPA 面板仍在加载,正在重试连接内容脚本...',
  2197. });
  2198. const result = await sendToContentScriptResilient('vps-panel', {
  2199. type: 'EXECUTE_STEP',
  2200. step: 1,
  2201. source: 'background',
  2202. payload: { vpsPassword: state.vpsPassword },
  2203. }, {
  2204. timeoutMs: 30000,
  2205. retryDelayMs: 700,
  2206. logMessage: '步骤 1:CPA 面板通信未就绪,正在等待页面恢复...',
  2207. });
  2208. if (result?.error) {
  2209. throw new Error(result.error);
  2210. }
  2211. }
  2212. // ============================================================
  2213. // Step 2: Open Signup Page (Background opens tab, signup-page.js clicks Register)
  2214. // ============================================================
  2215. async function executeStep2(state) {
  2216. if (!state.oauthUrl) {
  2217. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  2218. }
  2219. await addLog('步骤 2:正在打开认证链接...');
  2220. await reuseOrCreateTab('signup-page', state.oauthUrl);
  2221. await sendToContentScript('signup-page', {
  2222. type: 'EXECUTE_STEP',
  2223. step: 2,
  2224. source: 'background',
  2225. payload: {},
  2226. });
  2227. }
  2228. // ============================================================
  2229. // Step 3: Fill Email & Password (via signup-page.js)
  2230. // ============================================================
  2231. async function executeStep3(state) {
  2232. if (!state.email) {
  2233. throw new Error('缺少邮箱地址,请先在侧边栏粘贴邮箱。');
  2234. }
  2235. const password = state.customPassword || generatePassword();
  2236. await setPasswordState(password);
  2237. // Save account record
  2238. const accounts = state.accounts || [];
  2239. accounts.push({ email: state.email, password, createdAt: new Date().toISOString() });
  2240. await setState({ accounts });
  2241. await addLog(
  2242. `步骤 3:正在填写邮箱 ${state.email},密码为${state.customPassword ? '自定义' : '自动生成'}(${password.length} 位)`
  2243. );
  2244. await sendToContentScript('signup-page', {
  2245. type: 'EXECUTE_STEP',
  2246. step: 3,
  2247. source: 'background',
  2248. payload: { email: state.email, password },
  2249. });
  2250. }
  2251. // ============================================================
  2252. // Step 4: Get Signup Verification Code (qq-mail.js polls, then fills in signup-page.js)
  2253. // ============================================================
  2254. function getMailConfig(state) {
  2255. const provider = state.mailProvider || 'qq';
  2256. if (provider === '163') {
  2257. 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 邮箱' };
  2258. }
  2259. if (provider === '163-vip') {
  2260. 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 邮箱' };
  2261. }
  2262. if (provider === 'inbucket') {
  2263. const host = normalizeInbucketOrigin(state.inbucketHost);
  2264. const mailbox = (state.inbucketMailbox || '').trim();
  2265. if (!host) {
  2266. return { error: 'Inbucket 主机地址为空或无效。' };
  2267. }
  2268. if (!mailbox) {
  2269. return { error: 'Inbucket 邮箱名称为空。' };
  2270. }
  2271. return {
  2272. source: 'inbucket-mail',
  2273. url: `${host}/m/${encodeURIComponent(mailbox)}/`,
  2274. label: `Inbucket 邮箱(${mailbox})`,
  2275. navigateOnReuse: true,
  2276. inject: ['content/utils.js', 'content/inbucket-mail.js'],
  2277. injectSource: 'inbucket-mail',
  2278. };
  2279. }
  2280. return { source: 'qq-mail', url: 'https://wx.mail.qq.com/', label: 'QQ 邮箱' };
  2281. }
  2282. function normalizeInbucketOrigin(rawValue) {
  2283. const value = (rawValue || '').trim();
  2284. if (!value) return '';
  2285. const candidate = /^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(value) ? value : `https://${value}`;
  2286. try {
  2287. const parsed = new URL(candidate);
  2288. return parsed.origin;
  2289. } catch {
  2290. return '';
  2291. }
  2292. }
  2293. function getVerificationCodeStateKey(step) {
  2294. return step === 4 ? 'lastSignupCode' : 'lastLoginCode';
  2295. }
  2296. function getVerificationCodeLabel(step) {
  2297. return step === 4 ? '注册' : '登录';
  2298. }
  2299. function getVerificationPollPayload(step, state, overrides = {}) {
  2300. if (step === 4) {
  2301. return {
  2302. filterAfterTimestamp: state.flowStartTime || 0,
  2303. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'duckduckgo', 'forward'],
  2304. subjectFilters: ['verify', 'verification', 'code', '楠岃瘉', 'confirm'],
  2305. targetEmail: state.email,
  2306. maxAttempts: 5,
  2307. intervalMs: 3000,
  2308. ...overrides,
  2309. };
  2310. }
  2311. return {
  2312. filterAfterTimestamp: state.lastEmailTimestamp || state.flowStartTime || 0,
  2313. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'chatgpt', 'duckduckgo', 'forward'],
  2314. subjectFilters: ['verify', 'verification', 'code', '楠岃瘉', 'confirm', 'login'],
  2315. targetEmail: state.email,
  2316. maxAttempts: 5,
  2317. intervalMs: 3000,
  2318. ...overrides,
  2319. };
  2320. }
  2321. async function requestVerificationCodeResend(step) {
  2322. const signupTabId = await getTabId('signup-page');
  2323. if (!signupTabId) {
  2324. throw new Error('认证页面标签页已关闭,无法重新请求验证码。');
  2325. }
  2326. await chrome.tabs.update(signupTabId, { active: true });
  2327. await addLog(`步骤 ${step}:正在请求新的${getVerificationCodeLabel(step)}验证码...`, 'warn');
  2328. const result = await sendToContentScript('signup-page', {
  2329. type: 'RESEND_VERIFICATION_CODE',
  2330. step,
  2331. source: 'background',
  2332. payload: {},
  2333. });
  2334. if (step === 7) {
  2335. const restartError = getStep7RestartFromStep6Error(result);
  2336. if (restartError) {
  2337. throw restartError;
  2338. }
  2339. }
  2340. if (result && result.error) {
  2341. throw new Error(result.error);
  2342. }
  2343. return Date.now();
  2344. }
  2345. async function pollFreshVerificationCode(step, state, mail, pollOverrides = {}) {
  2346. const stateKey = getVerificationCodeStateKey(step);
  2347. const rejectedCodes = new Set();
  2348. if (state[stateKey]) {
  2349. rejectedCodes.add(state[stateKey]);
  2350. }
  2351. for (const code of (pollOverrides.excludeCodes || [])) {
  2352. if (code) rejectedCodes.add(code);
  2353. }
  2354. let lastError = null;
  2355. const filterAfterTimestamp = pollOverrides.filterAfterTimestamp ?? getVerificationPollPayload(step, state).filterAfterTimestamp;
  2356. const maxRounds = pollOverrides.maxRounds || VERIFICATION_POLL_MAX_ROUNDS;
  2357. for (let round = 1; round <= maxRounds; round++) {
  2358. if (round > 1) {
  2359. await requestVerificationCodeResend(step);
  2360. }
  2361. const payload = getVerificationPollPayload(step, state, {
  2362. ...pollOverrides,
  2363. filterAfterTimestamp,
  2364. excludeCodes: [...rejectedCodes],
  2365. });
  2366. try {
  2367. const result = await sendToMailContentScriptResilient(
  2368. mail,
  2369. {
  2370. type: 'POLL_EMAIL',
  2371. step,
  2372. source: 'background',
  2373. payload,
  2374. },
  2375. {
  2376. timeoutMs: 45000,
  2377. maxRecoveryAttempts: 2,
  2378. }
  2379. );
  2380. if (result && result.error) {
  2381. throw new Error(result.error);
  2382. }
  2383. if (!result || !result.code) {
  2384. throw new Error(`步骤 ${step}:邮箱轮询结束,但未获取到验证码。`);
  2385. }
  2386. if (rejectedCodes.has(result.code)) {
  2387. throw new Error(`步骤 ${step}:再次收到了相同的${getVerificationCodeLabel(step)}验证码:${result.code}`);
  2388. }
  2389. return result;
  2390. } catch (err) {
  2391. lastError = err;
  2392. await addLog(`步骤 ${step}:${err.message}`, 'warn');
  2393. if (round < maxRounds) {
  2394. await addLog(`步骤 ${step}:将重新发送验证码后重试(${round + 1}/${maxRounds})...`, 'warn');
  2395. }
  2396. }
  2397. }
  2398. throw lastError || new Error(`步骤 ${step}:无法获取新的${getVerificationCodeLabel(step)}验证码。`);
  2399. }
  2400. async function submitVerificationCode(step, code) {
  2401. const signupTabId = await getTabId('signup-page');
  2402. if (!signupTabId) {
  2403. throw new Error('认证页面标签页已关闭,无法填写验证码。');
  2404. }
  2405. await chrome.tabs.update(signupTabId, { active: true });
  2406. const result = await sendToContentScript('signup-page', {
  2407. type: 'FILL_CODE',
  2408. step,
  2409. source: 'background',
  2410. payload: { code },
  2411. });
  2412. if (step === 7) {
  2413. const restartError = getStep7RestartFromStep6Error(result);
  2414. if (restartError) {
  2415. throw restartError;
  2416. }
  2417. }
  2418. if (result && result.error) {
  2419. throw new Error(result.error);
  2420. }
  2421. return result || {};
  2422. }
  2423. async function resolveVerificationStep(step, state, mail, options = {}) {
  2424. const stateKey = getVerificationCodeStateKey(step);
  2425. const rejectedCodes = new Set();
  2426. if (state[stateKey]) {
  2427. rejectedCodes.add(state[stateKey]);
  2428. }
  2429. const nextFilterAfterTimestamp = options.filterAfterTimestamp ?? null;
  2430. const requestFreshCodeFirst = Boolean(options.requestFreshCodeFirst);
  2431. const maxSubmitAttempts = 3;
  2432. if (requestFreshCodeFirst) {
  2433. try {
  2434. await requestVerificationCodeResend(step);
  2435. await addLog(`步骤 ${step}:已先请求一封新的${getVerificationCodeLabel(step)}验证码,再开始轮询邮箱。`, 'warn');
  2436. } catch (err) {
  2437. if (step === 7 && isStep7RestartFromStep6Error(err)) {
  2438. throw err;
  2439. }
  2440. await addLog(`步骤 ${step}:首次重新获取验证码失败:${err.message},将继续使用当前时间窗口轮询。`, 'warn');
  2441. }
  2442. }
  2443. for (let attempt = 1; attempt <= maxSubmitAttempts; attempt++) {
  2444. const result = await pollFreshVerificationCode(step, state, mail, {
  2445. excludeCodes: [...rejectedCodes],
  2446. filterAfterTimestamp: nextFilterAfterTimestamp ?? undefined,
  2447. });
  2448. await addLog(`步骤 ${step}:已获取${getVerificationCodeLabel(step)}验证码:${result.code}`);
  2449. const submitResult = await submitVerificationCode(step, result.code);
  2450. if (submitResult.invalidCode) {
  2451. rejectedCodes.add(result.code);
  2452. await addLog(`步骤 ${step}:验证码被页面拒绝:${submitResult.errorText || result.code}`, 'warn');
  2453. if (attempt >= maxSubmitAttempts) {
  2454. throw new Error(`步骤 ${step}:验证码连续失败,已达到 ${maxSubmitAttempts} 次重试上限。`);
  2455. }
  2456. await requestVerificationCodeResend(step);
  2457. await addLog(`步骤 ${step}:提交失败后已请求新验证码(${attempt + 1}/${maxSubmitAttempts})...`, 'warn');
  2458. continue;
  2459. }
  2460. await setState({
  2461. lastEmailTimestamp: result.emailTimestamp,
  2462. [stateKey]: result.code,
  2463. });
  2464. await completeStepFromBackground(step, {
  2465. emailTimestamp: result.emailTimestamp,
  2466. code: result.code,
  2467. });
  2468. return;
  2469. }
  2470. }
  2471. async function executeStep4(state) {
  2472. const mail = getMailConfig(state);
  2473. if (mail.error) throw new Error(mail.error);
  2474. const stepStartedAt = Date.now();
  2475. const signupTabId = await getTabId('signup-page');
  2476. if (!signupTabId) {
  2477. throw new Error('认证页面标签页已关闭,无法继续步骤 4。');
  2478. }
  2479. await chrome.tabs.update(signupTabId, { active: true });
  2480. await addLog('步骤 4:正在确认注册验证码页面是否就绪,必要时自动恢复密码页超时报错...');
  2481. const prepareResult = await sendToContentScriptResilient(
  2482. 'signup-page',
  2483. {
  2484. type: 'PREPARE_SIGNUP_VERIFICATION',
  2485. step: 4,
  2486. source: 'background',
  2487. payload: { password: state.password || state.customPassword || '' },
  2488. },
  2489. {
  2490. timeoutMs: 30000,
  2491. retryDelayMs: 700,
  2492. logMessage: '步骤 4:认证页正在切换,等待页面重新就绪后继续检测...',
  2493. }
  2494. );
  2495. if (prepareResult && prepareResult.error) {
  2496. throw new Error(prepareResult.error);
  2497. }
  2498. if (prepareResult?.alreadyVerified) {
  2499. await completeStepFromBackground(4, {});
  2500. return;
  2501. }
  2502. await addLog(`步骤 4:正在打开${mail.label}...`);
  2503. // For mail tabs, only create if not alive — don't navigate (preserves login session)
  2504. const alive = await isTabAlive(mail.source);
  2505. if (alive) {
  2506. if (mail.navigateOnReuse) {
  2507. await reuseOrCreateTab(mail.source, mail.url, {
  2508. inject: mail.inject,
  2509. injectSource: mail.injectSource,
  2510. });
  2511. } else {
  2512. const tabId = await getTabId(mail.source);
  2513. await chrome.tabs.update(tabId, { active: true });
  2514. }
  2515. } else {
  2516. await reuseOrCreateTab(mail.source, mail.url, {
  2517. inject: mail.inject,
  2518. injectSource: mail.injectSource,
  2519. });
  2520. }
  2521. await resolveVerificationStep(4, state, mail, {
  2522. filterAfterTimestamp: stepStartedAt,
  2523. requestFreshCodeFirst: true,
  2524. });
  2525. return;
  2526. }
  2527. // ============================================================
  2528. // Step 5: Fill Name & Birthday (via signup-page.js)
  2529. // ============================================================
  2530. async function executeStep5(state) {
  2531. const { firstName, lastName } = generateRandomName();
  2532. const { year, month, day } = generateRandomBirthday();
  2533. await addLog(`步骤 5:已生成姓名 ${firstName} ${lastName},生日 ${year}-${month}-${day}`);
  2534. await sendToContentScript('signup-page', {
  2535. type: 'EXECUTE_STEP',
  2536. step: 5,
  2537. source: 'background',
  2538. payload: { firstName, lastName, year, month, day },
  2539. });
  2540. }
  2541. // ============================================================
  2542. // Step 6: Login ChatGPT (Background opens tab, chatgpt.js handles login)
  2543. // ============================================================
  2544. async function refreshOAuthUrlBeforeStep6(state) {
  2545. if (!state.vpsUrl) {
  2546. throw new Error('尚未配置 CPA 地址,请先在侧边栏填写。');
  2547. }
  2548. await addLog('步骤 6:正在刷新登录用的 CPA OAuth 链接...');
  2549. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] preparing fresh OAuth via step 1');
  2550. const waitForFreshOAuth = waitForStepComplete(1, 120000);
  2551. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] executing step 1 for fresh OAuth');
  2552. await executeStep1(state);
  2553. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] step 1 execute returned, waiting for completion signal');
  2554. await waitForFreshOAuth;
  2555. console.log(LOG_PREFIX, '[refreshOAuthUrlBeforeStep6] step 1 completion signal received');
  2556. const latestState = await getState();
  2557. if (!latestState.oauthUrl) {
  2558. throw new Error('刷新 OAuth 链接后仍未拿到可用链接。');
  2559. }
  2560. return latestState.oauthUrl;
  2561. }
  2562. async function executeStep6(state) {
  2563. if (!state.email) {
  2564. throw new Error('缺少邮箱地址,请先完成步骤 3。');
  2565. }
  2566. const oauthUrl = await refreshOAuthUrlBeforeStep6(state);
  2567. await addLog('步骤 6:正在打开最新 OAuth 链接并登录...');
  2568. // Reuse the signup-page tab — navigate it to the OAuth URL
  2569. await reuseOrCreateTab('signup-page', oauthUrl);
  2570. // signup-page.js will inject (same auth.openai.com domain) and handle login
  2571. await sendToContentScript('signup-page', {
  2572. type: 'EXECUTE_STEP',
  2573. step: 6,
  2574. source: 'background',
  2575. payload: { email: state.email, password: state.password },
  2576. });
  2577. }
  2578. // ============================================================
  2579. // Step 7: Get Login Verification Code (qq-mail.js polls, then fills in chatgpt.js)
  2580. // ============================================================
  2581. async function runStep7Attempt(state) {
  2582. const mail = getMailConfig(state);
  2583. if (mail.error) throw new Error(mail.error);
  2584. const stepStartedAt = Date.now();
  2585. const authTabId = await getTabId('signup-page');
  2586. if (authTabId) {
  2587. await chrome.tabs.update(authTabId, { active: true });
  2588. } else {
  2589. if (!state.oauthUrl) {
  2590. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  2591. }
  2592. await reuseOrCreateTab('signup-page', state.oauthUrl);
  2593. }
  2594. await addLog('步骤 7:正在准备认证页,必要时切换到一次性验证码登录...');
  2595. const prepareResult = await sendToContentScript('signup-page', {
  2596. type: 'PREPARE_LOGIN_CODE',
  2597. step: 7,
  2598. source: 'background',
  2599. payload: {},
  2600. });
  2601. const restartError = getStep7RestartFromStep6Error(prepareResult);
  2602. if (restartError) {
  2603. throw restartError;
  2604. }
  2605. if (prepareResult && prepareResult.error) {
  2606. throw new Error(prepareResult.error);
  2607. }
  2608. await addLog(`步骤 7:正在打开${mail.label}...`);
  2609. const alive = await isTabAlive(mail.source);
  2610. if (alive) {
  2611. if (mail.navigateOnReuse) {
  2612. await reuseOrCreateTab(mail.source, mail.url, {
  2613. inject: mail.inject,
  2614. injectSource: mail.injectSource,
  2615. });
  2616. } else {
  2617. const tabId = await getTabId(mail.source);
  2618. await chrome.tabs.update(tabId, { active: true });
  2619. }
  2620. } else {
  2621. await reuseOrCreateTab(mail.source, mail.url, {
  2622. inject: mail.inject,
  2623. injectSource: mail.injectSource,
  2624. });
  2625. }
  2626. await resolveVerificationStep(7, state, mail, {
  2627. filterAfterTimestamp: stepStartedAt,
  2628. requestFreshCodeFirst: true,
  2629. });
  2630. }
  2631. async function rerunStep6ForStep7Recovery() {
  2632. const currentState = await getState();
  2633. const waitForStep6 = waitForStepComplete(6, 120000);
  2634. await addLog('步骤 7:正在回到步骤 6,重新发起登录验证码流程...', 'warn');
  2635. await executeStep6(currentState);
  2636. await waitForStep6;
  2637. await sleepWithStop(3000);
  2638. }
  2639. async function executeStep7(state) {
  2640. let lastError = null;
  2641. for (let round = 1; round <= STEP7_RESTART_MAX_ROUNDS; round++) {
  2642. const currentState = round === 1 ? state : await getState();
  2643. try {
  2644. if (round > 1) {
  2645. await addLog(`步骤 7:正在进行第 ${round}/${STEP7_RESTART_MAX_ROUNDS} 轮登录验证码恢复尝试。`, 'warn');
  2646. }
  2647. await runStep7Attempt(currentState);
  2648. return;
  2649. } catch (err) {
  2650. lastError = err;
  2651. if (!isStep7RecoverableError(err)) {
  2652. throw err;
  2653. }
  2654. if (round >= STEP7_RESTART_MAX_ROUNDS) {
  2655. break;
  2656. }
  2657. await addLog(
  2658. isStep7RestartFromStep6Error(err)
  2659. ? `步骤 7:检测到登录页超时报错,准备从步骤 6 重新开始(${round + 1}/${STEP7_RESTART_MAX_ROUNDS})...`
  2660. : `步骤 7:检测到邮箱轮询类失败,准备从步骤 6 重新开始(${round + 1}/${STEP7_RESTART_MAX_ROUNDS})...`,
  2661. 'warn'
  2662. );
  2663. await rerunStep6ForStep7Recovery();
  2664. }
  2665. }
  2666. if (lastError && isStep7RecoverableError(lastError)) {
  2667. throw new Error(`步骤 7:登录验证码流程在 ${STEP7_RESTART_MAX_ROUNDS} 轮恢复后仍未成功。最后一次原因:${lastError.message}`);
  2668. }
  2669. throw lastError || new Error(`步骤 7:登录验证码流程在 ${STEP7_RESTART_MAX_ROUNDS} 轮后仍未成功。`);
  2670. }
  2671. // ============================================================
  2672. // Step 8: 完成 OAuth(自动点击 + localhost 回调监听)
  2673. // ============================================================
  2674. let webNavListener = null;
  2675. let webNavCommittedListener = null;
  2676. let step8TabUpdatedListener = null;
  2677. let step8PendingReject = null;
  2678. const STEP8_CLICK_EFFECT_TIMEOUT_MS = 10000;
  2679. const STEP8_CLICK_RETRY_DELAY_MS = 500;
  2680. const STEP8_READY_WAIT_TIMEOUT_MS = 30000;
  2681. const STEP8_MAX_ROUNDS = 5;
  2682. const STEP8_SIGNUP_PAGE_INJECT_FILES = ['content/utils.js', 'content/signup-page.js'];
  2683. const STEP8_STRATEGIES = [
  2684. { mode: 'content', strategy: 'requestSubmit', label: 'form.requestSubmit' },
  2685. { mode: 'debugger', label: 'debugger click' },
  2686. { mode: 'content', strategy: 'nativeClick', label: 'element.click' },
  2687. { mode: 'content', strategy: 'dispatchClick', label: 'dispatch click' },
  2688. { mode: 'debugger', label: 'debugger click retry' },
  2689. ];
  2690. function cleanupStep8NavigationListeners() {
  2691. if (webNavListener) {
  2692. chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
  2693. webNavListener = null;
  2694. }
  2695. if (webNavCommittedListener) {
  2696. chrome.webNavigation.onCommitted.removeListener(webNavCommittedListener);
  2697. webNavCommittedListener = null;
  2698. }
  2699. if (step8TabUpdatedListener) {
  2700. chrome.tabs.onUpdated.removeListener(step8TabUpdatedListener);
  2701. step8TabUpdatedListener = null;
  2702. }
  2703. }
  2704. function rejectPendingStep8(error) {
  2705. if (!step8PendingReject) return;
  2706. const reject = step8PendingReject;
  2707. step8PendingReject = null;
  2708. reject(error);
  2709. }
  2710. function throwIfStep8SettledOrStopped(isSettled = false) {
  2711. if (isSettled || stopRequested) {
  2712. throw new Error(STOP_ERROR_MESSAGE);
  2713. }
  2714. }
  2715. async function ensureStep8SignupPageReady(tabId, options = {}) {
  2716. await ensureContentScriptReadyOnTab('signup-page', tabId, {
  2717. inject: STEP8_SIGNUP_PAGE_INJECT_FILES,
  2718. injectSource: 'signup-page',
  2719. timeoutMs: options.timeoutMs ?? 15000,
  2720. retryDelayMs: options.retryDelayMs ?? 600,
  2721. logMessage: options.logMessage || '',
  2722. });
  2723. }
  2724. async function getStep8PageState(tabId, responseTimeoutMs = 1500) {
  2725. try {
  2726. const result = await sendTabMessageWithTimeout(tabId, 'signup-page', {
  2727. type: 'STEP8_GET_STATE',
  2728. source: 'background',
  2729. payload: {},
  2730. }, responseTimeoutMs);
  2731. if (result?.error) {
  2732. throw new Error(result.error);
  2733. }
  2734. return result;
  2735. } catch (err) {
  2736. if (isRetryableContentScriptTransportError(err)) {
  2737. return null;
  2738. }
  2739. throw err;
  2740. }
  2741. }
  2742. async function waitForStep8Ready(tabId, timeoutMs = STEP8_READY_WAIT_TIMEOUT_MS) {
  2743. const start = Date.now();
  2744. let recovered = false;
  2745. while (Date.now() - start < timeoutMs) {
  2746. throwIfStopped();
  2747. const pageState = await getStep8PageState(tabId);
  2748. if (pageState?.addPhonePage) {
  2749. throw new Error('步骤 8:认证页进入了手机号页面,当前不是 OAuth 同意页,无法继续自动授权。');
  2750. }
  2751. if (pageState?.consentReady) {
  2752. return pageState;
  2753. }
  2754. if (pageState === null && !recovered) {
  2755. recovered = true;
  2756. await ensureStep8SignupPageReady(tabId, {
  2757. timeoutMs: Math.min(10000, timeoutMs),
  2758. logMessage: '步骤 8:认证页内容脚本已失联,正在等待页面重新就绪...',
  2759. });
  2760. continue;
  2761. }
  2762. recovered = false;
  2763. await sleepWithStop(250);
  2764. }
  2765. throw new Error('步骤 8:长时间未进入 OAuth 同意页,无法定位“继续”按钮。');
  2766. }
  2767. async function prepareStep8DebuggerClick(tabId) {
  2768. await ensureStep8SignupPageReady(tabId, {
  2769. timeoutMs: 15000,
  2770. logMessage: '步骤 8:认证页内容脚本已失联,正在恢复后继续定位按钮...',
  2771. });
  2772. const result = await sendToContentScriptResilient('signup-page', {
  2773. type: 'STEP8_FIND_AND_CLICK',
  2774. source: 'background',
  2775. payload: {},
  2776. }, {
  2777. timeoutMs: 15000,
  2778. retryDelayMs: 600,
  2779. logMessage: '步骤 8:认证页正在切换,等待 OAuth 同意页按钮重新就绪...',
  2780. });
  2781. if (result?.error) {
  2782. throw new Error(result.error);
  2783. }
  2784. return result;
  2785. }
  2786. async function triggerStep8ContentStrategy(tabId, strategy) {
  2787. await ensureStep8SignupPageReady(tabId, {
  2788. timeoutMs: 15000,
  2789. logMessage: '步骤 8:认证页内容脚本已失联,正在恢复后继续点击“继续”按钮...',
  2790. });
  2791. const result = await sendToContentScriptResilient('signup-page', {
  2792. type: 'STEP8_TRIGGER_CONTINUE',
  2793. source: 'background',
  2794. payload: {
  2795. strategy,
  2796. findTimeoutMs: 4000,
  2797. enabledTimeoutMs: 3000,
  2798. },
  2799. }, {
  2800. timeoutMs: 15000,
  2801. retryDelayMs: 600,
  2802. logMessage: '步骤 8:认证页正在切换,等待“继续”按钮重新就绪...',
  2803. });
  2804. if (result?.error) {
  2805. throw new Error(result.error);
  2806. }
  2807. return result;
  2808. }
  2809. async function reloadStep8ConsentPage(tabId, timeoutMs = 30000) {
  2810. if (!Number.isInteger(tabId)) {
  2811. throw new Error('步骤 8:缺少有效的认证页标签页,无法刷新后重试。');
  2812. }
  2813. await chrome.tabs.update(tabId, { active: true }).catch(() => { });
  2814. await new Promise((resolve, reject) => {
  2815. let settled = false;
  2816. const timer = setTimeout(() => {
  2817. if (settled) return;
  2818. settled = true;
  2819. chrome.tabs.onUpdated.removeListener(listener);
  2820. reject(new Error('步骤 8:刷新认证页后等待页面完成加载超时。'));
  2821. }, timeoutMs);
  2822. const listener = (updatedTabId, changeInfo) => {
  2823. if (updatedTabId !== tabId) return;
  2824. if (changeInfo.status !== 'complete') return;
  2825. if (settled) return;
  2826. settled = true;
  2827. clearTimeout(timer);
  2828. chrome.tabs.onUpdated.removeListener(listener);
  2829. resolve();
  2830. };
  2831. chrome.tabs.onUpdated.addListener(listener);
  2832. chrome.tabs.reload(tabId, { bypassCache: false }).catch((err) => {
  2833. if (settled) return;
  2834. settled = true;
  2835. clearTimeout(timer);
  2836. chrome.tabs.onUpdated.removeListener(listener);
  2837. reject(err);
  2838. });
  2839. });
  2840. await ensureStep8SignupPageReady(tabId, {
  2841. timeoutMs: Math.min(15000, timeoutMs),
  2842. logMessage: '步骤 8:认证页刷新后内容脚本尚未就绪,正在等待页面恢复...',
  2843. });
  2844. }
  2845. async function waitForStep8ClickEffect(tabId, baselineUrl, timeoutMs = STEP8_CLICK_EFFECT_TIMEOUT_MS) {
  2846. const start = Date.now();
  2847. let recovered = false;
  2848. while (Date.now() - start < timeoutMs) {
  2849. throwIfStopped();
  2850. const tab = await chrome.tabs.get(tabId).catch(() => null);
  2851. if (!tab) {
  2852. throw new Error('步骤 8:认证页面标签页已关闭,无法继续自动授权。');
  2853. }
  2854. if (baselineUrl && typeof tab.url === 'string' && tab.url !== baselineUrl) {
  2855. return { progressed: true, reason: 'url_changed', url: tab.url };
  2856. }
  2857. const pageState = await getStep8PageState(tabId);
  2858. if (pageState?.addPhonePage) {
  2859. throw new Error('步骤 8:点击“继续”后页面跳到了手机号页面,当前流程无法继续自动授权。');
  2860. }
  2861. if (pageState === null) {
  2862. if (!recovered) {
  2863. recovered = true;
  2864. await ensureStep8SignupPageReady(tabId, {
  2865. timeoutMs: Math.max(3000, Math.min(8000, timeoutMs)),
  2866. logMessage: '步骤 8:点击后认证页正在重载,正在等待内容脚本重新就绪...',
  2867. }).catch(() => null);
  2868. continue;
  2869. }
  2870. await sleepWithStop(200);
  2871. continue;
  2872. }
  2873. recovered = false;
  2874. await sleepWithStop(200);
  2875. }
  2876. return { progressed: false, reason: 'no_effect' };
  2877. }
  2878. function getStep8EffectLabel(effect) {
  2879. switch (effect?.reason) {
  2880. case 'url_changed':
  2881. return `URL 已变化:${effect.url}`;
  2882. case 'page_reloading':
  2883. return '页面正在跳转或重载';
  2884. case 'left_consent_page':
  2885. return `页面已离开 OAuth 同意页:${effect.url || 'unknown'}`;
  2886. default:
  2887. return '页面仍停留在 OAuth 同意页';
  2888. }
  2889. }
  2890. async function executeStep8(state) {
  2891. if (!state.oauthUrl) {
  2892. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  2893. }
  2894. await addLog('步骤 8:正在监听 localhost 回调地址...');
  2895. return new Promise((resolve, reject) => {
  2896. let resolved = false;
  2897. let signupTabId = null;
  2898. const cleanupListener = () => {
  2899. cleanupStep8NavigationListeners();
  2900. step8PendingReject = null;
  2901. };
  2902. const rejectStep8 = (error) => {
  2903. if (resolved) return;
  2904. resolved = true;
  2905. clearTimeout(timeout);
  2906. cleanupListener();
  2907. reject(error);
  2908. };
  2909. const finalizeStep8Callback = (callbackUrl) => {
  2910. if (resolved || !callbackUrl) return;
  2911. resolved = true;
  2912. cleanupListener();
  2913. clearTimeout(timeout);
  2914. addLog(`步骤 8:已捕获 localhost 地址:${callbackUrl}`, 'ok').then(() => {
  2915. return completeStepFromBackground(8, { localhostUrl: callbackUrl });
  2916. }).then(() => {
  2917. resolve();
  2918. }).catch((err) => {
  2919. reject(err);
  2920. });
  2921. };
  2922. const timeout = setTimeout(() => {
  2923. rejectStep8(new Error('120 秒内未捕获到 localhost 回调跳转,步骤 8 的点击可能被拦截了。'));
  2924. }, 120000);
  2925. step8PendingReject = (error) => {
  2926. rejectStep8(error);
  2927. };
  2928. webNavListener = (details) => {
  2929. const callbackUrl = getStep8CallbackUrlFromNavigation(details, signupTabId);
  2930. finalizeStep8Callback(callbackUrl);
  2931. };
  2932. webNavCommittedListener = (details) => {
  2933. const callbackUrl = getStep8CallbackUrlFromNavigation(details, signupTabId);
  2934. finalizeStep8Callback(callbackUrl);
  2935. };
  2936. step8TabUpdatedListener = (tabId, changeInfo, tab) => {
  2937. const callbackUrl = getStep8CallbackUrlFromTabUpdate(tabId, changeInfo, tab, signupTabId);
  2938. finalizeStep8Callback(callbackUrl);
  2939. };
  2940. (async () => {
  2941. try {
  2942. throwIfStep8SettledOrStopped(resolved);
  2943. signupTabId = await getTabId('signup-page');
  2944. throwIfStep8SettledOrStopped(resolved);
  2945. if (signupTabId && await isTabAlive('signup-page')) {
  2946. await chrome.tabs.update(signupTabId, { active: true });
  2947. await addLog('步骤 8:已切回认证页,正在准备调试器点击...');
  2948. } else {
  2949. signupTabId = await reuseOrCreateTab('signup-page', state.oauthUrl);
  2950. await addLog('步骤 8:已重新打开认证页,正在准备调试器点击...');
  2951. }
  2952. throwIfStep8SettledOrStopped(resolved);
  2953. chrome.webNavigation.onBeforeNavigate.addListener(webNavListener);
  2954. chrome.webNavigation.onCommitted.addListener(webNavCommittedListener);
  2955. chrome.tabs.onUpdated.addListener(step8TabUpdatedListener);
  2956. await ensureStep8SignupPageReady(signupTabId, {
  2957. timeoutMs: 15000,
  2958. logMessage: '步骤 8:认证页内容脚本尚未就绪,正在等待页面恢复...',
  2959. });
  2960. for (let round = 1; round <= STEP8_MAX_ROUNDS && !resolved; round++) {
  2961. throwIfStep8SettledOrStopped(resolved);
  2962. const pageState = await waitForStep8Ready(signupTabId);
  2963. if (!pageState?.consentReady) {
  2964. await sleepWithStop(STEP8_CLICK_RETRY_DELAY_MS);
  2965. continue;
  2966. }
  2967. const strategy = STEP8_STRATEGIES[Math.min(round - 1, STEP8_STRATEGIES.length - 1)];
  2968. await addLog(`步骤 8:第 ${round}/${STEP8_MAX_ROUNDS} 轮尝试点击“继续”(${strategy.label})...`);
  2969. if (strategy.mode === 'debugger') {
  2970. const clickTarget = await prepareStep8DebuggerClick(signupTabId);
  2971. throwIfStep8SettledOrStopped(resolved);
  2972. await clickWithDebugger(signupTabId, clickTarget?.rect);
  2973. } else {
  2974. await triggerStep8ContentStrategy(signupTabId, strategy.strategy);
  2975. }
  2976. if (resolved) {
  2977. return;
  2978. }
  2979. const effect = await waitForStep8ClickEffect(signupTabId, pageState.url);
  2980. if (resolved) {
  2981. return;
  2982. }
  2983. if (effect.progressed) {
  2984. await addLog(`步骤 8:检测到本次点击已生效,${getStep8EffectLabel(effect)},继续等待 localhost 回调...`, 'info');
  2985. break;
  2986. }
  2987. if (round >= STEP8_MAX_ROUNDS) {
  2988. throw new Error(`步骤 8:连续 ${STEP8_MAX_ROUNDS} 轮点击“继续”后页面仍无反应。`);
  2989. }
  2990. await addLog(`步骤 8:${strategy.label} 本轮点击后页面无反应,正在刷新认证页后重试(下一轮 ${round + 1}/${STEP8_MAX_ROUNDS})...`, 'warn');
  2991. await reloadStep8ConsentPage(signupTabId);
  2992. await sleepWithStop(STEP8_CLICK_RETRY_DELAY_MS);
  2993. }
  2994. } catch (err) {
  2995. rejectStep8(err);
  2996. }
  2997. })();
  2998. });
  2999. }
  3000. // ============================================================
  3001. // Step 9: CPA 回调验证(通过 vps-panel.js)
  3002. // ============================================================
  3003. async function executeStep9(state) {
  3004. if (state.localhostUrl && !isLocalhostOAuthCallbackUrl(state.localhostUrl)) {
  3005. throw new Error('步骤 8 捕获到的 localhost OAuth 回调地址无效,请重新执行步骤 8。');
  3006. }
  3007. if (!state.localhostUrl) {
  3008. throw new Error('缺少 localhost 回调地址,请先完成步骤 8。');
  3009. }
  3010. if (!state.vpsUrl) {
  3011. throw new Error('尚未填写 CPA 地址,请先在侧边栏输入。');
  3012. }
  3013. if (shouldBypassStep9ForLocalCpa(state)) {
  3014. await addLog('步骤 9:检测到本地 CPA,步骤 8 完成后已自动添加,无需重复提交回调地址。', 'info');
  3015. await completeStepFromBackground(9, {
  3016. localhostUrl: state.localhostUrl,
  3017. verifiedStatus: 'local-auto',
  3018. });
  3019. return;
  3020. }
  3021. await addLog('步骤 9:正在打开 CPA 面板...');
  3022. const injectFiles = ['content/utils.js', 'content/vps-panel.js'];
  3023. let tabId = await getTabId('vps-panel');
  3024. const alive = tabId && await isTabAlive('vps-panel');
  3025. if (!alive) {
  3026. tabId = await reuseOrCreateTab('vps-panel', state.vpsUrl, {
  3027. inject: injectFiles,
  3028. reloadIfSameUrl: true,
  3029. });
  3030. } else {
  3031. await closeConflictingTabsForSource('vps-panel', state.vpsUrl, { excludeTabIds: [tabId] });
  3032. await chrome.tabs.update(tabId, { active: true });
  3033. await rememberSourceLastUrl('vps-panel', state.vpsUrl);
  3034. }
  3035. await ensureContentScriptReadyOnTab('vps-panel', tabId, {
  3036. inject: injectFiles,
  3037. });
  3038. await addLog('步骤 9:正在填写回调地址...');
  3039. const result = await sendToContentScriptResilient('vps-panel', {
  3040. type: 'EXECUTE_STEP',
  3041. step: 9,
  3042. source: 'background',
  3043. payload: { localhostUrl: state.localhostUrl, vpsPassword: state.vpsPassword },
  3044. }, {
  3045. timeoutMs: 30000,
  3046. retryDelayMs: 700,
  3047. logMessage: '步骤 9:CPA 面板通信未就绪,正在等待页面恢复...',
  3048. });
  3049. if (result?.error) {
  3050. throw new Error(result.error);
  3051. }
  3052. }
  3053. // ============================================================
  3054. // Open Side Panel on extension icon click
  3055. // ============================================================
  3056. chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });
  3057. chrome.alarms.onAlarm.addListener((alarm) => {
  3058. if (alarm.name !== AUTO_RUN_ALARM_NAME) {
  3059. return;
  3060. }
  3061. launchScheduledAutoRun('alarm').catch((err) => {
  3062. console.error(LOG_PREFIX, 'Failed to launch scheduled auto run from alarm:', err);
  3063. });
  3064. });
  3065. chrome.runtime.onStartup.addListener(() => {
  3066. restoreScheduledAutoRunIfNeeded().catch((err) => {
  3067. console.error(LOG_PREFIX, 'Failed to restore scheduled auto run on startup:', err);
  3068. });
  3069. });
  3070. chrome.runtime.onInstalled.addListener(() => {
  3071. restoreScheduledAutoRunIfNeeded().catch((err) => {
  3072. console.error(LOG_PREFIX, 'Failed to restore scheduled auto run on install/update:', err);
  3073. });
  3074. });
  3075. restoreScheduledAutoRunIfNeeded().catch((err) => {
  3076. console.error(LOG_PREFIX, 'Failed to restore scheduled auto run:', err);
  3077. });