vps-panel.js 14 KB

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