vps-panel.js 13 KB

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