vps-panel.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  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 STEP9_SUCCESS_BADGE_TIMEOUT_MS = 120000;
  28. const {
  29. isRecoverableStep9AuthFailure,
  30. } = self.MultiPageActivationUtils || {};
  31. if (document.documentElement.getAttribute(VPS_PANEL_LISTENER_SENTINEL) !== '1') {
  32. document.documentElement.setAttribute(VPS_PANEL_LISTENER_SENTINEL, '1');
  33. // Listen for commands from Background
  34. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  35. if (message.type === 'EXECUTE_STEP') {
  36. resetStopState();
  37. const startedAt = Date.now();
  38. console.log(LOG_PREFIX, `EXECUTE_STEP received for step ${message.step}`, {
  39. url: location.href,
  40. payloadKeys: Object.keys(message.payload || {}),
  41. snapshot: getVpsPanelSnapshot(),
  42. });
  43. handleStep(message.step, message.payload).then(() => {
  44. console.log(LOG_PREFIX, `EXECUTE_STEP resolved for step ${message.step} after ${Date.now() - startedAt}ms`, {
  45. url: location.href,
  46. snapshot: getVpsPanelSnapshot(),
  47. });
  48. sendResponse({ ok: true });
  49. }).catch(err => {
  50. console.error(LOG_PREFIX, `EXECUTE_STEP rejected for step ${message.step} after ${Date.now() - startedAt}ms: ${err?.message || err}`, {
  51. url: location.href,
  52. snapshot: getVpsPanelSnapshot(),
  53. });
  54. if (isStopError(err)) {
  55. log(`步骤 ${message.step}:已被用户停止。`, 'warn');
  56. sendResponse({ stopped: true, error: err.message });
  57. return;
  58. }
  59. reportError(message.step, err.message);
  60. sendResponse({ error: err.message });
  61. });
  62. return true;
  63. }
  64. });
  65. } else {
  66. console.log('[MultiPage:vps-panel] 消息监听已存在,跳过重复注册');
  67. }
  68. async function handleStep(step, payload) {
  69. switch (step) {
  70. case 1: return await step1_getOAuthLink(payload);
  71. case 9: return await step9_vpsVerify(payload);
  72. default:
  73. throw new Error(`vps-panel.js 不处理步骤 ${step}`);
  74. }
  75. }
  76. function isVisibleElement(el) {
  77. if (!el) return false;
  78. const style = window.getComputedStyle(el);
  79. const rect = el.getBoundingClientRect();
  80. return style.display !== 'none'
  81. && style.visibility !== 'hidden'
  82. && rect.width > 0
  83. && rect.height > 0;
  84. }
  85. function getActionText(el) {
  86. return [
  87. el?.textContent,
  88. el?.value,
  89. el?.getAttribute?.('aria-label'),
  90. el?.getAttribute?.('title'),
  91. ]
  92. .filter(Boolean)
  93. .join(' ')
  94. .replace(/\s+/g, ' ')
  95. .trim();
  96. }
  97. function getInlineTextSnippet(text, maxLength = 160) {
  98. const normalized = (text || '').replace(/\s+/g, ' ').trim();
  99. if (!normalized) return '';
  100. if (normalized.length <= maxLength) return normalized;
  101. return `${normalized.slice(0, maxLength)}...`;
  102. }
  103. function getPageTextSnippet(maxLength = 240) {
  104. const bodyText = document.body?.innerText || document.documentElement?.innerText || '';
  105. return getInlineTextSnippet(bodyText, maxLength);
  106. }
  107. function getVpsPanelSnapshot() {
  108. const authUrlEl = findAuthUrlElement();
  109. const oauthHeader = findCodexOAuthHeader();
  110. const managementKeyInput = findManagementKeyInput();
  111. const managementLoginButton = findManagementLoginButton();
  112. const rememberCheckbox = findRememberPasswordCheckbox();
  113. const oauthNavLink = findOAuthNavLink();
  114. return {
  115. url: location.href,
  116. readyState: document.readyState,
  117. title: getInlineTextSnippet(document.title || '', 80),
  118. authUrlVisible: Boolean(authUrlEl),
  119. authUrlText: getInlineTextSnippet(authUrlEl?.textContent || '', 120),
  120. oauthHeaderVisible: Boolean(oauthHeader),
  121. oauthHeaderText: getInlineTextSnippet(oauthHeader?.textContent || '', 120),
  122. managementKeyVisible: Boolean(managementKeyInput),
  123. managementLoginVisible: Boolean(managementLoginButton),
  124. managementLoginText: getInlineTextSnippet(getActionText(managementLoginButton), 60),
  125. rememberCheckboxVisible: Boolean(rememberCheckbox),
  126. rememberCheckboxChecked: Boolean(rememberCheckbox?.checked),
  127. oauthNavVisible: Boolean(oauthNavLink),
  128. oauthNavText: getInlineTextSnippet(getActionText(oauthNavLink), 80),
  129. bodySnippet: getPageTextSnippet(),
  130. };
  131. }
  132. function getVpsPanelSnapshotSignature(snapshot) {
  133. return JSON.stringify({
  134. readyState: snapshot.readyState,
  135. title: snapshot.title,
  136. authUrlVisible: snapshot.authUrlVisible,
  137. authUrlText: snapshot.authUrlText,
  138. oauthHeaderVisible: snapshot.oauthHeaderVisible,
  139. oauthHeaderText: snapshot.oauthHeaderText,
  140. managementKeyVisible: snapshot.managementKeyVisible,
  141. managementLoginVisible: snapshot.managementLoginVisible,
  142. rememberCheckboxVisible: snapshot.rememberCheckboxVisible,
  143. rememberCheckboxChecked: snapshot.rememberCheckboxChecked,
  144. oauthNavVisible: snapshot.oauthNavVisible,
  145. oauthNavText: snapshot.oauthNavText,
  146. bodySnippet: snapshot.bodySnippet,
  147. });
  148. }
  149. function parseUrlSafely(rawUrl) {
  150. if (!rawUrl) return null;
  151. try {
  152. return new URL(rawUrl);
  153. } catch {
  154. return null;
  155. }
  156. }
  157. function isLocalhostOAuthCallbackUrl(rawUrl) {
  158. const parsed = parseUrlSafely(rawUrl);
  159. if (!parsed) return false;
  160. if (!['http:', 'https:'].includes(parsed.protocol)) return false;
  161. if (!['localhost', '127.0.0.1'].includes(parsed.hostname)) return false;
  162. if (!['/auth/callback', '/codex/callback'].includes(parsed.pathname)) return false;
  163. const code = (parsed.searchParams.get('code') || '').trim();
  164. const state = (parsed.searchParams.get('state') || '').trim();
  165. return Boolean(code && state);
  166. }
  167. function getStatusBadgeSelectors() {
  168. return [
  169. '#root > div > div > div > main > div > div > div > div > div:nth-child(1) > div > div.OAuthPage-module__cardContent___1sXLA > div.status-badge',
  170. '#root .OAuthPage-module__cardContent___1sXLA > .status-badge',
  171. '.OAuthPage-module__cardContent___1sXLA > .status-badge',
  172. '.status-badge',
  173. ];
  174. }
  175. function getStatusBadgeEntries() {
  176. const seen = new Set();
  177. const entries = [];
  178. for (const selector of getStatusBadgeSelectors()) {
  179. const candidates = document.querySelectorAll(selector);
  180. for (const candidate of candidates) {
  181. if (seen.has(candidate)) continue;
  182. seen.add(candidate);
  183. entries.push({
  184. element: candidate,
  185. selector,
  186. visible: isVisibleElement(candidate),
  187. text: (candidate.textContent || '').replace(/\s+/g, ' ').trim(),
  188. className: String(candidate.className || '').replace(/\s+/g, ' ').trim(),
  189. });
  190. }
  191. }
  192. return entries;
  193. }
  194. function summarizeStatusBadgeEntries(entries) {
  195. if (!entries.length) return '无可见状态徽标';
  196. return entries
  197. .map((entry, index) => {
  198. const text = entry.text || '(空文本)';
  199. const className = entry.className ? ` class=${getInlineTextSnippet(entry.className, 80)}` : '';
  200. return `#${index + 1}="${getInlineTextSnippet(text, 80)}"${className}`;
  201. })
  202. .join(' | ');
  203. }
  204. function getStatusBadgeDiagnostics() {
  205. const entries = getStatusBadgeEntries();
  206. const visibleEntries = entries.filter((entry) => entry.visible);
  207. const selectedEntry = visibleEntries[0] || null;
  208. const selectedText = selectedEntry?.text || '';
  209. const successLikeEntries = visibleEntries.filter((entry) => /认证成功/.test(entry.text || ''));
  210. const exactSuccessEntries = visibleEntries.filter((entry) => entry.text === '认证成功!');
  211. const visibleSummary = summarizeStatusBadgeEntries(visibleEntries);
  212. const pageSnippet = getPageTextSnippet();
  213. return {
  214. selectedText,
  215. visibleCount: visibleEntries.length,
  216. visibleSummary,
  217. hasSuccessLikeVisibleBadge: successLikeEntries.length > 0,
  218. hasExactSuccessVisibleBadge: exactSuccessEntries.length > 0,
  219. successLikeSummary: summarizeStatusBadgeEntries(successLikeEntries),
  220. exactSuccessSummary: summarizeStatusBadgeEntries(exactSuccessEntries),
  221. pageSnippet,
  222. signature: JSON.stringify({
  223. selectedText,
  224. visibleCount: visibleEntries.length,
  225. visibleSummary,
  226. successLikeSummary: summarizeStatusBadgeEntries(successLikeEntries),
  227. }),
  228. summary: selectedText
  229. ? `当前选中徽标="${getInlineTextSnippet(selectedText, 80)}";可见徽标 ${visibleEntries.length} 个:${visibleSummary}`
  230. : `当前未选中任何可见状态徽标;可见徽标 ${visibleEntries.length} 个:${visibleSummary};页面片段="${getInlineTextSnippet(pageSnippet, 120)}"`,
  231. };
  232. }
  233. function getStatusBadgeElement() {
  234. const visibleEntry = getStatusBadgeEntries().find((entry) => entry.visible);
  235. return visibleEntry ? visibleEntry.element : null;
  236. }
  237. function getStatusBadgeText() {
  238. const diagnostics = getStatusBadgeDiagnostics();
  239. return diagnostics.selectedText;
  240. }
  241. function isOAuthCallbackTimeoutFailure(statusText) {
  242. return /认证失败:\s*Timeout waiting for OAuth callback/i.test(statusText || '');
  243. }
  244. async function waitForExactSuccessBadge(timeout = STEP9_SUCCESS_BADGE_TIMEOUT_MS) {
  245. const start = Date.now();
  246. let lastDiagnosticsSignature = '';
  247. let lastHeartbeatLoggedAt = 0;
  248. let lastSuccessLikeMismatchSignature = '';
  249. while (Date.now() - start < timeout) {
  250. throwIfStopped();
  251. const diagnostics = getStatusBadgeDiagnostics();
  252. const statusText = diagnostics.selectedText;
  253. const elapsed = Date.now() - start;
  254. if (diagnostics.signature !== lastDiagnosticsSignature) {
  255. lastDiagnosticsSignature = diagnostics.signature;
  256. lastHeartbeatLoggedAt = elapsed;
  257. log(`步骤 9:认证状态检测中,${diagnostics.summary}`);
  258. console.log(LOG_PREFIX, '[Step 9] status badge diagnostics changed', diagnostics);
  259. } else if (elapsed - lastHeartbeatLoggedAt >= 10000) {
  260. lastHeartbeatLoggedAt = elapsed;
  261. log(`步骤 9:仍在等待认证成功,${diagnostics.summary}`);
  262. console.log(LOG_PREFIX, '[Step 9] still waiting for success badge', diagnostics);
  263. }
  264. if (diagnostics.hasSuccessLikeVisibleBadge && !diagnostics.hasExactSuccessVisibleBadge) {
  265. const mismatchSignature = JSON.stringify({
  266. selectedText: diagnostics.selectedText,
  267. successLikeSummary: diagnostics.successLikeSummary,
  268. visibleSummary: diagnostics.visibleSummary,
  269. });
  270. if (mismatchSignature !== lastSuccessLikeMismatchSignature) {
  271. lastSuccessLikeMismatchSignature = mismatchSignature;
  272. log(
  273. `步骤 9:检测到“认证成功”相关徽标,但未命中精确条件。当前选中="${getInlineTextSnippet(diagnostics.selectedText || '(空)', 80)}";成功相关徽标:${diagnostics.successLikeSummary}`,
  274. 'warn'
  275. );
  276. console.warn(LOG_PREFIX, '[Step 9] success-like badge detected without exact match', diagnostics);
  277. }
  278. }
  279. if (isOAuthCallbackTimeoutFailure(statusText)) {
  280. throw new Error(`STEP9_OAUTH_TIMEOUT::${statusText}`);
  281. }
  282. if (typeof isRecoverableStep9AuthFailure === 'function' && isRecoverableStep9AuthFailure(statusText)) {
  283. throw new Error(`STEP9_OAUTH_RETRY::${statusText}`);
  284. }
  285. if (statusText === '认证成功!') {
  286. return statusText;
  287. }
  288. await sleep(200);
  289. }
  290. const finalDiagnostics = getStatusBadgeDiagnostics();
  291. const finalText = finalDiagnostics.selectedText;
  292. const diagnosticsSuffix = ` 当前诊断:${finalDiagnostics.summary}`;
  293. if (isOAuthCallbackTimeoutFailure(finalText)) {
  294. throw new Error(`STEP9_OAUTH_TIMEOUT::${finalText}${diagnosticsSuffix}`);
  295. }
  296. if (typeof isRecoverableStep9AuthFailure === 'function' && isRecoverableStep9AuthFailure(finalText)) {
  297. throw new Error(`STEP9_OAUTH_RETRY::${finalText}${diagnosticsSuffix}`);
  298. }
  299. throw new Error(finalText
  300. ? `CPA 面板状态不是“认证成功!”,当前为“${finalText}”。${diagnosticsSuffix}`
  301. : `CPA 面板长时间未出现“认证成功!”状态徽标。${diagnosticsSuffix}`);
  302. }
  303. function findManagementKeyInput() {
  304. const candidates = document.querySelectorAll(
  305. '.LoginPage-module__loginCard___OgP-R input[type="password"], input[placeholder*="管理密钥"], input[aria-label*="管理密钥"]'
  306. );
  307. return Array.from(candidates).find(isVisibleElement) || null;
  308. }
  309. function findManagementLoginButton() {
  310. const candidates = document.querySelectorAll('.LoginPage-module__loginCard___OgP-R button, .LoginPage-module__loginCard___OgP-R .btn');
  311. return Array.from(candidates).find((el) => {
  312. if (!isVisibleElement(el)) return false;
  313. return /登录|login/i.test(getActionText(el));
  314. }) || null;
  315. }
  316. function findRememberPasswordCheckbox() {
  317. const candidates = document.querySelectorAll('.LoginPage-module__loginCard___OgP-R input[type="checkbox"]');
  318. return Array.from(candidates).find((el) => {
  319. const label = el.closest('label');
  320. const text = getActionText(label || el);
  321. return /记住密码|remember/i.test(text);
  322. }) || null;
  323. }
  324. function findOAuthNavLink() {
  325. const candidates = document.querySelectorAll('a[href*="#/oauth"], a.nav-item, button, [role="link"], [role="button"]');
  326. return Array.from(candidates).find((el) => {
  327. if (!isVisibleElement(el)) return false;
  328. const text = getActionText(el);
  329. const href = el.getAttribute('href') || '';
  330. return href.includes('#/oauth') || /oauth/i.test(text);
  331. }) || null;
  332. }
  333. function findCodexOAuthHeader() {
  334. const candidates = document.querySelectorAll('.card-header, [class*="cardHeader"], .card, [class*="card"]');
  335. return Array.from(candidates).find((el) => {
  336. if (!isVisibleElement(el)) return false;
  337. const text = (el.textContent || '').toLowerCase();
  338. return text.includes('codex') && text.includes('oauth');
  339. }) || null;
  340. }
  341. function findOAuthCardLoginButton(header) {
  342. const card = header?.closest('.card, [class*="card"]') || header?.parentElement || document;
  343. const candidates = card.querySelectorAll('button.btn.btn-primary, button.btn-primary, button.btn');
  344. return Array.from(candidates).find((el) => isVisibleElement(el) && /登录|login/i.test(getActionText(el))) || null;
  345. }
  346. function findAuthUrlElement() {
  347. const candidates = document.querySelectorAll('[class*="authUrlValue"], .OAuthPage-module__authUrlValue___axvUJ');
  348. return Array.from(candidates).find((el) => isVisibleElement(el) && /^https?:\/\//i.test((el.textContent || '').trim())) || null;
  349. }
  350. async function ensureOAuthManagementPage(vpsPassword, step = 1, timeout = 45000) {
  351. const start = Date.now();
  352. let lastLoginAttemptAt = 0;
  353. let lastOauthNavAttemptAt = 0;
  354. let lastSnapshotSignature = '';
  355. let lastSnapshotLogAt = 0;
  356. console.log(LOG_PREFIX, `[Step ${step}] ensureOAuthManagementPage start`, {
  357. timeout,
  358. url: location.href,
  359. hasVpsPassword: Boolean(vpsPassword),
  360. snapshot: getVpsPanelSnapshot(),
  361. });
  362. while (Date.now() - start < timeout) {
  363. throwIfStopped();
  364. const elapsed = Date.now() - start;
  365. const snapshot = getVpsPanelSnapshot();
  366. const signature = getVpsPanelSnapshotSignature(snapshot);
  367. if (signature !== lastSnapshotSignature || elapsed - lastSnapshotLogAt >= 5000) {
  368. lastSnapshotSignature = signature;
  369. lastSnapshotLogAt = elapsed;
  370. console.log(LOG_PREFIX, `[Step ${step}] panel snapshot at ${elapsed}ms`, snapshot);
  371. }
  372. const authUrlEl = findAuthUrlElement();
  373. if (authUrlEl) {
  374. console.log(LOG_PREFIX, `[Step ${step}] found visible auth URL after ${elapsed}ms`, {
  375. url: location.href,
  376. authUrlText: getInlineTextSnippet(authUrlEl.textContent || '', 120),
  377. });
  378. return { header: findCodexOAuthHeader(), authUrlEl };
  379. }
  380. const oauthHeader = findCodexOAuthHeader();
  381. if (oauthHeader) {
  382. console.log(LOG_PREFIX, `[Step ${step}] found OAuth card header after ${elapsed}ms`, {
  383. url: location.href,
  384. headerText: getInlineTextSnippet(oauthHeader.textContent || '', 120),
  385. });
  386. return { header: oauthHeader, authUrlEl: null };
  387. }
  388. const managementKeyInput = findManagementKeyInput();
  389. const managementLoginButton = findManagementLoginButton();
  390. if (managementKeyInput && managementLoginButton) {
  391. if (!vpsPassword) {
  392. throw new Error('CPA 面板需要管理密钥,请先在侧边栏填写 CPA Key(管理密钥)。');
  393. }
  394. if ((managementKeyInput.value || '') !== vpsPassword) {
  395. await humanPause(350, 900);
  396. fillInput(managementKeyInput, vpsPassword);
  397. console.log(LOG_PREFIX, `[Step ${step}] filled management key after ${elapsed}ms`);
  398. log(`步骤 ${step}:已填写 CPA 管理密钥。`);
  399. }
  400. const rememberCheckbox = findRememberPasswordCheckbox();
  401. if (rememberCheckbox && !rememberCheckbox.checked) {
  402. simulateClick(rememberCheckbox);
  403. console.log(LOG_PREFIX, `[Step ${step}] toggled remember checkbox after ${elapsed}ms`);
  404. log(`步骤 ${step}:已勾选 CPA 面板“记住密码”。`);
  405. await sleep(300);
  406. }
  407. if (Date.now() - lastLoginAttemptAt > 3000) {
  408. lastLoginAttemptAt = Date.now();
  409. await humanPause(350, 900);
  410. simulateClick(managementLoginButton);
  411. console.log(LOG_PREFIX, `[Step ${step}] clicked management login after ${elapsed}ms`, {
  412. buttonText: getInlineTextSnippet(getActionText(managementLoginButton), 80),
  413. });
  414. log(`步骤 ${step}:已提交 CPA 管理登录。`);
  415. }
  416. await sleep(1500);
  417. continue;
  418. }
  419. const oauthNavLink = findOAuthNavLink();
  420. if (oauthNavLink && Date.now() - lastOauthNavAttemptAt > 2000) {
  421. lastOauthNavAttemptAt = Date.now();
  422. await humanPause(300, 800);
  423. simulateClick(oauthNavLink);
  424. console.log(LOG_PREFIX, `[Step ${step}] clicked OAuth nav after ${elapsed}ms`, {
  425. navText: getInlineTextSnippet(getActionText(oauthNavLink), 80),
  426. });
  427. log(`步骤 ${step}:已打开“OAuth 登录”导航。`);
  428. await sleep(1200);
  429. continue;
  430. }
  431. await sleep(250);
  432. }
  433. console.error(LOG_PREFIX, `[Step ${step}] ensureOAuthManagementPage timeout after ${Date.now() - start}ms`, {
  434. url: location.href,
  435. snapshot: getVpsPanelSnapshot(),
  436. });
  437. throw new Error('无法进入 CPA 的 OAuth 管理页面,请检查面板是否正常加载。URL: ' + location.href);
  438. }
  439. // ============================================================
  440. // Step 1: Get OAuth Link
  441. // ============================================================
  442. async function step1_getOAuthLink(payload) {
  443. const { vpsPassword } = payload || {};
  444. console.log(LOG_PREFIX, '[Step 1] step1_getOAuthLink start', {
  445. url: location.href,
  446. hasVpsPassword: Boolean(vpsPassword),
  447. snapshot: getVpsPanelSnapshot(),
  448. });
  449. log('步骤 1:正在等待 CPA 面板加载并进入 OAuth 页面...');
  450. const { header, authUrlEl: existingAuthUrlEl } = await ensureOAuthManagementPage(vpsPassword, 1);
  451. let authUrlEl = existingAuthUrlEl;
  452. console.log(LOG_PREFIX, '[Step 1] ensureOAuthManagementPage resolved', {
  453. url: location.href,
  454. hasHeader: Boolean(header),
  455. hasExistingAuthUrl: Boolean(existingAuthUrlEl),
  456. snapshot: getVpsPanelSnapshot(),
  457. });
  458. if (!authUrlEl) {
  459. const loginBtn = findOAuthCardLoginButton(header);
  460. if (!loginBtn) {
  461. throw new Error('已找到 Codex OAuth 卡片,但卡片内没有登录按钮。URL: ' + location.href);
  462. }
  463. if (loginBtn.disabled) {
  464. console.log(LOG_PREFIX, '[Step 1] OAuth login button is disabled, waiting for auth URL', {
  465. url: location.href,
  466. buttonText: getInlineTextSnippet(getActionText(loginBtn), 80),
  467. });
  468. log('步骤 1:OAuth 登录按钮当前不可用,正在等待授权链接出现...');
  469. } else {
  470. await humanPause(500, 1400);
  471. simulateClick(loginBtn);
  472. console.log(LOG_PREFIX, '[Step 1] clicked OAuth login button and waiting for auth URL', {
  473. url: location.href,
  474. buttonText: getInlineTextSnippet(getActionText(loginBtn), 80),
  475. });
  476. log('步骤 1:已点击 OAuth 登录按钮,正在等待授权链接...');
  477. }
  478. try {
  479. authUrlEl = await waitForElement('[class*="authUrlValue"]', 15000);
  480. } catch {
  481. throw new Error(
  482. '点击 OAuth 登录按钮后未出现授权链接。' +
  483. '请检查 CPA 面板服务是否正在运行。URL: ' + location.href
  484. );
  485. }
  486. } else {
  487. log('步骤 1:CPA 面板上已显示授权链接。');
  488. }
  489. const oauthUrl = (authUrlEl.textContent || '').trim();
  490. if (!oauthUrl || !oauthUrl.startsWith('http')) {
  491. throw new Error(`拿到的 OAuth 链接无效:\"${oauthUrl.slice(0, 50)}\"。应为 http 开头的 URL。`);
  492. }
  493. log(`步骤 1:已获取 OAuth 链接:${oauthUrl.slice(0, 80)}...`, 'ok');
  494. console.log(LOG_PREFIX, '[Step 1] reporting completion with oauthUrl', {
  495. url: location.href,
  496. oauthUrlPreview: oauthUrl.slice(0, 120),
  497. });
  498. reportComplete(1, { oauthUrl });
  499. }
  500. // ============================================================
  501. // 步骤 9:CPA 回调验证——填写 localhost 回调地址并提交
  502. // ============================================================
  503. async function step9_vpsVerify(payload) {
  504. await ensureOAuthManagementPage(payload?.vpsPassword, 9);
  505. // 优先从 payload 读取 localhostUrl;没有时再回退到全局状态
  506. let localhostUrl = payload?.localhostUrl;
  507. if (localhostUrl && !isLocalhostOAuthCallbackUrl(localhostUrl)) {
  508. throw new Error('步骤 9 只接受真实的 localhost OAuth 回调地址,请重新执行步骤 8。');
  509. }
  510. if (!localhostUrl) {
  511. log('步骤 9:payload 中没有 localhostUrl,正在从状态中读取...');
  512. const state = await chrome.runtime.sendMessage({ type: 'GET_STATE' });
  513. localhostUrl = state.localhostUrl;
  514. if (localhostUrl && !isLocalhostOAuthCallbackUrl(localhostUrl)) {
  515. throw new Error('步骤 9 只接受真实的 localhost OAuth 回调地址,请重新执行步骤 8。');
  516. }
  517. }
  518. if (!localhostUrl) {
  519. throw new Error('未找到 localhost 回调地址,请先完成步骤 8。');
  520. }
  521. log(`步骤 9:已获取 localhostUrl:${localhostUrl.slice(0, 60)}...`);
  522. log('步骤 9:正在查找回调地址输入框...');
  523. // Find the callback URL input
  524. // Actual DOM: <input class="input" placeholder="http://localhost:1455/auth/callback?code=...&state=...">
  525. let urlInput = null;
  526. try {
  527. urlInput = await waitForElement('[class*="callbackSection"] input.input', 10000);
  528. } catch {
  529. try {
  530. urlInput = await waitForElement('input[placeholder*="localhost"]', 5000);
  531. } catch {
  532. throw new Error('在 CPA 面板中未找到回调地址输入框。URL: ' + location.href);
  533. }
  534. }
  535. await humanPause(600, 1500);
  536. fillInput(urlInput, localhostUrl);
  537. log(`步骤 9:已填写回调地址:${localhostUrl.slice(0, 80)}...`);
  538. // Find and click "提交回调 URL" button
  539. let submitBtn = null;
  540. try {
  541. submitBtn = await waitForElementByText(
  542. '[class*="callbackActions"] button, [class*="callbackSection"] button',
  543. /提交/,
  544. 5000
  545. );
  546. } catch {
  547. try {
  548. submitBtn = await waitForElementByText('button.btn', /提交回调/, 5000);
  549. } catch {
  550. throw new Error('未找到“提交回调 URL”按钮。URL: ' + location.href);
  551. }
  552. }
  553. await humanPause(450, 1200);
  554. simulateClick(submitBtn);
  555. log('步骤 9:已点击“提交回调 URL”,正在等待认证结果...');
  556. const verifiedStatus = await waitForExactSuccessBadge();
  557. log(`步骤 9:${verifiedStatus}`, 'ok');
  558. reportComplete(9, { localhostUrl, verifiedStatus });
  559. }