Эх сурвалжийг харах

Clear session before signup flow retry

chendeben 4 сар өмнө
parent
commit
42f7dc3717

+ 43 - 0
background.js

@@ -5862,6 +5862,7 @@ const step1Executor = self.MultiPageBackgroundStep1?.createStep1Executor({
   addLog,
   completeStepFromBackground,
   openSignupEntryTab,
+  runPreStep1SessionCleanup,
 });
 const step2Executor = self.MultiPageBackgroundStep2?.createStep2Executor({
   addLog,
@@ -6410,6 +6411,48 @@ async function runPreStep6CookieCleanup() {
   await addLog(`步骤 6:已直接删除 ${removedCount} 个 ChatGPT / OpenAI cookies,准备继续获取链接并登录。`, 'ok');
 }
 
+async function runPreStep1SessionCleanup() {
+  await addLog('步骤 1:正在清理 ChatGPT / OpenAI 登录态...', 'info');
+
+  let removedCookieCount = 0;
+  if (chrome.cookies?.getAll && chrome.cookies?.remove) {
+    const cookies = await collectCookiesForPreLoginCleanup();
+    for (const cookie of cookies) {
+      if (await removeCookieDirectly(cookie)) {
+        removedCookieCount += 1;
+      }
+    }
+  }
+
+  if (chrome.browsingData?.remove) {
+    try {
+      await chrome.browsingData.remove({
+        since: 0,
+        origins: PRE_LOGIN_COOKIE_CLEAR_ORIGINS,
+      }, {
+        cookies: true,
+        localStorage: true,
+        cacheStorage: true,
+        indexedDB: true,
+        serviceWorkers: true,
+      });
+    } catch (err) {
+      await addLog(`步骤 1:清理站点存储失败:${getErrorMessage(err)}`, 'warn');
+    }
+  } else if (chrome.browsingData?.removeCookies) {
+    try {
+      await chrome.browsingData.removeCookies({
+        since: 0,
+        origins: PRE_LOGIN_COOKIE_CLEAR_ORIGINS,
+      });
+    } catch (err) {
+      await addLog(`步骤 1:browsingData 清理 cookies 失败:${getErrorMessage(err)}`, 'warn');
+    }
+  }
+
+  await addLog(`步骤 1:已清理登录态(cookies ${removedCookieCount} 个),准备以干净状态打开官网。`, 'ok');
+}
+
 // ============================================================
 // Step 7: Login and ensure the auth page reaches the login verification page
 // ============================================================

+ 5 - 3
background/signup-flow-helpers.js

@@ -22,10 +22,12 @@
       waitForTabUrlMatch,
     } = deps;
 
-    async function openSignupEntryTab(step = 1) {
+    async function openSignupEntryTab(step = 1, options = {}) {
+      const { reloadIfSameUrl = false } = options;
       const tabId = await reuseOrCreateTab('signup-page', SIGNUP_ENTRY_URL, {
         inject: SIGNUP_PAGE_INJECT_FILES,
         injectSource: 'signup-page',
+        reloadIfSameUrl,
       });
 
       await ensureContentScriptReadyOnTab('signup-page', tabId, {
@@ -39,8 +41,8 @@
       return tabId;
     }
 
-    async function ensureSignupEntryPageReady(step = 1) {
-      const tabId = await openSignupEntryTab(step);
+    async function ensureSignupEntryPageReady(step = 1, options = {}) {
+      const tabId = await openSignupEntryTab(step, options);
       const result = await sendToContentScriptResilient('signup-page', {
         type: 'ENSURE_SIGNUP_ENTRY_READY',
         step,

+ 5 - 1
background/steps/open-chatgpt.js

@@ -6,11 +6,15 @@
       addLog,
       completeStepFromBackground,
       openSignupEntryTab,
+      runPreStep1SessionCleanup,
     } = deps;
 
     async function executeStep1() {
       await addLog('步骤 1:正在打开 ChatGPT 官网...');
-      await openSignupEntryTab(1);
+      if (typeof runPreStep1SessionCleanup === 'function') {
+        await runPreStep1SessionCleanup();
+      }
+      await openSignupEntryTab(1, { reloadIfSameUrl: true });
       await completeStepFromBackground(1, {});
     }
 

+ 2 - 2
background/steps/submit-signup-email.js

@@ -25,10 +25,10 @@
         let signupTabId = await getTabId('signup-page');
         if (!signupTabId || !(await isTabAlive('signup-page'))) {
           await addLog('步骤 2:未发现可用的注册页标签,正在重新打开 ChatGPT 官网...', 'warn');
-          signupTabId = (await ensureSignupEntryPageReady(2)).tabId;
+          signupTabId = (await ensureSignupEntryPageReady(2, { reloadIfSameUrl: true })).tabId;
         } else if (attempt > 1) {
           await addLog(`步骤 2:第 ${attempt}/${maxAttempts} 次尝试,正在重新打开注册入口后重试邮箱提交...`, 'warn');
-          signupTabId = (await ensureSignupEntryPageReady(2)).tabId;
+          signupTabId = (await ensureSignupEntryPageReady(2, { reloadIfSameUrl: true })).tabId;
         } else {
           await chrome.tabs.update(signupTabId, { active: true });
           await ensureContentScriptReadyOnTab('signup-page', signupTabId, {

+ 3 - 3
hotmail-utils.js

@@ -301,7 +301,7 @@
   }
 
   function getHotmailVerificationPollConfig(step) {
-    if (step === 4 || step === 7) {
+    if (step === 4 || step === 8) {
       return {
         initialDelayMs: 5000,
         maxAttempts: 12,
@@ -331,11 +331,11 @@
       return Math.max(0, signupRequestedAt - bufferMs);
     }
 
-    if (step === 7 && loginRequestedAt) {
+    if (step === 8 && loginRequestedAt) {
       return Math.max(0, loginRequestedAt - bufferMs);
     }
 
-    return step === 7
+    return step === 8
       ? (lastEmailTimestamp || flowStartTime || 0)
       : (flowStartTime || 0);
   }

+ 4 - 1
tests/background-signup-step2-branching.test.js

@@ -87,6 +87,7 @@ test('step 2 keeps password flow when landing on password page', async () => {
 test('step 2 retries once after post-email landing check fails', async () => {
   const completedPayloads = [];
   let entryReadyCalls = 0;
+  const entryReadyOptions = [];
   let sendCalls = 0;
   let landingCalls = 0;
 
@@ -97,8 +98,9 @@ test('step 2 retries once after post-email landing check fails', async () => {
       completedPayloads.push({ step, payload });
     },
     ensureContentScriptReadyOnTab: async () => {},
-    ensureSignupEntryPageReady: async () => {
+    ensureSignupEntryPageReady: async (_step, options) => {
       entryReadyCalls += 1;
+      entryReadyOptions.push(options || null);
       return { tabId: 13 };
     },
     ensureSignupPostEmailPageReadyInTab: async () => {
@@ -124,6 +126,7 @@ test('step 2 retries once after post-email landing check fails', async () => {
   await executor.executeStep2({ email: 'user@example.com' });
 
   assert.equal(entryReadyCalls, 1);
+  assert.deepStrictEqual(entryReadyOptions, [{ reloadIfSameUrl: true }]);
   assert.equal(sendCalls, 2);
   assert.equal(landingCalls, 2);
   assert.deepStrictEqual(completedPayloads, [

+ 32 - 0
tests/background-step1-cleanup.test.js

@@ -0,0 +1,32 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+
+const source = fs.readFileSync('background/steps/open-chatgpt.js', 'utf8');
+const globalScope = {};
+const api = new Function('self', `${source}; return self.MultiPageBackgroundStep1;`)(globalScope);
+
+test('step 1 clears login state before opening signup entry tab', async () => {
+  const calls = [];
+
+  const executor = api.createStep1Executor({
+    addLog: async () => {},
+    completeStepFromBackground: async () => {
+      calls.push('complete');
+    },
+    openSignupEntryTab: async (_step, options) => {
+      calls.push(['open', options]);
+    },
+    runPreStep1SessionCleanup: async () => {
+      calls.push('cleanup');
+    },
+  });
+
+  await executor.executeStep1();
+
+  assert.deepStrictEqual(calls, [
+    'cleanup',
+    ['open', { reloadIfSameUrl: true }],
+    'complete',
+  ]);
+});

+ 2 - 2
tests/hotmail-utils.test.js

@@ -425,7 +425,7 @@ test('getHotmailVerificationPollConfig gives Hotmail a slower initial wait and l
     ignorePersistedLastCode: true,
   });
 
-  assert.deepEqual(getHotmailVerificationPollConfig(7), {
+  assert.deepEqual(getHotmailVerificationPollConfig(8), {
     initialDelayMs: 5000,
     maxAttempts: 12,
     intervalMs: 5000,
@@ -447,7 +447,7 @@ test('getHotmailVerificationRequestTimestamp prefers actual request timestamps w
   );
 
   assert.equal(
-    getHotmailVerificationRequestTimestamp(7, {
+    getHotmailVerificationRequestTimestamp(8, {
       loginVerificationRequestedAt: loginRequestedAt,
       lastEmailTimestamp: loginRequestedAt - 120_000,
       flowStartTime: loginRequestedAt - 300_000,