vps-panel.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. // content/vps-panel.js — Content script for VPS panel (steps 1, 9)
  2. // Injected on: VPS 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. // Listen for commands from Background
  27. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  28. if (message.type === 'EXECUTE_STEP') {
  29. resetStopState();
  30. handleStep(message.step, message.payload).then(() => {
  31. sendResponse({ ok: true });
  32. }).catch(err => {
  33. if (isStopError(err)) {
  34. log(`Step ${message.step}: Stopped by user.`, 'warn');
  35. sendResponse({ stopped: true, error: err.message });
  36. return;
  37. }
  38. reportError(message.step, err.message);
  39. sendResponse({ error: err.message });
  40. });
  41. return true;
  42. }
  43. });
  44. async function handleStep(step, payload) {
  45. switch (step) {
  46. case 1: return await step1_getOAuthLink();
  47. case 9: return await step9_vpsVerify(payload);
  48. default:
  49. throw new Error(`vps-panel.js does not handle step ${step}`);
  50. }
  51. }
  52. // ============================================================
  53. // Step 1: Get OAuth Link
  54. // ============================================================
  55. async function step1_getOAuthLink() {
  56. log('Step 1: Waiting for VPS panel to load (auto-login may take a moment)...');
  57. // The page may start at #/login and auto-redirect to #/oauth.
  58. // Wait for the Codex OAuth card to appear (up to 30s for auto-login + redirect).
  59. let loginBtn = null;
  60. try {
  61. // Wait for any card-header containing "Codex" to appear
  62. const header = await waitForElementByText('.card-header', /codex/i, 30000);
  63. loginBtn = header.querySelector('button.btn.btn-primary, button.btn');
  64. log('Step 1: Found Codex OAuth card');
  65. } catch {
  66. throw new Error(
  67. 'Codex OAuth card did not appear after 30s. Page may still be loading or not logged in. ' +
  68. 'Current URL: ' + location.href
  69. );
  70. }
  71. if (!loginBtn) {
  72. throw new Error('Found Codex OAuth card but no login button inside it. URL: ' + location.href);
  73. }
  74. // Check if button is disabled (already clicked / loading)
  75. if (loginBtn.disabled) {
  76. log('Step 1: Login button is disabled (already loading), waiting for auth URL...');
  77. } else {
  78. await humanPause(500, 1400);
  79. simulateClick(loginBtn);
  80. log('Step 1: Clicked login button, waiting for auth URL...');
  81. }
  82. // Wait for the auth URL to appear in the specific div
  83. let authUrlEl = null;
  84. try {
  85. authUrlEl = await waitForElement('[class*="authUrlValue"]', 15000);
  86. } catch {
  87. throw new Error(
  88. 'Auth URL did not appear after clicking login. ' +
  89. 'Check if VPS panel is logged in and Codex service is running. URL: ' + location.href
  90. );
  91. }
  92. const oauthUrl = (authUrlEl.textContent || '').trim();
  93. if (!oauthUrl || !oauthUrl.startsWith('http')) {
  94. throw new Error(`Invalid OAuth URL found: "${oauthUrl.slice(0, 50)}". Expected URL starting with http.`);
  95. }
  96. log(`Step 1: OAuth URL obtained: ${oauthUrl.slice(0, 80)}...`, 'ok');
  97. reportComplete(1, { oauthUrl });
  98. }
  99. // ============================================================
  100. // Step 9: VPS Verify — paste localhost URL and submit
  101. // ============================================================
  102. async function step9_vpsVerify(payload) {
  103. // Get localhostUrl from payload (passed directly by background) or fallback to state
  104. let localhostUrl = payload?.localhostUrl;
  105. if (!localhostUrl) {
  106. log('Step 9: localhostUrl not in payload, fetching from state...');
  107. const state = await chrome.runtime.sendMessage({ type: 'GET_STATE' });
  108. localhostUrl = state.localhostUrl;
  109. }
  110. if (!localhostUrl) {
  111. throw new Error('No localhost URL found. Complete step 8 first.');
  112. }
  113. log(`Step 9: Got localhostUrl: ${localhostUrl.slice(0, 60)}...`);
  114. log('Step 9: Looking for callback URL input...');
  115. // Find the callback URL input
  116. // Actual DOM: <input class="input" placeholder="http://localhost:1455/auth/callback?code=...&state=...">
  117. let urlInput = null;
  118. try {
  119. urlInput = await waitForElement('[class*="callbackSection"] input.input', 10000);
  120. } catch {
  121. try {
  122. urlInput = await waitForElement('input[placeholder*="localhost"]', 5000);
  123. } catch {
  124. throw new Error('Could not find callback URL input on VPS panel. URL: ' + location.href);
  125. }
  126. }
  127. await humanPause(600, 1500);
  128. fillInput(urlInput, localhostUrl);
  129. log(`Step 9: Filled callback URL: ${localhostUrl.slice(0, 80)}...`);
  130. // Find and click submit callback button (supports both Chinese and English UI)
  131. let submitBtn = null;
  132. try {
  133. submitBtn = await waitForElementByText(
  134. '[class*="callbackActions"] button, [class*="callbackSection"] button',
  135. /提交|submit/i,
  136. 5000
  137. );
  138. } catch {
  139. try {
  140. submitBtn = await waitForElementByText('button.btn', /提交回调|submit.*callback/i, 5000);
  141. } catch {
  142. // Last resort: find the button next to the input in callbackSection
  143. const section = document.querySelector('[class*="callbackSection"]');
  144. submitBtn = section?.querySelector('button');
  145. if (!submitBtn) {
  146. throw new Error('Could not find submit callback button. URL: ' + location.href);
  147. }
  148. }
  149. }
  150. await humanPause(450, 1200);
  151. simulateClick(submitBtn);
  152. log('Step 9: Clicked submit callback button, waiting for authentication result...');
  153. // Wait for success status (supports both Chinese and English)
  154. try {
  155. await waitForElementByText('.status-badge, [class*="status"]', /认证成功|auth.*success|verified|active/i, 30000);
  156. log('Step 9: Authentication successful!', 'ok');
  157. } catch {
  158. const statusEl = document.querySelector('.status-badge, [class*="status"]');
  159. const statusText = statusEl ? statusEl.textContent : 'unknown';
  160. if (/成功|success|verified|active/i.test(statusText)) {
  161. log('Step 9: Authentication successful!', 'ok');
  162. } else {
  163. log(`Step 9: Status after submit: "${statusText}". May still be processing.`, 'warn');
  164. }
  165. }
  166. reportComplete(9);
  167. }