Jelajahi Sumber

Merge branch 'dev' of https://github.com/QLHazyCoder/codex-oauth-automation-extension into dev

QLHazyCoder 4 bulan lalu
induk
melakukan
8f5d2bc363

+ 1 - 0
.gitignore

@@ -2,3 +2,4 @@
 
 /.github
 /_metadata/
+.vscode

+ 125 - 4
background.js

@@ -7437,18 +7437,139 @@ async function executeStep4(state) {
 // Step 5: Fill Name & Birthday (via signup-page.js)
 // ============================================================
 
+async function waitForStep5ChatgptRedirect(tabId, timeoutMs = 15000) {
+  if (!Number.isInteger(tabId)) {
+    return null;
+  }
+
+  const matchedTab = await waitForTabUrlMatch(tabId, (url) => /chatgpt\.com/i.test(url || ''), {
+    timeoutMs,
+    retryDelayMs: 300,
+  });
+  if (matchedTab) {
+    return matchedTab;
+  }
+
+  const currentTab = await chrome.tabs.get(tabId).catch(() => null);
+  if (currentTab && /chatgpt\.com/i.test(currentTab.url || '')) {
+    return currentTab;
+  }
+
+  return null;
+}
+
 async function executeStep5(state) {
   const { firstName, lastName } = generateRandomName();
   const { year, month, day } = generateRandomBirthday();
 
   await addLog(`步骤 5:已生成姓名 ${firstName} ${lastName},生日 ${year}-${month}-${day}`);
 
-  await sendToContentScript('signup-page', {
-    type: 'EXECUTE_STEP',
-    step: 5,
+  let step5Result = null;
+  let step5TransportError = null;
+
+  try {
+    step5Result = await sendToContentScript('signup-page', {
+      type: 'EXECUTE_STEP',
+      step: 5,
+      source: 'background',
+      payload: { firstName, lastName, year, month, day },
+    });
+  } catch (err) {
+    // Cross-origin navigation (auth page → chatgpt.com) destroys the content
+    // script, causing a transport error. Capture it so we can check if the tab
+    // ended up on chatgpt.com onboarding.
+    if (isRetryableContentScriptTransportError(err)) {
+      step5TransportError = err;
+      console.log(LOG_PREFIX, '步骤 5:内容脚本通信中断,正在检查是否跳转到 ChatGPT 引导页...', err?.message);
+    } else {
+      throw err;
+    }
+  }
+
+  // Case 1: content script successfully detected chatgpt redirect before dying
+  if (step5Result?.chatgptOnboarding) {
+    await addLog('步骤 5:检测到 ChatGPT 引导页跳转,正在处理引导页跳过...');
+    await handleChatgptOnboardingSkip();
+    return;
+  }
+
+  if (step5Result?.chatgptHome) {
+    await addLog('步骤 5:检测到已进入 ChatGPT 页面,注册成功。', 'ok');
+    return;
+  }
+
+  // Case 2: content script died due to cross-origin navigation — check tab URL
+  if (step5TransportError) {
+    const signupTabId = await getTabId('signup-page');
+    const redirectedTab = await waitForStep5ChatgptRedirect(signupTabId);
+    if (redirectedTab) {
+      await addLog('步骤 5:内容脚本因页面跳转到 ChatGPT 而断开,正在处理引导页跳过...');
+      await handleChatgptOnboardingSkip(redirectedTab.id);
+      return;
+    }
+    // Not on chatgpt.com — re-throw the original error
+    throw step5TransportError;
+  }
+}
+
+async function handleChatgptOnboardingSkip(knownTabId) {
+  const signupTabId = knownTabId || await getTabId('signup-page');
+  if (!signupTabId) {
+    throw new Error('步骤 5:无法找到注册页标签页,无法处理 ChatGPT 引导页。');
+  }
+
+  // Wait for the tab to navigate to chatgpt.com (may already be there)
+  const start = Date.now();
+  const timeout = 15000;
+  let tabUrl = '';
+  while (Date.now() - start < timeout) {
+    throwIfStopped();
+    const tab = await chrome.tabs.get(signupTabId).catch(() => null);
+    if (tab && /chatgpt\.com/i.test(tab.url || '')) {
+      tabUrl = tab.url;
+      break;
+    }
+    await sleepWithStop(500);
+  }
+
+  if (!tabUrl) {
+    throw new Error('步骤 5:等待页面跳转到 ChatGPT 引导页超时。');
+  }
+
+  // Wait for page to finish loading
+  await sleepWithStop(2000);
+
+  // Inject content script on chatgpt.com
+  await ensureContentScriptReadyOnTab('signup-page', signupTabId, {
+    inject: SIGNUP_PAGE_INJECT_FILES,
+    injectSource: 'signup-page',
+    timeoutMs: 15000,
+    logMessage: '步骤 5:正在等待 ChatGPT 引导页内容脚本就绪...',
+  });
+
+  // Send CHATGPT_SKIP_ONBOARDING message
+  const result = await sendToContentScriptResilient('signup-page', {
+    type: 'CHATGPT_SKIP_ONBOARDING',
     source: 'background',
-    payload: { firstName, lastName, year, month, day },
+    payload: {},
+  }, {
+    timeoutMs: 60000,
+    retryDelayMs: 1000,
+    logMessage: '步骤 5:ChatGPT 引导页正在处理,等待跳过完成...',
   });
+
+  if (result?.error) {
+    throw new Error(result.error);
+  }
+
+  if (result?.alreadyCompleted) {
+    await addLog('步骤 5:已进入 ChatGPT 页面,无需继续跳过引导,注册成功。', 'ok');
+    await completeStepFromBackground(5, { chatgptHome: true });
+    return;
+  }
+
+  await addLog('步骤 5:ChatGPT 引导页跳过完成,注册成功。', 'ok');
+  await completeStepFromBackground(5, { chatgptOnboarding: true });
 }
 
 // ============================================================

+ 312 - 18
content/signup-page.js

@@ -22,6 +22,7 @@ if (document.documentElement.getAttribute(SIGNUP_PAGE_LISTENER_SENTINEL) !== '1'
       || message.type === 'RESEND_VERIFICATION_CODE'
       || message.type === 'ENSURE_SIGNUP_ENTRY_READY'
       || message.type === 'ENSURE_SIGNUP_PASSWORD_PAGE_READY'
+      || message.type === 'CHATGPT_SKIP_ONBOARDING'
     ) {
       resetStopState();
       handleCommand(message).then((result) => {
@@ -83,6 +84,8 @@ async function handleCommand(message) {
       return getStep8State();
     case 'STEP8_TRIGGER_CONTINUE':
       return await step8_triggerContinue(message.payload);
+    case 'CHATGPT_SKIP_ONBOARDING':
+      return await skipChatgptOnboarding();
   }
 }
 
@@ -100,6 +103,8 @@ const VERIFICATION_CODE_INPUT_SELECTOR = [
 const ONE_TIME_CODE_LOGIN_PATTERN = /使用一次性验证码登录|改用(?:一次性)?验证码(?:登录)?|使用验证码登录|一次性验证码|验证码登录|one[-\s]*time\s*(?:passcode|password|code)|use\s+(?:a\s+)?one[-\s]*time\s*(?:passcode|password|code)(?:\s+instead)?|use\s+(?:a\s+)?code(?:\s+instead)?|sign\s+in\s+with\s+(?:email|code)|email\s+(?:me\s+)?(?:a\s+)?code/i;
 
 const RESEND_VERIFICATION_CODE_PATTERN = /重新发送(?:验证码)?|再次发送(?:验证码)?|重发(?:验证码)?|未收到(?:验证码|邮件)|resend(?:\s+code)?|send\s+(?:a\s+)?new\s+code|send\s+(?:it\s+)?again|request\s+(?:a\s+)?new\s+code|didn'?t\s+receive/i;
+const CHATGPT_ONBOARDING_TEXT_PATTERN = /welcome\s+to\s+chatgpt|what\s+should\s+chatgpt\s+call\s+you|how\s+do\s+you\s+want\s+chatgpt\s+to\s+respond|tell\s+chatgpt\s+what\s+traits|personal(?:ize|ise)\s+your\s+experience|介绍一下你自己|ChatGPT 应该如何称呼你|你希望 ChatGPT 如何回应/i;
+const CHATGPT_HOME_TEXT_PATTERN = /new\s+chat|temporary\s+chat|message\s+chatgpt|send\s+a\s+message|chatgpt\s+can\s+make\s+mistakes|新建聊天|临时聊天|给\s*ChatGPT\s*发消息|ChatGPT\s*可能会犯错/i;
 
 function isVisibleElement(el) {
   if (!el) return false;
@@ -206,6 +211,15 @@ async function resendVerificationCode(step, timeout = 45000) {
 
   while (Date.now() - start < timeout) {
     throwIfStopped();
+
+    // Check for 405 error page and recover by clicking "Try again"
+    if (is405MethodNotAllowedPage()) {
+      await handle405ResendError(step, timeout - (Date.now() - start));
+      // After recovery, loop back to find the resend button again
+      loggedWaiting = false;
+      continue;
+    }
+
     action = findResendVerificationCodeTrigger({ allowDisabled: true });
 
     if (action && isActionEnabled(action)) {
@@ -213,6 +227,15 @@ async function resendVerificationCode(step, timeout = 45000) {
       await humanPause(350, 900);
       simulateClick(action);
       await sleep(1200);
+
+      // After clicking resend, check if 405 error appeared
+      if (is405MethodNotAllowedPage()) {
+        log(`步骤 ${step}:点击重新发送后出现 405 错误,正在恢复...`, 'warn');
+        await handle405ResendError(step, timeout - (Date.now() - start));
+        loggedWaiting = false;
+        continue;
+      }
+
       return {
         resent: true,
         buttonText: getActionText(action),
@@ -230,6 +253,43 @@ async function resendVerificationCode(step, timeout = 45000) {
   throw new Error('无法点击重新发送验证码按钮。URL: ' + location.href);
 }
 
+function is405MethodNotAllowedPage() {
+  const pageText = document.body?.textContent || '';
+  return /405\s+Method\s+Not\s+Allowed/i.test(pageText)
+    || /Route\s+Error.*405/i.test(pageText);
+}
+
+async function handle405ResendError(step, remainingTimeout = 30000) {
+  const start = Date.now();
+  let retryCount = 0;
+
+  while (Date.now() - start < remainingTimeout) {
+    throwIfStopped();
+
+    if (!is405MethodNotAllowedPage()) {
+      // Page recovered — back to verification page
+      log(`步骤 ${step}:405 错误已恢复,页面已返回验证码页面。`);
+      return;
+    }
+
+    const retryBtn = getAuthRetryButton();
+    if (retryBtn) {
+      retryCount++;
+      log(`步骤 ${step}:检测到 405 错误页面,正在点击"Try again"(第 ${retryCount} 次)...`, 'warn');
+      await humanPause(300, 800);
+      simulateClick(retryBtn);
+
+      // Wait 3 seconds before checking again
+      await sleep(3000);
+      continue;
+    }
+
+    await sleep(500);
+  }
+
+  throw new Error(`步骤 ${step}:405 错误恢复超时,无法返回验证码页面。URL: ${location.href}`);
+}
+
 // ============================================================
 // Signup Entry Helpers
 // ============================================================
@@ -720,6 +780,70 @@ function getStep5ErrorText() {
   return messages.find((text) => STEP5_SUBMIT_ERROR_PATTERN.test(text)) || '';
 }
 
+function isChatgptOnboardingPage() {
+  if (!isChatgptUrl()) {
+    return false;
+  }
+
+  if (findChatgptSkipButton()) {
+    return true;
+  }
+
+  return CHATGPT_ONBOARDING_TEXT_PATTERN.test(getPageTextSnapshot());
+}
+
+function isChatgptUrl(rawUrl = location.href) {
+  return /(^https?:\/\/)?([^.]+\.)?chatgpt\.com(?::\d+)?/i.test(rawUrl || '');
+}
+
+function hasVisibleElementMatchingSelector(selector) {
+  return Array.from(document.querySelectorAll(selector)).some(isVisibleElement);
+}
+
+function isChatgptAuthenticatedHomePage() {
+  if (!isChatgptUrl()) {
+    return false;
+  }
+
+  if (isChatgptOnboardingPage()) {
+    return false;
+  }
+
+  const appShellSelectors = [
+    'textarea[placeholder*="Message" i]',
+    'textarea[aria-label*="Message" i]',
+    '[data-testid="composer-root"]',
+    '[data-testid="history-and-skills"]',
+    'button[aria-label*="New chat" i]',
+    'a[aria-label*="New chat" i]',
+    'a[href^="/c/"]',
+  ];
+  if (appShellSelectors.some((selector) => hasVisibleElementMatchingSelector(selector))) {
+    return true;
+  }
+
+  return CHATGPT_HOME_TEXT_PATTERN.test(getPageTextSnapshot());
+}
+
+async function waitForChatgptPostSignupState(timeout = 15000) {
+  const start = Date.now();
+  while (Date.now() - start < timeout) {
+    throwIfStopped();
+
+    if (isChatgptOnboardingPage()) {
+      return 'onboarding';
+    }
+
+    if (isChatgptAuthenticatedHomePage()) {
+      return 'home';
+    }
+
+    await sleep(300);
+  }
+
+  return null;
+}
+
 async function waitForStep5SubmitOutcome(timeout = 15000) {
   const start = Date.now();
 
@@ -735,6 +859,14 @@ async function waitForStep5SubmitOutcome(timeout = 15000) {
       return { success: true, addPhonePage: true };
     }
 
+    if (isChatgptOnboardingPage()) {
+      return { success: true, chatgptOnboarding: true };
+    }
+
+    if (isChatgptAuthenticatedHomePage()) {
+      return { success: true, chatgptHome: true };
+    }
+
     if (isStep8Ready()) {
       return { success: true };
     }
@@ -1258,28 +1390,55 @@ async function fillVerificationCode(step, payload) {
   }
 
   // Find code input — could be a single input or multiple separate inputs
+  // Retry with 405 error recovery if needed
+  const maxRetries = 3;
   let codeInput = null;
-  try {
-    codeInput = await waitForElement(VERIFICATION_CODE_INPUT_SELECTOR, 10000);
-  } catch {
-    // Check for multiple single-digit inputs (common pattern)
-    const singleInputs = document.querySelectorAll('input[maxlength="1"]');
-    if (singleInputs.length >= 6) {
-      log(`步骤 ${step}:发现分开的单字符验证码输入框,正在逐个填写...`);
-      for (let i = 0; i < 6 && i < singleInputs.length; i++) {
-        fillInput(singleInputs[i], code[i]);
-        await sleep(100);
+
+  for (let retry = 0; retry <= maxRetries; retry++) {
+    throwIfStopped();
+
+    // Before looking for input, check if page is in 405 error state
+    if (is405MethodNotAllowedPage()) {
+      log(`步骤 ${step}:检测到 405 错误页面,正在恢复...`, 'warn');
+      await handle405ResendError(step, 30000);
+      continue;
+    }
+
+    try {
+      codeInput = await waitForElement(VERIFICATION_CODE_INPUT_SELECTOR, 10000);
+      break; // Found it
+    } catch {
+      // Check for multiple single-digit inputs (common pattern)
+      const singleInputs = document.querySelectorAll('input[maxlength="1"]');
+      if (singleInputs.length >= 6) {
+        log(`步骤 ${step}:发现分开的单字符验证码输入框,正在逐个填写...`);
+        for (let i = 0; i < 6 && i < singleInputs.length; i++) {
+          fillInput(singleInputs[i], code[i]);
+          await sleep(100);
+        }
+        const outcome = await waitForVerificationSubmitOutcome(step);
+        if (outcome.invalidCode) {
+          log(`步骤 ${step}:验证码被拒绝:${outcome.errorText}`, 'warn');
+        } else if (outcome.addPhonePage) {
+          log(`步骤 ${step}:验证码已通过,并已跳转到手机号页面。`, 'ok');
+        } else {
+          log(`步骤 ${step}:验证码已通过${outcome.assumed ? '(按成功推定)' : ''}。`, 'ok');
+        }
+        return outcome;
       }
-      const outcome = await waitForVerificationSubmitOutcome(step);
-      if (outcome.invalidCode) {
-        log(`步骤 ${step}:验证码被拒绝:${outcome.errorText}`, 'warn');
-      } else if (outcome.addPhonePage) {
-        log(`步骤 ${step}:验证码已通过,并已跳转到手机号页面。`, 'ok');
-      } else {
-        log(`步骤 ${step}:验证码已通过${outcome.assumed ? '(按成功推定)' : ''}。`, 'ok');
+
+      // No input found — check if it's a 405 error and can be recovered
+      if (is405MethodNotAllowedPage() && retry < maxRetries) {
+        log(`步骤 ${step}:未找到验证码输入框且页面出现 405 错误,正在恢复...`, 'warn');
+        await handle405ResendError(step, 30000);
+        continue;
       }
-      return outcome;
+
+      throw new Error('未找到验证码输入框。URL: ' + location.href);
     }
+  }
+
+  if (!codeInput) {
     throw new Error('未找到验证码输入框。URL: ' + location.href);
   }
 
@@ -2009,6 +2168,41 @@ async function step5_fillNameBirthday(payload) {
   } else {
     throw new Error('未找到生日或年龄输入项。URL: ' + location.href);
   }
+  // 韩国IP判断勾选框""I agree"
+  const allConsentCheckbox = Array.from(document.querySelectorAll('input[name="allCheckboxes"][type="checkbox"]'))
+    .find((el) => {
+      const checkboxLabel = el.closest('label');
+      const labelText = normalizeInlineText(checkboxLabel?.textContent || '');
+      return (!checkboxLabel || isVisibleElement(checkboxLabel))
+        && /I\s+agree\s+to\s+all\s+of\s+the\s+following/i.test(labelText);
+    }) || null;
+
+  if (allConsentCheckbox) {
+    if (!allConsentCheckbox.checked) {
+      const checkboxLabel = allConsentCheckbox.closest('label');
+      await humanPause(500, 1500);
+      if (checkboxLabel && isVisibleElement(checkboxLabel)) {
+        simulateClick(checkboxLabel);
+      } else {
+        simulateClick(allConsentCheckbox);
+      }
+      await sleep(250);
+
+      if (!allConsentCheckbox.checked) {
+        allConsentCheckbox.click();
+        await sleep(250);
+      }
+
+      if (!allConsentCheckbox.checked) {
+        throw new Error('未能勾选 “I agree to all of the following” 复选框。');
+      }
+
+      log('步骤 5:已勾选 “I agree to all of the following”。');
+    } else {
+      log('步骤 5:“I agree to all of the following” 已勾选,跳过。');
+    }
+  }
+
 
   // Click "完成帐户创建" button
   await sleep(500);
@@ -2042,6 +2236,106 @@ async function step5_fillNameBirthday(payload) {
     throw new Error(`步骤 5:${outcome.errorText}`);
   }
 
+  if (outcome.chatgptOnboarding || outcome.chatgptHome) {
+    if (outcome.chatgptOnboarding) {
+      log('步骤 5:资料已通过,页面已跳转到 ChatGPT 引导页。', 'ok');
+    } else {
+      log('步骤 5:资料已通过,页面已进入已登录的 ChatGPT 页面。', 'ok');
+    }
+    reportComplete(5, {
+      chatgptOnboarding: Boolean(outcome.chatgptOnboarding),
+      chatgptHome: Boolean(outcome.chatgptHome),
+    });
+    return {
+      chatgptOnboarding: Boolean(outcome.chatgptOnboarding),
+      chatgptHome: Boolean(outcome.chatgptHome),
+    };
+  }
+
   log(`步骤 5:资料已通过。`, 'ok');
   reportComplete(5, { addPhonePage: Boolean(outcome.addPhonePage) });
 }
+
+// ============================================================
+// ChatGPT Onboarding: Skip buttons after signup redirect
+// ============================================================
+
+function findChatgptSkipButton() {
+  // Look for buttons containing "Skip" or "跳过" text with btn-ghost class
+  const buttons = document.querySelectorAll('button');
+  for (const btn of buttons) {
+    if (!isVisibleElement(btn)) continue;
+    const text = (btn.textContent || '').trim();
+    if (/^(skip|跳过)$/i.test(text) && /btn-ghost/i.test(btn.className)) {
+      return btn;
+    }
+  }
+  // Fallback: look for any button matching skip text without class constraint
+  for (const btn of buttons) {
+    if (!isVisibleElement(btn)) continue;
+    const text = (btn.textContent || '').trim();
+    if (/^(skip|跳过)$/i.test(text)) {
+      return btn;
+    }
+  }
+  return null;
+}
+
+async function waitForChatgptSkipButton(timeout = 15000) {
+  const start = Date.now();
+  while (Date.now() - start < timeout) {
+    throwIfStopped();
+    const btn = findChatgptSkipButton();
+    if (btn && isVisibleElement(btn)) {
+      return btn;
+    }
+    await sleep(300);
+  }
+  return null;
+}
+
+async function skipChatgptOnboarding() {
+  log('ChatGPT 页面:正在确认是引导页还是已登录主页...');
+
+  const initialState = await waitForChatgptPostSignupState(15000);
+  if (initialState === 'home') {
+    log('ChatGPT 页面:未出现可跳过引导,已进入登录后的 ChatGPT 页面,按注册成功处理。', 'ok');
+    return { success: true, alreadyCompleted: true };
+  }
+
+  if (initialState !== 'onboarding') {
+    throw new Error('ChatGPT 页面:未检测到可跳过引导,也未确认进入登录后的主页。URL: ' + location.href);
+  }
+
+  log('ChatGPT 引导页:正在查找第一个"Skip/跳过"按钮...');
+
+  // Find first Skip button: sibling of "Next" button, with btn-ghost class
+  const firstSkipBtn = await waitForChatgptSkipButton(15000);
+  if (!firstSkipBtn) {
+    throw new Error('ChatGPT 引导页:未找到第一个"Skip/跳过"按钮。URL: ' + location.href);
+  }
+
+  await humanPause(500, 1200);
+  simulateClick(firstSkipBtn);
+  log('ChatGPT 引导页:已点击第一个"Skip/跳过"按钮,等待第二个按钮出现...');
+
+  // Wait 3 seconds for the second skip button to appear
+  await sleep(3000);
+
+  // Find second Skip button: sibling of "Continue" button, with btn-ghost class
+  const secondSkipBtn = await waitForChatgptSkipButton(5000);
+  if (!secondSkipBtn) {
+    if (isChatgptAuthenticatedHomePage()) {
+      log('ChatGPT 引导页:未找到第二个"Skip/跳过"按钮,但页面已进入登录后的 ChatGPT 页面。', 'ok');
+    } else {
+      log('ChatGPT 引导页:5秒内未找到第二个"Skip/跳过"按钮,判定注册已完成。', 'ok');
+    }
+    return { success: true };
+  }
+
+  await humanPause(500, 1200);
+  simulateClick(secondSkipBtn);
+  log('ChatGPT 引导页:已点击第二个"Skip/跳过"按钮,注册流程完成。', 'ok');
+
+  return { success: true };
+}

+ 172 - 0
tests/step5-chatgpt-onboarding.test.js

@@ -0,0 +1,172 @@
+const assert = require('assert');
+const fs = require('fs');
+
+const source = fs.readFileSync('content/signup-page.js', 'utf8');
+
+function extractFunction(name) {
+  const markers = [`async function ${name}(`, `function ${name}(`];
+  const start = markers
+    .map((marker) => source.indexOf(marker))
+    .find((index) => index >= 0);
+  if (start < 0) {
+    throw new Error(`missing function ${name}`);
+  }
+
+  let parenDepth = 0;
+  let signatureEnded = false;
+  let braceStart = -1;
+  for (let i = start; i < source.length; i += 1) {
+    const ch = source[i];
+    if (ch === '(') {
+      parenDepth += 1;
+    } else if (ch === ')') {
+      parenDepth -= 1;
+      if (parenDepth === 0) {
+        signatureEnded = true;
+      }
+    } else if (ch === '{' && signatureEnded) {
+      braceStart = i;
+      break;
+    }
+  }
+  if (braceStart < 0) {
+    throw new Error(`missing body for function ${name}`);
+  }
+
+  let depth = 0;
+  let end = braceStart;
+  for (; end < source.length; end += 1) {
+    const ch = source[end];
+    if (ch === '{') depth += 1;
+    if (ch === '}') {
+      depth -= 1;
+      if (depth === 0) {
+        end += 1;
+        break;
+      }
+    }
+  }
+
+  return source.slice(start, end);
+}
+
+const bundle = [
+  extractFunction('getPageTextSnapshot'),
+  extractFunction('findChatgptSkipButton'),
+  extractFunction('waitForChatgptSkipButton'),
+  extractFunction('isChatgptOnboardingPage'),
+  extractFunction('isChatgptUrl'),
+  extractFunction('hasVisibleElementMatchingSelector'),
+  extractFunction('isChatgptAuthenticatedHomePage'),
+  extractFunction('waitForChatgptPostSignupState'),
+  extractFunction('skipChatgptOnboarding'),
+].join('\n');
+
+const api = new Function(`
+const CHATGPT_ONBOARDING_TEXT_PATTERN = /welcome\\s+to\\s+chatgpt|what\\s+should\\s+chatgpt\\s+call\\s+you|how\\s+do\\s+you\\s+want\\s+chatgpt\\s+to\\s+respond|tell\\s+chatgpt\\s+what\\s+traits|personal(?:ize|ise)\\s+your\\s+experience|介绍一下你自己|ChatGPT 应该如何称呼你|你希望 ChatGPT 如何回应/i;
+const CHATGPT_HOME_TEXT_PATTERN = /new\\s+chat|temporary\\s+chat|message\\s+chatgpt|send\\s+a\\s+message|chatgpt\\s+can\\s+make\\s+mistakes|新建聊天|临时聊天|给\\s*ChatGPT\\s*发消息|ChatGPT\\s*可能会犯错/i;
+
+let buttonList = [];
+let selectorMap = {};
+let pageText = '';
+let clickedButtons = [];
+let logs = [];
+const location = { href: 'https://chatgpt.com/' };
+const document = {
+  body: { innerText: '', textContent: '' },
+  querySelectorAll(selector) {
+    if (selector === 'button') {
+      return buttonList;
+    }
+    return selectorMap[selector] || [];
+  },
+};
+
+function isVisibleElement(el) {
+  return Boolean(el) && !el.hidden;
+}
+
+function throwIfStopped() {}
+async function sleep() {}
+async function humanPause() {}
+function log(message, level = 'info') {
+  logs.push({ message, level });
+}
+function simulateClick(button) {
+  clickedButtons.push(button.textContent || button.id || 'button');
+  button.hidden = true;
+}
+
+${bundle}
+
+return {
+  setPage({ href = 'https://chatgpt.com/', text = '', buttons = [], selectors = {} }) {
+    location.href = href;
+    pageText = text;
+    buttonList = buttons.map((button, index) => ({
+      id: button.id || \`button-\${index}\`,
+      textContent: button.textContent || '',
+      className: button.className || '',
+      hidden: Boolean(button.hidden),
+    }));
+    selectorMap = {};
+    for (const [selector, count] of Object.entries(selectors)) {
+      selectorMap[selector] = Array.from({ length: count }, (_, index) => ({ id: \`\${selector}-\${index}\`, hidden: false }));
+    }
+    document.body.innerText = pageText;
+    document.body.textContent = pageText;
+    clickedButtons = [];
+    logs = [];
+  },
+  isChatgptOnboardingPage() {
+    return isChatgptOnboardingPage();
+  },
+  isChatgptAuthenticatedHomePage() {
+    return isChatgptAuthenticatedHomePage();
+  },
+  async skipChatgptOnboarding() {
+    return skipChatgptOnboarding();
+  },
+  snapshot() {
+    return { clickedButtons, logs };
+  },
+};
+`)();
+
+(async () => {
+  api.setPage({
+    href: 'https://chatgpt.com/',
+    text: 'New chat ChatGPT can make mistakes',
+    selectors: {
+      'textarea[placeholder*="Message" i]': 1,
+    },
+  });
+
+  assert.strictEqual(api.isChatgptOnboardingPage(), false, '已登录主页不应仅因 chatgpt.com URL 被误判为 onboarding');
+  assert.strictEqual(api.isChatgptAuthenticatedHomePage(), true, '主页特征存在时应识别为已登录 ChatGPT 页面');
+
+  let result = await api.skipChatgptOnboarding();
+  let snapshot = api.snapshot();
+  assert.deepStrictEqual(result, { success: true, alreadyCompleted: true }, '无 Skip 按钮但已进入主页时应按成功处理');
+  assert.deepStrictEqual(snapshot.clickedButtons, [], '已登录主页场景不应再误点按钮');
+
+  api.setPage({
+    href: 'https://chatgpt.com/',
+    text: 'Welcome to ChatGPT',
+    buttons: [
+      { textContent: 'Skip', className: 'btn-ghost' },
+      { textContent: 'Skip', className: 'btn-ghost' },
+    ],
+  });
+
+  assert.strictEqual(api.isChatgptOnboardingPage(), true, '存在 Skip 按钮时应识别为 onboarding');
+  result = await api.skipChatgptOnboarding();
+  snapshot = api.snapshot();
+  assert.deepStrictEqual(result, { success: true }, '真实 onboarding 仍应继续执行跳过逻辑');
+  assert.deepStrictEqual(snapshot.clickedButtons, ['Skip', 'Skip'], '双 Skip onboarding 应依次点击两个按钮');
+
+  console.log('step5 chatgpt onboarding tests passed');
+})().catch((error) => {
+  console.error(error);
+  process.exit(1);
+});

+ 123 - 0
tests/step5-chatgpt-redirect-race.test.js

@@ -0,0 +1,123 @@
+const assert = require('assert');
+const fs = require('fs');
+
+const source = fs.readFileSync('background.js', 'utf8');
+
+function extractFunction(name) {
+  const markers = [`async function ${name}(`, `function ${name}(`];
+  const start = markers
+    .map((marker) => source.indexOf(marker))
+    .find((index) => index >= 0);
+  if (start < 0) {
+    throw new Error(`missing function ${name}`);
+  }
+
+  let parenDepth = 0;
+  let signatureEnded = false;
+  let braceStart = -1;
+  for (let i = start; i < source.length; i += 1) {
+    const ch = source[i];
+    if (ch === '(') {
+      parenDepth += 1;
+    } else if (ch === ')') {
+      parenDepth -= 1;
+      if (parenDepth === 0) {
+        signatureEnded = true;
+      }
+    } else if (ch === '{' && signatureEnded) {
+      braceStart = i;
+      break;
+    }
+  }
+  if (braceStart < 0) {
+    throw new Error(`missing body for function ${name}`);
+  }
+
+  let depth = 0;
+  let end = braceStart;
+  for (; end < source.length; end += 1) {
+    const ch = source[end];
+    if (ch === '{') depth += 1;
+    if (ch === '}') {
+      depth -= 1;
+      if (depth === 0) {
+        end += 1;
+        break;
+      }
+    }
+  }
+
+  return source.slice(start, end);
+}
+
+const bundle = [
+  extractFunction('waitForStep5ChatgptRedirect'),
+].join('\n');
+
+const api = new Function(`
+let waitArgs = null;
+let waitResult = null;
+let currentTab = null;
+
+const chrome = {
+  tabs: {
+    async get() {
+      return currentTab;
+    },
+  },
+};
+
+async function waitForTabUrlMatch(tabId, matcher, options = {}) {
+  waitArgs = { tabId, matcher, options };
+  return waitResult;
+}
+
+${bundle}
+
+return {
+  async run(tabId, timeoutMs) {
+    return waitForStep5ChatgptRedirect(tabId, timeoutMs);
+  },
+  setWaitResult(value) {
+    waitResult = value;
+  },
+  setCurrentTab(value) {
+    currentTab = value;
+  },
+  snapshot() {
+    return { waitArgs };
+  },
+};
+`)();
+
+(async () => {
+  const redirected = { id: 86, url: 'https://chatgpt.com/' };
+  api.setWaitResult(redirected);
+  api.setCurrentTab({ id: 86, url: 'https://auth.openai.com/' });
+
+  let result = await api.run(86, 22000);
+  let snapshot = api.snapshot();
+  assert.deepStrictEqual(result, redirected, '等待命中 chatgpt.com 时应直接返回匹配到的标签页');
+  assert.strictEqual(snapshot.waitArgs.tabId, 86, '应使用 signup-page 当前标签页等待跳转');
+  assert.strictEqual(snapshot.waitArgs.options.timeoutMs, 22000, '应透传等待超时时间');
+  assert.strictEqual(snapshot.waitArgs.options.retryDelayMs, 300, '应使用较短轮询间隔覆盖 URL 更新 race');
+  assert.strictEqual(snapshot.waitArgs.matcher('https://chatgpt.com/?model=gpt-5'), true, 'matcher 应接受 chatgpt.com');
+  assert.strictEqual(snapshot.waitArgs.matcher('https://auth.openai.com/u/signup'), false, 'matcher 不应把旧认证页误判为成功');
+
+  api.setWaitResult(null);
+  api.setCurrentTab({ id: 86, url: 'https://chatgpt.com/?temporary-chat=true' });
+  result = await api.run(86, 15000);
+  assert.deepStrictEqual(result, { id: 86, url: 'https://chatgpt.com/?temporary-chat=true' }, '等待超时后仍应回读当前标签页 URL 兜底');
+
+  api.setCurrentTab({ id: 86, url: 'https://auth.openai.com/u/signup' });
+  result = await api.run(86, 15000);
+  assert.strictEqual(result, null, '仍停留旧域名时不应误判为跳转成功');
+
+  result = await api.run(null, 15000);
+  assert.strictEqual(result, null, '无有效标签页时应直接返回 null');
+
+  console.log('step5 chatgpt redirect race tests passed');
+})().catch((error) => {
+  console.error(error);
+  process.exit(1);
+});