vps-panel.js 13 KB

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