vps-panel.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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(`步骤 ${message.step}:已被用户停止。`, '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(payload);
  47. case 9: return await step9_vpsVerify(payload);
  48. default:
  49. throw new Error(`vps-panel.js 不处理步骤 ${step}`);
  50. }
  51. }
  52. function isVisibleElement(el) {
  53. if (!el) return false;
  54. const style = window.getComputedStyle(el);
  55. const rect = el.getBoundingClientRect();
  56. return style.display !== 'none'
  57. && style.visibility !== 'hidden'
  58. && rect.width > 0
  59. && rect.height > 0;
  60. }
  61. function getActionText(el) {
  62. return [
  63. el?.textContent,
  64. el?.value,
  65. el?.getAttribute?.('aria-label'),
  66. el?.getAttribute?.('title'),
  67. ]
  68. .filter(Boolean)
  69. .join(' ')
  70. .replace(/\s+/g, ' ')
  71. .trim();
  72. }
  73. function findManagementKeyInput() {
  74. const candidates = document.querySelectorAll(
  75. '.LoginPage-module__loginCard___OgP-R input[type="password"], input[placeholder*="管理密钥"], input[aria-label*="管理密钥"]'
  76. );
  77. return Array.from(candidates).find(isVisibleElement) || null;
  78. }
  79. function findManagementLoginButton() {
  80. const candidates = document.querySelectorAll('.LoginPage-module__loginCard___OgP-R button, .LoginPage-module__loginCard___OgP-R .btn');
  81. return Array.from(candidates).find((el) => {
  82. if (!isVisibleElement(el)) return false;
  83. return /登录|login/i.test(getActionText(el));
  84. }) || null;
  85. }
  86. function findRememberPasswordCheckbox() {
  87. const candidates = document.querySelectorAll('.LoginPage-module__loginCard___OgP-R input[type="checkbox"]');
  88. return Array.from(candidates).find((el) => {
  89. const label = el.closest('label');
  90. const text = getActionText(label || el);
  91. return /记住密码|remember/i.test(text);
  92. }) || null;
  93. }
  94. function findOAuthNavLink() {
  95. const candidates = document.querySelectorAll('a[href*="#/oauth"], a.nav-item, button, [role="link"], [role="button"]');
  96. return Array.from(candidates).find((el) => {
  97. if (!isVisibleElement(el)) return false;
  98. const text = getActionText(el);
  99. const href = el.getAttribute('href') || '';
  100. return href.includes('#/oauth') || /oauth/i.test(text);
  101. }) || null;
  102. }
  103. function findCodexOAuthHeader() {
  104. const candidates = document.querySelectorAll('.card-header, [class*="cardHeader"], .card, [class*="card"]');
  105. return Array.from(candidates).find((el) => {
  106. if (!isVisibleElement(el)) return false;
  107. const text = (el.textContent || '').toLowerCase();
  108. return text.includes('codex') && text.includes('oauth');
  109. }) || null;
  110. }
  111. function findOAuthCardLoginButton(header) {
  112. const card = header?.closest('.card, [class*="card"]') || header?.parentElement || document;
  113. const candidates = card.querySelectorAll('button.btn.btn-primary, button.btn-primary, button.btn');
  114. return Array.from(candidates).find((el) => isVisibleElement(el) && /登录|login/i.test(getActionText(el))) || null;
  115. }
  116. function findAuthUrlElement() {
  117. const candidates = document.querySelectorAll('[class*="authUrlValue"], .OAuthPage-module__authUrlValue___axvUJ');
  118. return Array.from(candidates).find((el) => isVisibleElement(el) && /^https?:\/\//i.test((el.textContent || '').trim())) || null;
  119. }
  120. async function ensureOAuthManagementPage(vpsPassword, step = 1, timeout = 45000) {
  121. const start = Date.now();
  122. let lastLoginAttemptAt = 0;
  123. let lastOauthNavAttemptAt = 0;
  124. while (Date.now() - start < timeout) {
  125. throwIfStopped();
  126. const authUrlEl = findAuthUrlElement();
  127. if (authUrlEl) {
  128. return { header: findCodexOAuthHeader(), authUrlEl };
  129. }
  130. const oauthHeader = findCodexOAuthHeader();
  131. if (oauthHeader) {
  132. return { header: oauthHeader, authUrlEl: null };
  133. }
  134. const managementKeyInput = findManagementKeyInput();
  135. const managementLoginButton = findManagementLoginButton();
  136. if (managementKeyInput && managementLoginButton) {
  137. if (!vpsPassword) {
  138. throw new Error('VPS 面板需要管理密钥,请先在侧边栏填写 VPS Key(管理密钥)。');
  139. }
  140. if ((managementKeyInput.value || '') !== vpsPassword) {
  141. await humanPause(350, 900);
  142. fillInput(managementKeyInput, vpsPassword);
  143. log(`步骤 ${step}:已填写 VPS 管理密钥。`);
  144. }
  145. const rememberCheckbox = findRememberPasswordCheckbox();
  146. if (rememberCheckbox && !rememberCheckbox.checked) {
  147. simulateClick(rememberCheckbox);
  148. log(`步骤 ${step}:已勾选 VPS 面板“记住密码”。`);
  149. await sleep(300);
  150. }
  151. if (Date.now() - lastLoginAttemptAt > 3000) {
  152. lastLoginAttemptAt = Date.now();
  153. await humanPause(350, 900);
  154. simulateClick(managementLoginButton);
  155. log(`步骤 ${step}:已提交 VPS 管理登录。`);
  156. }
  157. await sleep(1500);
  158. continue;
  159. }
  160. const oauthNavLink = findOAuthNavLink();
  161. if (oauthNavLink && Date.now() - lastOauthNavAttemptAt > 2000) {
  162. lastOauthNavAttemptAt = Date.now();
  163. await humanPause(300, 800);
  164. simulateClick(oauthNavLink);
  165. log(`步骤 ${step}:已打开“OAuth 登录”导航。`);
  166. await sleep(1200);
  167. continue;
  168. }
  169. await sleep(250);
  170. }
  171. throw new Error('无法进入 VPS 的 OAuth 管理页面,请检查面板是否正常加载。URL: ' + location.href);
  172. }
  173. // ============================================================
  174. // Step 1: Get OAuth Link
  175. // ============================================================
  176. async function step1_getOAuthLink(payload) {
  177. const { vpsPassword } = payload || {};
  178. log('步骤 1:正在等待 VPS 面板加载并进入 OAuth 页面...');
  179. const { header, authUrlEl: existingAuthUrlEl } = await ensureOAuthManagementPage(vpsPassword, 1);
  180. let authUrlEl = existingAuthUrlEl;
  181. if (!authUrlEl) {
  182. const loginBtn = findOAuthCardLoginButton(header);
  183. if (!loginBtn) {
  184. throw new Error('已找到 Codex OAuth 卡片,但卡片内没有登录按钮。URL: ' + location.href);
  185. }
  186. if (loginBtn.disabled) {
  187. log('步骤 1:OAuth 登录按钮当前不可用,正在等待授权链接出现...');
  188. } else {
  189. await humanPause(500, 1400);
  190. simulateClick(loginBtn);
  191. log('步骤 1:已点击 OAuth 登录按钮,正在等待授权链接...');
  192. }
  193. try {
  194. authUrlEl = await waitForElement('[class*="authUrlValue"]', 15000);
  195. } catch {
  196. throw new Error(
  197. '点击 OAuth 登录按钮后未出现授权链接。' +
  198. '请检查 VPS 面板服务是否正在运行。URL: ' + location.href
  199. );
  200. }
  201. } else {
  202. log('步骤 1:VPS 面板上已显示授权链接。');
  203. }
  204. const oauthUrl = (authUrlEl.textContent || '').trim();
  205. if (!oauthUrl || !oauthUrl.startsWith('http')) {
  206. throw new Error(`拿到的 OAuth 链接无效:\"${oauthUrl.slice(0, 50)}\"。应为 http 开头的 URL。`);
  207. }
  208. log(`步骤 1:已获取 OAuth 链接:${oauthUrl.slice(0, 80)}...`, 'ok');
  209. reportComplete(1, { oauthUrl });
  210. }
  211. // ============================================================
  212. // Step 9: VPS Verify — paste localhost URL and submit
  213. // ============================================================
  214. async function step9_vpsVerify(payload) {
  215. await ensureOAuthManagementPage(payload?.vpsPassword, 9);
  216. // Get localhostUrl from payload (passed directly by background) or fallback to state
  217. let localhostUrl = payload?.localhostUrl;
  218. if (!localhostUrl) {
  219. log('步骤 9:payload 中没有 localhostUrl,正在从状态中读取...');
  220. const state = await chrome.runtime.sendMessage({ type: 'GET_STATE' });
  221. localhostUrl = state.localhostUrl;
  222. }
  223. if (!localhostUrl) {
  224. throw new Error('未找到 localhost 回调地址,请先完成步骤 8。');
  225. }
  226. log(`步骤 9:已获取 localhostUrl:${localhostUrl.slice(0, 60)}...`);
  227. log('步骤 9:正在查找回调地址输入框...');
  228. // Find the callback URL input
  229. // Actual DOM: <input class="input" placeholder="http://localhost:1455/auth/callback?code=...&state=...">
  230. let urlInput = null;
  231. try {
  232. urlInput = await waitForElement('[class*="callbackSection"] input.input', 10000);
  233. } catch {
  234. try {
  235. urlInput = await waitForElement('input[placeholder*="localhost"]', 5000);
  236. } catch {
  237. throw new Error('在 VPS 面板中未找到回调地址输入框。URL: ' + location.href);
  238. }
  239. }
  240. await humanPause(600, 1500);
  241. fillInput(urlInput, localhostUrl);
  242. log(`步骤 9:已填写回调地址:${localhostUrl.slice(0, 80)}...`);
  243. // Find and click "提交回调 URL" button
  244. let submitBtn = null;
  245. try {
  246. submitBtn = await waitForElementByText(
  247. '[class*="callbackActions"] button, [class*="callbackSection"] button',
  248. /提交/,
  249. 5000
  250. );
  251. } catch {
  252. try {
  253. submitBtn = await waitForElementByText('button.btn', /提交回调/, 5000);
  254. } catch {
  255. throw new Error('未找到“提交回调 URL”按钮。URL: ' + location.href);
  256. }
  257. }
  258. await humanPause(450, 1200);
  259. simulateClick(submitBtn);
  260. log('步骤 9:已点击“提交回调 URL”,正在等待认证结果...');
  261. // Wait for "认证成功!" status badge to appear
  262. try {
  263. await waitForElementByText('.status-badge, [class*="status"]', /认证成功/, 30000);
  264. log('步骤 9:认证成功!', 'ok');
  265. } catch {
  266. // Check if there's an error message instead
  267. const statusEl = document.querySelector('.status-badge, [class*="status"]');
  268. const statusText = statusEl ? statusEl.textContent : 'unknown';
  269. if (/成功|success/i.test(statusText)) {
  270. log('步骤 9:认证成功!', 'ok');
  271. } else {
  272. log(`步骤 9:提交后的状态为“${statusText}”,可能仍在处理中。`, 'warn');
  273. }
  274. }
  275. reportComplete(9);
  276. }