vps-panel.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  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' || message.type === 'REQUEST_OAUTH_URL') {
  36. resetStopState();
  37. const startedAt = Date.now();
  38. const actionLabel = message.type === 'REQUEST_OAUTH_URL'
  39. ? 'REQUEST_OAUTH_URL'
  40. : `EXECUTE_STEP received for step ${message.step}`;
  41. console.log(LOG_PREFIX, actionLabel, {
  42. url: location.href,
  43. payloadKeys: Object.keys(message.payload || {}),
  44. snapshot: getVpsPanelSnapshot(),
  45. });
  46. const handler = message.type === 'REQUEST_OAUTH_URL'
  47. ? requestOAuthUrl(message.payload)
  48. : handleStep(message.step, message.payload);
  49. handler.then((result) => {
  50. console.log(LOG_PREFIX, `${actionLabel} resolved after ${Date.now() - startedAt}ms`, {
  51. url: location.href,
  52. snapshot: getVpsPanelSnapshot(),
  53. });
  54. sendResponse({ ok: true, ...(result || {}) });
  55. }).catch(err => {
  56. console.error(LOG_PREFIX, `${actionLabel} rejected after ${Date.now() - startedAt}ms: ${err?.message || err}`, {
  57. url: location.href,
  58. snapshot: getVpsPanelSnapshot(),
  59. });
  60. if (isStopError(err)) {
  61. if (message.step) {
  62. log(`步骤 ${message.step}:已被用户停止。`, 'warn');
  63. }
  64. sendResponse({ stopped: true, error: err.message });
  65. return;
  66. }
  67. if (message.step) {
  68. reportError(message.step, err.message);
  69. }
  70. sendResponse({ error: err.message });
  71. });
  72. return true;
  73. }
  74. });
  75. } else {
  76. console.log('[MultiPage:vps-panel] 消息监听已存在,跳过重复注册');
  77. }
  78. async function handleStep(step, payload) {
  79. switch (step) {
  80. case 1: return await step1_getOAuthLink(payload);
  81. case 10: return await step9_vpsVerify(payload);
  82. default:
  83. throw new Error(`vps-panel.js 不处理步骤 ${step}`);
  84. }
  85. }
  86. function isVisibleElement(el) {
  87. if (!el) return false;
  88. const style = window.getComputedStyle(el);
  89. const rect = el.getBoundingClientRect();
  90. return style.display !== 'none'
  91. && style.visibility !== 'hidden'
  92. && rect.width > 0
  93. && rect.height > 0;
  94. }
  95. function getActionText(el) {
  96. return [
  97. el?.textContent,
  98. el?.value,
  99. el?.getAttribute?.('aria-label'),
  100. el?.getAttribute?.('title'),
  101. ]
  102. .filter(Boolean)
  103. .join(' ')
  104. .replace(/\s+/g, ' ')
  105. .trim();
  106. }
  107. function getInlineTextSnippet(text, maxLength = 160) {
  108. const normalized = (text || '').replace(/\s+/g, ' ').trim();
  109. if (!normalized) return '';
  110. if (normalized.length <= maxLength) return normalized;
  111. return `${normalized.slice(0, maxLength)}...`;
  112. }
  113. function getPageTextSnippet(maxLength = 240) {
  114. const bodyText = document.body?.innerText || document.documentElement?.innerText || '';
  115. return getInlineTextSnippet(bodyText, maxLength);
  116. }
  117. function getVpsPanelSnapshot() {
  118. const authUrlEl = findAuthUrlElement();
  119. const oauthHeader = findCodexOAuthHeader();
  120. const managementKeyInput = findManagementKeyInput();
  121. const managementLoginButton = findManagementLoginButton();
  122. const rememberCheckbox = findRememberPasswordCheckbox();
  123. const oauthNavLink = findOAuthNavLink();
  124. return {
  125. url: location.href,
  126. readyState: document.readyState,
  127. title: getInlineTextSnippet(document.title || '', 80),
  128. authUrlVisible: Boolean(authUrlEl),
  129. authUrlText: getInlineTextSnippet(authUrlEl?.textContent || '', 120),
  130. oauthHeaderVisible: Boolean(oauthHeader),
  131. oauthHeaderText: getInlineTextSnippet(oauthHeader?.textContent || '', 120),
  132. managementKeyVisible: Boolean(managementKeyInput),
  133. managementLoginVisible: Boolean(managementLoginButton),
  134. managementLoginText: getInlineTextSnippet(getActionText(managementLoginButton), 60),
  135. rememberCheckboxVisible: Boolean(rememberCheckbox),
  136. rememberCheckboxChecked: Boolean(rememberCheckbox?.checked),
  137. oauthNavVisible: Boolean(oauthNavLink),
  138. oauthNavText: getInlineTextSnippet(getActionText(oauthNavLink), 80),
  139. bodySnippet: getPageTextSnippet(),
  140. };
  141. }
  142. function getVpsPanelSnapshotSignature(snapshot) {
  143. return JSON.stringify({
  144. readyState: snapshot.readyState,
  145. title: snapshot.title,
  146. authUrlVisible: snapshot.authUrlVisible,
  147. authUrlText: snapshot.authUrlText,
  148. oauthHeaderVisible: snapshot.oauthHeaderVisible,
  149. oauthHeaderText: snapshot.oauthHeaderText,
  150. managementKeyVisible: snapshot.managementKeyVisible,
  151. managementLoginVisible: snapshot.managementLoginVisible,
  152. rememberCheckboxVisible: snapshot.rememberCheckboxVisible,
  153. rememberCheckboxChecked: snapshot.rememberCheckboxChecked,
  154. oauthNavVisible: snapshot.oauthNavVisible,
  155. oauthNavText: snapshot.oauthNavText,
  156. bodySnippet: snapshot.bodySnippet,
  157. });
  158. }
  159. function parseUrlSafely(rawUrl) {
  160. if (!rawUrl) return null;
  161. try {
  162. return new URL(rawUrl);
  163. } catch {
  164. return null;
  165. }
  166. }
  167. function isLocalhostOAuthCallbackUrl(rawUrl) {
  168. const parsed = parseUrlSafely(rawUrl);
  169. if (!parsed) return false;
  170. if (!['http:', 'https:'].includes(parsed.protocol)) return false;
  171. if (!['localhost', '127.0.0.1'].includes(parsed.hostname)) return false;
  172. if (!['/auth/callback', '/codex/callback'].includes(parsed.pathname)) return false;
  173. const code = (parsed.searchParams.get('code') || '').trim();
  174. const state = (parsed.searchParams.get('state') || '').trim();
  175. return Boolean(code && state);
  176. }
  177. function getStatusBadgeSelectors() {
  178. return [
  179. '#root > div > div > div > main > div > div > div > div > div:nth-child(1) > div > div.OAuthPage-module__cardContent___1sXLA > div.status-badge',
  180. '#root .OAuthPage-module__cardContent___1sXLA > .status-badge',
  181. '.OAuthPage-module__cardContent___1sXLA > .status-badge',
  182. '.status-badge',
  183. ];
  184. }
  185. function getStatusBadgeEntries() {
  186. const seen = new Set();
  187. const entries = [];
  188. for (const selector of getStatusBadgeSelectors()) {
  189. const candidates = document.querySelectorAll(selector);
  190. for (const candidate of candidates) {
  191. if (seen.has(candidate)) continue;
  192. seen.add(candidate);
  193. entries.push(createStep9Entry(candidate, selector));
  194. }
  195. }
  196. return entries;
  197. }
  198. function summarizeStatusBadgeEntries(entries) {
  199. if (!entries.length) return '无可见状态徽标';
  200. return entries
  201. .map((entry, index) => {
  202. const text = entry.text || '(空文本)';
  203. const className = entry.className ? ` class=${getInlineTextSnippet(entry.className, 80)}` : '';
  204. const errorVisual = entry.errorVisualSummary ? ` error=${getInlineTextSnippet(entry.errorVisualSummary, 80)}` : '';
  205. return `#${index + 1}="${getInlineTextSnippet(text, 80)}"${className}${errorVisual}`;
  206. })
  207. .join(' | ');
  208. }
  209. const STEP9_SUCCESS_STATUSES = new Set([
  210. 'Authentication successful!',
  211. 'Аутентификация успешна!',
  212. '认证成功!',
  213. ]);
  214. function normalizeStep9StatusText(statusText) {
  215. return String(statusText || '').replace(/\s+/g, ' ').trim();
  216. }
  217. function isOAuthCallbackTimeoutFailure(statusText) {
  218. return /认证失败:\s*(?:Timeout waiting for OAuth callback|timeout of \d+ms exceeded)/i.test(statusText || '');
  219. }
  220. function isStep9FailureText(statusText) {
  221. const text = normalizeStep9StatusText(statusText);
  222. if (!text) return false;
  223. if (isOAuthCallbackTimeoutFailure(text)) return true;
  224. if (typeof isRecoverableStep9AuthFailure === 'function' && isRecoverableStep9AuthFailure(text)) {
  225. return true;
  226. }
  227. return /回调\s*url\s*提交失败|callback\s*url\s*submit\s*failed|oauth flow is not pending/i.test(text);
  228. }
  229. function isStep9SuccessStatus(statusText) {
  230. return STEP9_SUCCESS_STATUSES.has(normalizeStep9StatusText(statusText));
  231. }
  232. function isStep9SuccessLikeStatus(statusText) {
  233. const text = normalizeStep9StatusText(statusText);
  234. return /authentication successful|аутентификац.*успеш|认证成功/i.test(text);
  235. }
  236. function parseCssColorChannels(colorText) {
  237. const text = String(colorText || '').trim().toLowerCase();
  238. if (!text || text === 'transparent' || text === 'inherit' || text === 'initial' || text === 'unset') {
  239. return null;
  240. }
  241. if (text.startsWith('#')) {
  242. const hex = text.slice(1);
  243. if (hex.length === 3 || hex.length === 4) {
  244. const expanded = hex.split('').map((part) => part + part);
  245. const [r, g, b, a = 'ff'] = expanded;
  246. return {
  247. r: Number.parseInt(r, 16),
  248. g: Number.parseInt(g, 16),
  249. b: Number.parseInt(b, 16),
  250. a: Number.parseInt(a, 16) / 255,
  251. };
  252. }
  253. if (hex.length === 6 || hex.length === 8) {
  254. const parts = hex.match(/.{1,2}/g) || [];
  255. const [r, g, b, a = 'ff'] = parts;
  256. return {
  257. r: Number.parseInt(r, 16),
  258. g: Number.parseInt(g, 16),
  259. b: Number.parseInt(b, 16),
  260. a: Number.parseInt(a, 16) / 255,
  261. };
  262. }
  263. }
  264. if (text.startsWith('rgb')) {
  265. const numericParts = text.match(/[\d.]+/g) || [];
  266. if (numericParts.length >= 3) {
  267. const [r, g, b, a = '1'] = numericParts.map(Number);
  268. return { r, g, b, a };
  269. }
  270. }
  271. return null;
  272. }
  273. function isReddishColor(colorText) {
  274. const channels = parseCssColorChannels(colorText);
  275. if (!channels) return false;
  276. const { r, g, b, a = 1 } = channels;
  277. if (a <= 0.05) return false;
  278. return r >= 120 && r >= g + 35 && r >= b + 35;
  279. }
  280. function getStep9ErrorVisualSignals(element, className = '') {
  281. const signals = [];
  282. const normalizedClassName = String(className || '').replace(/\s+/g, ' ').trim();
  283. if (/(?:error|danger|fail|destructive|text-red|text-danger|alert)/i.test(normalizedClassName)) {
  284. signals.push(`class=${getInlineTextSnippet(normalizedClassName, 80)}`);
  285. }
  286. if (!element) {
  287. return signals;
  288. }
  289. const style = window.getComputedStyle(element);
  290. if (isReddishColor(style.color)) {
  291. signals.push(`color=${style.color}`);
  292. }
  293. if (isReddishColor(style.borderColor)) {
  294. signals.push(`border=${style.borderColor}`);
  295. }
  296. if (isReddishColor(style.backgroundColor)) {
  297. signals.push(`background=${style.backgroundColor}`);
  298. }
  299. return signals;
  300. }
  301. function createStep9Entry(candidate, selector) {
  302. const className = String(candidate?.className || '').replace(/\s+/g, ' ').trim();
  303. const errorVisualSignals = getStep9ErrorVisualSignals(candidate, className);
  304. return {
  305. element: candidate,
  306. selector,
  307. visible: isVisibleElement(candidate),
  308. text: normalizeStep9StatusText(candidate?.textContent || ''),
  309. className,
  310. errorVisualSignals,
  311. errorVisualSummary: errorVisualSignals.join(', '),
  312. hasErrorVisualSignal: errorVisualSignals.length > 0,
  313. };
  314. }
  315. function getStep9PageErrorSelectors() {
  316. return [
  317. '[role="alert"]',
  318. '[aria-live="assertive"]',
  319. '[aria-live="polite"]',
  320. '.alert',
  321. '[class*="alert"]',
  322. '[class*="error"]',
  323. '[class*="danger"]',
  324. '.text-danger',
  325. '.text-red',
  326. ];
  327. }
  328. function getStep9PageErrorEntries() {
  329. const seen = new Set();
  330. const entries = [];
  331. for (const selector of getStep9PageErrorSelectors()) {
  332. const candidates = document.querySelectorAll(selector);
  333. for (const candidate of candidates) {
  334. if (seen.has(candidate)) continue;
  335. seen.add(candidate);
  336. if (!isVisibleElement(candidate)) continue;
  337. const entry = createStep9Entry(candidate, selector);
  338. if (!isStep9FailureText(entry.text)) continue;
  339. entries.push(entry);
  340. }
  341. }
  342. return entries;
  343. }
  344. function buildStep9StatusDiagnostics(entries = [], pageErrorEntries = [], pageSnippet = '') {
  345. const visibleEntries = entries.filter((entry) => entry.visible);
  346. const successLikeEntries = visibleEntries.filter((entry) => isStep9SuccessLikeStatus(entry.text));
  347. const exactSuccessEntries = visibleEntries.filter((entry) => isStep9SuccessStatus(entry.text) && !entry.hasErrorVisualSignal);
  348. const failureEntries = visibleEntries.filter((entry) => isStep9FailureText(entry.text));
  349. const errorStyledEntries = visibleEntries.filter((entry) => entry.hasErrorVisualSignal);
  350. const allFailureEntries = [...failureEntries, ...pageErrorEntries];
  351. const decisiveFailureEntry = allFailureEntries[0] || null;
  352. const selectedEntry = decisiveFailureEntry || exactSuccessEntries[0] || visibleEntries[0] || null;
  353. const selectedText = selectedEntry?.text || '';
  354. const visibleSummary = summarizeStatusBadgeEntries(visibleEntries);
  355. const successLikeSummary = summarizeStatusBadgeEntries(successLikeEntries);
  356. const exactSuccessSummary = summarizeStatusBadgeEntries(exactSuccessEntries);
  357. const failureSummary = summarizeStatusBadgeEntries(failureEntries);
  358. const pageErrorSummary = summarizeStatusBadgeEntries(pageErrorEntries);
  359. const errorStyledSummary = summarizeStatusBadgeEntries(errorStyledEntries);
  360. const extraFailureSuffix = pageErrorEntries.length ? `;额外错误提示:${pageErrorSummary}` : '';
  361. const errorStyledSuffix = errorStyledEntries.length ? `;红色/错误样式徽标:${errorStyledSummary}` : '';
  362. return {
  363. selectedText,
  364. exactSuccessText: exactSuccessEntries[0]?.text || '',
  365. failureText: decisiveFailureEntry?.text || '',
  366. visibleCount: visibleEntries.length,
  367. visibleSummary,
  368. hasSuccessLikeVisibleBadge: successLikeEntries.length > 0,
  369. hasExactSuccessVisibleBadge: exactSuccessEntries.length > 0,
  370. hasFailureVisibleBadge: allFailureEntries.length > 0,
  371. hasErrorStyledVisibleBadge: errorStyledEntries.length > 0,
  372. successLikeSummary,
  373. exactSuccessSummary,
  374. failureSummary,
  375. pageErrorSummary,
  376. errorStyledSummary,
  377. pageSnippet,
  378. signature: JSON.stringify({
  379. selectedText,
  380. visibleCount: visibleEntries.length,
  381. visibleSummary,
  382. successLikeSummary,
  383. exactSuccessSummary,
  384. failureSummary,
  385. pageErrorSummary,
  386. errorStyledSummary,
  387. }),
  388. summary: selectedText
  389. ? `当前聚焦状态="${getInlineTextSnippet(selectedText, 80)}";可见徽标 ${visibleEntries.length} 个:${visibleSummary}${extraFailureSuffix}${errorStyledSuffix}`
  390. : `当前未选中任何可见状态徽标;可见徽标 ${visibleEntries.length} 个:${visibleSummary}${extraFailureSuffix}${errorStyledSuffix};页面片段="${getInlineTextSnippet(pageSnippet, 120)}"`,
  391. };
  392. }
  393. function getStatusBadgeDiagnostics() {
  394. return buildStep9StatusDiagnostics(
  395. getStatusBadgeEntries(),
  396. getStep9PageErrorEntries(),
  397. getPageTextSnippet()
  398. );
  399. }
  400. function getStatusBadgeElement() {
  401. const visibleEntry = getStatusBadgeEntries().find((entry) => entry.visible);
  402. return visibleEntry ? visibleEntry.element : null;
  403. }
  404. function getStatusBadgeText() {
  405. const diagnostics = getStatusBadgeDiagnostics();
  406. return diagnostics.selectedText;
  407. }
  408. async function waitForExactSuccessBadge(timeout = STEP9_SUCCESS_BADGE_TIMEOUT_MS) {
  409. const start = Date.now();
  410. let lastDiagnosticsSignature = '';
  411. let lastHeartbeatLoggedAt = 0;
  412. let lastSuccessLikeMismatchSignature = '';
  413. let lastSuccessFailureConflictSignature = '';
  414. while (Date.now() - start < timeout) {
  415. throwIfStopped();
  416. const diagnostics = getStatusBadgeDiagnostics();
  417. const elapsed = Date.now() - start;
  418. if (diagnostics.signature !== lastDiagnosticsSignature) {
  419. lastDiagnosticsSignature = diagnostics.signature;
  420. lastHeartbeatLoggedAt = elapsed;
  421. log(`步骤 10:认证状态检测中,${diagnostics.summary}`);
  422. console.log(LOG_PREFIX, '[Step 9] status badge diagnostics changed', diagnostics);
  423. } else if (elapsed - lastHeartbeatLoggedAt >= 10000) {
  424. lastHeartbeatLoggedAt = elapsed;
  425. log(`步骤 10:仍在等待认证成功,${diagnostics.summary}`);
  426. console.log(LOG_PREFIX, '[Step 9] still waiting for success badge', diagnostics);
  427. }
  428. if (diagnostics.hasSuccessLikeVisibleBadge && !diagnostics.hasExactSuccessVisibleBadge) {
  429. const mismatchSignature = JSON.stringify({
  430. selectedText: diagnostics.selectedText,
  431. successLikeSummary: diagnostics.successLikeSummary,
  432. visibleSummary: diagnostics.visibleSummary,
  433. errorStyledSummary: diagnostics.errorStyledSummary,
  434. });
  435. if (mismatchSignature !== lastSuccessLikeMismatchSignature) {
  436. lastSuccessLikeMismatchSignature = mismatchSignature;
  437. const errorStyledSuffix = diagnostics.hasErrorStyledVisibleBadge
  438. ? `;错误样式徽标:${diagnostics.errorStyledSummary}`
  439. : '';
  440. log(
  441. `步骤 10:检测到“认证成功”相关徽标,但未命中精确成功条件。当前聚焦="${getInlineTextSnippet(diagnostics.selectedText || '(空)', 80)}";成功相关徽标:${diagnostics.successLikeSummary}${errorStyledSuffix}`,
  442. 'warn'
  443. );
  444. console.warn(LOG_PREFIX, '[Step 9] success-like badge detected without exact match', diagnostics);
  445. }
  446. }
  447. if (diagnostics.hasExactSuccessVisibleBadge && diagnostics.hasFailureVisibleBadge) {
  448. const conflictSignature = JSON.stringify({
  449. exactSuccessSummary: diagnostics.exactSuccessSummary,
  450. failureSummary: diagnostics.failureSummary,
  451. pageErrorSummary: diagnostics.pageErrorSummary,
  452. });
  453. if (conflictSignature !== lastSuccessFailureConflictSignature) {
  454. lastSuccessFailureConflictSignature = conflictSignature;
  455. const failureSummary = diagnostics.pageErrorSummary !== '无可见状态徽标'
  456. ? diagnostics.pageErrorSummary
  457. : diagnostics.failureSummary;
  458. log(
  459. `步骤 10:同时检测到成功徽标和失败提示,本轮不判定成功。成功徽标:${diagnostics.exactSuccessSummary};失败提示:${failureSummary}`,
  460. 'warn'
  461. );
  462. console.warn(LOG_PREFIX, '[Step 9] success badge is blocked by visible failure', diagnostics);
  463. }
  464. }
  465. if (diagnostics.failureText) {
  466. if (isOAuthCallbackTimeoutFailure(diagnostics.failureText)) {
  467. throw new Error(`STEP9_OAUTH_TIMEOUT::${diagnostics.failureText}`);
  468. }
  469. throw new Error(`STEP9_OAUTH_RETRY::${diagnostics.failureText}`);
  470. }
  471. if (diagnostics.exactSuccessText) {
  472. return diagnostics.exactSuccessText;
  473. }
  474. await sleep(200);
  475. }
  476. const finalDiagnostics = getStatusBadgeDiagnostics();
  477. const finalText = finalDiagnostics.failureText || finalDiagnostics.selectedText;
  478. const diagnosticsSuffix = ` 当前诊断:${finalDiagnostics.summary}`;
  479. if (isOAuthCallbackTimeoutFailure(finalText)) {
  480. throw new Error(`STEP9_OAUTH_TIMEOUT::${finalText}${diagnosticsSuffix}`);
  481. }
  482. if (isStep9FailureText(finalText)) {
  483. throw new Error(`STEP9_OAUTH_RETRY::${finalText}${diagnosticsSuffix}`);
  484. }
  485. throw new Error(finalText
  486. ? `CPA 面板状态未进入成功状态,当前为“${finalText}”。${diagnosticsSuffix}`
  487. : `CPA 面板长时间未出现成功状态徽标。${diagnosticsSuffix}`);
  488. }
  489. function findManagementKeyInput() {
  490. const candidates = document.querySelectorAll(
  491. '.LoginPage-module__loginCard___OgP-R input[type="password"], input[placeholder*="管理密钥"], input[aria-label*="管理密钥"]'
  492. );
  493. return Array.from(candidates).find(isVisibleElement) || null;
  494. }
  495. function findManagementLoginButton() {
  496. const candidates = document.querySelectorAll('.LoginPage-module__loginCard___OgP-R button, .LoginPage-module__loginCard___OgP-R .btn');
  497. return Array.from(candidates).find((el) => {
  498. if (!isVisibleElement(el)) return false;
  499. return /登录|login/i.test(getActionText(el));
  500. }) || null;
  501. }
  502. function findRememberPasswordCheckbox() {
  503. const candidates = document.querySelectorAll('.LoginPage-module__loginCard___OgP-R input[type="checkbox"]');
  504. return Array.from(candidates).find((el) => {
  505. const label = el.closest('label');
  506. const text = getActionText(label || el);
  507. return /记住密码|remember/i.test(text);
  508. }) || null;
  509. }
  510. function findOAuthNavLink() {
  511. const candidates = document.querySelectorAll('a[href*="#/oauth"], a.nav-item, button, [role="link"], [role="button"]');
  512. return Array.from(candidates).find((el) => {
  513. if (!isVisibleElement(el)) return false;
  514. const text = getActionText(el);
  515. const href = el.getAttribute('href') || '';
  516. return href.includes('#/oauth') || /oauth/i.test(text);
  517. }) || null;
  518. }
  519. function findCodexOAuthHeader() {
  520. const candidates = document.querySelectorAll('.card-header, [class*="cardHeader"], .card, [class*="card"]');
  521. return Array.from(candidates).find((el) => {
  522. if (!isVisibleElement(el)) return false;
  523. const text = (el.textContent || '').toLowerCase();
  524. return text.includes('codex') && text.includes('oauth');
  525. }) || null;
  526. }
  527. function findOAuthCardLoginButton(header) {
  528. const card = header?.closest('.card, [class*="card"]') || header?.parentElement || document;
  529. const candidates = card.querySelectorAll('button.btn.btn-primary, button.btn-primary, button.btn');
  530. return Array.from(candidates).find((el) => isVisibleElement(el) && /登录|login/i.test(getActionText(el))) || null;
  531. }
  532. function findAuthUrlElement() {
  533. const candidates = document.querySelectorAll('[class*="authUrlValue"], .OAuthPage-module__authUrlValue___axvUJ');
  534. return Array.from(candidates).find((el) => isVisibleElement(el) && /^https?:\/\//i.test((el.textContent || '').trim())) || null;
  535. }
  536. async function ensureOAuthManagementPage(vpsPassword, step = 1, timeout = 45000) {
  537. const start = Date.now();
  538. let lastLoginAttemptAt = 0;
  539. let lastOauthNavAttemptAt = 0;
  540. let lastSnapshotSignature = '';
  541. let lastSnapshotLogAt = 0;
  542. console.log(LOG_PREFIX, `[Step ${step}] ensureOAuthManagementPage start`, {
  543. timeout,
  544. url: location.href,
  545. hasVpsPassword: Boolean(vpsPassword),
  546. snapshot: getVpsPanelSnapshot(),
  547. });
  548. while (Date.now() - start < timeout) {
  549. throwIfStopped();
  550. const elapsed = Date.now() - start;
  551. const snapshot = getVpsPanelSnapshot();
  552. const signature = getVpsPanelSnapshotSignature(snapshot);
  553. if (signature !== lastSnapshotSignature || elapsed - lastSnapshotLogAt >= 5000) {
  554. lastSnapshotSignature = signature;
  555. lastSnapshotLogAt = elapsed;
  556. console.log(LOG_PREFIX, `[Step ${step}] panel snapshot at ${elapsed}ms`, snapshot);
  557. }
  558. const authUrlEl = findAuthUrlElement();
  559. if (authUrlEl) {
  560. console.log(LOG_PREFIX, `[Step ${step}] found visible auth URL after ${elapsed}ms`, {
  561. url: location.href,
  562. authUrlText: getInlineTextSnippet(authUrlEl.textContent || '', 120),
  563. });
  564. return { header: findCodexOAuthHeader(), authUrlEl };
  565. }
  566. const oauthHeader = findCodexOAuthHeader();
  567. if (oauthHeader) {
  568. console.log(LOG_PREFIX, `[Step ${step}] found OAuth card header after ${elapsed}ms`, {
  569. url: location.href,
  570. headerText: getInlineTextSnippet(oauthHeader.textContent || '', 120),
  571. });
  572. return { header: oauthHeader, authUrlEl: null };
  573. }
  574. const managementKeyInput = findManagementKeyInput();
  575. const managementLoginButton = findManagementLoginButton();
  576. if (managementKeyInput && managementLoginButton) {
  577. if (!vpsPassword) {
  578. throw new Error('CPA 面板需要管理密钥,请先在侧边栏填写 CPA Key(管理密钥)。');
  579. }
  580. if ((managementKeyInput.value || '') !== vpsPassword) {
  581. await humanPause(350, 900);
  582. fillInput(managementKeyInput, vpsPassword);
  583. console.log(LOG_PREFIX, `[Step ${step}] filled management key after ${elapsed}ms`);
  584. log(`步骤 ${step}:已填写 CPA 管理密钥。`);
  585. }
  586. const rememberCheckbox = findRememberPasswordCheckbox();
  587. if (rememberCheckbox && !rememberCheckbox.checked) {
  588. simulateClick(rememberCheckbox);
  589. console.log(LOG_PREFIX, `[Step ${step}] toggled remember checkbox after ${elapsed}ms`);
  590. log(`步骤 ${step}:已勾选 CPA 面板“记住密码”。`);
  591. await sleep(300);
  592. }
  593. if (Date.now() - lastLoginAttemptAt > 3000) {
  594. lastLoginAttemptAt = Date.now();
  595. await humanPause(350, 900);
  596. simulateClick(managementLoginButton);
  597. console.log(LOG_PREFIX, `[Step ${step}] clicked management login after ${elapsed}ms`, {
  598. buttonText: getInlineTextSnippet(getActionText(managementLoginButton), 80),
  599. });
  600. log(`步骤 ${step}:已提交 CPA 管理登录。`);
  601. }
  602. await sleep(1500);
  603. continue;
  604. }
  605. const oauthNavLink = findOAuthNavLink();
  606. if (oauthNavLink && Date.now() - lastOauthNavAttemptAt > 2000) {
  607. lastOauthNavAttemptAt = Date.now();
  608. await humanPause(300, 800);
  609. simulateClick(oauthNavLink);
  610. console.log(LOG_PREFIX, `[Step ${step}] clicked OAuth nav after ${elapsed}ms`, {
  611. navText: getInlineTextSnippet(getActionText(oauthNavLink), 80),
  612. });
  613. log(`步骤 ${step}:已打开“OAuth 登录”导航。`);
  614. await sleep(1200);
  615. continue;
  616. }
  617. await sleep(250);
  618. }
  619. console.error(LOG_PREFIX, `[Step ${step}] ensureOAuthManagementPage timeout after ${Date.now() - start}ms`, {
  620. url: location.href,
  621. snapshot: getVpsPanelSnapshot(),
  622. });
  623. throw new Error('无法进入 CPA 的 OAuth 管理页面,请检查面板是否正常加载。URL: ' + location.href);
  624. }
  625. async function requestOAuthUrl(payload = {}) {
  626. return step1_getOAuthLink(payload, { report: false });
  627. }
  628. // ============================================================
  629. // Step 1: Get OAuth Link
  630. // ============================================================
  631. async function step1_getOAuthLink(payload, options = {}) {
  632. const { report = true } = options;
  633. const { vpsPassword } = payload || {};
  634. const logStep = Number.isInteger(payload?.logStep) ? payload.logStep : 1;
  635. console.log(LOG_PREFIX, '[Step 1] step1_getOAuthLink start', {
  636. url: location.href,
  637. hasVpsPassword: Boolean(vpsPassword),
  638. snapshot: getVpsPanelSnapshot(),
  639. });
  640. log(`步骤 ${logStep}:正在等待 CPA 面板加载并进入 OAuth 页面...`);
  641. const { header, authUrlEl: existingAuthUrlEl } = await ensureOAuthManagementPage(vpsPassword, logStep);
  642. let authUrlEl = existingAuthUrlEl;
  643. console.log(LOG_PREFIX, '[Step 1] ensureOAuthManagementPage resolved', {
  644. url: location.href,
  645. hasHeader: Boolean(header),
  646. hasExistingAuthUrl: Boolean(existingAuthUrlEl),
  647. snapshot: getVpsPanelSnapshot(),
  648. });
  649. if (!authUrlEl) {
  650. const loginBtn = findOAuthCardLoginButton(header);
  651. if (!loginBtn) {
  652. throw new Error('已找到 Codex OAuth 卡片,但卡片内没有登录按钮。URL: ' + location.href);
  653. }
  654. if (loginBtn.disabled) {
  655. console.log(LOG_PREFIX, '[Step 1] OAuth login button is disabled, waiting for auth URL', {
  656. url: location.href,
  657. buttonText: getInlineTextSnippet(getActionText(loginBtn), 80),
  658. });
  659. log(`步骤 ${logStep}:OAuth 登录按钮当前不可用,正在等待授权链接出现...`);
  660. } else {
  661. await humanPause(500, 1400);
  662. simulateClick(loginBtn);
  663. console.log(LOG_PREFIX, '[Step 1] clicked OAuth login button and waiting for auth URL', {
  664. url: location.href,
  665. buttonText: getInlineTextSnippet(getActionText(loginBtn), 80),
  666. });
  667. log(`步骤 ${logStep}:已点击 OAuth 登录按钮,正在等待授权链接...`);
  668. }
  669. try {
  670. authUrlEl = await waitForElement('[class*="authUrlValue"]', 15000);
  671. } catch {
  672. throw new Error(
  673. '点击 OAuth 登录按钮后未出现授权链接。' +
  674. '请检查 CPA 面板服务是否正在运行。URL: ' + location.href
  675. );
  676. }
  677. } else {
  678. log(`步骤 ${logStep}:CPA 面板上已显示授权链接。`);
  679. }
  680. const oauthUrl = (authUrlEl.textContent || '').trim();
  681. if (!oauthUrl || !oauthUrl.startsWith('http')) {
  682. throw new Error(`拿到的 OAuth 链接无效:\"${oauthUrl.slice(0, 50)}\"。应为 http 开头的 URL。`);
  683. }
  684. log(`步骤 ${logStep}:已获取 OAuth 链接:${oauthUrl.slice(0, 80)}...`, 'ok');
  685. console.log(LOG_PREFIX, '[Step 1] reporting completion with oauthUrl', {
  686. url: location.href,
  687. oauthUrlPreview: oauthUrl.slice(0, 120),
  688. });
  689. if (report) {
  690. reportComplete(1, { oauthUrl });
  691. }
  692. return { oauthUrl };
  693. }
  694. // ============================================================
  695. // 步骤 10:CPA 回调验证——填写 localhost 回调地址并提交
  696. // ============================================================
  697. async function step9_vpsVerify(payload) {
  698. await ensureOAuthManagementPage(payload?.vpsPassword, 9);
  699. // 优先从 payload 读取 localhostUrl;没有时再回退到全局状态
  700. let localhostUrl = payload?.localhostUrl;
  701. if (localhostUrl && !isLocalhostOAuthCallbackUrl(localhostUrl)) {
  702. throw new Error('步骤 10 只接受真实的 localhost OAuth 回调地址,请重新执行步骤 9。');
  703. }
  704. if (!localhostUrl) {
  705. log('步骤 10:payload 中没有 localhostUrl,正在从状态中读取...');
  706. const state = await chrome.runtime.sendMessage({ type: 'GET_STATE' });
  707. localhostUrl = state.localhostUrl;
  708. if (localhostUrl && !isLocalhostOAuthCallbackUrl(localhostUrl)) {
  709. throw new Error('步骤 10 只接受真实的 localhost OAuth 回调地址,请重新执行步骤 9。');
  710. }
  711. }
  712. if (!localhostUrl) {
  713. throw new Error('未找到 localhost 回调地址,请先完成步骤 8。');
  714. }
  715. log(`步骤 10:已获取 localhostUrl:${localhostUrl.slice(0, 60)}...`);
  716. log('步骤 10:正在查找回调地址输入框...');
  717. // Find the callback URL input
  718. // Actual DOM: <input class="input" placeholder="http://localhost:1455/auth/callback?code=...&state=...">
  719. let urlInput = null;
  720. try {
  721. urlInput = await waitForElement('[class*="callbackSection"] input.input', 10000);
  722. } catch {
  723. try {
  724. urlInput = await waitForElement('input[placeholder*="localhost"]', 5000);
  725. } catch {
  726. throw new Error('在 CPA 面板中未找到回调地址输入框。URL: ' + location.href);
  727. }
  728. }
  729. await humanPause(600, 1500);
  730. fillInput(urlInput, localhostUrl);
  731. log(`步骤 10:已填写回调地址:${localhostUrl.slice(0, 80)}...`);
  732. // Find and click the callback submit button in supported UI languages.
  733. const callbackSubmitPattern = /提交回调\s*URL|Submit\s+Callback\s+URL|Отправить\s+Callback\s+URL/i;
  734. let submitBtn = null;
  735. try {
  736. submitBtn = await waitForElementByText(
  737. '[class*="callbackActions"] button, [class*="callbackSection"] button',
  738. callbackSubmitPattern,
  739. 5000
  740. );
  741. } catch {
  742. try {
  743. submitBtn = await waitForElementByText('button.btn', callbackSubmitPattern, 5000);
  744. } catch {
  745. throw new Error('未找到回调提交按钮(提交回调 URL / Submit Callback URL / Отправить Callback URL)。URL: ' + location.href);
  746. }
  747. }
  748. await humanPause(450, 1200);
  749. simulateClick(submitBtn);
  750. log('步骤 10:已点击回调提交按钮,正在等待认证结果...');
  751. const verifiedStatus = await waitForExactSuccessBadge();
  752. log(`步骤 10:${verifiedStatus}`, 'ok');
  753. reportComplete(10, { localhostUrl, verifiedStatus });
  754. }