vps-panel.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. // content/vps-panel.js — Content script for CPA panel (steps 1, 9)
  2. // Injected on: CPA panel (user-configured URL)
  3. //
  4. // Actual DOM structure (after login click):
  5. // <div class="card">
  6. // <div class="card-header">
  7. // <span class="OAuthPage-module__cardTitle___yFaP0">Codex OAuth</span>
  8. // <button class="btn btn-primary"><span>登录</span></button>
  9. // </div>
  10. // <div class="OAuthPage-module__cardContent___1sXLA">
  11. // <div class="OAuthPage-module__authUrlBox___Iu1d4">
  12. // <div class="OAuthPage-module__authUrlLabel___mYFJB">授权链接:</div>
  13. // <div class="OAuthPage-module__authUrlValue___axvUJ">https://auth.openai.com/...</div>
  14. // <div class="OAuthPage-module__authUrlActions___venPj">
  15. // <button class="btn btn-secondary btn-sm"><span>复制链接</span></button>
  16. // <button class="btn btn-secondary btn-sm"><span>打开链接</span></button>
  17. // </div>
  18. // </div>
  19. // <div class="OAuthPage-module__callbackSection___8kA31">
  20. // <input class="input" placeholder="http://localhost:1455/auth/callback?code=...&state=...">
  21. // <button class="btn btn-secondary btn-sm"><span>提交回调 URL</span></button>
  22. // </div>
  23. // </div>
  24. // </div>
  25. console.log('[MultiPage:vps-panel] Content script loaded on', location.href);
  26. const VPS_PANEL_LISTENER_SENTINEL = 'data-multipage-vps-panel-listener';
  27. if (document.documentElement.getAttribute(VPS_PANEL_LISTENER_SENTINEL) !== '1') {
  28. document.documentElement.setAttribute(VPS_PANEL_LISTENER_SENTINEL, '1');
  29. // Listen for commands from Background
  30. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  31. if (message.type === 'EXECUTE_STEP') {
  32. resetStopState();
  33. const startedAt = Date.now();
  34. console.log(LOG_PREFIX, `EXECUTE_STEP received for step ${message.step}`, {
  35. url: location.href,
  36. payloadKeys: Object.keys(message.payload || {}),
  37. snapshot: getVpsPanelSnapshot(),
  38. });
  39. handleStep(message.step, message.payload).then(() => {
  40. console.log(LOG_PREFIX, `EXECUTE_STEP resolved for step ${message.step} after ${Date.now() - startedAt}ms`, {
  41. url: location.href,
  42. snapshot: getVpsPanelSnapshot(),
  43. });
  44. sendResponse({ ok: true });
  45. }).catch(err => {
  46. console.error(LOG_PREFIX, `EXECUTE_STEP rejected for step ${message.step} after ${Date.now() - startedAt}ms: ${err?.message || err}`, {
  47. url: location.href,
  48. snapshot: getVpsPanelSnapshot(),
  49. });
  50. if (isStopError(err)) {
  51. log(`步骤 ${message.step}:已被用户停止。`, 'warn');
  52. sendResponse({ stopped: true, error: err.message });
  53. return;
  54. }
  55. reportError(message.step, err.message);
  56. sendResponse({ error: err.message });
  57. });
  58. return true;
  59. }
  60. });
  61. } else {
  62. console.log('[MultiPage:vps-panel] 消息监听已存在,跳过重复注册');
  63. }
  64. async function handleStep(step, payload) {
  65. switch (step) {
  66. case 1: return await step1_getOAuthLink(payload);
  67. case 9: return await step9_vpsVerify(payload);
  68. default:
  69. throw new Error(`vps-panel.js 不处理步骤 ${step}`);
  70. }
  71. }
  72. function isVisibleElement(el) {
  73. if (!el) return false;
  74. const style = window.getComputedStyle(el);
  75. const rect = el.getBoundingClientRect();
  76. return style.display !== 'none'
  77. && style.visibility !== 'hidden'
  78. && rect.width > 0
  79. && rect.height > 0;
  80. }
  81. function getActionText(el) {
  82. return [
  83. el?.textContent,
  84. el?.value,
  85. el?.getAttribute?.('aria-label'),
  86. el?.getAttribute?.('title'),
  87. ]
  88. .filter(Boolean)
  89. .join(' ')
  90. .replace(/\s+/g, ' ')
  91. .trim();
  92. }
  93. function getInlineTextSnippet(text, maxLength = 160) {
  94. const normalized = (text || '').replace(/\s+/g, ' ').trim();
  95. if (!normalized) return '';
  96. if (normalized.length <= maxLength) return normalized;
  97. return `${normalized.slice(0, maxLength)}...`;
  98. }
  99. function getPageTextSnippet(maxLength = 240) {
  100. const bodyText = document.body?.innerText || document.documentElement?.innerText || '';
  101. return getInlineTextSnippet(bodyText, maxLength);
  102. }
  103. function getVpsPanelSnapshot() {
  104. const authUrlEl = findAuthUrlElement();
  105. const oauthHeader = findCodexOAuthHeader();
  106. const managementKeyInput = findManagementKeyInput();
  107. const managementLoginButton = findManagementLoginButton();
  108. const rememberCheckbox = findRememberPasswordCheckbox();
  109. const oauthNavLink = findOAuthNavLink();
  110. return {
  111. url: location.href,
  112. readyState: document.readyState,
  113. title: getInlineTextSnippet(document.title || '', 80),
  114. authUrlVisible: Boolean(authUrlEl),
  115. authUrlText: getInlineTextSnippet(authUrlEl?.textContent || '', 120),
  116. oauthHeaderVisible: Boolean(oauthHeader),
  117. oauthHeaderText: getInlineTextSnippet(oauthHeader?.textContent || '', 120),
  118. managementKeyVisible: Boolean(managementKeyInput),
  119. managementLoginVisible: Boolean(managementLoginButton),
  120. managementLoginText: getInlineTextSnippet(getActionText(managementLoginButton), 60),
  121. rememberCheckboxVisible: Boolean(rememberCheckbox),
  122. rememberCheckboxChecked: Boolean(rememberCheckbox?.checked),
  123. oauthNavVisible: Boolean(oauthNavLink),
  124. oauthNavText: getInlineTextSnippet(getActionText(oauthNavLink), 80),
  125. bodySnippet: getPageTextSnippet(),
  126. };
  127. }
  128. function getVpsPanelSnapshotSignature(snapshot) {
  129. return JSON.stringify({
  130. readyState: snapshot.readyState,
  131. title: snapshot.title,
  132. authUrlVisible: snapshot.authUrlVisible,
  133. authUrlText: snapshot.authUrlText,
  134. oauthHeaderVisible: snapshot.oauthHeaderVisible,
  135. oauthHeaderText: snapshot.oauthHeaderText,
  136. managementKeyVisible: snapshot.managementKeyVisible,
  137. managementLoginVisible: snapshot.managementLoginVisible,
  138. rememberCheckboxVisible: snapshot.rememberCheckboxVisible,
  139. rememberCheckboxChecked: snapshot.rememberCheckboxChecked,
  140. oauthNavVisible: snapshot.oauthNavVisible,
  141. oauthNavText: snapshot.oauthNavText,
  142. bodySnippet: snapshot.bodySnippet,
  143. });
  144. }
  145. function parseUrlSafely(rawUrl) {
  146. if (!rawUrl) return null;
  147. try {
  148. return new URL(rawUrl);
  149. } catch {
  150. return null;
  151. }
  152. }
  153. function isLocalhostOAuthCallbackUrl(rawUrl) {
  154. const parsed = parseUrlSafely(rawUrl);
  155. if (!parsed) return false;
  156. if (!['http:', 'https:'].includes(parsed.protocol)) return false;
  157. if (!['localhost', '127.0.0.1'].includes(parsed.hostname)) return false;
  158. if (!['/auth/callback', '/codex/callback'].includes(parsed.pathname)) return false;
  159. const code = (parsed.searchParams.get('code') || '').trim();
  160. const state = (parsed.searchParams.get('state') || '').trim();
  161. return Boolean(code && state);
  162. }
  163. function getStatusBadgeElement() {
  164. const selectors = [
  165. '#root > div > div > div > main > div > div > div > div > div:nth-child(1) > div > div.OAuthPage-module__cardContent___1sXLA > div.status-badge',
  166. '#root .OAuthPage-module__cardContent___1sXLA > .status-badge',
  167. '.OAuthPage-module__cardContent___1sXLA > .status-badge',
  168. '.status-badge',
  169. ];
  170. for (const selector of selectors) {
  171. const candidates = document.querySelectorAll(selector);
  172. const visible = Array.from(candidates).find(isVisibleElement);
  173. if (visible) return visible;
  174. }
  175. return null;
  176. }
  177. function getStatusBadgeText() {
  178. const statusEl = getStatusBadgeElement();
  179. return statusEl ? (statusEl.textContent || '').replace(/\s+/g, ' ').trim() : '';
  180. }
  181. function isOAuthCallbackTimeoutFailure(statusText) {
  182. return /认证失败:\s*Timeout waiting for OAuth callback/i.test(statusText || '');
  183. }
  184. async function waitForExactSuccessBadge(timeout = 30000) {
  185. const start = Date.now();
  186. while (Date.now() - start < timeout) {
  187. throwIfStopped();
  188. const statusText = getStatusBadgeText();
  189. if (statusText === '认证成功!') {
  190. return statusText;
  191. }
  192. await sleep(200);
  193. }
  194. const finalText = getStatusBadgeText();
  195. if (isOAuthCallbackTimeoutFailure(finalText)) {
  196. throw new Error(`STEP9_OAUTH_TIMEOUT::${finalText}`);
  197. }
  198. throw new Error(finalText
  199. ? `CPA 面板状态不是“认证成功!”,当前为“${finalText}”。`
  200. : 'CPA 面板长时间未出现“认证成功!”状态徽标。');
  201. }
  202. function findManagementKeyInput() {
  203. const candidates = document.querySelectorAll(
  204. '.LoginPage-module__loginCard___OgP-R input[type="password"], input[placeholder*="管理密钥"], input[aria-label*="管理密钥"]'
  205. );
  206. return Array.from(candidates).find(isVisibleElement) || null;
  207. }
  208. function findManagementLoginButton() {
  209. const candidates = document.querySelectorAll('.LoginPage-module__loginCard___OgP-R button, .LoginPage-module__loginCard___OgP-R .btn');
  210. return Array.from(candidates).find((el) => {
  211. if (!isVisibleElement(el)) return false;
  212. return /登录|login/i.test(getActionText(el));
  213. }) || null;
  214. }
  215. function findRememberPasswordCheckbox() {
  216. const candidates = document.querySelectorAll('.LoginPage-module__loginCard___OgP-R input[type="checkbox"]');
  217. return Array.from(candidates).find((el) => {
  218. const label = el.closest('label');
  219. const text = getActionText(label || el);
  220. return /记住密码|remember/i.test(text);
  221. }) || null;
  222. }
  223. function findOAuthNavLink() {
  224. const candidates = document.querySelectorAll('a[href*="#/oauth"], a.nav-item, button, [role="link"], [role="button"]');
  225. return Array.from(candidates).find((el) => {
  226. if (!isVisibleElement(el)) return false;
  227. const text = getActionText(el);
  228. const href = el.getAttribute('href') || '';
  229. return href.includes('#/oauth') || /oauth/i.test(text);
  230. }) || null;
  231. }
  232. function findCodexOAuthHeader() {
  233. const candidates = document.querySelectorAll('.card-header, [class*="cardHeader"], .card, [class*="card"]');
  234. return Array.from(candidates).find((el) => {
  235. if (!isVisibleElement(el)) return false;
  236. const text = (el.textContent || '').toLowerCase();
  237. return text.includes('codex') && text.includes('oauth');
  238. }) || null;
  239. }
  240. function findOAuthCardLoginButton(header) {
  241. const card = header?.closest('.card, [class*="card"]') || header?.parentElement || document;
  242. const candidates = card.querySelectorAll('button.btn.btn-primary, button.btn-primary, button.btn');
  243. return Array.from(candidates).find((el) => isVisibleElement(el) && /登录|login/i.test(getActionText(el))) || null;
  244. }
  245. function findAuthUrlElement() {
  246. const candidates = document.querySelectorAll('[class*="authUrlValue"], .OAuthPage-module__authUrlValue___axvUJ');
  247. return Array.from(candidates).find((el) => isVisibleElement(el) && /^https?:\/\//i.test((el.textContent || '').trim())) || null;
  248. }
  249. async function ensureOAuthManagementPage(vpsPassword, step = 1, timeout = 45000) {
  250. const start = Date.now();
  251. let lastLoginAttemptAt = 0;
  252. let lastOauthNavAttemptAt = 0;
  253. let lastSnapshotSignature = '';
  254. let lastSnapshotLogAt = 0;
  255. console.log(LOG_PREFIX, `[Step ${step}] ensureOAuthManagementPage start`, {
  256. timeout,
  257. url: location.href,
  258. hasVpsPassword: Boolean(vpsPassword),
  259. snapshot: getVpsPanelSnapshot(),
  260. });
  261. while (Date.now() - start < timeout) {
  262. throwIfStopped();
  263. const elapsed = Date.now() - start;
  264. const snapshot = getVpsPanelSnapshot();
  265. const signature = getVpsPanelSnapshotSignature(snapshot);
  266. if (signature !== lastSnapshotSignature || elapsed - lastSnapshotLogAt >= 5000) {
  267. lastSnapshotSignature = signature;
  268. lastSnapshotLogAt = elapsed;
  269. console.log(LOG_PREFIX, `[Step ${step}] panel snapshot at ${elapsed}ms`, snapshot);
  270. }
  271. const authUrlEl = findAuthUrlElement();
  272. if (authUrlEl) {
  273. console.log(LOG_PREFIX, `[Step ${step}] found visible auth URL after ${elapsed}ms`, {
  274. url: location.href,
  275. authUrlText: getInlineTextSnippet(authUrlEl.textContent || '', 120),
  276. });
  277. return { header: findCodexOAuthHeader(), authUrlEl };
  278. }
  279. const oauthHeader = findCodexOAuthHeader();
  280. if (oauthHeader) {
  281. console.log(LOG_PREFIX, `[Step ${step}] found OAuth card header after ${elapsed}ms`, {
  282. url: location.href,
  283. headerText: getInlineTextSnippet(oauthHeader.textContent || '', 120),
  284. });
  285. return { header: oauthHeader, authUrlEl: null };
  286. }
  287. const managementKeyInput = findManagementKeyInput();
  288. const managementLoginButton = findManagementLoginButton();
  289. if (managementKeyInput && managementLoginButton) {
  290. if (!vpsPassword) {
  291. throw new Error('CPA 面板需要管理密钥,请先在侧边栏填写 CPA Key(管理密钥)。');
  292. }
  293. if ((managementKeyInput.value || '') !== vpsPassword) {
  294. await humanPause(350, 900);
  295. fillInput(managementKeyInput, vpsPassword);
  296. console.log(LOG_PREFIX, `[Step ${step}] filled management key after ${elapsed}ms`);
  297. log(`步骤 ${step}:已填写 CPA 管理密钥。`);
  298. }
  299. const rememberCheckbox = findRememberPasswordCheckbox();
  300. if (rememberCheckbox && !rememberCheckbox.checked) {
  301. simulateClick(rememberCheckbox);
  302. console.log(LOG_PREFIX, `[Step ${step}] toggled remember checkbox after ${elapsed}ms`);
  303. log(`步骤 ${step}:已勾选 CPA 面板“记住密码”。`);
  304. await sleep(300);
  305. }
  306. if (Date.now() - lastLoginAttemptAt > 3000) {
  307. lastLoginAttemptAt = Date.now();
  308. await humanPause(350, 900);
  309. simulateClick(managementLoginButton);
  310. console.log(LOG_PREFIX, `[Step ${step}] clicked management login after ${elapsed}ms`, {
  311. buttonText: getInlineTextSnippet(getActionText(managementLoginButton), 80),
  312. });
  313. log(`步骤 ${step}:已提交 CPA 管理登录。`);
  314. }
  315. await sleep(1500);
  316. continue;
  317. }
  318. const oauthNavLink = findOAuthNavLink();
  319. if (oauthNavLink && Date.now() - lastOauthNavAttemptAt > 2000) {
  320. lastOauthNavAttemptAt = Date.now();
  321. await humanPause(300, 800);
  322. simulateClick(oauthNavLink);
  323. console.log(LOG_PREFIX, `[Step ${step}] clicked OAuth nav after ${elapsed}ms`, {
  324. navText: getInlineTextSnippet(getActionText(oauthNavLink), 80),
  325. });
  326. log(`步骤 ${step}:已打开“OAuth 登录”导航。`);
  327. await sleep(1200);
  328. continue;
  329. }
  330. await sleep(250);
  331. }
  332. console.error(LOG_PREFIX, `[Step ${step}] ensureOAuthManagementPage timeout after ${Date.now() - start}ms`, {
  333. url: location.href,
  334. snapshot: getVpsPanelSnapshot(),
  335. });
  336. throw new Error('无法进入 CPA 的 OAuth 管理页面,请检查面板是否正常加载。URL: ' + location.href);
  337. }
  338. // ============================================================
  339. // Step 1: Get OAuth Link
  340. // ============================================================
  341. async function step1_getOAuthLink(payload) {
  342. const { vpsPassword } = payload || {};
  343. console.log(LOG_PREFIX, '[Step 1] step1_getOAuthLink start', {
  344. url: location.href,
  345. hasVpsPassword: Boolean(vpsPassword),
  346. snapshot: getVpsPanelSnapshot(),
  347. });
  348. log('步骤 1:正在等待 CPA 面板加载并进入 OAuth 页面...');
  349. const { header, authUrlEl: existingAuthUrlEl } = await ensureOAuthManagementPage(vpsPassword, 1);
  350. let authUrlEl = existingAuthUrlEl;
  351. console.log(LOG_PREFIX, '[Step 1] ensureOAuthManagementPage resolved', {
  352. url: location.href,
  353. hasHeader: Boolean(header),
  354. hasExistingAuthUrl: Boolean(existingAuthUrlEl),
  355. snapshot: getVpsPanelSnapshot(),
  356. });
  357. if (!authUrlEl) {
  358. const loginBtn = findOAuthCardLoginButton(header);
  359. if (!loginBtn) {
  360. throw new Error('已找到 Codex OAuth 卡片,但卡片内没有登录按钮。URL: ' + location.href);
  361. }
  362. if (loginBtn.disabled) {
  363. console.log(LOG_PREFIX, '[Step 1] OAuth login button is disabled, waiting for auth URL', {
  364. url: location.href,
  365. buttonText: getInlineTextSnippet(getActionText(loginBtn), 80),
  366. });
  367. log('步骤 1:OAuth 登录按钮当前不可用,正在等待授权链接出现...');
  368. } else {
  369. await humanPause(500, 1400);
  370. simulateClick(loginBtn);
  371. console.log(LOG_PREFIX, '[Step 1] clicked OAuth login button and waiting for auth URL', {
  372. url: location.href,
  373. buttonText: getInlineTextSnippet(getActionText(loginBtn), 80),
  374. });
  375. log('步骤 1:已点击 OAuth 登录按钮,正在等待授权链接...');
  376. }
  377. try {
  378. authUrlEl = await waitForElement('[class*="authUrlValue"]', 15000);
  379. } catch {
  380. throw new Error(
  381. '点击 OAuth 登录按钮后未出现授权链接。' +
  382. '请检查 CPA 面板服务是否正在运行。URL: ' + location.href
  383. );
  384. }
  385. } else {
  386. log('步骤 1:CPA 面板上已显示授权链接。');
  387. }
  388. const oauthUrl = (authUrlEl.textContent || '').trim();
  389. if (!oauthUrl || !oauthUrl.startsWith('http')) {
  390. throw new Error(`拿到的 OAuth 链接无效:\"${oauthUrl.slice(0, 50)}\"。应为 http 开头的 URL。`);
  391. }
  392. log(`步骤 1:已获取 OAuth 链接:${oauthUrl.slice(0, 80)}...`, 'ok');
  393. console.log(LOG_PREFIX, '[Step 1] reporting completion with oauthUrl', {
  394. url: location.href,
  395. oauthUrlPreview: oauthUrl.slice(0, 120),
  396. });
  397. reportComplete(1, { oauthUrl });
  398. }
  399. // ============================================================
  400. // 步骤 9:CPA 回调验证——填写 localhost 回调地址并提交
  401. // ============================================================
  402. async function step9_vpsVerify(payload) {
  403. await ensureOAuthManagementPage(payload?.vpsPassword, 9);
  404. // 优先从 payload 读取 localhostUrl;没有时再回退到全局状态
  405. let localhostUrl = payload?.localhostUrl;
  406. if (localhostUrl && !isLocalhostOAuthCallbackUrl(localhostUrl)) {
  407. throw new Error('步骤 9 只接受真实的 localhost OAuth 回调地址,请重新执行步骤 8。');
  408. }
  409. if (!localhostUrl) {
  410. log('步骤 9:payload 中没有 localhostUrl,正在从状态中读取...');
  411. const state = await chrome.runtime.sendMessage({ type: 'GET_STATE' });
  412. localhostUrl = state.localhostUrl;
  413. if (localhostUrl && !isLocalhostOAuthCallbackUrl(localhostUrl)) {
  414. throw new Error('步骤 9 只接受真实的 localhost OAuth 回调地址,请重新执行步骤 8。');
  415. }
  416. }
  417. if (!localhostUrl) {
  418. throw new Error('未找到 localhost 回调地址,请先完成步骤 8。');
  419. }
  420. log(`步骤 9:已获取 localhostUrl:${localhostUrl.slice(0, 60)}...`);
  421. log('步骤 9:正在查找回调地址输入框...');
  422. // Find the callback URL input
  423. // Actual DOM: <input class="input" placeholder="http://localhost:1455/auth/callback?code=...&state=...">
  424. let urlInput = null;
  425. try {
  426. urlInput = await waitForElement('[class*="callbackSection"] input.input', 10000);
  427. } catch {
  428. try {
  429. urlInput = await waitForElement('input[placeholder*="localhost"]', 5000);
  430. } catch {
  431. throw new Error('在 CPA 面板中未找到回调地址输入框。URL: ' + location.href);
  432. }
  433. }
  434. await humanPause(600, 1500);
  435. fillInput(urlInput, localhostUrl);
  436. log(`步骤 9:已填写回调地址:${localhostUrl.slice(0, 80)}...`);
  437. // Find and click "提交回调 URL" button
  438. let submitBtn = null;
  439. try {
  440. submitBtn = await waitForElementByText(
  441. '[class*="callbackActions"] button, [class*="callbackSection"] button',
  442. /提交/,
  443. 5000
  444. );
  445. } catch {
  446. try {
  447. submitBtn = await waitForElementByText('button.btn', /提交回调/, 5000);
  448. } catch {
  449. throw new Error('未找到“提交回调 URL”按钮。URL: ' + location.href);
  450. }
  451. }
  452. await humanPause(450, 1200);
  453. simulateClick(submitBtn);
  454. log('步骤 9:已点击“提交回调 URL”,正在等待认证结果...');
  455. const verifiedStatus = await waitForExactSuccessBadge();
  456. log(`步骤 9:${verifiedStatus}`, 'ok');
  457. reportComplete(9, { localhostUrl, verifiedStatus });
  458. }