vps-panel.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. handleStep(message.step, message.payload).then(() => {
  34. sendResponse({ ok: true });
  35. }).catch(err => {
  36. if (isStopError(err)) {
  37. log(`步骤 ${message.step}:已被用户停止。`, 'warn');
  38. sendResponse({ stopped: true, error: err.message });
  39. return;
  40. }
  41. reportError(message.step, err.message);
  42. sendResponse({ error: err.message });
  43. });
  44. return true;
  45. }
  46. });
  47. } else {
  48. console.log('[MultiPage:vps-panel] 消息监听已存在,跳过重复注册');
  49. }
  50. async function handleStep(step, payload) {
  51. switch (step) {
  52. case 1: return await step1_getOAuthLink(payload);
  53. case 9: return await step9_vpsVerify(payload);
  54. default:
  55. throw new Error(`vps-panel.js 不处理步骤 ${step}`);
  56. }
  57. }
  58. function isVisibleElement(el) {
  59. if (!el) return false;
  60. const style = window.getComputedStyle(el);
  61. const rect = el.getBoundingClientRect();
  62. return style.display !== 'none'
  63. && style.visibility !== 'hidden'
  64. && rect.width > 0
  65. && rect.height > 0;
  66. }
  67. function getActionText(el) {
  68. return [
  69. el?.textContent,
  70. el?.value,
  71. el?.getAttribute?.('aria-label'),
  72. el?.getAttribute?.('title'),
  73. ]
  74. .filter(Boolean)
  75. .join(' ')
  76. .replace(/\s+/g, ' ')
  77. .trim();
  78. }
  79. function parseUrlSafely(rawUrl) {
  80. if (!rawUrl) return null;
  81. try {
  82. return new URL(rawUrl);
  83. } catch {
  84. return null;
  85. }
  86. }
  87. function isLocalhostOAuthCallbackUrl(rawUrl) {
  88. const parsed = parseUrlSafely(rawUrl);
  89. if (!parsed) return false;
  90. if (!['http:', 'https:'].includes(parsed.protocol)) return false;
  91. if (!['localhost', '127.0.0.1'].includes(parsed.hostname)) return false;
  92. if (parsed.pathname !== '/auth/callback') return false;
  93. const code = (parsed.searchParams.get('code') || '').trim();
  94. const state = (parsed.searchParams.get('state') || '').trim();
  95. return Boolean(code && state);
  96. }
  97. function getStatusBadgeElement() {
  98. const selectors = [
  99. '#root > div > div > div > main > div > div > div > div > div:nth-child(1) > div > div.OAuthPage-module__cardContent___1sXLA > div.status-badge',
  100. '#root .OAuthPage-module__cardContent___1sXLA > .status-badge',
  101. '.OAuthPage-module__cardContent___1sXLA > .status-badge',
  102. '.status-badge',
  103. ];
  104. for (const selector of selectors) {
  105. const candidates = document.querySelectorAll(selector);
  106. const visible = Array.from(candidates).find(isVisibleElement);
  107. if (visible) return visible;
  108. }
  109. return null;
  110. }
  111. function getStatusBadgeText() {
  112. const statusEl = getStatusBadgeElement();
  113. return statusEl ? (statusEl.textContent || '').replace(/\s+/g, ' ').trim() : '';
  114. }
  115. function isOAuthCallbackTimeoutFailure(statusText) {
  116. return /认证失败:\s*Timeout waiting for OAuth callback/i.test(statusText || '');
  117. }
  118. async function waitForExactSuccessBadge(timeout = 30000) {
  119. const start = Date.now();
  120. while (Date.now() - start < timeout) {
  121. throwIfStopped();
  122. const statusText = getStatusBadgeText();
  123. if (statusText === '认证成功!') {
  124. return statusText;
  125. }
  126. await sleep(200);
  127. }
  128. const finalText = getStatusBadgeText();
  129. if (isOAuthCallbackTimeoutFailure(finalText)) {
  130. throw new Error(`STEP9_OAUTH_TIMEOUT::${finalText}`);
  131. }
  132. throw new Error(finalText
  133. ? `CPA 面板状态不是“认证成功!”,当前为“${finalText}”。`
  134. : 'CPA 面板长时间未出现“认证成功!”状态徽标。');
  135. }
  136. function findManagementKeyInput() {
  137. const candidates = document.querySelectorAll(
  138. '.LoginPage-module__loginCard___OgP-R input[type="password"], input[placeholder*="管理密钥"], input[aria-label*="管理密钥"]'
  139. );
  140. return Array.from(candidates).find(isVisibleElement) || null;
  141. }
  142. function findManagementLoginButton() {
  143. const candidates = document.querySelectorAll('.LoginPage-module__loginCard___OgP-R button, .LoginPage-module__loginCard___OgP-R .btn');
  144. return Array.from(candidates).find((el) => {
  145. if (!isVisibleElement(el)) return false;
  146. return /登录|login/i.test(getActionText(el));
  147. }) || null;
  148. }
  149. function findRememberPasswordCheckbox() {
  150. const candidates = document.querySelectorAll('.LoginPage-module__loginCard___OgP-R input[type="checkbox"]');
  151. return Array.from(candidates).find((el) => {
  152. const label = el.closest('label');
  153. const text = getActionText(label || el);
  154. return /记住密码|remember/i.test(text);
  155. }) || null;
  156. }
  157. function findOAuthNavLink() {
  158. const candidates = document.querySelectorAll('a[href*="#/oauth"], a.nav-item, button, [role="link"], [role="button"]');
  159. return Array.from(candidates).find((el) => {
  160. if (!isVisibleElement(el)) return false;
  161. const text = getActionText(el);
  162. const href = el.getAttribute('href') || '';
  163. return href.includes('#/oauth') || /oauth/i.test(text);
  164. }) || null;
  165. }
  166. function findCodexOAuthHeader() {
  167. const candidates = document.querySelectorAll('.card-header, [class*="cardHeader"], .card, [class*="card"]');
  168. return Array.from(candidates).find((el) => {
  169. if (!isVisibleElement(el)) return false;
  170. const text = (el.textContent || '').toLowerCase();
  171. return text.includes('codex') && text.includes('oauth');
  172. }) || null;
  173. }
  174. function findOAuthCardLoginButton(header) {
  175. const card = header?.closest('.card, [class*="card"]') || header?.parentElement || document;
  176. const candidates = card.querySelectorAll('button.btn.btn-primary, button.btn-primary, button.btn');
  177. return Array.from(candidates).find((el) => isVisibleElement(el) && /登录|login/i.test(getActionText(el))) || null;
  178. }
  179. function findAuthUrlElement() {
  180. const candidates = document.querySelectorAll('[class*="authUrlValue"], .OAuthPage-module__authUrlValue___axvUJ');
  181. return Array.from(candidates).find((el) => isVisibleElement(el) && /^https?:\/\//i.test((el.textContent || '').trim())) || null;
  182. }
  183. async function ensureOAuthManagementPage(vpsPassword, step = 1, timeout = 45000) {
  184. const start = Date.now();
  185. let lastLoginAttemptAt = 0;
  186. let lastOauthNavAttemptAt = 0;
  187. while (Date.now() - start < timeout) {
  188. throwIfStopped();
  189. const authUrlEl = findAuthUrlElement();
  190. if (authUrlEl) {
  191. return { header: findCodexOAuthHeader(), authUrlEl };
  192. }
  193. const oauthHeader = findCodexOAuthHeader();
  194. if (oauthHeader) {
  195. return { header: oauthHeader, authUrlEl: null };
  196. }
  197. const managementKeyInput = findManagementKeyInput();
  198. const managementLoginButton = findManagementLoginButton();
  199. if (managementKeyInput && managementLoginButton) {
  200. if (!vpsPassword) {
  201. throw new Error('CPA 面板需要管理密钥,请先在侧边栏填写 CPA Key(管理密钥)。');
  202. }
  203. if ((managementKeyInput.value || '') !== vpsPassword) {
  204. await humanPause(350, 900);
  205. fillInput(managementKeyInput, vpsPassword);
  206. log(`步骤 ${step}:已填写 CPA 管理密钥。`);
  207. }
  208. const rememberCheckbox = findRememberPasswordCheckbox();
  209. if (rememberCheckbox && !rememberCheckbox.checked) {
  210. simulateClick(rememberCheckbox);
  211. log(`步骤 ${step}:已勾选 CPA 面板“记住密码”。`);
  212. await sleep(300);
  213. }
  214. if (Date.now() - lastLoginAttemptAt > 3000) {
  215. lastLoginAttemptAt = Date.now();
  216. await humanPause(350, 900);
  217. simulateClick(managementLoginButton);
  218. log(`步骤 ${step}:已提交 CPA 管理登录。`);
  219. }
  220. await sleep(1500);
  221. continue;
  222. }
  223. const oauthNavLink = findOAuthNavLink();
  224. if (oauthNavLink && Date.now() - lastOauthNavAttemptAt > 2000) {
  225. lastOauthNavAttemptAt = Date.now();
  226. await humanPause(300, 800);
  227. simulateClick(oauthNavLink);
  228. log(`步骤 ${step}:已打开“OAuth 登录”导航。`);
  229. await sleep(1200);
  230. continue;
  231. }
  232. await sleep(250);
  233. }
  234. throw new Error('无法进入 CPA 的 OAuth 管理页面,请检查面板是否正常加载。URL: ' + location.href);
  235. }
  236. // ============================================================
  237. // Step 1: Get OAuth Link
  238. // ============================================================
  239. async function step1_getOAuthLink(payload) {
  240. const { vpsPassword } = payload || {};
  241. log('步骤 1:正在等待 CPA 面板加载并进入 OAuth 页面...');
  242. const { header, authUrlEl: existingAuthUrlEl } = await ensureOAuthManagementPage(vpsPassword, 1);
  243. let authUrlEl = existingAuthUrlEl;
  244. if (!authUrlEl) {
  245. const loginBtn = findOAuthCardLoginButton(header);
  246. if (!loginBtn) {
  247. throw new Error('已找到 Codex OAuth 卡片,但卡片内没有登录按钮。URL: ' + location.href);
  248. }
  249. if (loginBtn.disabled) {
  250. log('步骤 1:OAuth 登录按钮当前不可用,正在等待授权链接出现...');
  251. } else {
  252. await humanPause(500, 1400);
  253. simulateClick(loginBtn);
  254. log('步骤 1:已点击 OAuth 登录按钮,正在等待授权链接...');
  255. }
  256. try {
  257. authUrlEl = await waitForElement('[class*="authUrlValue"]', 15000);
  258. } catch {
  259. throw new Error(
  260. '点击 OAuth 登录按钮后未出现授权链接。' +
  261. '请检查 CPA 面板服务是否正在运行。URL: ' + location.href
  262. );
  263. }
  264. } else {
  265. log('步骤 1:CPA 面板上已显示授权链接。');
  266. }
  267. const oauthUrl = (authUrlEl.textContent || '').trim();
  268. if (!oauthUrl || !oauthUrl.startsWith('http')) {
  269. throw new Error(`拿到的 OAuth 链接无效:\"${oauthUrl.slice(0, 50)}\"。应为 http 开头的 URL。`);
  270. }
  271. log(`步骤 1:已获取 OAuth 链接:${oauthUrl.slice(0, 80)}...`, 'ok');
  272. reportComplete(1, { oauthUrl });
  273. }
  274. // ============================================================
  275. // 步骤 9:CPA 回调验证——填写 localhost 回调地址并提交
  276. // ============================================================
  277. async function step9_vpsVerify(payload) {
  278. await ensureOAuthManagementPage(payload?.vpsPassword, 9);
  279. // 优先从 payload 读取 localhostUrl;没有时再回退到全局状态
  280. let localhostUrl = payload?.localhostUrl;
  281. if (localhostUrl && !isLocalhostOAuthCallbackUrl(localhostUrl)) {
  282. throw new Error('步骤 9 只接受真实的 localhost OAuth 回调地址,请重新执行步骤 8。');
  283. }
  284. if (!localhostUrl) {
  285. log('步骤 9:payload 中没有 localhostUrl,正在从状态中读取...');
  286. const state = await chrome.runtime.sendMessage({ type: 'GET_STATE' });
  287. localhostUrl = state.localhostUrl;
  288. if (localhostUrl && !isLocalhostOAuthCallbackUrl(localhostUrl)) {
  289. throw new Error('步骤 9 只接受真实的 localhost OAuth 回调地址,请重新执行步骤 8。');
  290. }
  291. }
  292. if (!localhostUrl) {
  293. throw new Error('未找到 localhost 回调地址,请先完成步骤 8。');
  294. }
  295. log(`步骤 9:已获取 localhostUrl:${localhostUrl.slice(0, 60)}...`);
  296. log('步骤 9:正在查找回调地址输入框...');
  297. // Find the callback URL input
  298. // Actual DOM: <input class="input" placeholder="http://localhost:1455/auth/callback?code=...&state=...">
  299. let urlInput = null;
  300. try {
  301. urlInput = await waitForElement('[class*="callbackSection"] input.input', 10000);
  302. } catch {
  303. try {
  304. urlInput = await waitForElement('input[placeholder*="localhost"]', 5000);
  305. } catch {
  306. throw new Error('在 CPA 面板中未找到回调地址输入框。URL: ' + location.href);
  307. }
  308. }
  309. await humanPause(600, 1500);
  310. fillInput(urlInput, localhostUrl);
  311. log(`步骤 9:已填写回调地址:${localhostUrl.slice(0, 80)}...`);
  312. // Find and click "提交回调 URL" button
  313. let submitBtn = null;
  314. try {
  315. submitBtn = await waitForElementByText(
  316. '[class*="callbackActions"] button, [class*="callbackSection"] button',
  317. /提交/,
  318. 5000
  319. );
  320. } catch {
  321. try {
  322. submitBtn = await waitForElementByText('button.btn', /提交回调/, 5000);
  323. } catch {
  324. throw new Error('未找到“提交回调 URL”按钮。URL: ' + location.href);
  325. }
  326. }
  327. await humanPause(450, 1200);
  328. simulateClick(submitBtn);
  329. log('步骤 9:已点击“提交回调 URL”,正在等待认证结果...');
  330. const verifiedStatus = await waitForExactSuccessBadge();
  331. log(`步骤 9:${verifiedStatus}`, 'ok');
  332. reportComplete(9, { localhostUrl, verifiedStatus });
  333. }