background.js 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850
  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. initializeSessionStorageAccess();
  9. // ============================================================
  10. // State Management (chrome.storage.session)
  11. // ============================================================
  12. const DEFAULT_STATE = {
  13. currentStep: 0,
  14. stepStatuses: {
  15. 1: 'pending', 2: 'pending', 3: 'pending', 4: 'pending', 5: 'pending',
  16. 6: 'pending', 7: 'pending', 8: 'pending', 9: 'pending',
  17. },
  18. oauthUrl: null,
  19. email: null,
  20. password: null,
  21. accounts: [], // { email, password, createdAt }
  22. lastEmailTimestamp: null,
  23. lastSignupCode: null,
  24. lastLoginCode: null,
  25. localhostUrl: null,
  26. flowStartTime: null,
  27. tabRegistry: {},
  28. logs: [],
  29. vpsUrl: '',
  30. vpsPassword: '',
  31. customPassword: '',
  32. autoRunSkipFailures: false,
  33. autoRunning: false,
  34. autoRunPhase: 'idle',
  35. autoRunCurrentRun: 0,
  36. autoRunTotalRuns: 1,
  37. autoRunAttemptRun: 0,
  38. mailProvider: '163', // 'qq' or '163'
  39. inbucketHost: '',
  40. inbucketMailbox: '',
  41. };
  42. async function getState() {
  43. const state = await chrome.storage.session.get(null);
  44. return { ...DEFAULT_STATE, ...state };
  45. }
  46. async function initializeSessionStorageAccess() {
  47. try {
  48. if (chrome.storage?.session?.setAccessLevel) {
  49. await chrome.storage.session.setAccessLevel({
  50. accessLevel: 'TRUSTED_AND_UNTRUSTED_CONTEXTS',
  51. });
  52. console.log(LOG_PREFIX, 'Enabled storage.session for content scripts');
  53. }
  54. } catch (err) {
  55. console.warn(LOG_PREFIX, 'Failed to enable storage.session for content scripts:', err?.message || err);
  56. }
  57. }
  58. async function setState(updates) {
  59. console.log(LOG_PREFIX, 'storage.set:', JSON.stringify(updates).slice(0, 200));
  60. await chrome.storage.session.set(updates);
  61. }
  62. function broadcastDataUpdate(payload) {
  63. chrome.runtime.sendMessage({
  64. type: 'DATA_UPDATED',
  65. payload,
  66. }).catch(() => {});
  67. }
  68. async function setEmailState(email) {
  69. await setState({ email });
  70. broadcastDataUpdate({ email });
  71. }
  72. async function setPasswordState(password) {
  73. await setState({ password });
  74. broadcastDataUpdate({ password });
  75. }
  76. async function resetState() {
  77. console.log(LOG_PREFIX, 'Resetting all state');
  78. // Preserve settings and persistent data across resets
  79. const prev = await chrome.storage.session.get([
  80. 'seenCodes',
  81. 'seenInbucketMailIds',
  82. 'accounts',
  83. 'tabRegistry',
  84. 'vpsUrl',
  85. 'vpsPassword',
  86. 'customPassword',
  87. 'autoRunSkipFailures',
  88. 'mailProvider',
  89. 'inbucketHost',
  90. 'inbucketMailbox',
  91. ]);
  92. await chrome.storage.session.clear();
  93. await chrome.storage.session.set({
  94. ...DEFAULT_STATE,
  95. seenCodes: prev.seenCodes || [],
  96. seenInbucketMailIds: prev.seenInbucketMailIds || [],
  97. accounts: prev.accounts || [],
  98. tabRegistry: prev.tabRegistry || {},
  99. vpsUrl: prev.vpsUrl || '',
  100. vpsPassword: prev.vpsPassword || '',
  101. customPassword: prev.customPassword || '',
  102. autoRunSkipFailures: Boolean(prev.autoRunSkipFailures),
  103. mailProvider: prev.mailProvider || '163',
  104. inbucketHost: prev.inbucketHost || '',
  105. inbucketMailbox: prev.inbucketMailbox || '',
  106. });
  107. }
  108. /**
  109. * Generate a random password: 14 chars, mix of uppercase, lowercase, digits, symbols.
  110. */
  111. function generatePassword() {
  112. const upper = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
  113. const lower = 'abcdefghjkmnpqrstuvwxyz';
  114. const digits = '23456789';
  115. const symbols = '!@#$%&*?';
  116. const all = upper + lower + digits + symbols;
  117. // Ensure at least one of each type
  118. let pw = '';
  119. pw += upper[Math.floor(Math.random() * upper.length)];
  120. pw += lower[Math.floor(Math.random() * lower.length)];
  121. pw += digits[Math.floor(Math.random() * digits.length)];
  122. pw += symbols[Math.floor(Math.random() * symbols.length)];
  123. // Fill remaining 10 chars
  124. for (let i = 0; i < 10; i++) {
  125. pw += all[Math.floor(Math.random() * all.length)];
  126. }
  127. // Shuffle
  128. return pw.split('').sort(() => Math.random() - 0.5).join('');
  129. }
  130. // ============================================================
  131. // Tab Registry
  132. // ============================================================
  133. async function getTabRegistry() {
  134. const state = await getState();
  135. return state.tabRegistry || {};
  136. }
  137. async function registerTab(source, tabId) {
  138. const registry = await getTabRegistry();
  139. registry[source] = { tabId, ready: true };
  140. await setState({ tabRegistry: registry });
  141. console.log(LOG_PREFIX, `Tab registered: ${source} -> ${tabId}`);
  142. }
  143. async function isTabAlive(source) {
  144. const registry = await getTabRegistry();
  145. const entry = registry[source];
  146. if (!entry) return false;
  147. try {
  148. await chrome.tabs.get(entry.tabId);
  149. return true;
  150. } catch {
  151. // Tab no longer exists — clean up registry
  152. registry[source] = null;
  153. await setState({ tabRegistry: registry });
  154. return false;
  155. }
  156. }
  157. async function getTabId(source) {
  158. const registry = await getTabRegistry();
  159. return registry[source]?.tabId || null;
  160. }
  161. // ============================================================
  162. // Command Queue (for content scripts not yet ready)
  163. // ============================================================
  164. const pendingCommands = new Map(); // source -> { message, resolve, reject, timer }
  165. function queueCommand(source, message, timeout = 15000) {
  166. return new Promise((resolve, reject) => {
  167. const timer = setTimeout(() => {
  168. pendingCommands.delete(source);
  169. const err = `Content script on ${source} did not respond in ${timeout / 1000}s. Try refreshing the tab and retry.`;
  170. console.error(LOG_PREFIX, err);
  171. reject(new Error(err));
  172. }, timeout);
  173. pendingCommands.set(source, { message, resolve, reject, timer });
  174. console.log(LOG_PREFIX, `Command queued for ${source} (waiting for ready)`);
  175. });
  176. }
  177. function flushCommand(source, tabId) {
  178. const pending = pendingCommands.get(source);
  179. if (pending) {
  180. clearTimeout(pending.timer);
  181. pendingCommands.delete(source);
  182. chrome.tabs.sendMessage(tabId, pending.message).then(pending.resolve).catch(pending.reject);
  183. console.log(LOG_PREFIX, `Flushed queued command to ${source} (tab ${tabId})`);
  184. }
  185. }
  186. function cancelPendingCommands(reason = STOP_ERROR_MESSAGE) {
  187. for (const [source, pending] of pendingCommands.entries()) {
  188. clearTimeout(pending.timer);
  189. pending.reject(new Error(reason));
  190. pendingCommands.delete(source);
  191. console.log(LOG_PREFIX, `Cancelled queued command for ${source}`);
  192. }
  193. }
  194. // ============================================================
  195. // Reuse or create tab
  196. // ============================================================
  197. async function reuseOrCreateTab(source, url, options = {}) {
  198. const alive = await isTabAlive(source);
  199. if (alive) {
  200. const tabId = await getTabId(source);
  201. const currentTab = await chrome.tabs.get(tabId);
  202. const sameUrl = currentTab.url === url;
  203. const shouldReloadOnReuse = sameUrl && options.reloadIfSameUrl;
  204. const registry = await getTabRegistry();
  205. if (sameUrl) {
  206. await chrome.tabs.update(tabId, { active: true });
  207. console.log(LOG_PREFIX, `Reused tab ${source} (${tabId}) on same URL`);
  208. if (shouldReloadOnReuse) {
  209. if (registry[source]) registry[source].ready = false;
  210. await setState({ tabRegistry: registry });
  211. await chrome.tabs.reload(tabId);
  212. await new Promise((resolve) => {
  213. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  214. const listener = (tid, info) => {
  215. if (tid === tabId && info.status === 'complete') {
  216. chrome.tabs.onUpdated.removeListener(listener);
  217. clearTimeout(timer);
  218. resolve();
  219. }
  220. };
  221. chrome.tabs.onUpdated.addListener(listener);
  222. });
  223. }
  224. // For dynamically injected pages like the VPS panel, re-inject immediately.
  225. if (options.inject) {
  226. if (registry[source]) registry[source].ready = false;
  227. await setState({ tabRegistry: registry });
  228. if (options.injectSource) {
  229. await chrome.scripting.executeScript({
  230. target: { tabId },
  231. func: (injectedSource) => {
  232. window.__MULTIPAGE_SOURCE = injectedSource;
  233. },
  234. args: [options.injectSource],
  235. });
  236. }
  237. await chrome.scripting.executeScript({
  238. target: { tabId },
  239. files: options.inject,
  240. });
  241. await new Promise(r => setTimeout(r, 500));
  242. }
  243. return tabId;
  244. }
  245. // Mark as not ready BEFORE navigating — so READY signal from new page is captured correctly
  246. if (registry[source]) registry[source].ready = false;
  247. await setState({ tabRegistry: registry });
  248. // Navigate existing tab to new URL
  249. await chrome.tabs.update(tabId, { url, active: true });
  250. console.log(LOG_PREFIX, `Reused tab ${source} (${tabId}), navigated to ${url.slice(0, 60)}`);
  251. // Wait for page load complete (with 30s timeout)
  252. await new Promise((resolve) => {
  253. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  254. const listener = (tid, info) => {
  255. if (tid === tabId && info.status === 'complete') {
  256. chrome.tabs.onUpdated.removeListener(listener);
  257. clearTimeout(timer);
  258. resolve();
  259. }
  260. };
  261. chrome.tabs.onUpdated.addListener(listener);
  262. });
  263. // If dynamic injection needed (VPS panel), re-inject after navigation
  264. if (options.inject) {
  265. if (options.injectSource) {
  266. await chrome.scripting.executeScript({
  267. target: { tabId },
  268. func: (injectedSource) => {
  269. window.__MULTIPAGE_SOURCE = injectedSource;
  270. },
  271. args: [options.injectSource],
  272. });
  273. }
  274. await chrome.scripting.executeScript({
  275. target: { tabId },
  276. files: options.inject,
  277. });
  278. }
  279. // Wait a bit for content script to inject and send READY
  280. await new Promise(r => setTimeout(r, 500));
  281. return tabId;
  282. }
  283. // Create new tab
  284. const tab = await chrome.tabs.create({ url, active: true });
  285. console.log(LOG_PREFIX, `Created new tab ${source} (${tab.id})`);
  286. // If dynamic injection needed (VPS panel), inject scripts after load
  287. if (options.inject) {
  288. await new Promise((resolve) => {
  289. const timer = setTimeout(() => { chrome.tabs.onUpdated.removeListener(listener); resolve(); }, 30000);
  290. const listener = (tabId, info) => {
  291. if (tabId === tab.id && info.status === 'complete') {
  292. chrome.tabs.onUpdated.removeListener(listener);
  293. clearTimeout(timer);
  294. resolve();
  295. }
  296. };
  297. chrome.tabs.onUpdated.addListener(listener);
  298. });
  299. if (options.injectSource) {
  300. await chrome.scripting.executeScript({
  301. target: { tabId: tab.id },
  302. func: (injectedSource) => {
  303. window.__MULTIPAGE_SOURCE = injectedSource;
  304. },
  305. args: [options.injectSource],
  306. });
  307. }
  308. await chrome.scripting.executeScript({
  309. target: { tabId: tab.id },
  310. files: options.inject,
  311. });
  312. }
  313. return tab.id;
  314. }
  315. // ============================================================
  316. // Send command to content script (with readiness check)
  317. // ============================================================
  318. async function sendToContentScript(source, message) {
  319. const registry = await getTabRegistry();
  320. const entry = registry[source];
  321. if (!entry || !entry.ready) {
  322. console.log(LOG_PREFIX, `${source} not ready, queuing command`);
  323. return queueCommand(source, message);
  324. }
  325. // Verify tab is still alive
  326. const alive = await isTabAlive(source);
  327. if (!alive) {
  328. // Tab was closed — queue the command, it will be sent when tab is reopened
  329. console.log(LOG_PREFIX, `${source} tab was closed, queuing command`);
  330. return queueCommand(source, message);
  331. }
  332. console.log(LOG_PREFIX, `Sending to ${source} (tab ${entry.tabId}):`, message.type);
  333. return chrome.tabs.sendMessage(entry.tabId, message);
  334. }
  335. // ============================================================
  336. // Logging
  337. // ============================================================
  338. async function addLog(message, level = 'info') {
  339. const state = await getState();
  340. const logs = state.logs || [];
  341. const entry = { message, level, timestamp: Date.now() };
  342. logs.push(entry);
  343. // Keep last 500 logs
  344. if (logs.length > 500) logs.splice(0, logs.length - 500);
  345. await setState({ logs });
  346. // Broadcast to side panel
  347. chrome.runtime.sendMessage({ type: 'LOG_ENTRY', payload: entry }).catch(() => {});
  348. }
  349. function getSourceLabel(source) {
  350. const labels = {
  351. 'sidepanel': '侧边栏',
  352. 'signup-page': '认证页',
  353. 'vps-panel': 'VPS 面板',
  354. 'qq-mail': 'QQ 邮箱',
  355. 'mail-163': '163 邮箱',
  356. 'inbucket-mail': 'Inbucket 邮箱',
  357. 'duck-mail': 'Duck 邮箱',
  358. };
  359. return labels[source] || source || '未知来源';
  360. }
  361. // ============================================================
  362. // Step Status Management
  363. // ============================================================
  364. async function setStepStatus(step, status) {
  365. const state = await getState();
  366. const statuses = { ...state.stepStatuses };
  367. statuses[step] = status;
  368. await setState({ stepStatuses: statuses, currentStep: step });
  369. // Broadcast to side panel
  370. chrome.runtime.sendMessage({
  371. type: 'STEP_STATUS_CHANGED',
  372. payload: { step, status },
  373. }).catch(() => {});
  374. }
  375. function isStopError(error) {
  376. const message = typeof error === 'string' ? error : error?.message;
  377. return message === STOP_ERROR_MESSAGE;
  378. }
  379. function isStepDoneStatus(status) {
  380. return status === 'completed' || status === 'manual_completed';
  381. }
  382. function clearStopRequest() {
  383. stopRequested = false;
  384. }
  385. function getAutoRunStatusPayload(phase, payload = {}) {
  386. const currentRun = payload.currentRun ?? autoRunCurrentRun;
  387. const totalRuns = payload.totalRuns ?? autoRunTotalRuns;
  388. const attemptRun = payload.attemptRun ?? autoRunAttemptRun;
  389. const autoRunning = phase === 'running' || phase === 'waiting_email' || phase === 'retrying';
  390. return {
  391. autoRunning,
  392. autoRunPhase: phase,
  393. autoRunCurrentRun: currentRun,
  394. autoRunTotalRuns: totalRuns,
  395. autoRunAttemptRun: attemptRun,
  396. };
  397. }
  398. async function broadcastAutoRunStatus(phase, payload = {}) {
  399. const statusPayload = {
  400. phase,
  401. currentRun: payload.currentRun ?? autoRunCurrentRun,
  402. totalRuns: payload.totalRuns ?? autoRunTotalRuns,
  403. attemptRun: payload.attemptRun ?? autoRunAttemptRun,
  404. };
  405. await setState(getAutoRunStatusPayload(phase, statusPayload));
  406. chrome.runtime.sendMessage({
  407. type: 'AUTO_RUN_STATUS',
  408. payload: statusPayload,
  409. }).catch(() => {});
  410. }
  411. function isAutoRunLockedState(state) {
  412. return Boolean(state.autoRunning) && (state.autoRunPhase === 'running' || state.autoRunPhase === 'retrying');
  413. }
  414. function isAutoRunPausedState(state) {
  415. return Boolean(state.autoRunning) && state.autoRunPhase === 'waiting_email';
  416. }
  417. async function ensureManualInteractionAllowed(actionLabel) {
  418. const state = await getState();
  419. if (isAutoRunLockedState(state)) {
  420. throw new Error(`自动流程运行中,请先停止后再${actionLabel}。`);
  421. }
  422. if (isAutoRunPausedState(state)) {
  423. throw new Error(`自动流程当前已暂停。请点击“继续”,或先确认接管自动流程后再${actionLabel}。`);
  424. }
  425. return state;
  426. }
  427. async function getSignupManualCompletionState() {
  428. const signupTabId = await getTabId('signup-page');
  429. if (!signupTabId) {
  430. throw new Error('认证页标签页不存在,请先打开认证页并手动完成相应操作。');
  431. }
  432. const result = await sendToContentScript('signup-page', {
  433. type: 'GET_MANUAL_COMPLETION_STATE',
  434. source: 'background',
  435. payload: {},
  436. });
  437. if (result?.error) {
  438. throw new Error(result.error);
  439. }
  440. return result || {};
  441. }
  442. function ensureKnownPassword(state, step) {
  443. const resolvedPassword = state.password || state.customPassword;
  444. if (!resolvedPassword) {
  445. throw new Error(`步骤 ${step} 需要已知密码,请先在侧边栏填写固定密码后再手动同步。`);
  446. }
  447. return resolvedPassword;
  448. }
  449. async function validateManualStepCompletion(step, state) {
  450. switch (step) {
  451. case 2: {
  452. const authState = await getSignupManualCompletionState();
  453. if (!['credentials', 'verification', 'profile', 'add_phone', 'consent'].includes(authState.stage)) {
  454. throw new Error(`认证页当前还没有进入注册流程后续页面,不能将步骤 2 标记为手动完成。当前状态:${authState.summary || authState.stage || '未知'}`);
  455. }
  456. return {};
  457. }
  458. case 3: {
  459. if (!state.email) {
  460. throw new Error('步骤 3 需要邮箱地址,请先在侧边栏填写邮箱。');
  461. }
  462. const password = ensureKnownPassword(state, 3);
  463. const authState = await getSignupManualCompletionState();
  464. if (!['verification', 'profile', 'add_phone', 'consent'].includes(authState.stage)) {
  465. throw new Error(`认证页当前还没有离开邮箱/密码页面,不能将步骤 3 标记为手动完成。当前状态:${authState.summary || authState.stage || '未知'}`);
  466. }
  467. return state.password ? {} : { stateUpdates: { password } };
  468. }
  469. case 4: {
  470. const authState = await getSignupManualCompletionState();
  471. if (!['profile', 'add_phone', 'consent'].includes(authState.stage)) {
  472. throw new Error(`认证页当前还没有进入验证码后的下一阶段,不能将步骤 4 标记为手动完成。当前状态:${authState.summary || authState.stage || '未知'}`);
  473. }
  474. return {};
  475. }
  476. case 5: {
  477. const authState = await getSignupManualCompletionState();
  478. if (!['add_phone', 'consent'].includes(authState.stage)) {
  479. throw new Error(`认证页当前还没有离开姓名/生日页面,不能将步骤 5 标记为手动完成。当前状态:${authState.summary || authState.stage || '未知'}`);
  480. }
  481. return {};
  482. }
  483. case 6: {
  484. if (!state.email) {
  485. throw new Error('步骤 6 需要已知邮箱地址,请先在侧边栏填写邮箱。');
  486. }
  487. const authState = await getSignupManualCompletionState();
  488. if (!['verification', 'add_phone', 'consent'].includes(authState.stage)) {
  489. throw new Error(`认证页当前还没有进入登录后的下一阶段,不能将步骤 6 标记为手动完成。当前状态:${authState.summary || authState.stage || '未知'}`);
  490. }
  491. return {};
  492. }
  493. case 7: {
  494. const authState = await getSignupManualCompletionState();
  495. if (!['add_phone', 'consent'].includes(authState.stage)) {
  496. throw new Error(`认证页当前还没有离开登录验证码页面,不能将步骤 7 标记为手动完成。当前状态:${authState.summary || authState.stage || '未知'}`);
  497. }
  498. return {};
  499. }
  500. case 8: {
  501. if (!state.localhostUrl) {
  502. throw new Error('尚未捕获 localhost 回调地址,不能将步骤 8 标记为手动完成。');
  503. }
  504. return {};
  505. }
  506. default:
  507. throw new Error(`步骤 ${step} 不支持手动完成同步。`);
  508. }
  509. }
  510. async function markStepManualComplete(step) {
  511. const state = await ensureManualInteractionAllowed('手动同步步骤');
  512. if (!Number.isInteger(step) || step < 1 || step > 9) {
  513. throw new Error(`无效步骤:${step}`);
  514. }
  515. if (step === 1 || step === 9) {
  516. throw new Error(`步骤 ${step} 不支持手动完成同步。`);
  517. }
  518. const statuses = { ...(state.stepStatuses || {}) };
  519. const currentStatus = statuses[step];
  520. if (currentStatus === 'running') {
  521. throw new Error(`步骤 ${step} 正在运行中,不能手动同步。`);
  522. }
  523. if (isStepDoneStatus(currentStatus)) {
  524. throw new Error(`步骤 ${step} 已完成,无需再手动同步。`);
  525. }
  526. if (step > 1) {
  527. const prevStatus = statuses[step - 1];
  528. if (!isStepDoneStatus(prevStatus)) {
  529. throw new Error(`请先完成步骤 ${step - 1},再同步步骤 ${step}。`);
  530. }
  531. }
  532. const validation = await validateManualStepCompletion(step, state);
  533. if (validation?.stateUpdates) {
  534. await setState(validation.stateUpdates);
  535. }
  536. await setStepStatus(step, 'manual_completed');
  537. await addLog(`步骤 ${step} 已标记为手动完成`, 'warn');
  538. return { ok: true, step, status: 'manual_completed' };
  539. }
  540. function throwIfStopped() {
  541. if (stopRequested) {
  542. throw new Error(STOP_ERROR_MESSAGE);
  543. }
  544. }
  545. async function sleepWithStop(ms) {
  546. const start = Date.now();
  547. while (Date.now() - start < ms) {
  548. throwIfStopped();
  549. await new Promise(r => setTimeout(r, Math.min(100, ms - (Date.now() - start))));
  550. }
  551. }
  552. async function humanStepDelay(min = HUMAN_STEP_DELAY_MIN, max = HUMAN_STEP_DELAY_MAX) {
  553. const duration = Math.floor(Math.random() * (max - min + 1)) + min;
  554. await sleepWithStop(duration);
  555. }
  556. async function clickWithDebugger(tabId, rect) {
  557. if (!tabId) {
  558. throw new Error('未找到用于调试点击的认证页面标签页。');
  559. }
  560. if (!rect || !Number.isFinite(rect.centerX) || !Number.isFinite(rect.centerY)) {
  561. throw new Error('步骤 8 的调试器兜底点击需要有效的按钮坐标。');
  562. }
  563. const target = { tabId };
  564. try {
  565. await chrome.debugger.attach(target, '1.3');
  566. } catch (err) {
  567. throw new Error(
  568. `步骤 8 的调试器兜底点击附加失败:${err.message}。` +
  569. '如果认证页标签已打开 DevTools,请先关闭后重试。'
  570. );
  571. }
  572. try {
  573. const x = Math.round(rect.centerX);
  574. const y = Math.round(rect.centerY);
  575. await chrome.debugger.sendCommand(target, 'Page.bringToFront');
  576. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  577. type: 'mouseMoved',
  578. x,
  579. y,
  580. button: 'none',
  581. buttons: 0,
  582. clickCount: 0,
  583. });
  584. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  585. type: 'mousePressed',
  586. x,
  587. y,
  588. button: 'left',
  589. buttons: 1,
  590. clickCount: 1,
  591. });
  592. await chrome.debugger.sendCommand(target, 'Input.dispatchMouseEvent', {
  593. type: 'mouseReleased',
  594. x,
  595. y,
  596. button: 'left',
  597. buttons: 0,
  598. clickCount: 1,
  599. });
  600. } finally {
  601. await chrome.debugger.detach(target).catch(() => {});
  602. }
  603. }
  604. async function broadcastStopToContentScripts() {
  605. const registry = await getTabRegistry();
  606. for (const entry of Object.values(registry)) {
  607. if (!entry?.tabId) continue;
  608. try {
  609. await chrome.tabs.sendMessage(entry.tabId, {
  610. type: 'STOP_FLOW',
  611. source: 'background',
  612. payload: {},
  613. });
  614. } catch {}
  615. }
  616. }
  617. let stopRequested = false;
  618. // ============================================================
  619. // Message Handler (central router)
  620. // ============================================================
  621. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  622. console.log(LOG_PREFIX, `Received: ${message.type} from ${message.source || 'sidepanel'}`, message);
  623. handleMessage(message, sender).then(response => {
  624. sendResponse(response);
  625. }).catch(err => {
  626. console.error(LOG_PREFIX, 'Handler error:', err);
  627. sendResponse({ error: err.message });
  628. });
  629. return true; // async response
  630. });
  631. async function handleMessage(message, sender) {
  632. switch (message.type) {
  633. case 'CONTENT_SCRIPT_READY': {
  634. const tabId = sender.tab?.id;
  635. if (tabId && message.source) {
  636. await registerTab(message.source, tabId);
  637. flushCommand(message.source, tabId);
  638. await addLog(`内容脚本已就绪:${getSourceLabel(message.source)}(标签页 ${tabId})`);
  639. }
  640. return { ok: true };
  641. }
  642. case 'LOG': {
  643. const { message: msg, level } = message.payload;
  644. await addLog(`[${getSourceLabel(message.source)}] ${msg}`, level);
  645. return { ok: true };
  646. }
  647. case 'STEP_COMPLETE': {
  648. if (stopRequested) {
  649. await setStepStatus(message.step, 'stopped');
  650. notifyStepError(message.step, STOP_ERROR_MESSAGE);
  651. return { ok: true };
  652. }
  653. await setStepStatus(message.step, 'completed');
  654. await addLog(`步骤 ${message.step} 已完成`, 'ok');
  655. await handleStepData(message.step, message.payload);
  656. notifyStepComplete(message.step, message.payload);
  657. return { ok: true };
  658. }
  659. case 'STEP_ERROR': {
  660. if (isStopError(message.error)) {
  661. await setStepStatus(message.step, 'stopped');
  662. await addLog(`步骤 ${message.step} 已被用户停止`, 'warn');
  663. notifyStepError(message.step, message.error);
  664. } else {
  665. await setStepStatus(message.step, 'failed');
  666. await addLog(`步骤 ${message.step} 失败:${message.error}`, 'error');
  667. notifyStepError(message.step, message.error);
  668. }
  669. return { ok: true };
  670. }
  671. case 'GET_STATE': {
  672. return await getState();
  673. }
  674. case 'RESET': {
  675. clearStopRequest();
  676. await resetState();
  677. await addLog('流程已重置', 'info');
  678. return { ok: true };
  679. }
  680. case 'EXECUTE_STEP': {
  681. clearStopRequest();
  682. if (message.source === 'sidepanel') {
  683. await ensureManualInteractionAllowed('手动执行步骤');
  684. }
  685. const step = message.payload.step;
  686. // Save email if provided (from side panel step 3)
  687. if (message.payload.email) {
  688. await setEmailState(message.payload.email);
  689. }
  690. await executeStep(step);
  691. return { ok: true };
  692. }
  693. case 'AUTO_RUN': {
  694. clearStopRequest();
  695. const totalRuns = message.payload?.totalRuns || 1;
  696. const autoRunSkipFailures = Boolean(message.payload?.autoRunSkipFailures);
  697. await setState({ autoRunSkipFailures });
  698. autoRunLoop(totalRuns, { autoRunSkipFailures }); // fire-and-forget
  699. return { ok: true };
  700. }
  701. case 'RESUME_AUTO_RUN': {
  702. clearStopRequest();
  703. if (message.payload.email) {
  704. await setEmailState(message.payload.email);
  705. }
  706. resumeAutoRun(); // fire-and-forget
  707. return { ok: true };
  708. }
  709. case 'TAKEOVER_AUTO_RUN': {
  710. await requestStop({ logMessage: '已确认手动接管,正在停止自动流程并切换为手动控制...' });
  711. await addLog('自动流程已切换为手动控制。', 'warn');
  712. return { ok: true };
  713. }
  714. case 'MARK_STEP_MANUAL_COMPLETE': {
  715. const step = Number(message.payload?.step);
  716. return await markStepManualComplete(step);
  717. }
  718. case 'SAVE_SETTING': {
  719. const updates = {};
  720. if (message.payload.vpsUrl !== undefined) updates.vpsUrl = message.payload.vpsUrl;
  721. if (message.payload.vpsPassword !== undefined) updates.vpsPassword = message.payload.vpsPassword;
  722. if (message.payload.customPassword !== undefined) updates.customPassword = message.payload.customPassword;
  723. if (message.payload.autoRunSkipFailures !== undefined) updates.autoRunSkipFailures = Boolean(message.payload.autoRunSkipFailures);
  724. if (message.payload.mailProvider !== undefined) updates.mailProvider = message.payload.mailProvider;
  725. if (message.payload.inbucketHost !== undefined) updates.inbucketHost = message.payload.inbucketHost;
  726. if (message.payload.inbucketMailbox !== undefined) updates.inbucketMailbox = message.payload.inbucketMailbox;
  727. await setState(updates);
  728. return { ok: true };
  729. }
  730. // Side panel data updates
  731. case 'SAVE_EMAIL': {
  732. const state = await getState();
  733. if (isAutoRunLockedState(state)) {
  734. throw new Error('自动流程运行中,当前不能手动修改邮箱。');
  735. }
  736. await setEmailState(message.payload.email);
  737. return { ok: true, email: message.payload.email };
  738. }
  739. case 'FETCH_DUCK_EMAIL': {
  740. clearStopRequest();
  741. const state = await getState();
  742. if (isAutoRunLockedState(state)) {
  743. throw new Error('自动流程运行中,当前不能手动获取 Duck 邮箱。');
  744. }
  745. const email = await fetchDuckEmail(message.payload || {});
  746. return { ok: true, email };
  747. }
  748. case 'STOP_FLOW': {
  749. await requestStop();
  750. return { ok: true };
  751. }
  752. default:
  753. console.warn(LOG_PREFIX, `Unknown message type: ${message.type}`);
  754. return { error: `Unknown message type: ${message.type}` };
  755. }
  756. }
  757. // ============================================================
  758. // Step Data Handlers
  759. // ============================================================
  760. async function handleStepData(step, payload) {
  761. switch (step) {
  762. case 1:
  763. if (payload.oauthUrl) {
  764. await setState({ oauthUrl: payload.oauthUrl });
  765. broadcastDataUpdate({ oauthUrl: payload.oauthUrl });
  766. }
  767. break;
  768. case 3:
  769. if (payload.email) await setEmailState(payload.email);
  770. break;
  771. case 4:
  772. if (payload.emailTimestamp) await setState({ lastEmailTimestamp: payload.emailTimestamp });
  773. break;
  774. case 8:
  775. if (payload.localhostUrl) {
  776. await setState({ localhostUrl: payload.localhostUrl });
  777. broadcastDataUpdate({ localhostUrl: payload.localhostUrl });
  778. }
  779. break;
  780. }
  781. }
  782. // ============================================================
  783. // Step Completion Waiting
  784. // ============================================================
  785. // Map of step -> { resolve, reject } for waiting on step completion
  786. const stepWaiters = new Map();
  787. let resumeWaiter = null;
  788. function waitForStepComplete(step, timeoutMs = 120000) {
  789. return new Promise((resolve, reject) => {
  790. throwIfStopped();
  791. const timer = setTimeout(() => {
  792. stepWaiters.delete(step);
  793. reject(new Error(`Step ${step} timed out after ${timeoutMs / 1000}s`));
  794. }, timeoutMs);
  795. stepWaiters.set(step, {
  796. resolve: (data) => { clearTimeout(timer); stepWaiters.delete(step); resolve(data); },
  797. reject: (err) => { clearTimeout(timer); stepWaiters.delete(step); reject(err); },
  798. });
  799. });
  800. }
  801. function notifyStepComplete(step, payload) {
  802. const waiter = stepWaiters.get(step);
  803. if (waiter) waiter.resolve(payload);
  804. }
  805. function notifyStepError(step, error) {
  806. const waiter = stepWaiters.get(step);
  807. if (waiter) waiter.reject(new Error(error));
  808. }
  809. async function completeStepFromBackground(step, payload = {}) {
  810. if (stopRequested) {
  811. await setStepStatus(step, 'stopped');
  812. notifyStepError(step, STOP_ERROR_MESSAGE);
  813. return;
  814. }
  815. await setStepStatus(step, 'completed');
  816. await addLog(`步骤 ${step} 已完成`, 'ok');
  817. await handleStepData(step, payload);
  818. notifyStepComplete(step, payload);
  819. }
  820. async function markRunningStepsStopped() {
  821. const state = await getState();
  822. const runningSteps = Object.entries(state.stepStatuses || {})
  823. .filter(([, status]) => status === 'running')
  824. .map(([step]) => Number(step));
  825. for (const step of runningSteps) {
  826. await setStepStatus(step, 'stopped');
  827. }
  828. }
  829. async function requestStop(options = {}) {
  830. const { logMessage = '已收到停止请求,正在取消当前操作...' } = options;
  831. if (stopRequested) return;
  832. stopRequested = true;
  833. cancelPendingCommands();
  834. if (webNavListener) {
  835. chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
  836. webNavListener = null;
  837. }
  838. await addLog(logMessage, 'warn');
  839. await broadcastStopToContentScripts();
  840. for (const waiter of stepWaiters.values()) {
  841. waiter.reject(new Error(STOP_ERROR_MESSAGE));
  842. }
  843. stepWaiters.clear();
  844. if (resumeWaiter) {
  845. resumeWaiter.reject(new Error(STOP_ERROR_MESSAGE));
  846. resumeWaiter = null;
  847. }
  848. await markRunningStepsStopped();
  849. autoRunActive = false;
  850. await broadcastAutoRunStatus('stopped', {
  851. currentRun: autoRunCurrentRun,
  852. totalRuns: autoRunTotalRuns,
  853. attemptRun: autoRunAttemptRun,
  854. });
  855. }
  856. // ============================================================
  857. // Step Execution
  858. // ============================================================
  859. async function executeStep(step) {
  860. console.log(LOG_PREFIX, `Executing step ${step}`);
  861. throwIfStopped();
  862. await setStepStatus(step, 'running');
  863. await addLog(`步骤 ${step} 开始执行`);
  864. await humanStepDelay();
  865. const state = await getState();
  866. // Set flow start time on first step
  867. if (step === 1 && !state.flowStartTime) {
  868. await setState({ flowStartTime: Date.now() });
  869. }
  870. try {
  871. switch (step) {
  872. case 1: await executeStep1(state); break;
  873. case 2: await executeStep2(state); break;
  874. case 3: await executeStep3(state); break;
  875. case 4: await executeStep4(state); break;
  876. case 5: await executeStep5(state); break;
  877. case 6: await executeStep6(state); break;
  878. case 7: await executeStep7(state); break;
  879. case 8: await executeStep8(state); break;
  880. case 9: await executeStep9(state); break;
  881. default:
  882. throw new Error(`未知步骤:${step}`);
  883. }
  884. } catch (err) {
  885. if (isStopError(err)) {
  886. await setStepStatus(step, 'stopped');
  887. await addLog(`步骤 ${step} 已被用户停止`, 'warn');
  888. throw err;
  889. }
  890. await setStepStatus(step, 'failed');
  891. await addLog(`步骤 ${step} 失败:${err.message}`, 'error');
  892. throw err;
  893. }
  894. }
  895. /**
  896. * Execute a step and wait for it to complete before returning.
  897. * @param {number} step
  898. * @param {number} delayAfter - ms to wait after completion (for page transitions)
  899. */
  900. async function executeStepAndWait(step, delayAfter = 2000) {
  901. throwIfStopped();
  902. const promise = waitForStepComplete(step, 120000);
  903. await executeStep(step);
  904. await promise;
  905. // Extra delay for page transitions / DOM updates
  906. if (delayAfter > 0) {
  907. await sleepWithStop(delayAfter + Math.floor(Math.random() * 1200));
  908. }
  909. }
  910. async function fetchDuckEmail(options = {}) {
  911. throwIfStopped();
  912. const { generateNew = true } = options;
  913. await addLog(`Duck 邮箱:正在打开自动填充设置(${generateNew ? '生成新地址' : '复用当前地址'})...`);
  914. await reuseOrCreateTab('duck-mail', DUCK_AUTOFILL_URL);
  915. const result = await sendToContentScript('duck-mail', {
  916. type: 'FETCH_DUCK_EMAIL',
  917. source: 'background',
  918. payload: { generateNew },
  919. });
  920. if (result?.error) {
  921. throw new Error(result.error);
  922. }
  923. if (!result?.email) {
  924. throw new Error('未返回 Duck 邮箱地址。');
  925. }
  926. await setEmailState(result.email);
  927. await addLog(`Duck 邮箱:${result.generated ? '已生成' : '已读取'} ${result.email}`, 'ok');
  928. return result.email;
  929. }
  930. // ============================================================
  931. // Auto Run Flow
  932. // ============================================================
  933. let autoRunActive = false;
  934. let autoRunCurrentRun = 0;
  935. let autoRunTotalRuns = 1;
  936. let autoRunAttemptRun = 0;
  937. // Outer loop: keep retrying until the target number of successful runs is reached.
  938. async function autoRunLoop(totalRuns, options = {}) {
  939. if (autoRunActive) {
  940. await addLog('自动运行已在进行中', 'warn');
  941. return;
  942. }
  943. clearStopRequest();
  944. autoRunActive = true;
  945. autoRunTotalRuns = totalRuns;
  946. autoRunCurrentRun = 0;
  947. autoRunAttemptRun = 0;
  948. const autoRunSkipFailures = Boolean(options.autoRunSkipFailures);
  949. const maxAttempts = autoRunSkipFailures ? Math.max(totalRuns * 10, totalRuns + 20) : totalRuns;
  950. let successfulRuns = 0;
  951. let attemptRuns = 0;
  952. let forceFreshTabsNextRun = false;
  953. await setState({
  954. autoRunSkipFailures,
  955. ...getAutoRunStatusPayload('running', { currentRun: 0, totalRuns, attemptRun: 0 }),
  956. });
  957. while (successfulRuns < totalRuns && attemptRuns < maxAttempts) {
  958. attemptRuns += 1;
  959. const targetRun = successfulRuns + 1;
  960. autoRunCurrentRun = targetRun;
  961. autoRunAttemptRun = attemptRuns;
  962. // Reset everything at the start of each attempt (keep user settings).
  963. const prevState = await getState();
  964. const keepSettings = {
  965. vpsUrl: prevState.vpsUrl,
  966. vpsPassword: prevState.vpsPassword,
  967. customPassword: prevState.customPassword,
  968. autoRunSkipFailures: prevState.autoRunSkipFailures,
  969. mailProvider: prevState.mailProvider,
  970. inbucketHost: prevState.inbucketHost,
  971. inbucketMailbox: prevState.inbucketMailbox,
  972. ...getAutoRunStatusPayload('running', { currentRun: targetRun, totalRuns, attemptRun: attemptRuns }),
  973. ...(forceFreshTabsNextRun ? { tabRegistry: {} } : {}),
  974. };
  975. await resetState();
  976. await setState(keepSettings);
  977. chrome.runtime.sendMessage({ type: 'AUTO_RUN_RESET' }).catch(() => {});
  978. await sleepWithStop(500);
  979. if (forceFreshTabsNextRun) {
  980. await addLog(`兜底模式:上一轮已放弃,当前开始第 ${attemptRuns} 次尝试,将使用新线程继续补足第 ${targetRun}/${totalRuns} 轮。`, 'warn');
  981. forceFreshTabsNextRun = false;
  982. }
  983. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:第 ${attemptRuns} 次尝试,阶段 1,获取 OAuth 链接并打开注册页 ===`, 'info');
  984. try {
  985. throwIfStopped();
  986. await broadcastAutoRunStatus('running', {
  987. currentRun: targetRun,
  988. totalRuns,
  989. attemptRun: attemptRuns,
  990. });
  991. await executeStepAndWait(1, 2000);
  992. await executeStepAndWait(2, 2000);
  993. let emailReady = false;
  994. try {
  995. const duckEmail = await fetchDuckEmail({ generateNew: true });
  996. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:Duck 邮箱已就绪:${duckEmail}(第 ${attemptRuns} 次尝试)===`, 'ok');
  997. emailReady = true;
  998. } catch (err) {
  999. await addLog(`Duck 邮箱自动获取失败:${err.message}`, 'warn');
  1000. }
  1001. if (!emailReady) {
  1002. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮已暂停:请先获取 Duck 邮箱或手动粘贴邮箱,然后继续 ===`, 'warn');
  1003. await broadcastAutoRunStatus('waiting_email', {
  1004. currentRun: targetRun,
  1005. totalRuns,
  1006. attemptRun: attemptRuns,
  1007. });
  1008. await waitForResume();
  1009. const resumedState = await getState();
  1010. if (!resumedState.email) {
  1011. throw new Error('无法继续:当前没有邮箱地址。');
  1012. }
  1013. }
  1014. await addLog(`=== 目标 ${targetRun}/${totalRuns} 轮:阶段 2,注册、验证、登录并完成授权(第 ${attemptRuns} 次尝试)===`, 'info');
  1015. await broadcastAutoRunStatus('running', {
  1016. currentRun: targetRun,
  1017. totalRuns,
  1018. attemptRun: attemptRuns,
  1019. });
  1020. const signupTabId = await getTabId('signup-page');
  1021. if (signupTabId) {
  1022. await chrome.tabs.update(signupTabId, { active: true });
  1023. }
  1024. await executeStepAndWait(3, 3000);
  1025. await executeStepAndWait(4, 2000);
  1026. await executeStepAndWait(5, 3000);
  1027. await executeStepAndWait(6, 3000);
  1028. await executeStepAndWait(7, 2000);
  1029. await executeStepAndWait(8, 2000);
  1030. await executeStepAndWait(9, 1000);
  1031. successfulRuns += 1;
  1032. autoRunCurrentRun = successfulRuns;
  1033. await addLog(`=== 目标 ${successfulRuns}/${totalRuns} 轮已完成(第 ${attemptRuns} 次尝试成功)===`, 'ok');
  1034. continue;
  1035. } catch (err) {
  1036. if (isStopError(err)) {
  1037. await addLog(`目标 ${targetRun}/${totalRuns} 轮已被用户停止`, 'warn');
  1038. await broadcastAutoRunStatus('stopped', {
  1039. currentRun: targetRun,
  1040. totalRuns,
  1041. attemptRun: attemptRuns,
  1042. });
  1043. break;
  1044. }
  1045. if (!autoRunSkipFailures) {
  1046. await addLog(`目标 ${targetRun}/${totalRuns} 轮失败:${err.message}`, 'error');
  1047. await broadcastAutoRunStatus('stopped', {
  1048. currentRun: targetRun,
  1049. totalRuns,
  1050. attemptRun: attemptRuns,
  1051. });
  1052. break;
  1053. }
  1054. await addLog(`目标 ${targetRun}/${totalRuns} 轮的第 ${attemptRuns} 次尝试失败:${err.message}`, 'error');
  1055. await addLog('兜底开关已开启:将放弃当前线程,重新开一轮继续补足目标次数。', 'warn');
  1056. cancelPendingCommands('当前尝试已放弃。');
  1057. await broadcastStopToContentScripts();
  1058. await broadcastAutoRunStatus('retrying', {
  1059. currentRun: targetRun,
  1060. totalRuns,
  1061. attemptRun: attemptRuns,
  1062. });
  1063. forceFreshTabsNextRun = true;
  1064. }
  1065. }
  1066. if (!stopRequested && autoRunSkipFailures && successfulRuns < totalRuns && attemptRuns >= maxAttempts) {
  1067. await addLog(`已达到安全重试上限(${attemptRuns} 次尝试),当前仅完成 ${successfulRuns}/${totalRuns} 轮。`, 'error');
  1068. await broadcastAutoRunStatus('stopped', {
  1069. currentRun: successfulRuns,
  1070. totalRuns: autoRunTotalRuns,
  1071. attemptRun: attemptRuns,
  1072. });
  1073. } else if (stopRequested) {
  1074. await addLog(`=== 已停止,完成 ${successfulRuns}/${autoRunTotalRuns} 轮,共尝试 ${attemptRuns} 次 ===`, 'warn');
  1075. await broadcastAutoRunStatus('stopped', {
  1076. currentRun: successfulRuns,
  1077. totalRuns: autoRunTotalRuns,
  1078. attemptRun: attemptRuns,
  1079. });
  1080. } else if (successfulRuns >= autoRunTotalRuns) {
  1081. await addLog(`=== 全部 ${autoRunTotalRuns} 轮均已成功完成,共尝试 ${attemptRuns} 次 ===`, 'ok');
  1082. await broadcastAutoRunStatus('complete', {
  1083. currentRun: successfulRuns,
  1084. totalRuns: autoRunTotalRuns,
  1085. attemptRun: attemptRuns,
  1086. });
  1087. } else {
  1088. await addLog(`=== 已停止,完成 ${successfulRuns}/${autoRunTotalRuns} 轮,共尝试 ${attemptRuns} 次 ===`, 'warn');
  1089. await broadcastAutoRunStatus('stopped', {
  1090. currentRun: successfulRuns,
  1091. totalRuns: autoRunTotalRuns,
  1092. attemptRun: attemptRuns,
  1093. });
  1094. }
  1095. autoRunActive = false;
  1096. autoRunAttemptRun = attemptRuns;
  1097. await setState(getAutoRunStatusPayload(stopRequested ? 'stopped' : (successfulRuns >= autoRunTotalRuns ? 'complete' : 'stopped'), {
  1098. currentRun: successfulRuns,
  1099. totalRuns: autoRunTotalRuns,
  1100. attemptRun: attemptRuns,
  1101. }));
  1102. clearStopRequest();
  1103. }
  1104. function waitForResume() {
  1105. return new Promise((resolve, reject) => {
  1106. throwIfStopped();
  1107. resumeWaiter = { resolve, reject };
  1108. });
  1109. }
  1110. async function resumeAutoRun() {
  1111. throwIfStopped();
  1112. const state = await getState();
  1113. if (!state.email) {
  1114. await addLog('无法继续:当前没有邮箱地址,请先在侧边栏填写邮箱。', 'error');
  1115. return;
  1116. }
  1117. if (resumeWaiter) {
  1118. resumeWaiter.resolve();
  1119. resumeWaiter = null;
  1120. }
  1121. }
  1122. // ============================================================
  1123. // Step 1: Get OAuth Link (via vps-panel.js)
  1124. // ============================================================
  1125. async function executeStep1(state) {
  1126. if (!state.vpsUrl) {
  1127. throw new Error('尚未配置 VPS 地址,请先在侧边栏填写。');
  1128. }
  1129. await addLog('步骤 1:正在打开 VPS 面板...');
  1130. await reuseOrCreateTab('vps-panel', state.vpsUrl, {
  1131. inject: ['content/utils.js', 'content/vps-panel.js'],
  1132. reloadIfSameUrl: true,
  1133. });
  1134. await sendToContentScript('vps-panel', {
  1135. type: 'EXECUTE_STEP',
  1136. step: 1,
  1137. source: 'background',
  1138. payload: { vpsPassword: state.vpsPassword },
  1139. });
  1140. }
  1141. // ============================================================
  1142. // Step 2: Open Signup Page (Background opens tab, signup-page.js clicks Register)
  1143. // ============================================================
  1144. async function executeStep2(state) {
  1145. if (!state.oauthUrl) {
  1146. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  1147. }
  1148. await addLog('步骤 2:正在打开认证链接...');
  1149. await reuseOrCreateTab('signup-page', state.oauthUrl);
  1150. await sendToContentScript('signup-page', {
  1151. type: 'EXECUTE_STEP',
  1152. step: 2,
  1153. source: 'background',
  1154. payload: {},
  1155. });
  1156. }
  1157. // ============================================================
  1158. // Step 3: Fill Email & Password (via signup-page.js)
  1159. // ============================================================
  1160. async function executeStep3(state) {
  1161. if (!state.email) {
  1162. throw new Error('缺少邮箱地址,请先在侧边栏粘贴邮箱。');
  1163. }
  1164. const password = state.customPassword || generatePassword();
  1165. await setPasswordState(password);
  1166. // Save account record
  1167. const accounts = state.accounts || [];
  1168. accounts.push({ email: state.email, password, createdAt: new Date().toISOString() });
  1169. await setState({ accounts });
  1170. await addLog(
  1171. `步骤 3:正在填写邮箱 ${state.email},密码为${state.customPassword ? '自定义' : '自动生成'}(${password.length} 位)`
  1172. );
  1173. await sendToContentScript('signup-page', {
  1174. type: 'EXECUTE_STEP',
  1175. step: 3,
  1176. source: 'background',
  1177. payload: { email: state.email, password },
  1178. });
  1179. }
  1180. // ============================================================
  1181. // Step 4: Get Signup Verification Code (qq-mail.js polls, then fills in signup-page.js)
  1182. // ============================================================
  1183. function getMailConfig(state) {
  1184. const provider = state.mailProvider || 'qq';
  1185. if (provider === '163') {
  1186. 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 邮箱' };
  1187. }
  1188. if (provider === 'inbucket') {
  1189. const host = normalizeInbucketOrigin(state.inbucketHost);
  1190. const mailbox = (state.inbucketMailbox || '').trim();
  1191. if (!host) {
  1192. return { error: 'Inbucket 主机地址为空或无效。' };
  1193. }
  1194. if (!mailbox) {
  1195. return { error: 'Inbucket 邮箱名称为空。' };
  1196. }
  1197. return {
  1198. source: 'inbucket-mail',
  1199. url: `${host}/m/${encodeURIComponent(mailbox)}/`,
  1200. label: `Inbucket 邮箱(${mailbox})`,
  1201. navigateOnReuse: true,
  1202. inject: ['content/utils.js', 'content/inbucket-mail.js'],
  1203. injectSource: 'inbucket-mail',
  1204. };
  1205. }
  1206. return { source: 'qq-mail', url: 'https://wx.mail.qq.com/', label: 'QQ 邮箱' };
  1207. }
  1208. function normalizeInbucketOrigin(rawValue) {
  1209. const value = (rawValue || '').trim();
  1210. if (!value) return '';
  1211. const candidate = /^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(value) ? value : `https://${value}`;
  1212. try {
  1213. const parsed = new URL(candidate);
  1214. return parsed.origin;
  1215. } catch {
  1216. return '';
  1217. }
  1218. }
  1219. function getVerificationCodeStateKey(step) {
  1220. return step === 4 ? 'lastSignupCode' : 'lastLoginCode';
  1221. }
  1222. function getVerificationCodeLabel(step) {
  1223. return step === 4 ? '注册' : '登录';
  1224. }
  1225. function getVerificationPollPayload(step, state, overrides = {}) {
  1226. if (step === 4) {
  1227. return {
  1228. filterAfterTimestamp: state.flowStartTime || 0,
  1229. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'duckduckgo', 'forward'],
  1230. subjectFilters: ['verify', 'verification', 'code', '楠岃瘉', 'confirm'],
  1231. targetEmail: state.email,
  1232. maxAttempts: 5,
  1233. intervalMs: 3000,
  1234. ...overrides,
  1235. };
  1236. }
  1237. return {
  1238. filterAfterTimestamp: state.lastEmailTimestamp || state.flowStartTime || 0,
  1239. senderFilters: ['openai', 'noreply', 'verify', 'auth', 'chatgpt', 'duckduckgo', 'forward'],
  1240. subjectFilters: ['verify', 'verification', 'code', '楠岃瘉', 'confirm', 'login'],
  1241. targetEmail: state.email,
  1242. maxAttempts: 5,
  1243. intervalMs: 3000,
  1244. ...overrides,
  1245. };
  1246. }
  1247. async function requestVerificationCodeResend(step) {
  1248. const signupTabId = await getTabId('signup-page');
  1249. if (!signupTabId) {
  1250. throw new Error('认证页面标签页已关闭,无法重新请求验证码。');
  1251. }
  1252. await chrome.tabs.update(signupTabId, { active: true });
  1253. await addLog(`步骤 ${step}:正在请求新的${getVerificationCodeLabel(step)}验证码...`, 'warn');
  1254. const result = await sendToContentScript('signup-page', {
  1255. type: 'RESEND_VERIFICATION_CODE',
  1256. step,
  1257. source: 'background',
  1258. payload: {},
  1259. });
  1260. if (result && result.error) {
  1261. throw new Error(result.error);
  1262. }
  1263. return Date.now();
  1264. }
  1265. async function pollFreshVerificationCode(step, state, mail, pollOverrides = {}) {
  1266. const stateKey = getVerificationCodeStateKey(step);
  1267. const rejectedCodes = new Set();
  1268. if (state[stateKey]) {
  1269. rejectedCodes.add(state[stateKey]);
  1270. }
  1271. for (const code of (pollOverrides.excludeCodes || [])) {
  1272. if (code) rejectedCodes.add(code);
  1273. }
  1274. let lastError = null;
  1275. let filterAfterTimestamp = pollOverrides.filterAfterTimestamp ?? getVerificationPollPayload(step, state).filterAfterTimestamp;
  1276. const maxRounds = pollOverrides.maxRounds || 3;
  1277. for (let round = 1; round <= maxRounds; round++) {
  1278. if (round > 1) {
  1279. filterAfterTimestamp = await requestVerificationCodeResend(step);
  1280. }
  1281. const payload = getVerificationPollPayload(step, state, {
  1282. ...pollOverrides,
  1283. filterAfterTimestamp,
  1284. excludeCodes: [...rejectedCodes],
  1285. });
  1286. try {
  1287. const result = await sendToContentScript(mail.source, {
  1288. type: 'POLL_EMAIL',
  1289. step,
  1290. source: 'background',
  1291. payload,
  1292. });
  1293. if (result && result.error) {
  1294. throw new Error(result.error);
  1295. }
  1296. if (!result || !result.code) {
  1297. throw new Error(`步骤 ${step}:邮箱轮询结束,但未获取到验证码。`);
  1298. }
  1299. if (rejectedCodes.has(result.code)) {
  1300. throw new Error(`步骤 ${step}:再次收到了相同的${getVerificationCodeLabel(step)}验证码:${result.code}`);
  1301. }
  1302. return result;
  1303. } catch (err) {
  1304. lastError = err;
  1305. await addLog(`步骤 ${step}:${err.message}`, 'warn');
  1306. if (round < maxRounds) {
  1307. await addLog(`步骤 ${step}:将重新发送验证码后重试(${round + 1}/${maxRounds})...`, 'warn');
  1308. }
  1309. }
  1310. }
  1311. throw lastError || new Error(`步骤 ${step}:无法获取新的${getVerificationCodeLabel(step)}验证码。`);
  1312. }
  1313. async function submitVerificationCode(step, code) {
  1314. const signupTabId = await getTabId('signup-page');
  1315. if (!signupTabId) {
  1316. throw new Error('认证页面标签页已关闭,无法填写验证码。');
  1317. }
  1318. await chrome.tabs.update(signupTabId, { active: true });
  1319. const result = await sendToContentScript('signup-page', {
  1320. type: 'FILL_CODE',
  1321. step,
  1322. source: 'background',
  1323. payload: { code },
  1324. });
  1325. if (result && result.error) {
  1326. throw new Error(result.error);
  1327. }
  1328. return result || {};
  1329. }
  1330. async function resolveVerificationStep(step, state, mail) {
  1331. const stateKey = getVerificationCodeStateKey(step);
  1332. const rejectedCodes = new Set();
  1333. if (state[stateKey]) {
  1334. rejectedCodes.add(state[stateKey]);
  1335. }
  1336. let nextFilterAfterTimestamp = null;
  1337. const maxSubmitAttempts = 3;
  1338. for (let attempt = 1; attempt <= maxSubmitAttempts; attempt++) {
  1339. const result = await pollFreshVerificationCode(step, state, mail, {
  1340. excludeCodes: [...rejectedCodes],
  1341. filterAfterTimestamp: nextFilterAfterTimestamp ?? undefined,
  1342. });
  1343. await addLog(`步骤 ${step}:已获取${getVerificationCodeLabel(step)}验证码:${result.code}`);
  1344. const submitResult = await submitVerificationCode(step, result.code);
  1345. if (submitResult.invalidCode) {
  1346. rejectedCodes.add(result.code);
  1347. await addLog(`步骤 ${step}:验证码被页面拒绝:${submitResult.errorText || result.code}`, 'warn');
  1348. if (attempt >= maxSubmitAttempts) {
  1349. throw new Error(`步骤 ${step}:验证码连续失败,已达到 ${maxSubmitAttempts} 次重试上限。`);
  1350. }
  1351. nextFilterAfterTimestamp = await requestVerificationCodeResend(step);
  1352. await addLog(`步骤 ${step}:提交失败后已请求新验证码(${attempt + 1}/${maxSubmitAttempts})...`, 'warn');
  1353. continue;
  1354. }
  1355. await setState({
  1356. lastEmailTimestamp: result.emailTimestamp,
  1357. [stateKey]: result.code,
  1358. });
  1359. await completeStepFromBackground(step, {
  1360. emailTimestamp: result.emailTimestamp,
  1361. code: result.code,
  1362. });
  1363. return;
  1364. }
  1365. }
  1366. async function executeStep4(state) {
  1367. const mail = getMailConfig(state);
  1368. if (mail.error) throw new Error(mail.error);
  1369. await addLog(`步骤 4:正在打开${mail.label}...`);
  1370. // For mail tabs, only create if not alive — don't navigate (preserves login session)
  1371. const alive = await isTabAlive(mail.source);
  1372. if (alive) {
  1373. if (mail.navigateOnReuse) {
  1374. await reuseOrCreateTab(mail.source, mail.url, {
  1375. inject: mail.inject,
  1376. injectSource: mail.injectSource,
  1377. });
  1378. } else {
  1379. const tabId = await getTabId(mail.source);
  1380. await chrome.tabs.update(tabId, { active: true });
  1381. }
  1382. } else {
  1383. await reuseOrCreateTab(mail.source, mail.url, {
  1384. inject: mail.inject,
  1385. injectSource: mail.injectSource,
  1386. });
  1387. }
  1388. await resolveVerificationStep(4, state, mail);
  1389. return;
  1390. }
  1391. // ============================================================
  1392. // Step 5: Fill Name & Birthday (via signup-page.js)
  1393. // ============================================================
  1394. async function executeStep5(state) {
  1395. const { firstName, lastName } = generateRandomName();
  1396. const { year, month, day } = generateRandomBirthday();
  1397. await addLog(`步骤 5:已生成姓名 ${firstName} ${lastName},生日 ${year}-${month}-${day}`);
  1398. await sendToContentScript('signup-page', {
  1399. type: 'EXECUTE_STEP',
  1400. step: 5,
  1401. source: 'background',
  1402. payload: { firstName, lastName, year, month, day },
  1403. });
  1404. }
  1405. // ============================================================
  1406. // Step 6: Login ChatGPT (Background opens tab, chatgpt.js handles login)
  1407. // ============================================================
  1408. async function executeStep6(state) {
  1409. if (!state.oauthUrl) {
  1410. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  1411. }
  1412. if (!state.email) {
  1413. throw new Error('缺少邮箱地址,请先完成步骤 3。');
  1414. }
  1415. await addLog('步骤 6:正在打开用于登录的 OAuth 链接...');
  1416. // Reuse the signup-page tab — navigate it to the OAuth URL
  1417. await reuseOrCreateTab('signup-page', state.oauthUrl);
  1418. // signup-page.js will inject (same auth.openai.com domain) and handle login
  1419. await sendToContentScript('signup-page', {
  1420. type: 'EXECUTE_STEP',
  1421. step: 6,
  1422. source: 'background',
  1423. payload: { email: state.email, password: state.password },
  1424. });
  1425. }
  1426. // ============================================================
  1427. // Step 7: Get Login Verification Code (qq-mail.js polls, then fills in chatgpt.js)
  1428. // ============================================================
  1429. async function executeStep7(state) {
  1430. const mail = getMailConfig(state);
  1431. if (mail.error) throw new Error(mail.error);
  1432. const authTabId = await getTabId('signup-page');
  1433. if (authTabId) {
  1434. await chrome.tabs.update(authTabId, { active: true });
  1435. } else {
  1436. if (!state.oauthUrl) {
  1437. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  1438. }
  1439. await reuseOrCreateTab('signup-page', state.oauthUrl);
  1440. }
  1441. await addLog('步骤 7:正在准备认证页,必要时切换到一次性验证码登录...');
  1442. const prepareResult = await sendToContentScript('signup-page', {
  1443. type: 'PREPARE_LOGIN_CODE',
  1444. step: 7,
  1445. source: 'background',
  1446. payload: {},
  1447. });
  1448. if (prepareResult && prepareResult.error) {
  1449. throw new Error(prepareResult.error);
  1450. }
  1451. await addLog(`步骤 7:正在打开${mail.label}...`);
  1452. const alive = await isTabAlive(mail.source);
  1453. if (alive) {
  1454. if (mail.navigateOnReuse) {
  1455. await reuseOrCreateTab(mail.source, mail.url, {
  1456. inject: mail.inject,
  1457. injectSource: mail.injectSource,
  1458. });
  1459. } else {
  1460. const tabId = await getTabId(mail.source);
  1461. await chrome.tabs.update(tabId, { active: true });
  1462. }
  1463. } else {
  1464. await reuseOrCreateTab(mail.source, mail.url, {
  1465. inject: mail.inject,
  1466. injectSource: mail.injectSource,
  1467. });
  1468. }
  1469. await resolveVerificationStep(7, state, mail);
  1470. return;
  1471. }
  1472. // ============================================================
  1473. // Step 8: Complete OAuth (auto click + localhost listener)
  1474. // ============================================================
  1475. let webNavListener = null;
  1476. async function executeStep8(state) {
  1477. if (!state.oauthUrl) {
  1478. throw new Error('缺少 OAuth 链接,请先完成步骤 1。');
  1479. }
  1480. await addLog('步骤 8:正在监听 localhost 回调地址...');
  1481. // Register webNavigation listener (scoped to this step)
  1482. return new Promise((resolve, reject) => {
  1483. let resolved = false;
  1484. let resolveCaptureWait = null;
  1485. const captureWait = new Promise((resolveCapture) => {
  1486. resolveCaptureWait = resolveCapture;
  1487. });
  1488. const cleanupListener = () => {
  1489. if (webNavListener) {
  1490. chrome.webNavigation.onBeforeNavigate.removeListener(webNavListener);
  1491. webNavListener = null;
  1492. }
  1493. };
  1494. const timeout = setTimeout(() => {
  1495. cleanupListener();
  1496. reject(new Error('120 秒内未捕获到 localhost 回调跳转,步骤 8 的点击可能被拦截了。'));
  1497. }, 120000);
  1498. webNavListener = (details) => {
  1499. if (details.url.startsWith('http://localhost')) {
  1500. console.log(LOG_PREFIX, `Captured localhost redirect: ${details.url}`);
  1501. resolved = true;
  1502. cleanupListener();
  1503. clearTimeout(timeout);
  1504. if (resolveCaptureWait) resolveCaptureWait(details.url);
  1505. setState({ localhostUrl: details.url }).then(() => {
  1506. addLog(`步骤 8:已捕获 localhost 地址:${details.url}`, 'ok');
  1507. setStepStatus(8, 'completed');
  1508. notifyStepComplete(8, { localhostUrl: details.url });
  1509. broadcastDataUpdate({ localhostUrl: details.url });
  1510. resolve();
  1511. });
  1512. }
  1513. };
  1514. chrome.webNavigation.onBeforeNavigate.addListener(webNavListener);
  1515. // After step 7, the auth page shows a consent screen ("使用 ChatGPT 登录到 Codex")
  1516. // with a "继续" button. We locate the button in-page, then click it through
  1517. // the debugger Input API directly.
  1518. (async () => {
  1519. try {
  1520. let signupTabId = await getTabId('signup-page');
  1521. if (signupTabId) {
  1522. await chrome.tabs.update(signupTabId, { active: true });
  1523. await addLog('步骤 8:已切回认证页,正在准备调试器点击...');
  1524. } else {
  1525. signupTabId = await reuseOrCreateTab('signup-page', state.oauthUrl);
  1526. await addLog('步骤 8:已重新打开认证页,正在准备调试器点击...');
  1527. }
  1528. const clickResult = await sendToContentScript('signup-page', {
  1529. type: 'STEP8_FIND_AND_CLICK',
  1530. source: 'background',
  1531. payload: {},
  1532. });
  1533. if (clickResult?.error) {
  1534. throw new Error(clickResult.error);
  1535. }
  1536. if (!resolved) {
  1537. await clickWithDebugger(signupTabId, clickResult?.rect);
  1538. await addLog('步骤 8:已发送调试器点击,正在等待跳转...');
  1539. }
  1540. } catch (err) {
  1541. clearTimeout(timeout);
  1542. cleanupListener();
  1543. reject(err);
  1544. }
  1545. })();
  1546. });
  1547. }
  1548. // ============================================================
  1549. // Step 9: VPS Verify (via vps-panel.js)
  1550. // ============================================================
  1551. async function executeStep9(state) {
  1552. if (!state.localhostUrl) {
  1553. throw new Error('缺少 localhost 回调地址,请先完成步骤 8。');
  1554. }
  1555. if (!state.vpsUrl) {
  1556. throw new Error('尚未填写 VPS 地址,请先在侧边栏输入。');
  1557. }
  1558. await addLog('步骤 9:正在打开 VPS 面板...');
  1559. let tabId = await getTabId('vps-panel');
  1560. const alive = tabId && await isTabAlive('vps-panel');
  1561. if (!alive) {
  1562. // Create new tab
  1563. const tab = await chrome.tabs.create({ url: state.vpsUrl, active: true });
  1564. tabId = tab.id;
  1565. await new Promise(resolve => {
  1566. const listener = (tid, info) => {
  1567. if (tid === tabId && info.status === 'complete') {
  1568. chrome.tabs.onUpdated.removeListener(listener);
  1569. resolve();
  1570. }
  1571. };
  1572. chrome.tabs.onUpdated.addListener(listener);
  1573. });
  1574. } else {
  1575. await chrome.tabs.update(tabId, { active: true });
  1576. }
  1577. // Inject scripts directly and wait for them to be ready
  1578. await chrome.scripting.executeScript({
  1579. target: { tabId },
  1580. files: ['content/utils.js', 'content/vps-panel.js'],
  1581. });
  1582. await new Promise(r => setTimeout(r, 1000));
  1583. // Send command directly — bypass queue/ready mechanism
  1584. await addLog('步骤 9:正在填写回调地址...');
  1585. await chrome.tabs.sendMessage(tabId, {
  1586. type: 'EXECUTE_STEP',
  1587. step: 9,
  1588. source: 'background',
  1589. payload: { localhostUrl: state.localhostUrl, vpsPassword: state.vpsPassword },
  1590. });
  1591. }
  1592. // ============================================================
  1593. // Open Side Panel on extension icon click
  1594. // ============================================================
  1595. chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });