background.js 104 KB

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